Python unit test with base and sub class

前端 未结 15 2280
独厮守ぢ
独厮守ぢ 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:14

    So this is kind of an old thread but I came across this problem today and thought of my own hack for it. It uses a decorator that makes the values of the functions None when acessed through the base class. Don't need to worry about setup and setupclass because if the baseclass has no tests they won't run.

    import types
    import unittest
    
    
    class FunctionValueOverride(object):
        def __init__(self, cls, default, override=None):
            self.cls = cls
            self.default = default
            self.override = override
    
        def __get__(self, obj, klass):
            if klass == self.cls:
                return self.override
            else:
                if obj:
                    return types.MethodType(self.default, obj)
                else:
                    return self.default
    
    
    def fixture(cls):
        for t in vars(cls):
            if not callable(getattr(cls, t)) or t[:4] != "test":
                continue
            setattr(cls, t, FunctionValueOverride(cls, getattr(cls, t)))
        return cls
    
    
    @fixture
    class BaseTest(unittest.TestCase):
        def testCommon(self):
            print('Calling BaseTest:testCommon')
            value = 5
            self.assertEqual(value, 5)
    
    
    class SubTest1(BaseTest):
        def testSub1(self):
            print('Calling SubTest1:testSub1')
            sub = 3
            self.assertEqual(sub, 3)
    
    
    class SubTest2(BaseTest):
    
        def testSub2(self):
            print('Calling SubTest2:testSub2')
            sub = 4
            self.assertEqual(sub, 4)
    
    if __name__ == '__main__':
        unittest.main()
    

提交回复
热议问题