pytest(11):assert斷言
阿新 • • 發佈:2020-10-13
前言
一條測試用例必須要有斷言才是完整的用例,沒有斷言的用例是沒有靈魂的,雖然斷言的作用非常大,但使用起來非常簡單。
例子:
# content of test_sample.py def inc(x): return x + 1 def test_answer(): assert inc(3) == 5
執行結果:
$ pytest =========================== test session starts ============================ platform linux -- Python 3.x.y, pytest-6.x.y, py-1.x.y, pluggy-0.x.y cachedir: $PYTHON_PREFIX/.pytest_cache rootdir: $REGENDOC_TMPDIR collected 1 item test_sample.py F [100%] ================================= FAILURES ================================= _______________________________ test_answer ________________________________ def test_answer():> assert inc(3) == 5 E assert 4 == 5 E + where 4 = inc(3) test_sample.py:6: AssertionError ========================= short test summary info ========================== FAILED test_sample.py::test_answer - assert 4 == 5 ============================ 1 failed in 0.12s =============================
錯誤原因顯示4==5所以會斷言錯誤。
常用斷言
pytest裡面斷言實際上就是python裡面的assert斷言方法,常用的有以下幾種
- assert xx 判斷xx為真
- assert not xx 判斷xx不為真
- assert a in b 判斷b包含a
- assert a == b 判斷a等於b
- assert a != b 判斷a不等於b
import pytest def is_true(a): if a > 0: return True else: return False def test_001():
'''斷言為真''' a = 5 b = -1 assert is_true(a) assert not is_true(b) def test_02(): '''斷言b包含 a''' a = "zeng" b = "zengxuejie" assert a in b def test_03(): '''斷言相等''' a = "zeng" b = "zeng" assert a == b def test_04(): '''斷言不等於''' a = 5 b = 6 assert a != b
總體而言,斷言很重要,但是使用起來不復雜,是測試用例必不可少的一部分。
關注個人公眾號:測試開發進階之路