
- 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 允許我們在測試函式上使用標記。標記用於設定各種特性/屬性以測試函式。Pytest 提供了許多內建標記,如 xfail、skip 和 parametrize。除此之外,使用者可以建立自己的標記名稱。將使用以下給出的語法在測試中應用標記 −
@pytest.mark.<markername>
要使用標記,我們必須在測試檔案中 匯入 pytest 模組。我們可以將我們自定義的標記名稱定義為測試,並執行具有這些標記名稱的測試。
要執行標記測試,我們可以使用以下語法 −
pytest -m <markername> -v
-m <markername> 表示要執行的測試的標記名稱。
使用以下程式碼更新我們的 test_compare.py 和 test_square.py 測試檔案。我們定義了 3 個標記 – great、square、others。
test_compare.py
import pytest @pytest.mark.great def test_greater(): num = 100 assert num > 100 @pytest.mark.great def test_greater_equal(): num = 100 assert num >= 100 @pytest.mark.others def test_less(): num = 100 assert num < 200
test_square.py
import pytest import math @pytest.mark.square def test_sqrt(): num = 25 assert math.sqrt(num) == 5 @pytest.mark.square def testsquare(): num = 7 assert 7*7 == 40 @pytest.mark.others def test_equality(): assert 10 == 11
現在要執行標記為 others 的測試,執行以下命令 −
pytest -m others -v
檢視下面的結果。它運行了標記為 others 的 2 個測試。
test_compare.py::test_less PASSED test_square.py::test_equality FAILED ============================================== FAILURES ============================================== ___________________________________________ test_equality ____________________________________________ @pytest.mark.others def test_equality(): > assert 10 == 11 E assert 10 == 11 test_square.py:16: AssertionError ========================== 1 failed, 1 passed, 4 deselected in 0.08 seconds ==========================
同樣,我們也可以執行帶有其他標記的測試 – great、compare
廣告