繁体   English   中英

如何仅使用python unittest2在测试失败时执行代码?

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

我在python的unittest2框架中运行了一些基于类的单元测试。 我们正在使用Selenium WebDriver,它具有方便的save_screenshot()方法。 我想在每个测试失败时在tearDown()中抓取一个屏幕截图,以减少调试为什么测试失败的时间。

但是,我找不到仅在测试失败时运行代码的任何方法。 无论测试是否成功,都将调用tearDown() ,并且我不希望使用成百上千的浏览器屏幕快照来使我们的文件系统混乱,以确保测试成功。

您将如何处理?

找到了解决方案-我可以覆盖failureException

@property
def failureException(self):
    class MyFailureException(AssertionError):
        def __init__(self_, *args, **kwargs):
            self.b.save_screenshot('%s.png' % self.id())
            return super(MyFailureException, self_).__init__(*args, **kwargs)
    MyFailureException.__name__ = AssertionError.__name__
    return MyFailureException

这似乎难以置信,但到目前为止它似乎仍然有效。

覆盖fail()以生成屏幕截图,然后调用TestCase.fail(self)吗?

sys.exc_info()应该为您提供有关测试是否失败的退出信息。 所以像这样:

def tearDown(self):
    if sys.exc_info()[0]:
        path = os.path.join(os.path.dirname(os.path.abspath(__file__)), '../failures', self.driver.browser)
        if not os.path.exists(path):
            try:
                os.makedirs(path)
            except Exception:
                # Since this might not be thread safe
                pass
        filename = '%s.%s.png' % (self.__class__.__name__, self._testMethodName)
        file_path = os.path.join(path, filename)
        self.driver.get_screenshot_as_file(file_path)

这是与@craigds答案类似的方法,但具有目录支持和与Python 3的更好兼容性:

@property
def failureException(self):
    class MyFailureException(AssertionError):
        def __init__(self_, *args, **kwargs):
            screenshot_dir = 'reports/screenshots'
            if not os.path.exists(screenshot_dir):
                os.makedirs(screenshot_dir)
            self.driver.save_screenshot('{0}/{1}.png'.format(screenshot_dir, self.id()))
            return super(MyFailureException, self_).__init__(*args, **kwargs)
    MyFailureException.__name__ = AssertionError.__name__
    return MyFailureException

实际上是在此博客中找到的。

我用argparse进一步扩展了它:

parser.add_argument("-r", "--reports-dir", action="store",   dest="dir",      help="Directory to save screenshots.", default="reports")     

因此,可以通过系统变量或传递的参数动态指定目录:

screenshot_dir = os.environ.get('REPORTS_DIR', self.args.dir) + '/screenshots'

如果您有其他包装程序来运行所有脚本(如基类),则此功能特别有用。

在每个测试周围使用装饰器。

记住装饰新测试或避免返回并装饰一堆现有测试的最安全方法是使用元类包装所有测试功能。 如何包装一个类的每个方法? 答案提供了您所需的基础知识。

您可能应该过滤仅包含测试的功能,例如:

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM