在 tearDown() 方法中获取 Python 的单元测试结果 [英] Getting Python's unittest results in a tearDown() method

查看:24
本文介绍了在 tearDown() 方法中获取 Python 的单元测试结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在tearDown() 方法中获取测试结果(即是否所有断言都已通过)?我正在运行 Selenium 脚本,我想从 tearDown() 内部做一些报告,但我不知道这是否可行.

Is it possible to get the results of a test (i.e. whether all assertions have passed) in a tearDown() method? I'm running Selenium scripts, and I'd like to do some reporting from inside tearDown(), however I don't know if this is possible.

推荐答案

CAVEAT:我目前没有办法仔细检查以下理论,因为远离开发箱.所以这可能是在黑暗中拍摄.

CAVEAT: I have no way of double checking the following theory at the moment, being away from a dev box. So this may be a shot in the dark.

也许你可以在你的tearDown()方法中检查sys.exc_info()的返回值,如果它返回(None, None, None),你知道测试用例成功.否则,您可以使用返回的元组来查询异常对象.

Perhaps you could check the return value of sys.exc_info() inside your tearDown() method, if it returns (None, None, None), you know the test case succeeded. Otherwise, you could use returned tuple to interrogate the exception object.

请参阅sys.exc_info 文档.

另一种更明确的方法是编写一个方法装饰器,您可以将其添加到所有需要这种特殊处理的测试用例方法上.这个装饰器可以拦截断言异常,并在此基础上修改 self 中的一些状态,让你的 tearDown 方法了解发生了什么.

Another more explicit approach is to write a method decorator that you could slap onto all your test case methods that require this special handling. This decorator can intercept assertion exceptions and based on that modify some state in self allowing your tearDown method to learn what's up.

@assertion_tracker
def test_foo(self):
    # some test logic

这篇关于在 tearDown() 方法中获取 Python 的单元测试结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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