使用 pytest
進行測試用例的組織可以通過以下幾個步驟來實現:
項目結構: 首先,你需要一個合理的項目結構來組織你的測試代碼。一個典型的項目結構可能如下:
my_project/
├── src/
│ └── my_module.py
├── tests/
│ ├── __init__.py
│ ├── test_module1.py
│ └── test_module2.py
├── conftest.py
└── pytest.ini
src/
目錄存放你的源代碼。tests/
目錄存放你的測試代碼。conftest.py
用于配置 pytest
,比如設置全局夾具(fixtures)。pytest.ini
是 pytest
的配置文件,可以用來設置一些全局配置選項。編寫測試用例:
在 tests/
目錄下創建測試文件,比如 test_module1.py
和 test_module2.py
。每個測試文件中可以包含多個測試函數。
# tests/test_module1.py
import pytest
from src.my_module import my_function
def test_example1():
assert my_function(2, 3) == 5
def test_example2():
assert my_function(0, 0) == 0
使用夾具(Fixtures):
如果你有一些需要在多個測試函數之間共享的設置和清理代碼,可以使用 pytest
的夾具功能。
# conftest.py
import pytest
@pytest.fixture
def setup_data():
# 設置數據
data = ...
yield data
# 清理數據
...
# tests/test_module1.py
def test_with_fixture(setup_data):
assert setup_data is not None
...
參數化測試:
如果你想對同一個測試函數使用不同的輸入數據進行多次測試,可以使用 pytest.mark.parametrize
裝飾器。
# tests/test_module1.py
import pytest
from src.my_module import my_function
@pytest.mark.parametrize("a, b, expected", [
(2, 3, 5),
(0, 0, 0),
(-1, -1, -2),
])
def test_my_function(a, b, expected):
assert my_function(a, b) == expected
運行測試: 你可以使用以下命令來運行測試:
pytest
這將會自動發現并運行 tests/
目錄下的所有測試文件和測試函數。
生成測試報告:
pytest
支持生成各種格式的測試報告,比如 HTML 報告。你可以使用插件 pytest-html
來生成 HTML 報告。
安裝插件:
pip install pytest-html
生成報告:
pytest --html=report.html
通過以上步驟,你可以有效地組織和管理你的測試用例,確保你的代碼質量和可靠性。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。