我正在用pytest
编写测试,我遇到了一个问题:我有一个测试测试某个变量,然后我执行了一些繁重的计算,然后我想执行另一个测试。
问题是,如果第一个assert
测试失败,则整个测试失败,pytest
不执行第二个测试。代码:
class TestSomething:
def tests_method(self, some_variables):
# Some actions that take a lot of time!
assert some_var == 1
# Some actions that take a lot of time!
assert some_var == 2
我知道这种测试方法可以分为 2 种方法,但这里的性能问题至关重要。
有没有办法在一种方法中运行 2 个断言?
通常,我只是让测试在第一个断言上失败。但是,如果您真的想进行多个比较,请比较元组。下面是一个简单的示例:
def foo(x):
return x + 1
def bar(y):
return y - 1
def test_foo():
# some expensive calculation
a = foo(10)
# another expensive calculation
b = bar(10)
assert (a, b) == (10, 9)
当我使用 pytest 运行时,它向我显示了两个值:
$ pytest scratch.py
============================= test session starts =============================
platform linux2 -- Python 2.7.12, pytest-3.0.7, py-1.4.33, pluggy-0.4.0
rootdir: /home/don/workspace/scratch, inifile:
collected 1 items
scratch.py F
================================== FAILURES ===================================
__________________________________ test_foo ___________________________________
def test_foo():
# some expensive calculation
a = foo(10)
# another expensive calculation
b = bar(10)
> assert (a, b) == (10, 9)
E assert (11, 9) == (10, 9)
E At index 0 diff: 11 != 10
E Use -v to get the full diff
scratch.py:16: AssertionError
========================== 1 failed in 0.02 seconds ===========================
我还尝试使用and
来组合比较,但由于短路,这不起作用。例如,我尝试了这个断言:
assert a == 10 and b == 9
Pytest 报告了此失败:
> assert a == 10 and b == 9
E assert (11 == 10)
它不会报告 b
的值,除非您使用 --showlocals
选项。