Pythonでunittest

unittestモジュールをimportし、unittest.TestCaseクラスを継承したテストクラスを作成する。その際、テストメソッドはtestという単語で始まる必要がある。

import uittest
from my_module import my_function

class MyTest(unittest.TestCase):
    def test_my_function(self):
        result = my_function(2)
        self.assertEqual(result, 4)

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

具体例

import unittest

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

class TestAddFunction(unittest.TestCase):

    def test_add_integer(self):
        result = add(2, 3)
        self.assertEqual(result, 5)

    def test_add_floats(self):
        result = add(2.5, 3.5)
        self.assertAlmostEqual(result, 6.0, places=2)

    def test_add_strings(self):
        result = add("Hello, ", "world!")
        self.assertEqual(result, "Hello, world!")

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

$ python3 test.py

———————————————————————-
Ran 3 tests in 0.000s

OK

return a + b + 1 とすると、
$ python3 test.py
FFE
======================================================================
ERROR: test_add_strings (__main__.TestAddFunction)
———————————————————————-
Traceback (most recent call last):
File “/home/vagrant/dev/blockchain/test.py”, line 17, in test_add_strings
result = add(“Hello, “, “world!”)
File “/home/vagrant/dev/blockchain/test.py”, line 4, in add
return a + b + 1
TypeError: can only concatenate str (not “int”) to str

======================================================================
FAIL: test_add_floats (__main__.TestAddFunction)
———————————————————————-
Traceback (most recent call last):
File “/home/vagrant/dev/blockchain/test.py”, line 14, in test_add_floats
self.assertAlmostEqual(result, 6.0, places=2)
AssertionError: 7.0 != 6.0 within 2 places (1.0 difference)

======================================================================
FAIL: test_add_integer (__main__.TestAddFunction)
———————————————————————-
Traceback (most recent call last):
File “/home/vagrant/dev/blockchain/test.py”, line 10, in test_add_integer
self.assertEqual(result, 5)
AssertionError: 6 != 5

———————————————————————-
Ran 3 tests in 0.000s

FAILED (failures=2, errors=1)

Test Classの中で、setUp, tearDownを入れると、テストの実行前後でそれぞれ実行される。

class TestAddFunction(unittest.TestCase):

    def setUp(self):
        print("setUp() called")

    def test_add_integer(self):
        result = add(2, 3)
        self.assertEqual(result, 5)

    def test_add_floats(self):
        result = add(2.5, 3.5)
        self.assertAlmostEqual(result, 6.0, places=2)

    def test_add_strings(self):
        result = add("Hello, ", "world!")
        self.assertEqual(result, "Hello, world!")

    def tearDown(self):
        print("tearDown() called")