This is an archived version of the course. Please find the latest version of the course on the main webpage.

Chapter 8: Unit testing

unittest module

face Josiah Wang

Now, let’s explore our test case in more detail.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import unittest

from euclidean import euclidean_distance

class EuclideanTest(unittest.TestCase):
    def test_positive_input(self):
        dist = euclidean_distance(3, 2, 5, 6)
        expected_answer = 2.828427
        epsilon = 0.000001
        assert abs(dist - expected_answer) < epsilon

    def test_negative_input(self):
        dist = euclidean_distance(-3, -2, 5, 6)
        expected_answer = 10
        epsilon = 0.000001
        assert abs(dist - expected_answer) < epsilon

    def test_zero_input(self):
        dist = euclidean_distance(0, 0, 0, 0)
        expected_answer = 0
        epsilon = 0.000001
        assert abs(dist - expected_answer) < epsilon

if __name__ == '__main__':
    unittest.main()

The basic unit for a test in unittest is a TestCase. You create a test case to group all related tests together.

To create a TestCase, you create a new class that inherits from unittest.TestCase (Line 5).

You then create different methods to test different scenarios. The name of your test methods must all start with test. This is so that unittest will be able to automatically discover your test methods without any additional effort from you. It will not run any methods not starting with test automatically, unless you specify them manually.

Line 24-25 can actually be omitted. But if you omit this, you will have to run your tests using python3 -m unittest test_euclidean (passing your module name to the unittest module).