多重断言
前言:
前面我们也介绍过了pytest的断言,pytest的断言一般使用python自带的assert进行断言,但是assert不能进行多重断言,当某些特殊场景需要做多重断言(即多个结果的断言)
时该如何处理。
一、assert进行多重断言时的特点:
直接来看示例:
def test_assert(): print("this is test_assert") assert 1 == 1 assert 1 == 2 assert 2 == 2
执行结果:
_____ test_assert ______ def test_assert(): print("this is test_assert") assert 1 == 1 > assert 1 == 2 E assert 2 == 2 test_3.py:7: AssertionError ====== short test summary info ====== FAILED test_3.py::test_assert - assert 1 == 2 ====== 1 failed in 0.04s ======
我们可以看到,虽然编写多个assert断言,程序仍然可以执行,但当其中一个断言失败时,后续的断言将不会执行。如assert 1==2断言失败,则assert 2==2则不会被执行。
二、使用pytest-assume进行多重断言:
使用assume进行多重断言时,需要导入pytest并调用assume()方法。
示例:
import pytest def test_assert(): print("this is test_assert") assert 1 == 1 assert 1 == 2 assert 2 == 2 def test_assume(): print("this is test_assume") pytest.assume(1 == 1) pytest.assume(1 == 2) print("over") pytest.assume(2 == 2)
执行结果:
test_3.py this is test_assert F this is test_assume over F
我们可以看到,pytest.assume每一个都执行了。因为第二个pytest.assume(1 == 2)断言失败,所以用例整体断言失败。
总结:
1.assert只适用于单个结果断言。进行多个断言时,其中有一个断言失败后,后续断言将不执行。
2.assume适用于多个结果断言。进行多个断言时,其中有一个断言失败后,后续断言将会继续执行,只有所有断言都通过用例整体才算通过,否则为断言失败用例不通过。
浙公网安备 33010602011771号