我可以在一个Python pytest方法中处理多个断言吗?
我正在用我可以在一个Python pytest方法中处理多个断言吗?,python,python-2.7,python-3.x,unit-testing,pytest,Python,Python 2.7,Python 3.x,Unit Testing,Pytest,我正在用pytest编写测试,我遇到了下一个问题:我有一个测试,测试一些变量,然后我执行一些繁重的计算,然后我想执行另一个测试 问题是-如果第一个assert失败,则整个测试失败,并且pystest不执行第二个测试。 守则: class TestSomething: def tests_method(self, some_variables): # Some actions that take a lot of time! assert some_var
pytest
编写测试,我遇到了下一个问题:我有一个测试,测试一些变量,然后我执行一些繁重的计算,然后我想执行另一个测试
问题是-如果第一个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
我知道这个测试方法可以分为两种,但是这里的性能问题是至关重要的
有一种方法可以在一个方法中运行两个断言吗?通常,我只是让测试在第一个断言中失败。但是,如果您真的想做不止一个比较,请比较元组。下面是一个简单的例子:
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 ===========================
我还尝试使用和
来组合比较,但由于存在错误,这不起作用。例如,我尝试了以下断言:
assert a == 10 and b == 9
Pytest报告了此故障:
> assert a == 10 and b == 9
E assert (11 == 10)
除非使用
--showlocals
选项,否则它不会报告b
的值。如果第一次断言失败,第二次断言成功与否重要吗?@simeonviser Yes,这是我执行的另一个测试,我也想知道它的结果。也许你需要一个设置函数来处理这两个断言?你可以使用跟踪所有断言的布尔标志,然后你可以应用和覆盖所有值,并断言resultUnit测试不是重计算的地方。您最好找到一个较小的测试用例,或者模拟繁重的计算(),例如,用虚假的、预设的对象/数据替换繁重的计算。