我正在用pytest
编写测试,我遇到了下一个问题:我有一个测试某个变量的测试,然后我执行了一些繁重的计算,之后我想再执行一次测试。 / p>
问题是 - 如果第一个assert
失败,整个测试失败,pystest
没有执行第二次测试。
代码:
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个断言吗?
答案 0 :(得分:5)
通常,我只是让第一个断言的测试失败。但是,如果您真的想要进行多次比较,请比较元组。这是一个简单的例子:
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
来结合比较,但由于short circuiting而无效。例如,我尝试了这个断言:
assert a == 10 and b == 9
Pytest报告了这次失败:
> assert a == 10 and b == 9
E assert (11 == 10)
除非您使用b
选项,否则它不会报告--showlocals
的值。