Lab: a pull-request pipeline with caching and a test matrix
Build a GitHub Actions workflow for a small Python project that runs on pull requests, on main and in the merge queue, with a dependent lint job, a cached test matrix across two Python versions, uploaded JUnit reports and actions pinned to verified commit SHAs.
Contentsand lesson path
On this page
- What you will build
- Step 1: Create the Starter Project and Run It Locally
- Step 2: Write the Workflow
- Step 3: Verify Every Pinned SHA Yourself
- Step 4: Open a Pull Request and Read the Run
- Check your understanding
- Apply it
- Review prompt
Lessons of Continuous Integration
- Integrating continuously: small batches and a green main Concept · 15 min
- Anatomy of a pipeline: triggers, jobs, runners, steps and reuse Concept · 20 min
- Lab: a pull-request pipeline with caching and a test matrix Lab · 30 min
- Merge gates and reading a failing run Worked example · 20 min
- Securing the pipeline itself: lessons from compromised actions Worked example · 20 min
- Check: fix and harden a broken workflow Knowledge check · 6 questions
What you will learn
- Write a CI workflow (GitHub Actions or GitLab CI) that runs on pull requests and on main, with dependent jobs, dependency caching and a test matrix.
Prerequisites: Git Workflow, Build & Test Pipeline
01. What you will build
In this lab you build a small but complete GitHub Actions pipeline for a Python project. It will:
- Run on the right events: every pull request to
main, every push tomain, and themerge_groupevent used by GitHub merge queues. - Fail fast: the slower
testjob declaresneeds: lint, so it only starts when the quicklintjob passes. - Test a matrix: the test job runs once per Python version (
3.13and3.14), in parallel, on separate runners. - Cache dependencies: pip's download cache is saved under a key that includes
hashFiles('requirements-dev.txt'), so the key changes whenever the pinned dependencies change. - Keep test reports: each leg writes a JUnit XML report and uploads it as a workflow artifact, even when tests fail.
What you need: a GitHub account and an empty repository you can push to, Git, and Python 3.12 or newer locally. The workflow was written against actions/checkout v7.0.1, actions/setup-python v7.1.0, actions/cache v6.1.0 and actions/upload-artifact v7.0.2, the latest releases on 17 November 2026, and runs on the ubuntu-24.04 hosted runner. The tests use pytest==9.1.1.
GitHub-hosted caches are not permanent. By default GitHub removes cache entries that have not been accessed for 7 days, and limits the total cache size per repository (10 GB unless an administrator raises it); when a repository goes over its limit, the least recently used entries are evicted first. The pipeline must still pass with an empty cache.
02. Step 1: Create the Starter Project and Run It Locally
Create a new directory for the repository and add the three files below: a tiny module, its tests and a pinned development requirement. Then create a virtual environment, install the requirement and run the tests the same way CI will. python -m pytest (rather than plain pytest) puts the current directory on the import path, so import pricing works without packaging the project.
def apply_discount(price_cents: int, percent: int) -> int:
if not 0 <= percent <= 100:
raise ValueError("percent must be between 0 and 100")
return price_cents * (100 - percent) // 100import pytest
from pricing import apply_discount
def test_ten_percent_off():
assert apply_discount(2000, 10) == 1800
def test_rounds_down_to_whole_cents():
assert apply_discount(999, 15) == 849
def test_rejects_impossible_discount():
with pytest.raises(ValueError):
apply_discount(1000, 120)printf 'pytest==9.1.1\n' > requirements-dev.txt
python3 -m venv .venv && . .venv/bin/activate
python -m pip install -r requirements-dev.txt
python -m pytest -q --junitxml=reports/junit-local.xml... [100%]
3 passed in 0.02sThe JUnit report is what CI will keep, so check that it counted the same tests:
grep -oE '(failures|tests)="[0-9]+"' reports/junit-local.xmlfailures="0"
tests="3"03. Step 2: Write the Workflow
Save the workflow below as .github/workflows/ci.yml (create the folders first with mkdir -p .github/workflows). Read it before you commit it:
- Triggers.
pull_requestchecks proposed changes,pushonmainchecks what actually landed, andmerge_groupmakes the same checks report inside a GitHub merge queue. Withoutmerge_group, a queue whose required checks come from this workflow waits until its status-check timeout and then drops the pull request. - No path filters. When a workflow is skipped by a path or branch filter, its checks stay Pending, and a pull request that requires them cannot merge. Only filter workflows whose checks are not required.
- Concurrency. A new commit on the same pull request cancels the older, now pointless run. On
maina started run is never cancelled, but a group keeps only one waiting run, so a newer push replaces an older run that has not started. - Permissions.
contents: readmakes the job token read-only, andpersist-credentials: falsestops checkout from keeping it on the runner for later steps (in.git/configup to v5, in a file under$RUNNER_TEMPfrom v6). - Dependent jobs and the matrix.
testwaits forlintthroughneeds. Each matrix leg runs on its own fresh virtual machine, so legs cannot share files; anything you want to keep must be uploaded as an artifact.fail-fast: falselets every leg finish, so one failure does not hide another. - Expressions use single quotes. Inside
${{ }}, string literals must be single-quoted:hashFiles('requirements-dev.txt')works, while a double-quoted string is a syntax error and the workflow is rejected.
Every action is pinned to a full 40-character commit SHA, with the release tag in a comment for humans and for Dependabot. A tag such as v6 can be moved to different code by whoever controls the repository; a commit SHA cannot. The pin only protects you if the SHA really is the commit behind the tag, so never copy a SHA you have not checked yourself (Step 3).
name: ci
on:
pull_request:
branches: [main]
push:
branches: [main]
merge_group:
concurrency:
group: ci-${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
permissions:
contents: read
jobs:
lint:
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0
with:
python-version: "3.14"
- name: Byte-compile every module (catches syntax errors fast)
run: python -m compileall -q .
test:
needs: lint
name: test (py${{ matrix.python-version }})
runs-on: ubuntu-24.04
strategy:
fail-fast: false
matrix:
python-version: ["3.13", "3.14"]
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0
with:
python-version: ${{ matrix.python-version }}
- name: Restore the pip download cache
uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
with:
path: ~/.cache/pip
key: >-
pip-${{ runner.os }}-py${{ matrix.python-version }}-${{
hashFiles('requirements-dev.txt') }}
restore-keys: |
pip-${{ runner.os }}-py${{ matrix.python-version }}-
- name: Install dependencies
run: python -m pip install -r requirements-dev.txt
- name: Run the tests
run: |
python -m pytest \
--junitxml=reports/junit-py${{ matrix.python-version }}.xml
- name: Upload the test report
if: always()
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
name: junit-py${{ matrix.python-version }}
path: reports/The key: >- block is a YAML folded scalar: the two lines are joined with a space, giving pip-${{ runner.os }}-py${{ matrix.python-version }}-${{ hashFiles('requirements-dev.txt') }}. Artifact names must be unique within a run, hence the version in name. If you prefer less YAML, actions/setup-python can manage the pip cache itself with cache: pip; the separate actions/cache step is used here so you can see the key.
Before you commit, keep the virtual environment and the local reports out of Git, and check the workflow with actionlint, a static checker for GitHub Actions workflows. It reports YAML mistakes, unknown keys and broken ${{ }} expressions, and it also checks the run: scripts when ShellCheck is installed. Download actionlint 1.7.12 for your system from its releases page (https://github.com/rhysd/actionlint/releases) and put the binary on your PATH. A clean workflow produces no actionlint output, so the echo below runs only when the check passes.
printf '.venv/\nreports/\n' > .gitignore
cat .gitignore
actionlint .github/workflows/ci.yml && echo "actionlint: no problems found".venv/
reports/
actionlint: no problems found04. Step 3: Verify Every Pinned SHA Yourself
Before committing, check that each SHA in the workflow is the commit that the official repository publishes for the tag in the comment. git ls-remote asks the remote repository directly, without cloning it. Compare each line with the workflow. If a tag is annotated, the list also shows a line ending in ^{}; the SHA on that line is the commit to pin. Later, let Dependabot (package-ecosystem: github-actions) propose SHA updates.
git ls-remote --tags https://github.com/actions/checkout 'refs/tags/v7.0.1*'
git ls-remote --tags https://github.com/actions/setup-python 'refs/tags/v7.1.0*'
git ls-remote --tags https://github.com/actions/cache 'refs/tags/v6.1.0*'
git ls-remote --tags https://github.com/actions/upload-artifact 'refs/tags/v7.0.2*'3d3c42e5aac5ba805825da76410c181273ba90b1 refs/tags/v7.0.1
6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 refs/tags/v7.1.0
55cc8345863c7cc4c66a329aec7e433d2d1c52a9 refs/tags/v6.1.0
cf430e030ddbb5b0abf93d22962f4752f3646cd9 refs/tags/v7.0.205. Step 4: Open a Pull Request and Read the Run
Push the project to main; the push run fills the cache. Then create a branch, change something small (add a test, for example), push it and open a pull request. In the Checks tab you should see lint, then test (py3.13) and test (py3.14) running in parallel once lint has passed. Open a test job and expand the cache step.
On the very first run the cache step reports a miss, pip downloads pytest and its dependencies, and the post step saves a new entry. Runs on a pull request can restore entries saved by runs on main, so your pull request should report a hit. The test step prints the Python version of that leg, and each leg uploads its own report as junit-py3.13 or junit-py3.14 on the run summary page. On this tiny project the cache saves little; measure the gain on your own projects.
Break a test on purpose and push again. The failing leg turns red, but its upload step still runs because of if: always(), so you can download the JUnit report and read the failed assertion without rerunning anything on your laptop.
Run actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9
Cache restored from key: pip-Linux-py3.13-<sha256 of requirements-dev.txt>
Run python -m pip install -r requirements-dev.txt
Collecting pytest==9.1.1 (from -r requirements-dev.txt (line 1))
Using cached pytest-9.1.1-py3-none-any.whl.metadata
Run python -m pytest --junitxml=reports/junit-py3.13.xml
platform linux -- Python 3.13.x, pytest-9.1.1, pluggy-1.x
collected 3 items
tests/test_pricing.py ... [100%]
============================== 3 passed in 0.0Xs ===============================
Run actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9
Artifact junit-py3.13 has been successfully uploaded!Finally, protect main with a branch ruleset that requires a pull request and the checks lint, test (py3.13) and test (py3.14). Checks are required by name, so keep job names stable.
On a busy repository a second problem appears. Two pull requests can each pass against yesterday's main and still break it when merged one after the other. A merge queue (GitHub merge queue, GitLab merge trains) solves this by testing each pull request against the state of main it will actually land on, including the changes queued ahead of it, and merging only if those checks pass. That removes the "stale green check" problem, but it is only as strong as your tests: anything they do not cover can still break. On GitHub, required checks report inside the queue only if the workflow listens to merge_group, which is why it is in the trigger list.
06. Check your understanding
07. Apply it
In your own repository:
- Use your real entry point: replace
python -m pytestwith the command that builds and tests your project, and cache the directory your package manager actually uses (~/.cache/pip,~/.npm,~/.cache/pypoetry) keyed on its lockfile. - Run on pull requests, on main and in the merge queue: keep
merge_groupif you use a queue, and avoid path filters on workflows that provide required checks. - Keep the fallback:
restore-keyswith the key prefix gives a partial hit after a lockfile change. - Upload diagnostics with
if: always(): test reports, coverage and logs should survive a red build. - Pin and verify: pin every third-party action to a SHA you resolved yourself, add the tag as a comment, and let Dependabot propose updates.
- Protect main: require the lint job and every matrix leg as status checks, with read-only token permissions by default.
08. Review prompt
Without looking back, explain how a matrix strategy runs one job across several runtime versions and why its legs cannot share files. Trace a cache key from its parts to a hit, a prefix fallback and a miss. Say why the workflow listens to merge_group, why path filters can block a pull request, how you check that a pinned SHA matches its tag, and why the report upload uses if: always().
References
- GitHub Actions documentation
- GitHub Docs: Dependency caching reference (keys, restore keys, eviction)
- GitHub Docs: Workflow syntax (triggers, path filters, matrix, needs)
- GitHub Docs: Expressions (literals must use single quotes)
- GitHub Docs: Managing a merge queue (merge_group trigger)
- GitHub Docs: Secure use reference (pinning actions to a full-length commit SHA)
- actions/cache README
- GitLab CI/CD documentation
- Martin Fowler: Continuous Integration
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.