Codzy

Unit testing

A unit test automatically checks that a small piece of code (often a function) gives the right result. The simplest way: assert condition, which does nothing if the condition is true and raises an AssertionError otherwise.

For bigger projects, you group tests into classes with the unittest module (self.assertEqual(...)), or you use the very popular pytest: you write test_... functions with assert, then run the pytest command. Tests let you change your code without fear of breaking everything.

import io
import unittest

def add(a, b):
    return a + b

assert add(2, 3) == 5

class TestAdd(unittest.TestCase):
    def test_positive(self):
        self.assertEqual(add(2, 3), 5)

    def test_negative(self):
        self.assertEqual(add(-1, -1), -2)

suite = unittest.TestLoader().loadTestsFromTestCase(TestAdd)
result = unittest.TextTestRunner(stream=io.StringIO()).run(suite)
print("Tests run:", result.testsRun, "- failures:", len(result.failures))

Start the lesson