xSKILLby Infirals
Register

Python for Beginners

0 of 24 notes read 0%

Reading progress is saved to your INFIRALS account. Sign in to keep this note marked as read.

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.

python
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.

Interview questions

2 questions from this note. Open one to see the answer; no account needed.

  • 01Why does a test pass in isolation but fail in a suite?

    It probably depends on state left by another test. Build fresh input inside each test instead of sharing mutable data.

  • 02What should a first test cover?

    One normal case and one edge case for the smallest function you have. Broader coverage can follow once the shape is stable.