Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 4 of 6 · Lab · 30 min · revision 3

Lab: lint, test and package a service with reports

Build a Makefile that pins Python, installs from a hashed lock, runs a syntax check as its lint stage, tests with a JUnit XML report and packages a small service, then build it twice and get the same sha256.

Contentsand lesson path

What you will learn

  • Script a build that runs identically on a laptop and a CI runner, with pinned toolchain versions and locked dependencies.
  • Order lint, unit test, integration test and packaging steps so they fail fast and emit machine-readable test reports.

01. What the lab builds

Printing test results to the terminal works for one developer, but a CI system needs results it can read. When a suite has thousands of tests, nobody wants to search a long log for the one failing assertion.

Most test runners can write a JUnit XML report, a de facto standard file format that pytest, Jest, Go tools, Maven and the major CI platforms understand. A JUnit XML report records:

  • Suites and test cases: each test with its module and name, inside a <testsuite> element that counts tests, errors and failures.
  • Durations: the time of each test (time="0.042"), which CI tools use to show slow tests and to split a suite into balanced shards.
  • Failure details: the assertion message and captured output inside <failure>, <system-out> and <system-err> elements, so a CI platform can show the failure next to the pull request instead of in a raw log.

The lab also makes the build repeatable on a laptop and on a CI runner. It pins the Python version in a file, installs the test tools from a lock file with hashes, and packages the code so that two builds of the same commit, in two different directories, give the same SHA-256.

02. Lab Exercise: Executing the Pipeline and Validating Artifacts

You will build a small Python service with a Makefile that runs four stages in order (ci: toolchain lint test package): a check that the right Python runs, a lint stage that here is only a syntax check, the tests with a JUnit XML report written to reports/junit.xml, and a reproducible tarball in dist/. Every file is printed below, so you can run the lab from an empty directory.

You need uv (it downloads Python 3.13 if you do not have it), GNU Make, Git and GNU tar 1.28 or later (for --sort=name; macOS users can install gnu-tar and use gtar). The output below was produced with uv 0.12.2, Python 3.13 and pytest 9.1.1. The finished layout is:

  • service-lab/Makefile, .python-version, .gitignore
  • service-lab/requirements-dev.in (what you ask for) and requirements-dev.txt (the lock)
  • service-lab/src/service.py
  • service-lab/tests/test_service.py
  1. Create the project, pin the interpreter and lock the test tools. uv python pin 3.13 writes the version into .python-version, a small file that uv and pyenv read on a laptop and that actions/setup-python reads in CI through python-version-file: .python-version. One committed file then decides the Python version everywhere, instead of a line in a README. requirements-dev.in names only pytest; uv pip compile --generate-hashes resolves it into requirements-dev.txt, which pins every package, including pytest's own dependencies, to an exact version with its SHA-256 hashes. --require-hashes then refuses any package that is missing from the lock or whose download does not match.
Bash · Step 1: skeleton, pinned interpreter and hashed lock file
mkdir -p service-lab/src service-lab/tests && cd service-lab
git init -q .
printf '.venv/\ndist/\nreports/\n__pycache__/\n.pytest_cache/\n' > .gitignore
uv python pin 3.13
printf 'pytest==9.1.1\n' > requirements-dev.in
uv pip compile -q --generate-hashes requirements-dev.in -o requirements-dev.txt
uv venv -q .venv
uv pip install -q --python .venv/bin/python --require-hashes \
  -r requirements-dev.txt
cat .python-version
.venv/bin/python -m pytest --version
Expected output
Pinned `.python-version` to `3.13`
3.13
pytest 9.1.1

Open requirements-dev.txt. Besides pytest==9.1.1 it lists packages you never named, such as pluggy and iniconfig, each with exact versions and --hash=sha256: lines. Those transitive dependencies are what usually drifts between two machines. Commit both files; to upgrade, change requirements-dev.in, compile again and review the diff of the lock.

  1. Write the service. A single pricing function with input validation.
Python · src/service.py
"""Pricing helpers for the lab service."""


def apply_discount(price: float, rate: float) -> float:
    """Return price reduced by rate (0.0 to 1.0), rounded to cents."""
    if not 0.0 <= rate <= 1.0:
        raise ValueError(f"rate must be between 0 and 1, got {rate}")
    return round(price * (1.0 - rate), 2)
  1. Write the tests. Three cases: a normal discount, no discount, and an invalid rate that must raise ValueError.
Python · tests/test_service.py
import pytest

from service import apply_discount


def test_standard_discount():
    assert apply_discount(80.0, 0.25) == 60.0


def test_zero_discount():
    assert apply_discount(19.99, 0.0) == 19.99


def test_invalid_rate():
    with pytest.raises(ValueError):
        apply_discount(10.0, 1.5)
  1. Write the Makefile. Recipe lines must start with a Tab character. The toolchain target stops the build when the interpreter is not the version in .python-version, so a wrong Python fails loudly instead of producing a slightly different build. Here lint only runs py_compile, which finds syntax errors and nothing else. A real project runs a linter such as Ruff (ruff check src tests) in this target, locked with hashes like pytest; it also finds unused imports and undefined names. pytest --junitxml writes the machine-readable report; the plain unittest runner prints results but writes no XML. The package recipe uses lesson 01's rules: sorted names, every modification time set to the last commit (SOURCE_DATE_EPOCH), numeric owner and group 0, fixed file modes and archive format, gzip -n, and no __pycache__ (which py_compile creates). The flags for modes and format deserve a closer look. --mode=a=rX,u+w sets the same permission bits on every file, because permissions come from each user's umask: in a test on ext4, a file created under umask 0002 changed the archive hash, while with --mode both umasks gave the same hash. --format=gnu keeps tar from writing access and change times, which some distributions add by default with the pax format.
Makefile · Makefile
.PHONY: all toolchain lint test package ci clean

PYTHON ?= python3
SRC_DIR = src
TEST_DIR = tests
DIST_DIR = dist
REPORT_DIR = reports
VERSION = 1.0.0
PY_WANT := $(shell cat .python-version)
SOURCE_DATE_EPOCH ?= $(shell git log -1 --pretty=%ct 2>/dev/null || echo 0)

all: ci

clean:
	rm -rf $(DIST_DIR) $(REPORT_DIR) .pytest_cache
	find . -name __pycache__ -type d -prune -exec rm -rf {} +

toolchain:
	@$(PYTHON) -c 'import sys; v = "%d.%d" % sys.version_info[:2]; \
	sys.exit(0 if v == "$(PY_WANT)" else f"need Python $(PY_WANT), got {v}")'
	@echo "[OK] Python $(PY_WANT), as pinned in .python-version"

lint:
	@echo "==> Running syntax checks..."
	$(PYTHON) -m py_compile $(SRC_DIR)/service.py
	@echo "[OK] Syntax check passed."

test:
	@echo "==> Running tests, writing $(REPORT_DIR)/junit.xml..."
	mkdir -p $(REPORT_DIR)
	PYTHONPATH=$(SRC_DIR) $(PYTHON) -m pytest $(TEST_DIR) -v --no-header \
		--junitxml=$(REPORT_DIR)/junit.xml

package:
	@echo "==> Creating distribution package artifact..."
	mkdir -p $(DIST_DIR)
	tar --sort=name --mtime="@$(SOURCE_DATE_EPOCH)" --format=gnu \
		--owner=0 --group=0 --numeric-owner --mode=a=rX,u+w \
		--exclude=__pycache__ -cf - -C $(SRC_DIR) . \
		| gzip -n > $(DIST_DIR)/service-$(VERSION).tar.gz
	@echo "[OK] Package created: $(DIST_DIR)/service-$(VERSION).tar.gz"

ci: toolchain lint test package
	@echo "==> [SUCCESS] All pipeline stages passed successfully."
  1. Commit and run the pipeline. The commit gives SOURCE_DATE_EPOCH a value; without Git history the Makefile falls back to 0.
Bash · Step 5: run the pipeline
git add . && git commit -qm "lab: service"
make ci PYTHON=.venv/bin/python
Illustrative output (your path, timing and epoch value will differ)
[OK] Python 3.13, as pinned in .python-version
==> Running syntax checks...
.venv/bin/python -m py_compile src/service.py
[OK] Syntax check passed.
==> Running tests, writing reports/junit.xml...
mkdir -p reports
PYTHONPATH=src .venv/bin/python -m pytest tests -v --no-header \
	--junitxml=reports/junit.xml
============================= test session starts ==============================
collecting ... collected 3 items

tests/test_service.py::test_standard_discount PASSED                     [ 33%]
tests/test_service.py::test_zero_discount PASSED                         [ 66%]
tests/test_service.py::test_invalid_rate PASSED                          [100%]

- generated xml file: /home/you/service-lab/reports/junit.xml -
============================== 3 passed in 0.18s ===============================
==> Creating distribution package artifact...
mkdir -p dist
tar --sort=name --mtime="@1794853008" --format=gnu \
	--owner=0 --group=0 --numeric-owner --mode=a=rX,u+w \
	--exclude=__pycache__ -cf - -C src . \
	| gzip -n > dist/service-1.0.0.tar.gz
[OK] Package created: dist/service-1.0.0.tar.gz
==> [SUCCESS] All pipeline stages passed successfully.
  1. Check the report, then build the same commit in a second directory. The report must contain three <testcase> elements. A fresh clone in another directory is what a CI runner starts from: a different path, new file timestamps from the checkout, and no __pycache__. If the package is reproducible, both archives have the same SHA-256.
Bash · Step 6: verify the report and rebuild from a clone
grep -o '<testcase ' reports/junit.xml | wc -l
git clone -q . ../service-lab-copy
make -C ../service-lab-copy package >/dev/null
(cd dist && sha256sum service-1.0.0.tar.gz)
(cd ../service-lab-copy/dist && sha256sum service-1.0.0.tar.gz)
Illustrative output (your hash depends on your commit time; the two lines must match)
3
30da0c3556b60b68f97b6cc0b5aaf357d1c6b73ce604a3f65721159c90a14ef3  service-1.0.0.tar.gz
30da0c3556b60b68f97b6cc0b5aaf357d1c6b73ce604a3f65721159c90a14ef3  service-1.0.0.tar.gz
  1. Break it on purpose. Introduce a bug, run the pipeline again, and confirm three things: make exits non-zero, the JUnit report still records the failure, and no package is built, because package runs only after test succeeds.
Bash · Step 7: a failing test stops the pipeline
make clean >/dev/null
sed -i "s/(1.0 - rate)/(1.0 + rate)/" src/service.py
make ci PYTHON=.venv/bin/python; echo "make exit: $?"
grep -o 'failures="[0-9]*"' reports/junit.xml | head -1
ls dist
sed -i "s/(1.0 + rate)/(1.0 - rate)/" src/service.py  # undo the bug
Illustrative output (abridged: the traceback is omitted; your timing differs)
tests/test_service.py::test_standard_discount FAILED                     [ 33%]
tests/test_service.py::test_zero_discount PASSED                         [ 66%]
tests/test_service.py::test_invalid_rate PASSED                          [100%]
...
FAILED tests/test_service.py::test_standard_discount - assert 100.0 == 60.0
========================= 1 failed, 2 passed in 4.24s ==========================
make: *** [Makefile:31: test] Error 1
make exit: 2
failures="1"
ls: cannot access 'dist': No such file or directory

The output shows the four stages running in fail-fast order. The interpreter matched .python-version, the syntax check passed, pytest ran the three tests and wrote reports/junit.xml, and the packaging target created dist/service-1.0.0.tar.gz. A clean clone in another directory produced the same archive bytes. When a test failed, the pipeline stopped before packaging, and the report still described the failure.

In CI, you upload reports/junit.xml and the tarball as build artifacts (for example with actions/upload-artifact, pinned to a commit SHA) so each package can be traced back to its commit and test results. Release pipelines also record the SHA-256 of the package. A checksum detects corrupted or incomplete downloads. It detects deliberate substitution only when the expected value comes from somewhere an attacker cannot also change, such as the digest your CI recorded in your own repository or a signed checksum file; a checksums.txt downloaded from the same server as the package proves nothing if that server is compromised.

03. Keep the report when the tests fail

Plan for the failing run, because that is when you need the report most. A CI job stops at the first step that fails, so if the test step fails, the later step that uploads the JUnit XML report is skipped by default, and nobody can see which test broke.

A step condition fixes this: if: always() in GitHub Actions or artifacts: when: always in GitLab CI runs the report upload whether the tests passed or failed, and if: failure() runs a step only after a failure (these conditions still cannot upload a report that was never written, for example when the job was cancelled before the tests ran).

Keep other diagnostics the same way: browser test screenshots, network traces or heap snapshots often let you diagnose an intermittent CI failure without reproducing it locally.

04. Check your understanding

Practice check · 3 questions

Deterministic packaging and Make order

Three questions on the lab's Makefile and its package step.

Q1. The lab's `package` recipe pipes tar into `gzip -n`. What does the `-n` flag do for the build?
Q2. In step 7 of the lab a test fails. Why is no `dist/` archive created?
Q3. A teammate builds the same commit with an older recipe that has no `--mode` flag and gets a different SHA-256. `tar -tvzf` shows `-rw-rw-r--` in their archive and `-rw-r--r--` in yours. What explains the difference?
Practice only: not graded, not saved, not evidence.

05. Apply it

Apply the lab to your own service repository:

  • Pin the toolchain in the repository: commit .python-version (or .nvmrc, .tool-versions) and point the CI setup step at the same file, for example python-version-file: .python-version.
  • Install only from the lock: commit the lock file and install with --require-hashes, uv sync --locked, npm ci or the equivalent strict command, so CI fails instead of resolving new versions (uv sync --locked stops when uv.lock no longer matches pyproject.toml).
  • Emit JUnit XML in every CI test run and upload it with if: always(), so the report survives a failing test.
  • Record where an artifact came from without breaking reproducibility: store the full commit SHA and the SOURCE_DATE_EPOCH value next to the artifact. Do not embed the current build time, because then no two builds of the same commit can match.
  • Prove reproducibility in CI: build twice from clean checkouts and fail the job if the SHA-256 values differ.

06. Review prompt

Without looking back, explain which file pins the Python version and which file pins every dependency, and what --require-hashes refuses. Name four things that can make two builds of the same commit differ (time, file order, owner, permissions) and the tar or gzip flag that removes each. Then explain why the report upload in CI needs if: always().

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check