end0tknr's kipple - web写経開発

太宰府天満宮の狛犬って、妙にカワイイ

python unittestのオレオレ 雛形(テンプレート template )

python srcのオレオレ 雛形(テンプレート template ) - end0tknr's kipple - web写経開発

上記の unittest 版です

#!python
# -*- coding: utf-8 -*-

import sys
import unittest

class TestMyClass(unittest.TestCase):  # unittest.TestCase を要 継承

    # test_~()毎の実行前に呼ばれます
    def setUp(self):
        pass

    # test_~()毎の実行後に呼ばれます
    def tearDown(self):
        pass

    def test_a(self):
        func_name = sys._getframe().f_code.co_name

        # assert~()失敗時に停止させない為、with化
        tmp_comment = func_name
        with self.subTest(tmp_comment):
            self.assertEqual(True, [True,None],tmp_comment)
            self.assertEqual(False,[True,None],tmp_comment)


    def test_b(self):
        func_name = sys._getframe().f_code.co_name

        # assert~()失敗時に停止させない為、with化
        tmp_comment = func_name
        with self.subTest(tmp_comment):
            self.assertIn(1,[1,None],tmp_comment)
            self.assertIn(2,[1,None],tmp_comment)


        
# subTest()毎にtest数をcountする為のものです
class VerboseTestResult(unittest.TextTestResult):
    def addSubTest(self, test, subtest, outcome):
        super(VerboseTestResult, self).addSubTest(test, subtest, outcome)
        self.testsRun += 1


if __name__ == "__main__":
    runner = unittest.TextTestRunner(resultclass=VerboseTestResult,
                                     verbosity=2)
    unittest.main(testRunner=runner)
    #unittest.main(verbosity=2)

↑こう書くと、↓こう出力されます

..\python38\python.exe .\test_foo.py
test_a (__main__.TestMyClass) ... test_b (__main__.TestMyClass) ...
======================================================================
FAIL: test_a (__main__.TestMyClass) [test_a]
----------------------------------------------------------------------
Traceback (most recent call last):
  File ".\foo.py", line 23, in test_a
    self.assertEqual(True, [True,None],tmp_comment)
AssertionError: True != [True, None] : test_a

======================================================================
FAIL: test_b (__main__.TestMyClass) [test_b]
----------------------------------------------------------------------
Traceback (most recent call last):
  File ".\foo.py", line 34, in test_b
    self.assertIn(2,[1,None],tmp_comment)
AssertionError: 2 not found in [1, None] : test_b

----------------------------------------------------------------------
Ran 4 tests in 0.002s

FAILED (failures=2)