1. 程式人生 > 實用技巧 >pytest入門到放棄21--pytest-assume多重效驗外掛

pytest入門到放棄21--pytest-assume多重效驗外掛

1、目的:

  解決多個assert斷言中,其中一個斷言失敗,後續斷言不再繼續執行的問題。

2、使用外掛:

  pytest-assume

3、安裝: 

pip install pytest-assume -i https://pypi.tuna.tsinghua.edu.cn/simple

  

4、assert 多重斷言:

# File  : test_demo_18_assume.py
# IDE   : PyCharm

a = 6
b = 3
def test_calc_1():
    assert a / b == 2
    assert a + b == 8
    assert
a * b == 18 assert a - b == 2 print('測試結束!')

  執行結果,遇到斷言失敗即終止測試,最後的 print 沒有列印:

E:\personal\python38\python.exe E:/personal/GitWorkSpace/pytest_basic/main.py
test_demo_18_assume.py::test_calc_1
當前用例執行測試環境:http://xx.xx.xx.xx:xxxx
F
================================== FAILURES ===================================
_________________________________
test_calc_1 _________________________________ def test_calc_1(): assert a / b == 2 > assert a + b == 8 E assert (6 + 3) == 8 test_demo_18_assume.py:12: AssertionError =========================== short test summary info =========================== FAILED test_demo_18_assume.py::test_calc_1
- assert (6 + 3) == 8 1 failed in 0.13s Process finished with exit code 0

5、assume 斷言

import pytest

def test_calc_2():
    pytest.assume(a / b == 2)
    pytest.assume(a + b == 8)
    pytest.assume(a * b == 18)
    pytest.assume(a - b == 2)
    print('測試結束!')

  執行結果,後面斷言即使失敗,仍然繼續執行後面的程式碼。

E:\personal\python38\python.exe E:/personal/GitWorkSpace/pytest_basic/main.py
test_demo_18_assume.py::test_calc_2
當前用例執行測試環境:http://xx.xx.xx.xx:xxxx
測試結束!
F
================================== FAILURES ===================================
_________________________________ test_calc_2 _________________________________

tp = <class 'pytest_assume.plugin.FailedAssumption'>, value = None, tb = None

    def reraise(tp, value, tb=None):
        try:
            if value is None:
                value = tp()
            if value.__traceback__ is not tb:
>               raise value.with_traceback(tb)
E               pytest_assume.plugin.FailedAssumption: 
E               2 Failed Assumptions:
E               
E               test_demo_18_assume.py:21: AssumptionFailure
E               >>    pytest.assume(a + b == 8)
E               AssertionError: assert False
E               
E               test_demo_18_assume.py:23: AssumptionFailure
E               >>    pytest.assume(a - b == 2)
E               AssertionError: assert False

..\..\python38\lib\site-packages\six.py:702: FailedAssumption
=========================== short test summary info ===========================
FAILED test_demo_18_assume.py::test_calc_2 - pytest_assume.plugin.FailedAssum...
1 failed in 0.19s

Process finished with exit code 0