How to execute code only on test failures with python unittest2?

后端 未结 5 2167
既然无缘
既然无缘 2020-12-06 11:01

I have some class-based unit tests running in python\'s unittest2 framework. We\'re using Selenium WebDriver, which has a convenient save_screenshot() method. I

5条回答
  •  自闭症患者
    2020-12-06 11:56

    Use a decorator around each test.

    The safest way to remember to decorate new tests, or to avoid going back and decorating a bunch of existing tests, is to use a metaclass to wrap all of the test functions. The How to wrap every method of a class? answer provides the basics of what you need.

    You probably should filter the functions that are wrapped down to just the tests, e.g.:

    class ScreenshotMetaClass(type):
        """Wraps all tests with screenshot_on_error"""
        def __new__(meta, classname, bases, classDict):
            newClassDict = {}
            for attributeName, attribute in classDict.items():
                if type(attribute) == FunctionType and 'test' in attributeName.lower():
                    # replace the function with a wrapped version
                    attribute = screenshot_on_error(attribute)
                newClassDict[attributeName] = attribute
            return type.__new__(meta, classname, bases, newClassDict)
    

提交回复
热议问题