- Pytest 教程
- Pytest - 主頁
- Pytest - 簡介
- Pytest - 環境設定
- 識別測試檔案和函式
- Pytest - 從基本測試開始
- Pytest - 檔案執行
- 執行測試套件子集
- 測試名稱的子字串匹配
- Pytest - 分組測試
- Pytest - 輔助函式
- Pytest - Conftest.py
- Pytest - 測試引數化
- Pytest - Xfail/Skip 測試
- 在 N 次測試失敗後停止測試套件
- Pytest - 並行執行測試
- XML 中的測試執行結果
- Pytest - 總結
- Pytest - 結論
- Pytest 有用資源
- Pytest - 快速指南
- Pytest - 有用資源
- Pytest - 討論
Pytest - 從基本測試開始
現在,我們將從我們的第一個 pytest 程式開始。我們首先建立一個目錄,然後在目錄中建立我們的測試檔案。
讓我們按照下面顯示的步驟操作 −
建立一個名為automation的新目錄,並在命令列中導航到該目錄。
建立一個名為test_square.py的檔案,並將以下程式碼新增到該檔案。
import math def test_sqrt(): num = 25 assert math.sqrt(num) == 5 def testsquare(): num = 7 assert 7*7 == 40 def tesequality(): assert 10 == 11
使用以下命令執行測試 −
pytest
上述命令將生成以下輸出 −
test_square.py .F ============================================== FAILURES ============================================== ______________________________________________ testsquare _____________________________________________ def testsquare(): num=7 > assert 7*7 == 40 E assert (7 * 7) == 40 test_square.py:9: AssertionError ================================= 1 failed, 1 passed in 0.06 seconds =================================
檢視結果的第一行。它顯示檔名和結果。F 表示測試失敗,點(.) 表示測試成功。
在該行下方,我們可以看到失敗測試的詳細資訊。它將顯示測試在哪個語句處失敗。在我們的示例中,7*7 與 40 進行相等性比較,這是錯誤的。最後,我們可以看到測試執行摘要,1 個失敗,1 個透過。
不會執行函式 tesequality,因為 pytest 不會將其視為測試,因為其名稱不是test*格式。
現在,執行以下命令並再次檢視結果 −
pytest -v
-v 增加詳細資訊。
test_square.py::test_sqrt PASSED test_square.py::testsquare FAILED ============================================== FAILURES ============================================== _____________________________________________ testsquare _____________________________________________ def testsquare(): num = 7 > assert 7*7 == 40 E assert (7 * 7) == 40 test_square.py:9: AssertionError ================================= 1 failed, 1 passed in 0.04 seconds =================================
現在結果更能說明失敗的測試和透過的測試。
注意 − pytest 命令將執行當前目錄和子目錄中所有格式為test_*或*_test的檔案。
廣告