gpt4 book ai didi

python - 在 tearDown() 方法中获取 Python 的单元测试结果

转载 作者:IT老高 更新时间:2023-10-28 21:44:38 24 4
gpt4 key购买 nike

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

最佳答案

截至 2022 年 3 月,此答案已更新为支持 3.4 和 3.11 之间的 Python 版本(包括最新的开发 Python 版本)。错误/失败的分类与输出 unittest 中使用的分类相同。它在tearDown() 之前无需对代码进行任何修改即可工作。它正确识别装饰器 skipIf()expectedFailure。它也兼容 pytest .

代码:

import unittest

class MyTest(unittest.TestCase):
def tearDown(self):
if hasattr(self._outcome, 'errors'):
# Python 3.4 - 3.10 (These two methods have no side effects)
result = self.defaultTestResult()
self._feedErrorsToResult(result, self._outcome.errors)
else:
# Python 3.11+
result = self._outcome.result
ok = all(test != self for test, text in result.errors + result.failures)

# Demo output: (print short info immediately - not important)
if ok:
print('\nOK: %s' % (self.id(),))
for typ, errors in (('ERROR', result.errors), ('FAIL', result.failures)):
for test, text in errors:
if test is self:
# the full traceback is in the variable `text`
msg = [x for x in text.split('\n')[1:]
if not x.startswith(' ')][0]
print("\n\n%s: %s\n %s" % (typ, self.id(), msg))

如果您不需要异常信息,则可以删除后半部分。如果您还想要回溯,请使用整个变量 text 而不是 msg。它只是无法识别预期失败 block 中的意外成功

示例测试方法:

    def test_error(self):
self.assertEqual(1 / 0, 1)

def test_fail(self):
self.assertEqual(2, 1)

def test_success(self):
self.assertEqual(1, 1)

示例输出:

$ python3 -m unittest test

ERROR: q.MyTest.test_error
ZeroDivisionError: division by zero
E

FAIL: q.MyTest.test_fail
AssertionError: 2 != 1
F

OK: q.MyTest.test_success
.
======================================================================
... skipped the usual output from unittest with tracebacks ...
...
Ran 3 tests in 0.001s

FAILED (failures=1, errors=1)

Complete code包括 expectedFailure 装饰器示例

编辑:当我将此解决方案更新到 Python 3.11 时,我删除了与旧 Python < 3.4 相关的所有内容以及许多小注释。

关于python - 在 tearDown() 方法中获取 Python 的单元测试结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4414234/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com