Python unit test with base and sub class

前端 未结 15 2360
独厮守ぢ
独厮守ぢ 2020-11-28 18:44

I currently have a few unit tests which share a common set of tests. Here\'s an example:

import unittest

class BaseTest(unittest.TestCase):

    def testCo         


        
15条回答
  •  广开言路
    2020-11-28 19:07

    A way I've thought of solving this is by hiding the test methods if the base class is used. This way the tests aren't skipped, so the test results can be green instead of yellow in many test reporting tools.

    Compared to the mixin method, ide's like PyCharm won't complain that unit test methods are missing from the base class.

    If a base class inherits from this class, it will need to override the setUpClass and tearDownClass methods.

    class BaseTest(unittest.TestCase):
        @classmethod
        def setUpClass(cls):
            cls._test_methods = []
            if cls is BaseTest:
                for name in dir(cls):
                    if name.startswith('test') and callable(getattr(cls, name)):
                        cls._test_methods.append((name, getattr(cls, name)))
                        setattr(cls, name, lambda self: None)
    
        @classmethod
        def tearDownClass(cls):
            if cls is BaseTest:
                for name, method in cls._test_methods:
                    setattr(cls, name, method)
                cls._test_methods = []
    

提交回复
热议问题