
- Pytest 教程
- Pytest - 首頁
- Pytest - 簡介
- Pytest - 環境設定
- 識別測試檔案和功能
- Pytest - 從基本測試開始
- Pytest - 檔案執行
- 執行測試套件的一個子集
- 測試名稱的子字串匹配
- Pytest - 對測試分組
- Pytest - 夾具
- Pytest - conftest.py
- Pytest - 引數化測試
- Pytest - Xfail/跳過測試
- 在 N 次測試失敗後停止測試套件
- Pytest - 並行執行測試
- XML 中的測試執行結果
- Pytest - 總結
- Pytest - 結論
- Pytest 實用資源
- Pytest - 快速指南
- Pytest - 實用資源
- Pytest - 討論
Pytest - conftest.py
我們可以在此檔案中定義夾具函式,以使其可以在多個測試檔案中訪問。
建立一個新檔案 **conftest.py**,並將以下程式碼新增到其中 -
import pytest @pytest.fixture def input_value(): input = 39 return input
編輯 **test_div_by_3_6.py** 以刪除夾具函式 -
import pytest def test_divisible_by_3(input_value): assert input_value % 3 == 0 def test_divisible_by_6(input_value): assert input_value % 6 == 0
建立一個新檔案 **test_div_by_13.py** -
import pytest def test_divisible_by_13(input_value): assert input_value % 13 == 0
現在,我們有了檔案 **test_div_by_3_6.py** 和 **test_div_by_13.py**,它們使用 **conftest.py** 中定義的夾具。
透過執行以下命令執行測試 -
pytest -k divisible -v
以上命令將生成以下結果 -
test_div_by_13.py::test_divisible_by_13 PASSED test_div_by_3_6.py::test_divisible_by_3 PASSED test_div_by_3_6.py::test_divisible_by_6 FAILED ============================================== FAILURES ============================================== ________________________________________ test_divisible_by_6 _________________________________________ input_value = 39 def test_divisible_by_6(input_value): > assert input_value % 6 == 0 E assert (39 % 6) == 0 test_div_by_3_6.py:7: AssertionError ========================== 1 failed, 2 passed, 6 deselected in 0.09 seconds ==========================
測試將在同一檔案中查詢夾具。由於在檔案中未找到夾具,因此它將在 conftest.py 檔案中查詢夾具。在找到它後,將呼叫夾具方法並將結果返回給測試的輸入引數。
廣告