How do I concisely implement multiple similar unit tests in the Python unittest framework?

后端 未结 9 1075
予麋鹿
予麋鹿 2020-12-24 15:10

I\'m implementing unit tests for a family of functions that all share a number of invariants. For example, calling the function with two matrices produce a matrix of known s

9条回答
  •  孤独总比滥情好
    2020-12-24 15:44

    The above metaclass code has trouble with nose because nose's wantMethod in its selector.py is looking at a given test method's __name__, not the attribute dict key.

    To use a metaclass defined test method with nose, the method name and dictionary key must be the same, and prefixed to be detected by nose (ie with 'test_').

    # test class that uses a metaclass
    class TCType(type):
        def __new__(cls, name, bases, dct):
            def generate_test_method():
                def test_method(self):
                    pass
                return test_method
    
            dct['test_method'] = generate_test_method()
            return type.__new__(cls, name, bases, dct)
    
    class TestMetaclassed(object):
        __metaclass__ = TCType
    
        def test_one(self):
            pass
        def test_two(self):
            pass
    

提交回复
热议问题