Testing Python from Zero: unittest, 9 Tests, and One Deliberate Failure
Python 3.12.3, unittest, zero packages: 9 tests in 3 classes, all passing — subtotal 18390 cents, 10% off 16551, average 6130.0, cheapest 4500 — plus one deliberately wrong expectation failing as expected (18390 != 18391).

When AI writes your code, the biggest risk is not that it cannot write it, but that what it writes looks right and quietly goes wrong in some corner. Change one function and you accidentally break another — this happens all the time with AI-generated code, because the model changes several places at once and no human can eyeball all of them. The only reliable defense is tests: write down what "correct" means as assertions that run automatically, run them after every change, and only call it done when they are green. This guide covers Python's built-in unittest. Nothing to install: Python 3.12.3 ships it, and if you have Python, you have it.
First, the demo setup and data. Every command in this guide was actually run on this machine: Python 3.12.3, zero third-party packages. The demo uses a fictional little bookshop pricing example: three books priced at 5990, 7900 and 4500 cents — 5990 cents is 59.9 dollars. Prices are in cents rather than dollars to dodge floating-point noise, and you will see why when we get to assertAlmostEqual. The bookshop, the books and the prices are all made-up demo data, not a real shop. The demo script is demo254_g1.py: it generates the code under test, shop.py, and the test file, test_shop.py, on the spot, then runs the tests twice — once all passing, once with a deliberately wrong expectation so you can see what failure looks like. The script and the Chinese and English transcripts are in the draft directory, and every number in this article can be found in the transcripts.
The code under test is tiny: four functions in shop.py. subtotal adds up a list of prices and raises ValueError on a negative price; apply_discount computes the discounted price for a rate that must sit between 0 and 1; average computes the mean price and raises ValueError on an empty list; cheapest finds the lowest price and also raises ValueError on an empty list. Four functions, under 30 lines. The smallness is deliberate: the point of this guide is not the code under test, but how tests are written, run, and read when they fail.
The test file, test_shop.py, has 3 test classes and 9 test methods. A test class inherits from unittest.TestCase, and test method names must start with test — that is how unittest discovers tests. TestSubtotal covers the total: three books, 5990 + 7900 + 4500, equal 18390; an empty list totals 0; a negative price must raise ValueError. TestDiscount covers discounts: 18390 at 10 percent off is 16551, and a rate of 1.5 must raise ValueError. TestAverageAndCheapest covers the mean and the cheapest book: the three books average 6130.0, the cheapest is 4500, asking for the average of an empty list must raise ValueError, plus one test built on a setUp fixture that checks the data really holds 3 books and really totals 18390.
The command that runs the tests is python3 -m unittest discover -s . -p "test_shop.py" -v. The -m unittest part starts the test framework as a module, discover is the auto-discovery mode, -s says which directory to search, -p gives the filename pattern, and -v is verbose output, one line per test. Section 1 of the demo script runs exactly this command, and the output is 9 lines of ok followed by OK. Note that the tests run in alphabetical order: test_average_empty_raises comes before test_average_three_books, and test_empty_list comes before test_three_books. That is not a coincidence — unittest runs test methods in alphabetical order by default. Knowing this matters: tests must not depend on each other, and you cannot count on test A running before test B, because the order is set by the alphabet, not by the order you wrote them in the file.
The split of the 9 tests across the 3 test classes is easier to see in the chart.

Assertions are the body of a test. The most-used ones in unittest are: assertEqual(a, b) for equality, assertTrue(x) and assertFalse(x) for truth, assertIn(a, b) for membership, assertIsNone(x) for None, assertRaises(exception type) for expecting a specific exception, and assertAlmostEqual(a, b) for floats that are close enough. assertAlmostEqual deserves its own sentence: 0.1 + 0.2 in binary floating point is not 0.3, it is 0.30000000000000004, so assertEqual(0.1 + 0.2, 0.3) fails while assertAlmostEqual(0.1 + 0.2, 0.3) passes. This was verified on this machine, and that is the conclusion. So whenever a result carries decimals — money, averages — either compute in integer cents the way the demo does, or use assertAlmostEqual. Never point assertEqual at a float.
The assertRaises style uses a with statement: with self.assertRaises(ValueError): followed by the line that should raise, indented underneath. The demo's test_negative_price_raises is written exactly this way: subtotal([5990, -100]) must raise ValueError, and if it does not, the test fails. The advantage is that the exception type is verified too — a different exception, or no exception at all, both count as failure. Checking only that "something goes wrong" is not enough; you also need to check that it goes wrong in the way you expect, and assertRaises does both at once.
setUp is preparation work that runs once before every test method. TestAverageAndCheapest has a setUp that sets self.prices to [5990, 7900, 4500] before each test, so all 4 test methods can use self.prices directly instead of each writing it out. setUp runs fresh for every test, so if one test mutates self.prices, the next test is unaffected — each test gets fresh data. That is the key property of setUp: tests do not share mutable state. If you have something all tests share and that is expensive to prepare only once — opening a temporary file, building a temporary directory — use setUpClass, which runs a single time before the whole test class. That was verified separately on this machine: a shared list prepared in setUpClass was readable by the class's tests, and all 3 tests passed. The division of labor is one sentence: fresh data per test goes in setUp; one shared, expensive setup for the whole class goes in setUpClass.
Writing tests is only half the job; reading failures is the other half. Section 2 of the demo script deliberately changes the expected value in test_three_books from 18390 to 18391 and runs again, and the output becomes three lines: FAIL: test_three_books (test_shop.TestSubtotal.test_three_books), AssertionError: 18390 != 18391, FAILED (failures=1). There is a fixed order for reading failure output: the FAIL line tells you which test broke; the AssertionError line tells you how the actual value differs from the expected value; the FAILED (failures=1) line tells you how many broke in total. This time the cause is obvious at a glance: the code computed 18390, the test expected 18391, so the test itself was wrong, not the code under test. That is how failure output is read in real work: locate the test first, compare the two values second, and only then decide whether to fix the code or fix the test. One more number to remember: the failing run exited with code 1; the all-green run exited with code 0. The exit code is for machines to read: CI pipelines judge pass or fail by the exit code. Humans read the output, machines read the exit code.
As tests pile up, you do not need to run all of them every time. Run a single test with python3 -m unittest test_shop.TestSubtotal.test_three_books, a dotted path down to the method. Run a single class with python3 -m unittest test_shop.TestSubtotal. Run a single file with python3 -m unittest test_shop. Changed the total logic, run only TestSubtotal; changed the discount, run only TestDiscount. Start narrow when tracking a problem down: the smaller the scope, the shorter the failure output, and the faster you find the cause. Verified on this machine: running test_three_books alone gives OK. One more detail: you can also run the test file directly with python3 test_shop.py, because the file ends with if __name__ == "__main__": unittest.main(). But python3 -m unittest is the more convenient daily driver, since it does not care where the file lives and discover can run a whole directory at once.
Some code is awkward to test directly: code that hits the network, reads files, or connects to a database. The standard library's unittest.mock is for that: patch temporarily swaps a function for a fixed return value and restores it automatically when the test ends. Verified on this machine: inside with patch("shop_scratch.subtotal", return_value=100): calling subtotal([1, 2, 3]) returns 100, and outside the with block the original is back. The rule for mock is to use it only at the boundary, replacing things you cannot afford to test for real, such as network calls or the system clock. Never mock the business logic itself — mocking the total function and then testing the total proves nothing. This site already has a guide on mock strategy that uses Vitest and Jest, about test doubles for AI-generated code; the unittest.mock here is the Python standard library's version of the same idea. They cover different tools and do not overlap.
For file layout, the convention is to keep tested code and tests apart, with test files starting with test_, in the same directory or in a dedicated tests directory. The demo uses shop.py and test_shop.py side by side, which is enough for a small project. When the project grows, split tests into a tests directory and point discover's -s flag at it. For naming, test method names should say what they test: test_three_books, test_empty_list, test_negative_price_raises — read the name and you know which case it covers. Well-named tests pay off twice: the FAIL line in failure output reads like a plain sentence, and locating the problem gets twice as fast.
Beyond the ones above, unittest's assertions are a whole family, and a batch was verified separately on this machine: assertIn(5990, [5990, 7900, 4500]) checks membership, assertNotIn(100, [5990, 7900, 4500]) checks absence, assertGreater(7900, 5990) and assertLess(4500, 5990) compare sizes, assertIs(x, x) checks identity, and assertRegex("18390 cents", r"^\d+ cents$") checks a string against a regular expression. All 4 tests passed. The rule for picking an assertion is to use the most specific one. To check membership, use assertIn, not assertTrue(5990 in prices), because when assertIn fails it prints both values, while assertTrue only prints one line of False and leaves you guessing which value was missing. The more specific the assertion, the more useful the failure output — that is the most valuable design lesson in unittest.
Test discovery has a few more details that trip people up the first time. discover looks for files matching the test*.py pattern by default, so a test file must start with test — a file called shop_test.py will not be found. The -s flag sets the directory to search from, and -t sets the top-level directory, which you only need when tests live in subdirectories. One more easily missed point: once discover finds a test file it imports it as a module, so do not put code that runs immediately at the top level of a test file, apart from the two lines if __name__ == "__main__": unittest.main(). Top-level code runs at import time, which at best slows discovery down and at worst fails outright. And if two modules in the same directory share a name, the import may grab the wrong file; keeping test files and tested code in separate directories avoids that class of problem.
People often ask: there is already a pytest guide, so why learn unittest? The practical answer is that pytest needs installing and unittest does not. The pytest guide on this site covers adding a safety net with pytest, a third-party tool; this guide covers the built-in set, which runs on any machine with Python installed — no pip, no network, no version juggling. They test the same kind of thing with different syntax, so pick by project: if the project already uses pytest, stay with pytest; if you just want a quick check on a small script or a vibe project, unittest costs nothing. Once you understand unittest's TestCase, assertions, setUp and discovery, much of pytest will feel familiar — the concepts carry over, and the learning is not spent twice.
Tests themselves can be wrong, and section 2 of the demo already showed it: the expected value written as 18391 made the test fail, and the test was at fault, not the code. This happens a lot in real projects, especially when the expected values come from AI. When AI writes your tests, it may invent the expected values along with them and miscalculate without telling you. So expected values must be worked out by hand, or come from a source you can check independently: 5990 + 7900 + 4500 = 18390 is hand-computed, not model-generated. The value of a test lies in the fact that you set the expected value and the code is the thing under suspicion; if the code sets the expected value too, the test is only parroting back, and it verifies nothing. When reviewing AI-generated tests, the first job is to check every expected value one by one. If a number does not add up, fix the test first, then talk about the code.
Refactoring and tests are a pair. Without tests, refactoring is changing code on nerve and hoping; with tests, it is running everything green first, changing things, running everything green again, and letting the failing tests pinpoint exactly what broke. AI code changes need this rhythm even more: get the tests green before it starts refactoring, and require them to stay green afterwards. The demo's 9 tests are the smallest version of this rhythm: total, discount, average, cheapest each have their own tests, so changing one area makes the other three areas' tests speak up immediately if they were affected. That is also why tests are grouped by function into classes — TestSubtotal, TestDiscount and TestAverageAndCheapest each own one area, and when something fails you can see at a glance which area broke.
Not all code deserves tests, and that is a judgment call too. One-off scripts, one-time data cleanup, prototypes still being explored — the cost of tests there outweighs the benefit, so get them running first. But anything that will run repeatedly — bookshop pricing, handling an API response, the core logic of a scheduled job — is worth testing. The test is one sentence: will this code be changed again later, by future-you or by AI? If yes, write tests; if no, do not. Tests are not better in larger numbers, they are better when they are precise. Nine tests covering four functions, each with a definite expected value, is exactly the right density; a pile of tests that only assert True inflates the output and proves nothing.
Make it a habit to run the tests before every commit, no matter how small the change. One changed line can still break a total. Tests should run fast — fast enough that you never feel tempted to skip them. The demo's 9 tests finish in a blink; the timing is so short that the "Ran 9 tests in 0.00Xs" line differs on every run, so the demo script filters it out and keeps only the deterministic numbers. Tests get slow when they test things they should not: real network calls, real file writes, real sleeps. When that happens, reach for fake data, mock, or smaller inputs instead of tolerating slow tests — slow tests will eventually be skipped, and a skipped test is the same as no test. This site also has a GitHub Actions guide about running tests automatically on every push. Running them locally is step one; running them automatically on push is step two. Only with both steps do tests become a real safety net.
Finally, the whole flow in order, ready to copy into your own project. Step one: write one minimal function under test, such as subtotal for the total. Step two: in the same directory, create a file starting with test_, write one TestCase with one test method, and use assertEqual with a result you worked out by hand, such as 5990 + 7900 + 4500 = 18390. Step three: run python3 -m unittest discover -v and see ok. Step four: deliberately break one expected value, run again, see FAILED (failures=1), confirm you can read the failure output, then change it back. Step five: make tests part of your daily flow — before letting AI change code, write the behavior of that change as a test first, run the tests after the change, and only commit when they are green. Five steps, and your vibe project has its first real safety net. The demo script demo254_g1.py and the Chinese and English transcripts are in the draft directory. Reproducing them takes two commands: python3 demo254_g1.py --lang zh and python3 demo254_g1.py --lang en. Both exit with code 0, all 9 tests pass, and the numbers match exactly.
Comments (0)
Sources
Related articles
tmux 3.4, zero packages: 1 session, 2 windows, 3 panes; the logs window prints 1 to 5, editor panes report ready. Detach with Ctrl-b d, reattach with tmux attach — the session outlives the connection. Mouse, prefix key and history limit in ~/.tmux.conf included.
GCC 13.3.0, C17, zero packages: a first C program, sizeof results 1/2/4/8/8/4/8/8, sum 1..100 is 5050, 10! is 3628800, 8 numbers sorted, 3 books total 1088 pages, 3 file lines and 70 chars read back. Preprocessing alone expands 3 lines to 815.
64 start tags, 5 headings, 4 links, 1 image; 3 books cost 90030 cents, 20 copies; 3 local checks, 200, 200, 404. Python 3.12.3 standard library only, page file 1834 bytes.