Pytest - 檔案執行



在本章節中,我們將學習如何執行單個測試檔案和多個測試檔案。我們已經建立了測試檔案test_square.py。建立一個包含以下程式碼的新測試檔案test_compare.py

def test_greater():
   num = 100
   assert num > 100

def test_greater_equal():
   num = 100
   assert num >= 100

def test_less():
   num = 100
   assert num < 200

現在,要執行所有檔案中的所有測試(此處為 2 個檔案),我們需要執行以下命令 −

pytest -v

上述命令將執行test_square.pytest_compare.py中的測試。輸出將如下生成 −

test_compare.py::test_greater FAILED
test_compare.py::test_greater_equal PASSED
test_compare.py::test_less PASSED
test_square.py::test_sqrt PASSED
test_square.py::testsquare FAILED
================================================ FAILURES 
================================================
______________________________________________ test_greater 
______________________________________________
   def test_greater():
   num = 100
>  assert num > 100
E  assert 100 > 100

test_compare.py:3: AssertionError
_______________________________________________ testsquare 
_______________________________________________
   def testsquare():
   num = 7
>  assert 7*7 == 40
E  assert (7 * 7) == 40

test_square.py:9: AssertionError
=================================== 2 failed, 3 passed in 0.07 seconds 
===================================

要從特定檔案執行測試,請使用以下語法 −

pytest <filename> -v

現在,執行以下命令 −

pytest test_compare.py -v

上述命令將僅從檔案test_compare.py執行測試。我們的結果將為 −

test_compare.py::test_greater FAILED
test_compare.py::test_greater_equal PASSED
test_compare.py::test_less PASSED
============================================== FAILURES 
==============================================
____________________________________________ test_greater 
____________________________________________
   def test_greater():
   num = 100
>  assert num > 100
E  assert 100 > 100
test_compare.py:3: AssertionError
================================= 1 failed, 2 passed in 0.04 seconds 
=================================
廣告
© . All rights reserved.