How to write unit tests in Python that catch wrong code

For experts4 min read

How to write unit tests in Python is a skill AI trainers use daily, because tests decide whether an answer is accepted. A good test fails when the code is wrong. Here is a worked example with both unittest and pytest.

How to write unit tests in Python: start from the spec

Write down what the function must do before you look at any implementation. Here is the spec for a helper that splits a list into chunks.

  • chunk(items, size) returns a list of lists, each of length size, except the last, which may be shorter.
  • An empty list returns an empty list.
  • A size below 1 raises ValueError.
  • The input list is not changed.

Now a model-written implementation that you want to check.

Python
def chunk(items, size):    if size < 1:        raise ValueError("size must be at least 1")    return [items[i:i + size] for i in range(0, len(items), size)]

A unittest version

In the Python standard library, a test case is a subclass of unittest.TestCase, and every method whose name starts with test runs as its own test. assertEqual compares values, and assertRaises used as a context manager checks that a block raises the named exception.

Python
import unittestfrom chunks import chunk class ChunkTests(unittest.TestCase):    def test_uneven_last_chunk(self):        self.assertEqual(chunk([1, 2, 3, 4, 5], 2), [[1, 2], [3, 4], [5]])     def test_empty_list(self):        self.assertEqual(chunk([], 3), [])     def test_size_larger_than_list(self):        self.assertEqual(chunk([1, 2], 5), [[1, 2]])     def test_bad_size_raises(self):        with self.assertRaises(ValueError):            chunk([1, 2, 3], 0)     def test_input_not_changed(self):        data = [1, 2, 3]        chunk(data, 2)        self.assertEqual(data, [1, 2, 3]) if __name__ == "__main__":    unittest.main()

Run it with python -m unittest, or name a file, a class or one method. Add -v for the name of each test as it runs.

Source: Python docs: unittest(opens in a new tab)

The same idea in pytest

pytest tests are plain functions with plain assert statements. Parametrize runs one test body over several value sets, so a list of cases stays readable.

Python
import pytestfrom chunks import chunk @pytest.mark.parametrize("items,size,expected", [    ([1, 2, 3, 4, 5], 2, [[1, 2], [3, 4], [5]]),    ([], 3, []),    ([1, 2], 5, [[1, 2]]),    ([1, 2, 3], 3, [[1, 2, 3]]),])def test_chunk(items, size, expected):    assert chunk(items, size) == expected

Source: pytest docs: parametrize(opens in a new tab)

Why each test exists

Every test above targets a specific wrong version of the code. The uneven case catches an implementation that drops the remainder. The empty case catches an index error. The size-larger-than-list case catches code that assumes at least one full chunk. The last test catches code that empties the input with pop. If you cannot name the wrong version a test catches, it may not be needed.

Name tests after the behaviour, not the function. test_empty_list_returns_empty_list tells the reader what broke before they open the file. A good failure message saves the next reader a debugging session, and in a graded task it shows the reviewer that you understood the spec.

Keep each test short. Arrange the input, call the function, assert the result. If setup grows past a few lines, move it into a helper or a fixture so the test itself stays readable.

Mistakes that make a test suite useless

  • Copying the code's output into the expected value. If the code is wrong, the test is wrong with it.
  • One huge test with ten assertions. The first failure hides the rest and the name tells you nothing.
  • Testing the implementation, such as calling a private helper, instead of behaviour. Any correct rewrite then fails.
  • Random inputs with no fixed seed, so a failure cannot be reproduced.
  • Tests that depend on each other or on the order they run in.

For the failure path, test the type of the error and, when it matters, its message. A bare except in the code under test can hide a bug that a precise exception check would show.

Writing tests for other people's code

In AI training tasks you often write tests for a function you did not write, and a model might have produced several versions. Good tests give the same verdict to every correct version, even one that is written in a very different style, and a different verdict to wrong versions.

That means testing results, not steps. Do not assert that a particular helper was called. Do not depend on dictionary order, floating point text or the exact wording of an error unless the spec fixes it. If a spec leaves something open, leave it out of the test.

Finally, run your tests against broken code on purpose. Change the less-than to a less-than-or-equal, delete the validation, return the wrong type. A suite that still passes is telling you it is blind in that spot. This habit, sometimes called mutation testing when it is automated, is the quickest way to learn which of your tests matter.

A practice routine

  1. Choose five small functions: chunk, flatten, merge intervals, is palindrome, group by key.
  2. For each, write the spec in four lines before any code.
  3. Write the tests, then write two wrong implementations on purpose and check that the tests fail on both.
  4. Write one correct implementation in a different style and check that it passes.

Curatrain tests Python skills at graded levels and matches experts only to jobs whose tests they passed. Every score is kept and you see yours when you finish. Sign up free at curatrain.com/login.