A test is a small piece of code that runs your code with a known input and checks that it produces the expected output. Writing tests feels slow at first, but it pays off the moment you change something: instead of rerunning your whole program and eyeballing the output, you run the tests and know within a second whether anything broke. For challenge solutions, testing your parser against the puzzle's worked example before running it on the real input catches most mistakes early.
The pytest framework is the standard way to write tests in Python. Tests are plain functions with plain assert statements, and pytest takes care of finding them, running them, and explaining exactly what went wrong when one fails.
Pytest is a third-party package, so it goes into your project's environment as a development dependency (see Packages & Environments):
uv add --dev pytestTo check that it is installed properly:
uv run pytest --versionpytest 9.2.0Pytest looks for any file named test_*.py or *_test.py in the current directory and all subdirectories.
Inside these files, Pytest looks for functions whose names start with test and runs each one as an individual test. A test passes if it returns without raising an exception, so plain assert statements are all you need.
Let's write a simple testing file that tests a function called my_func:
1import pytest
2
3def my_func(num):
4 return num + 1
5
6Let's run pytest in the current directory and see if our function works!
uv run pytest============================= test session starts ==============================platform linux -- Python 3.12.14, pytest-9.2.0, pluggy-1.7.0rootdir: .configfile: pyproject.tomlcollected 1 itemtest_func.py F [100%]=================================== FAILURES ===================================__________________________________ test_func ___________________________________ def test_func():> assert my_func(3) == 5E assert 4 == 5E + where 4 = my_func(3)test_func.py:7: AssertionErrorLet's go over this in sections:
test_func.py FThis is a short list of tests that passed or failed. There are three values each one can be:
F: Test failed. Test failure will be enumerated below..: Test passed.E: An error happened outside the test itself, such as in a fixture that sets it up.A test that raises any exception other than AssertionError, such as a NameError from a typo, still shows as F; the traceback below tells you which kind of failure it was.
def test_func():
> assert my_func(3) == 5
E assert 4 == 5
E + where 4 = my_func(3)
test_func.py:7: AssertionErrorThis is a failed test. This shows the steps that Pytest took to verify the assertion. It shows that my_func(3) returned 4 and failed to assert 4 == 5. This raises an AssertionError, as seen on the last line.
Tests normally live in their own file and import the code they test. Here's a small module with one function, the port parser from Exceptions:
1def parse_port(text):
2 port = int(text)
3 if not 0 < port <A test file next to it imports parse_port and checks its behavior:
1from parse import parse_port
2
3
4def test_parses_a_port():
5 assert parse_port("443")Name each test after the behavior it checks. When one fails, the name in the report tells you what broke before you read any code. If the module you're testing has top-level code, such as a solve script that reads its input when run, put that code behind an if __name__ == "__main__": guard so importing it in a test doesn't run the whole solution.
Checking that code fails correctly matters as much as checking that it works. pytest.raises is a context manager that passes only if the block inside it raises the given exception, and fails the test if nothing is raised. Its match argument is a regular expression checked against the exception's message:
1import pytest
2
3from parse import parse_port
4
5
6def test_rejects_out_of_range()Testing the same function with many inputs by copying a test over and over gets tedious. The @pytest.mark.parametrize decorator runs one test function once for each set of arguments. It takes the parameter names as a comma-separated string and a list of values:
1import pytest
2
3from parse import parse_port
4
5
6@pytest.Each set of values becomes a separate test with its own result, labeled with its parameters, so a failure points straight at the input that caused it. Running with -v lists every one:
uv run pytest -v============================= test session starts ==============================platform linux -- Python 3.12.14, pytest-9.2.0, pluggy-1.7.0rootdir: .configfile: pyproject.tomlcollecting ... collected 8 itemstest_parse.py::test_valid_ports[80-80] PASSED [ 12%]test_parse.py::test_valid_ports[443-443] PASSED [ 25%]test_parse.py::test_valid_ports[ 8080\n-8080] PASSED [ 37%]test_parse.py::test_valid_ports[65535-65535] PASSED [ 50%]test_parse.py::test_out_of_range[0] PASSED [ 62%]test_parse.py::test_out_of_range[65536] PASSED [ 75%]test_parse.py::test_out_of_range[-1] PASSED [ 87%]test_parse.py::test_not_a_number PASSED [100%]============================== 8 passed in 0.01s ===============================Parametrize is ideal for edge cases: the smallest and largest valid values, one past each end, empty input, and input with stray whitespace. Those boundaries are where most bugs live.
A fixture is a function that prepares something a test needs, such as sample data or a temporary file. You define it with the @pytest.fixture decorator, and a test receives it by naming it as a parameter; pytest calls the fixture and passes in the result:
1import pytest
2
3
4@pytest.fixture
5def sample_input():
Each test gets a fresh result from the fixture, so tests can't affect each other through shared data. Pytest also has built-in fixtures. The most useful is tmp_path, a fresh temporary directory as a Path, which lets you test code that reads or writes files without touching real ones:
1def test_reads_ports_file(tmp_path):
2 path = tmp_path / "ports.txt"
3 path.write_text("22\n80\n443\n")
4
A natural fixture for a challenge solution is the puzzle's worked example: write it as a fixture, assert that your solution produces the example's answer, and only then run it on your real input.
A few command-line options cover most day-to-day use:
| Flag | Effect |
|---|---|
-v | List every test by name with its result |
-q | Quieter output: just the dots and the summary |
-x | Stop at the first failure |
-k EXPR | Run only tests whose names match the expression, such as -k range |
--lf | Rerun only the tests that failed last time |
-s | Show print() output from tests, which pytest hides by default |
FILE::NAME | Run one test, such as pytest test_parse.py::test_not_a_number |
For example, running just the out-of-range tests:
uv run pytest -q -k range... [100%]3 passed, 5 deselected in 0.00sThe usual loop while fixing a bug is pytest -x to find the first failure, fix it, then pytest --lf to confirm the fix before running everything again.