Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 24 additions & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -25,4 +25,27 @@ jobs:
run: make lint

- name: Run tests
run: make test
run: make test-fast

build:
runs-on: ${{ matrix.runner }}

# Each architecture builds on its own runner, so nothing runs under QEMU.
strategy:
fail-fast: false
matrix:
include:
- arch: amd64
runner: ubuntu-24.04
- arch: arm64
runner: ubuntu-24.04-arm

steps:
- uses: actions/checkout@v7

- uses: astral-sh/setup-uv@v7
with:
enable-cache: true

- name: Run build tests
run: make test-${{ matrix.arch }}
40 changes: 24 additions & 16 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ all are required:
variables.
3. **Per-file tests**: content and rendered variables of a file, only for files
with something to check beyond existing.
4. **Build tests**: every valid parameter combination generates a project that
4. **Build tests**: every option of every choice generates a project that
passes `make build`.

A full-project test can pass while a single file is wrong (wrong content, stale
Expand All @@ -21,13 +21,13 @@ replaces the other.
```
tests/
conftest.py # generate and render fixtures
helpers.py # choices(), debian_packagings(), matrix(), case_id()
helpers.py # choices(), debian_packagings(), matrix(), variants(), case_id()
files/
test_rendered.py # expected files exist, no unrendered syntax
test_<file>.py # per-file content tests (only where needed)
variables/
test_variables.py # derived cookiecutter.json variables
builds/ # build tests over the parameter matrix
builds/ # build tests over the parameter variants
test_build.py
hooks/ # hook tests (separate)
extensions/ # extension tests (separate)
Expand All @@ -37,8 +37,10 @@ tests/

- `pytest` + `pytest-cookies` (the `cookies` fixture) for generating
projects.
- Run `make test` (all tests) or `make test-fast` (everything except the slow
`build` tests).
- Run `make test` (all tests), `make test-fast` (everything except the slow
`build` tests), `make test-amd64` (build tests for amd64 and the Python
package) or `make test-arm64` (build tests for arm64). CI runs each build
target on a runner of its architecture.
- Test names: `test_when<Condition>_expect<Outcome>`, camelCase after the
prefix.
- `<Condition>` is the input state, written as `<Subject>Is<State>`
Expand All @@ -63,10 +65,11 @@ Already implemented; reuse them, do not reimplement them.
- **`gitconfig` fixture** (`tests/conftest.py`, autouse): isolates tests from
the machine's git config. Do not remove it.
- **`build` marker**: registered in `tests/conftest.py`.
- **`choices()` / `debian_packagings()` / `matrix()` / `case_id()`**
(`tests/helpers.py`): the choice variables, the `packaging` choices that build
a Debian package, every combination of the choices (all derived from
`cookiecutter.json`) and a readable pytest id for a combination.
- **`choices()` / `debian_packagings()` / `matrix()` / `variants()` /
`case_id()`** (`tests/helpers.py`): the choice variables, the `packaging`
choices that build a Debian package, every combination of the choices, the
fewest cases that use every option once (all derived from
`cookiecutter.json`) and a readable pytest id for a case.

## 1. File existence

Expand Down Expand Up @@ -133,13 +136,18 @@ Rules:

## 4. Build tests

For **any** valid combination of parameters, the generated project passes
`make build`, the command CI runs.

- **The cases are derived from `cookiecutter.json`** (`choices()`, `matrix()`),
never hardcoded. Adding a new option or choice must automatically add build cases.
Do not filter combinations out; if one is invalid, forbid it in the
`pre_gen_project` hook so it fails at generation instead.
For **every** option of every choice, the generated project passes `make
build`, the command CI runs.

- **The cases are derived from `cookiecutter.json`** (`choices()`,
`variants()`), never hardcoded. Adding a new option or choice must
automatically add build cases.
- **Use every option once, not every combination**: builds are slow and every
combination grows with the product of the options, while `variants()` grows
with the largest one. Content that depends on a combination of options is
checked in per-file tests over `matrix()` instead.
- If a combination is invalid, forbid it in the `pre_gen_project` hook so it
fails at generation instead.
- **Run the real command**: `make build` in the generated project, no mocks
and no patched Makefile.
- **Show the output on failure**: include stdout and stderr in the assertion
Expand Down
16 changes: 13 additions & 3 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ MAKEFLAGS += --no-builtin-rules

.PHONY: help
help: ## Display this help
@sed -rn 's/^([a-zA-Z_%-]+):.*?## (.*)$$/"\1" "\2"/p' \
@sed -rn 's/^([a-zA-Z0-9_%-]+):.*?## (.*)$$/"\1" "\2"/p' \
< $(firstword $(MAKEFILE_LIST)) | \
xargs printf "make %-27s# %s\n"

Expand Down Expand Up @@ -50,15 +50,25 @@ uninstall-pre-commit-hook: ## Uninstall pre-commit hook
uv run pre-commit uninstall

.PHONY: test
test: install-deps ## Run pytest with coverage
test: install-deps ## Run all tests
uv run pytest -s -v --cov --cov-report=term-missing \
--junit-xml=junit.xml --cov-report=xml:coverage.xml

.PHONY: test-fast
test-fast: install-deps ## Run pytest with coverage, skipping slow build tests
test-fast: install-deps ## Run all tests except the build tests
uv run pytest -s -v -m "not build" --cov --cov-report=term-missing \
--junit-xml=junit.xml --cov-report=xml:coverage.xml

.PHONY: test-amd64
test-amd64: install-deps ## Run the amd64 and Python build tests
uv run pytest -s -v -m build -k "not arm64" --cov --cov-report=term-missing \
--junit-xml=junit.xml --cov-report=xml:coverage.xml

.PHONY: test-arm64
test-arm64: install-deps ## Run the arm64 build tests
uv run pytest -s -v -m build -k arm64 --cov --cov-report=term-missing \
--junit-xml=junit.xml --cov-report=xml:coverage.xml

.PHONY: git-clean
git-clean: ## Clean the project using git clean
git clean -Xdf
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[project]
name = "template"
version = "0.1.0"
version = "0.2.0"
description = "Skip the setup. Start building."
license = "MIT"
license-files = ["LICENSE"]
Expand Down
34 changes: 22 additions & 12 deletions tests/builds/test_build.py
Original file line number Diff line number Diff line change
@@ -1,31 +1,36 @@
import functools
import os
import platform
import subprocess
from pathlib import Path

import docker
import pytest

from tests.helpers import Generate, Render, case_id, matrix
from tests.helpers import Generate, Render, case_id, variants

TIMEOUT_S = 1800
BUILDX_PATH = "/usr/local/libexec/docker/cli-plugins/docker-buildx"
HOST_ARCH = {"x86_64": "amd64", "aarch64": "arm64"}[platform.machine()]


@functools.cache
def docker_config(base: Path) -> Path:
"""Give the Docker CLI buildx and QEMU, to build for any architecture."""
client = docker.from_env(timeout=TIMEOUT_S)

# QEMU: register binfmt handlers so the host can run foreign-arch binaries.
client.containers.run(
def install_qemu() -> None:
"""Register binfmt handlers so the host can run foreign-arch binaries."""
docker.from_env(timeout=TIMEOUT_S).containers.run(
"tonistiigi/binfmt",
"--install arm64,amd64",
privileged=True,
remove=True,
)

# buildx: copy the plugin out of the official docker:cli image.

@functools.cache
def docker_config(base: Path) -> Path:
"""Give the Docker CLI buildx, to build for any architecture."""
client = docker.from_env(timeout=TIMEOUT_S)

# Copy the plugin out of the official docker:cli image.
config = base / "docker"
plugins = config / "cli-plugins"
plugins.mkdir(parents=True)
Expand All @@ -42,9 +47,13 @@ def docker_config(base: Path) -> Path:


def debian_variables(
context: dict[str, str], tmp_path_factory: pytest.TempPathFactory
context: dict[str, str], arch: str, tmp_path_factory: pytest.TempPathFactory
) -> list[str]:
"""Make variables that isolate a Debian build from the host."""
# Emulate only builds for another architecture.
if arch != HOST_ARCH:
install_qemu()

base = tmp_path_factory.getbasetemp()
return [
# Stay out of the home and image of any real project with the same name.
Expand All @@ -55,7 +64,7 @@ def debian_variables(


@pytest.mark.build
@pytest.mark.parametrize("context", matrix(), ids=case_id)
@pytest.mark.parametrize("context", variants(), ids=case_id)
def test_whenAnyParametersAreChosen_expectBuildPasses(
generate: Generate,
render: Render,
Expand All @@ -67,8 +76,9 @@ def test_whenAnyParametersAreChosen_expectBuildPasses(
subprocess.run(["git", "add", "."], cwd=project, check=True, capture_output=True)

variables = []
if render(**context)["__packaging"] == "debian":
variables = debian_variables(context, tmp_path_factory)
rendered = render(**context)
if rendered["__packaging"] == "debian":
variables = debian_variables(context, rendered["__arch"], tmp_path_factory)

result = subprocess.run(
["make", "build", *variables],
Expand Down
12 changes: 11 additions & 1 deletion tests/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,16 @@ def matrix() -> list[dict[str, str]]:
]


def variants() -> list[dict[str, str]]:
"""Every option of every choice variable at least once, as few cases as possible."""
options = choices()
count = max(len(values) for values in options.values())
return [
{name: values[i % len(values)] for name, values in options.items()}
for i in range(count)
]


def case_id(context: dict[str, str]) -> str:
"""Readable pytest id for one `matrix()` combination."""
"""Readable pytest id for one `matrix()` or `variants()` case."""
return "-".join(context.values())
2 changes: 1 addition & 1 deletion uv.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion {{cookiecutter.artifact}}/Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ DOCKER_RUN = docker run --rm --interactive \

.PHONY: help
help: ## Display this help
@sed -rn 's/^([a-zA-Z_%-]+):.*?## (.*)$$/"\1" "\2"/p' \
@sed -rn 's/^([a-zA-Z0-9_%-]+):.*?## (.*)$$/"\1" "\2"/p' \
< $(firstword $(MAKEFILE_LIST)) | \
xargs printf "make %-27s# %s\n"

Expand Down
Loading