Testing the CLI
Table of contents
- Introduction
- Running the tests
- Testing pure logic
- Testing a command that writes files
- Testing a command that runs processes
- Testing a whole flow
- Using the shared fixtures
- In CI
- Finding what the tests do not check
- Checking contract inference on the published features
- Asserting on a result
- Adding a command
Introduction
CLI commands read environment variables, touch the filesystem and call docker and git. You test them with Click’s CliRunner, pytest’s tmp_path and unittest.mock.patch. Every command reads its context through the service layer, so pointing WORKING_DIR at a temporary folder redirects a whole command there, with no Docker.
cd /workspace/splent_cli
pytest tests/ -v
Running the tests
pytest tests/unit/commands/product/test_product_status.py -v
pytest tests/unit/commands/env/test_env_list.py::TestFilter::test_filter_by_prefix -v
pytest tests/ --cov=splent_cli --cov-report=term-missing
Tests live under tests/unit/ (services/, utils/, commands/<group>/), tests/integration/ and tests/scenarios/, with the shared fixtures in tests/conftest.py.
Testing pure logic
from splent_cli.services.compose import project_name
def test_project_name_replaces_special_chars():
assert project_name("splent_io/notes@v1.0", "prod") == "splent_io_notes_v1_0_prod"
Testing a command that writes files
from click.testing import CliRunner
from splent_cli.commands.cache.cache_status import cache_status
def test_cache_shows_versioned_feature(tmp_path, monkeypatch):
monkeypatch.setenv("WORKING_DIR", str(tmp_path))
cache = tmp_path / ".splent_cache" / "features" / "splent_io" / "splent_feature_notes@v1.0.0"
cache.mkdir(parents=True)
result = CliRunner().invoke(cache_status, [])
assert result.exit_code == 0
assert "v1.0.0" in result.output
Testing a command that runs processes
Mock subprocess.run with a MagicMock of the right shape.
import json
from unittest.mock import patch, MagicMock
from click.testing import CliRunner
from splent_cli.commands.product.product_containers import product_docker
def test_shows_running_containers(product_workspace):
out = json.dumps({"Service": "web", "State": "running", "Publishers": []})
with patch("subprocess.run", return_value=MagicMock(returncode=0, stdout=out, stderr="")):
result = CliRunner().invoke(product_docker, ["--dev"])
assert result.exit_code == 0
assert "running" in result.output
Testing a whole flow
A unit test calls one command, so it misses what breaks between two of them, such as a file one writes and the next misreads, or a prompt nobody answers. tests/scenarios/ runs the commands a developer runs, each in its own splent process, in a temporary workspace.
def test_feature_pull_fast_forwards_a_clean_copy(sandbox, published, other):
sandbox.splent(other, "feature:install", FEATURE, "--editable")
head = _upstream_commit(sandbox, published, "upstream change")
sandbox.splent(other, "feature:pull")
assert sandbox.git(other / "splent_feature_notes", "rev-parse", "HEAD") == head
| Fixture | Gives |
|---|---|
sandbox |
A home, a git identity and a forge of its own. sandbox.workspace(name) makes a workspace, sandbox.splent(ws, *args, input=...) runs a command in it and fails the test unless it exits 0 (ok=False returns the result instead), sandbox.publish(repo, namespace, tag=...) pushes a repository to the forge |
shop |
A workspace with the line shop_line, the feature splent_feature_notes in it and the product shop using it, selected |
Nothing reaches the network. The forge is a folder of bare repositories that git reaches under the real https://git.splent.io/ and ssh:// URLs, and every HTTP request goes to a proxy that refuses it. A command that would download something fails in the scenario, so a flow that passes here passes offline.
Using the shared fixtures
| Fixture | Gives |
|---|---|
runner |
A CliRunner(mix_stderr=False), so stderr is in result.stderr |
workspace |
A tmp_path set as WORKING_DIR, with SPLENT_APP and SPLENT_ENV cleared |
product_workspace |
A workspace with a test_app product selected in dev, its pyproject.toml and compose files |
tests/conftest.py also has helpers such as make_env_file, make_cache_entry, make_spl_working_copy, make_spl_cache_entry and write_product_spl_pin.
make_cache_entry(workspace, "splent_io", "splent_feature_notes", "v1.0.0")
What every test gets
Autouse fixtures keep the developer’s machine out of every test.
| Fixture | Does |
|---|---|
no_real_workspace |
Points WORKING_DIR at an empty folder, so a test that builds no workspace never reads yours |
cli_forgets_what_it_found |
Clears the commands and help the shared cli object found, as a fresh process would |
forge_env_is_clean |
Removes every SPLENT_FORGE_* variable, then sets SPLENT_FORGE_HOST=github.com, whose URL shapes the suite asserts |
splent_env_is_not_inherited |
Removes SPLENT_ENV |
pypi_is_not_asked |
Answers “could not ask” for every PyPI check |
no_builtin_spl_pins |
Empties the CLI’s built-in SPL pins |
contract_maps_are_not_shared |
Clears the memoised contract maps |
host_tools_are_stubbed |
Puts stubs of docker, mysqldump and mysql first on PATH, so a command’s check for them passes on any machine and a test that forgets to mock subprocess.run fails instead of reaching your Docker |
GITHUB_TOKENandGITHUB_USERare not removed. Unset them in your shell before you run the suite.
In CI
Every push to main runs .forgejo/workflows/ci.yml on the forge. It runs ruff check and ruff format --check with ruff 0.11.8, then the whole suite twice, as root like the CLI’s container and as a plain user like a developer’s host. Bugs about owners and permissions show in only one of them.
The runner is Linux without Docker. A test that passes on your Mac and fails there usually depends on a tool your machine has or on BSD behaviour, such as sed -i. Reproduce it in a container.
docker run --rm -v "$PWD:/src/splent_cli" -v "$PWD/../splent_framework:/src/splent_framework" python:3.13 bash -c '
cp -r /src /w && cd /w/splent_cli && pip install -q uv &&
uv pip install --system -q -e ../splent_framework -e ".[dev,uvl]" &&
python -m pytest tests -q -n auto'
Finding what the tests do not check
Coverage says a line ran, not that a test would notice it going wrong. mutmut changes the code one small edit at a time, such as < for <= or a string for another, and runs the tests that reach it. A change no test notices is a survivor, and it points at a test to write.
The modules it changes are listed under [tool.mutmut] in pyproject.toml. Pick code where a silent bug costs most, such as the TOML editor or the upgrade planner, and add a module there when it earns it.
docker run --rm -v "$PWD:/src/splent_cli" -v "$PWD/../splent_framework:/src/splent_framework" python:3.13 bash -c '
cp -r /src /w && cd /w/splent_cli && pip install -q uv &&
uv pip install --system -q -e ../splent_framework ".[dev,uvl]" mutmut==3.7.0 &&
mutmut run --max-children 4; mutmut results'
The CLI must not be installed editable, because mutmut runs the tests on a mutated copy that an editable install would hide. That is why the command uses a container, or use a virtualenv of its own.
mutmut results lists the survivors, and mutmut show <name> prints the change one of them made.
mutmut results | awk -F'__mutmut_' '{print $1}' | sort | uniq -c | sort -rn # survivors per function
mutmut show splent_cli.utils.toml_edit.x__key__mutmut_2
Read each survivor before writing a test for it. Some change nothing a caller can see, such as a bound on an empty range, and those stay. .forgejo/workflows/mutation.yml runs it every Sunday and prints the survivors per function, without failing.
Checking contract inference on the published features
Contract inference is checked against every feature of the marketplace index as well as by unit tests. tests/ecosystem/run.py clones each one at a fixed tag and compares what feature:contract --write gives it with tests/ecosystem/contracts.json.
python tests/ecosystem/run.py # compare
python tests/ecosystem/run.py --corpus ~/eco # keep the clones between runs
python tests/ecosystem/run.py --update # latest tags, rewrite contracts.json
A difference prints the features it changes, field by field, and exits 1. If you meant it, run --update and commit contracts.json in the same commit, where the review reads it. .forgejo/workflows/ecosystem.yml runs the check when the inference changes and every night.
Asserting on a result
result = runner.invoke(my_command, ["--flag"])
assert result.exit_code == 0, result.output
Assert exit_code first. result.output holds stdout, and result.exception the exception when a command crashed.
Test the error paths too, such as a missing SPLENT_APP, flags that exclude each other, or a missing file.
def test_requires_splent_app(runner, workspace):
result = runner.invoke(product_up, ["--dev"])
assert result.exit_code == 1
assert "SPLENT_APP" in result.output
When you assert that a name does not appear, pick names that are not substrings of each other.
"SET_VAR"is inside"UNSET_VAR".
Adding a command
- Create
tests/unit/commands/<group>/test_<command>.py, and import the command function directly. - Use
workspace,product_workspaceortmp_path, and mock any external tool. - Test flag validation, the happy path and at least one error path.
- Write its reference page under
splent_cli/in the docs repository, titled with the command itself (title: feature:foo). It then appears in the Command index. A page with a prose title names its commands in the front matter, as incommand: doctororcommand: [locust, "locust:stop"].
The docs test tests/test_command_index.py fails when a command has no page, or a page documents a command the CLI lacks.