Testing basics with unittest
More Python11 min readLesson 7 of 7
7.1 A test is a small program with an expectation
Tests catch regressions and document intended behaviour. The standard library ships unittest: write a class that inherits TestCase, add methods whose names start with test, and call unittest.main() to run them.
Each test should build its own state and check one behaviour. Order independence matters because test runners may reorder or run tests in parallel later.
import unittest
def average(marks):
return sum(marks) / len(marks)
class TestAverage(unittest.TestCase):
def test_whole_numbers(self):
self.assertEqual(average([10, 20, 30]), 20)
def test_single_value(self):
self.assertEqual(average([7]), 7)
if __name__ == "__main__":
unittest.main()Output
.. ---------------------------------------------------------------------- Ran 2 tests in 0.000s OK
Name the file test_*.py so discovery finds it, and run the suite with python -m unittest. For more features such as fixtures and readable assertions, pytest is a common next step, but the standard library is enough to start.
