Skip to main content

CI/CD and automation · Intermediate · 17 min

Run Python tests and linters in GitHub Actions with uv

By Padding · Updated 18 Nov 2026
Debian (python:3.15) · Python 3.15 and 3.14 · uv 0.13.10 · GitHub Actions (astral-sh/setup-uv v10.4.0) · actionlint 1.7.12

You will have a GitHub Actions workflow that installs a Python project with uv from its lock file, fails on a stale uv.lock, runs Ruff and pytest with a coverage floor on two Python versions, caches uv's downloads and keeps the coverage report as an artifact.

On this page

A Python project in CI fails in ways your laptop hides. Someone edits pyproject.toml and forgets the lock file, so the pipeline installs different versions from the ones you tested. A formatting change slips through because nobody ran the formatter. A new module lands without a single test, and the suite stays green because nothing measures what it skipped.

In this tutorial you build a small library, bundle-calc, which compares prepaid mobile data bundles by their price per gigabyte. You set up four checks that each fail for a clear reason: uv sync --locked for the lock file, ruff check for lint, ruff format --check for formatting, and pytest with a coverage floor. You run each check on your own machine first, and break each one on purpose so you know what its failure looks like. Then you put the same commands in a GitHub Actions workflow with a lint job and a test job over Python 3.14 and 3.15.

This is the Python counterpart to /tutorials/run-node-tests-in-github-actions. You need uv 0.13 (uv --version prints it), and uv fetches any Python version it cannot find.

Step 1 · Create the project

Make a demo folder and ask uv for a library project. --lib puts the code under src/bundle_calc/ and adds a build backend, so your tests import the installed package rather than whatever sits in the current folder:

Bash
mkdir -p ~/bundle-demo
cd ~/bundle-demo
uv init --lib --python 3.15 bundle-calc
cd bundle-calc

Replace the generated pyproject.toml with one that holds the whole setup. The dev group lists the tools CI needs and users of the library never install. requires-python is >=3.14 because the workflow will test 3.14 as well as 3.15:

Bash
cat > pyproject.toml <<'TOML'
[project]
name = "bundle-calc"
version = "0.1.0"
description = "Compare prepaid data bundles by price per gigabyte"
readme = "README.md"
requires-python = ">=3.14"
dependencies = []

[dependency-groups]
dev = [
    "pytest>=9.2,<9.3",
    "pytest-cov>=7.1,<7.2",
    "ruff>=0.17.6,<0.18",
]

[build-system]
requires = ["uv_build>=0.13.10,<0.14"]
build-backend = "uv_build"

[tool.ruff]
line-length = 100

[tool.ruff.lint]
select = ["E", "F", "W", "I", "B", "UP"]

[tool.ruff.lint.isort]
known-first-party = ["bundle_calc"]

[tool.pytest.ini_options]
testpaths = ["tests"]
addopts = "--cov=bundle_calc --cov-branch --cov-report=term-missing --cov-fail-under=95"
TOML

The settings do three jobs. Ruff checks pycodestyle errors and warnings (E, W), Pyflakes (F), import order (I), common bugs (B) and outdated syntax for your minimum Python (UP). known-first-party tells the import sorter that bundle_calc is your own code. The addopts line makes every pytest run measure line and branch coverage of bundle_calc, list the lines no test reached, and fail if the total drops below 95%. Because the settings live in the project, the same command behaves the same on your laptop and on GitHub.

Now the library. Prices are whole numbers in the currency's smallest unit (kobo, cents, pesewas) so no rounding sneaks in before the comparison:

Bash
cat > src/bundle_calc/__init__.py <<'PY'
"""Compare prepaid mobile data bundles by price per gigabyte."""

from dataclasses import dataclass

__all__ = ["Bundle", "cheapest", "cost_per_gb"]


@dataclass(frozen=True)
class Bundle:
    name: str
    price: int  # in the smallest unit of the currency, such as kobo or cents
    megabytes: int


def cost_per_gb(bundle: Bundle) -> float:
    """Return what one gigabyte (1,024 MB) costs in this bundle."""
    if bundle.megabytes <= 0:
        raise ValueError(f"{bundle.name}: megabytes must be more than zero")
    return bundle.price * 1024 / bundle.megabytes


def cheapest(bundles: list[Bundle]) -> Bundle:
    """Return the bundle with the lowest price per gigabyte."""
    if not bundles:
        raise ValueError("no bundles to compare")
    return min(bundles, key=cost_per_gb)
PY

And its tests. A daily, a weekly and a monthly bundle cover the normal cases, and two more tests cover the errors:

Bash
mkdir -p tests
cat > tests/test_bundles.py <<'PY'
import pytest

from bundle_calc import Bundle, cheapest, cost_per_gb

DAILY = Bundle("daily 500 MB", price=10_000, megabytes=500)
WEEKLY = Bundle("weekly 2 GB", price=50_000, megabytes=2_048)
MONTHLY = Bundle("monthly 10 GB", price=150_000, megabytes=10_240)


def test_cost_per_gb_for_whole_gigabytes():
    assert cost_per_gb(WEEKLY) == 25_000


def test_cost_per_gb_for_part_of_a_gigabyte():
    assert cost_per_gb(DAILY) == pytest.approx(20_480)


def test_cost_per_gb_rejects_an_empty_bundle():
    with pytest.raises(ValueError, match="more than zero"):
        cost_per_gb(Bundle("broken", price=100, megabytes=0))


def test_cheapest_picks_the_lowest_price_per_gb():
    assert cheapest([DAILY, WEEKLY, MONTHLY]) == MONTHLY


def test_cheapest_needs_at_least_one_bundle():
    with pytest.raises(ValueError, match="no bundles"):
        cheapest([])
PY

Keep coverage output out of Git. This appends to the .gitignore that uv init wrote, which already lists .venv and __pycache__/:

Bash
cat >> .gitignore <<'TXT'

# Coverage output
.coverage
coverage.xml
htmlcov/
TXT

Finally, resolve the dependencies and write uv.lock. It records the exact version and hash of every package, for every platform, and you commit it with the code:

Bash
uv lock

Check it worked

uv lock ends with something like Resolved 10 packages. ls shows pyproject.toml, uv.lock, src and tests, and grep -c '^name = ' uv.lock counts the packages in the lock file.

Step 2 · Install from the lock file and run the tests

uv sync --locked creates .venv and installs exactly what uv.lock lists, including the dev group. --locked adds one rule: if the lock file no longer matches pyproject.toml, stop with an error instead of quietly updating it. That rule is what you want in CI.

Bash
uv sync --locked
uv run pytest

uv run runs the command inside the project's environment, so you never activate .venv by hand.

uv keeps every package it downloads in a cache (uv cache dir prints where), and the next uv sync, in this project or another one, installs from there. On a prepaid data plan that matters: after the first download, recreating the environment costs nothing.

Check it worked

pytest reports 5 passed. Above that, the coverage table shows src/bundle_calc/__init__.py with nothing in the Miss or BrPart columns and 100% in Cover, followed by Required test coverage of 95% reached. Total coverage: 100.00%.

Step 3 · Lint and format with Ruff

Add a second module the way it might arrive in a rushed pull request: an import nobody uses, imports in the wrong groups, one blank line where Ruff's formatter wants two, and no spaces around an operator:

Bash
cat > src/bundle_calc/report.py <<'PY'
import os
from bundle_calc import Bundle, cost_per_gb

def label(bundle: Bundle) -> str:
    return f"{bundle.name}: {cost_per_gb(bundle)/100:,.2f} per GB"
PY

Run the two checks the workflow will run. Each exits with code 1 here, so the commands print a note instead of stopping your shell:

Bash
uv run ruff check || echo "ruff check failed, as expected"
uv run ruff format --check || echo "ruff format --check failed, as expected"

ruff check reports F401 (os imported but unused) and I001 (the import block is not sorted: your own package belongs in a group of its own, below the standard library). ruff format --check changes nothing. It lists src/bundle_calc/report.py as a file that would be reformatted and shows the difference.

Both problems have automatic fixes. Let Ruff apply them, then look at the result:

Bash
uv run ruff check --fix
uv run ruff format
cat src/bundle_calc/report.py

On your own projects, run these two fixing commands before you commit, or have an editor or a pre-commit hook run them. CI only ever runs the non-fixing versions: a pipeline that rewrites code would pass while the repository stays wrong.

Check it worked

report.py now starts with from bundle_calc import Bundle, cost_per_gb, has two blank lines before def label, and reads cost_per_gb(bundle) / 100. Both checks pass: ruff check prints All checks passed! and ruff format --check prints that all files are already formatted.

Bash
uv run ruff check
uv run ruff format --check

Step 4 · Let the coverage floor catch untested code

report.py is lint-clean, but nothing tests it. The tests still pass. Run them and look at the end of the output:

Bash
uv run pytest || echo "pytest failed, as expected"

All five tests pass, yet the run fails. The table shows report.py at 0% with lines 1-5 missing, the total drops to about 84%, and pytest-cov prints FAIL Required test coverage of 95% not reached. with the real figure. The exit code is non-zero, which is all GitHub Actions needs to mark the job red.

Write the missing test:

Bash
cat > tests/test_report.py <<'PY'
from bundle_calc import Bundle
from bundle_calc.report import label


def test_label_shows_the_price_per_gb_in_main_units():
    weekly = Bundle("weekly 2 GB", price=50_000, megabytes=2_048)
    assert label(weekly) == "weekly 2 GB: 250.00 per GB"
PY
uv run pytest

Choose the floor for your own project from where its coverage is today, not from a round number. A floor slightly below the current figure stops it sliding; raise it as you add tests. Coverage shows which lines ran, not whether the assertions were any good, so it supports code review rather than replacing it.

Check it worked

pytest reports 6 passed, both files at 100%, and Required test coverage of 95% reached.

Step 5 · See a stale lock file fail

The most common CI surprise in a uv project is a pyproject.toml change without a matching uv.lock. Simulate it: uv add --frozen writes a new dependency into pyproject.toml and leaves the lock file alone, which is what happens when someone edits the file by hand:

Bash
uv add --frozen "httpx>=0.28"
uv sync --locked || echo "uv sync --locked failed, as expected"

uv resolves the new requirements, sees that they differ from the lock file and stops with something like error: The lockfile at uv.lock needs to be updated, but --locked was provided. Without --locked, uv sync would have updated the lock file on the runner and carried on, and CI would have tested versions nobody committed.

The real fix is to run uv lock and commit both files. Here, undo the change, because the library does not need httpx:

Bash
uv remove --frozen httpx
uv sync --locked

Check it worked

grep -n '^dependencies' pyproject.toml prints dependencies = [] again, and uv sync --locked finishes without an error.

Step 6 · Run the suite on two Python versions

The workflow will test Python 3.14 and 3.15. Run both on your machine first. UV_PYTHON tells every uv command which interpreter to use, overriding .python-version, and uv python install fetches a version you do not have:

Bash
for version in 3.14 3.15; do
  uv python install "$version"
  UV_PYTHON="$version" uv sync --locked
  UV_PYTHON="$version" uv run python --version
  UV_PYTHON="$version" uv run pytest -q
done
uv sync --locked

uv rebuilds .venv each time the interpreter changes, so each run is a clean install from uv.lock on that version. The last uv sync --locked puts the environment back on 3.15, the version in .python-version. One lock file covers both versions, because uv resolves for every Python your requires-python allows.

Check it worked

The loop prints Python 3.14. and then Python 3.15. followed by a patch number, and each pytest -q run ends with 6 passed.

Step 7 · Write the workflow

Create .github/workflows/python-checks.yml. It has two jobs: lint runs Ruff once, and test runs pytest on each Python version in the matrix. Splitting them means a formatting slip and a failing test show up as separate red marks, and the lint job does not repeat itself per Python version:

Bash
mkdir -p .github/workflows
cat > .github/workflows/python-checks.yml <<'YAML'
name: Python checks

on:
  push:
    branches: [main]
  pull_request:

permissions:
  contents: read

concurrency:
  group: python-checks-${{ github.ref }}
  cancel-in-progress: true

jobs:
  lint:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v7
        with:
          persist-credentials: false

      - uses: astral-sh/setup-uv@v10.4.0
        with:
          version: "0.13.10"
          enable-cache: true
          cache-dependency-glob: uv.lock

      - run: uv sync --locked
      - run: uv run ruff check --output-format=github
      - run: uv run ruff format --check

  test:
    runs-on: ubuntu-latest
    strategy:
      fail-fast: false
      matrix:
        python-version: ["3.14", "3.15"]
    steps:
      - uses: actions/checkout@v7
        with:
          persist-credentials: false

      - uses: astral-sh/setup-uv@v10.4.0
        with:
          version: "0.13.10"
          python-version: ${{ matrix.python-version }}
          enable-cache: true
          cache-dependency-glob: uv.lock
          cache-suffix: py${{ matrix.python-version }}

      - run: uv python install ${{ matrix.python-version }}
      - run: uv sync --locked
      - run: uv run pytest --cov-report=xml --cov-report=html

      - uses: actions/upload-artifact@v7
        if: ${{ !cancelled() }}
        with:
          name: coverage-py${{ matrix.python-version }}
          path: |
            coverage.xml
            htmlcov/
          retention-days: 14
          if-no-files-found: error
YAML

What each part does:

  • astral-sh/setup-uv@v10.4.0 installs uv. Its v10 releases are published with full version tags only (there is no @v10 to point at), so pin the exact release and let Dependabot or Renovate propose upgrades. version: "0.13.10" pins uv itself to the version you used locally, so a new uv release cannot change CI behaviour overnight.
  • enable-cache: true saves uv's cache folder at the end of a job and restores it at the start of the next. cache-dependency-glob: uv.lock builds the cache key from the lock file's hash, so the cache is replaced only when your dependencies change. cache-suffix keeps the two Python versions in separate entries, because packages with compiled parts differ per version.
  • python-version makes setup-uv export UV_PYTHON, exactly as you did in the loop, and uv python install puts that version on the runner. Every later uv command in the job uses it.
  • uv sync --locked fails the job on a stale uv.lock, before any test runs.
  • --output-format=github makes Ruff print each problem as a GitHub annotation, so it appears on the offending line in the pull request's Files changed view.
  • The extra --cov-report options add coverage.xml and an htmlcov/ folder to the terminal table from addopts. The 95% floor still applies.
  • if: ${{ !cancelled() }} uploads the report even when the tests failed, which is when you most want to read it. Each matrix leg uploads under its own name; two uploads with the same name in one run would conflict. if-no-files-found: error fails loudly if the report was never written. retention-days: 14 deletes it after two weeks instead of keeping it for the repository's default period.
  • persist-credentials: false stops checkout from leaving the job's token in .git/config, where any later step could read it. Nothing here pushes, so nothing needs it. permissions: contents: read keeps the token read-only for the same reason.
  • concurrency cancels the previous run on the same branch when you push again.

The runners download Python and packages over GitHub's network, not yours, so the cache saves job minutes rather than your data.

Check it worked

Run the three lint-job commands and the test-job commands from the file, in the order the workflow runs them:

Bash
uv sync --locked
uv run ruff check --output-format=github
uv run ruff format --check
uv run pytest --cov-report=xml --cov-report=html
ls coverage.xml htmlcov/index.html

ruff check prints no ::error annotation lines because there is nothing to report, pytest ends with Coverage HTML written to dir htmlcov and Coverage XML written to file coverage.xml above the coverage line, and ls lists both files. Open htmlcov/index.html in a browser to see the report the artifact will hold.

Step 8 · Check the workflow file and push it

actionlint, from github.com/rhysd/actionlint, checks workflow files for syntax errors, unknown keys, bad expressions and type mistakes before GitHub sees them. Download release 1.7.12 for your system as shown in /tutorials/github-actions-first-workflow, then run it in the repository:

Bash
actionlint
echo "actionlint exit code: $?"

No output and exit code 0 mean it found nothing wrong.

Commit everything, uv.lock included. uv init already created the Git repository:

Bash
git add .
git commit -m "Add bundle-calc with lint, coverage and CI workflow"
git ls-files | grep -E "^(uv.lock|.github/workflows/python-checks.yml)$"

Then push to a GitHub repository you own. Replace YOUR-USER/YOUR-REPO with yours:

Bash
git remote add origin git@github.com:YOUR-USER/YOUR-REPO.git
git push -u origin main

Follow the run from the terminal with the GitHub CLI, then download one leg's coverage report. RUN-ID is the number gh run list prints:

Bash
gh run list --workflow python-checks.yml
gh run watch
gh run download RUN-ID -n coverage-py3.15

To make the checks binding, add a branch rule for main in the repository settings that requires lint, test (3.14) and test (3.15) to pass before merging. The check names appear in the rule's search box only after they have run once.

Check it worked

The Actions tab shows a run of Python checks with three jobs: lint, test (3.14) and test (3.15), all green. The summary page of the run lists two artifacts, coverage-py3.14 and coverage-py3.15. On the second push, the setup-uv step in each job reports that it restored the cache from the key it saved the first time. If you then push a commit that edits pyproject.toml without uv lock, the uv sync --locked step fails in every job with the lock file error from earlier.

Next steps

  • Write better tests to sit behind the coverage floor: /tutorials/test-python-code-with-pytest.
  • Choose and tune Ruff's rules for a larger codebase: /tutorials/lint-and-format-python-with-ruff.
  • Turn the library into a wheel and an sdist with the same pyproject.toml: /tutorials/package-a-python-project-with-uv-and-pyproject-toml.
  • Compare with the Node.js version of this pipeline: /tutorials/run-node-tests-in-github-actions.

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.