如何仅使用python unittest2在测试失败时执行代码? [英] How to execute code only on test failures with python unittest2?

查看:118
本文介绍了如何仅使用python unittest2在测试失败时执行代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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'd like to grab a screenshot in tearDown() for every test failure, to reduce the time spent debugging why a test failed.

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

However, I can't find any way to run code on test failures only. tearDown() is called regardless of whether the test succeeds, and I don't want to clutter our filesystem with hundreds of browser screenshots for tests that succeeded.

您将如何处理?

推荐答案

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

Found a solution - I can override 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

这似乎令人难以置信,但是到目前为止,它似乎仍然有效.

This seems incredibly hacky but it seems to work so far.

这篇关于如何仅使用python unittest2在测试失败时执行代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆