name: python-testing description: Python 測試速查。當需要:(1) 執行 pytest 測試 (2) 使用 mock/patch (3) 引數化測試 (4) fixtures (5) 非同步測試 (6) 覆蓋率測試時使用。
小蔥技能站7w4.net每天更新,海量AI技能等你發現。
Python 測試框架核心用法速查。
pytest # 執行所有測試
pytest -v # 詳細輸出
pytest test_module.py # 指定檔案
pytest -k "login" # 匹配測試名
pytest -x # 失敗時停止
pytest -n 4 # 並行執行
def test_addition():
assert 1 + 1 == 2
@pytest.mark.parametrize("a,b,expected", [(1,2,3), (2,3,5)])
def test_add(a, b, expected):
assert add(a, b) == expected
from unittest.mock import Mock, patch
mock_db = Mock()
mock_db.query.return_value = []
@patch('module.function')
def test_with_mock(mock_func):
mock_func.return_value = 42
@pytest.fixture
def database():
db = Database(":memory:")
yield db
db.close()
def test_query(database):
assert database.query("SELECT 1")
pytest --cov=myapp
pytest --cov=myapp --cov-report=html
@pytest.mark.slow # 標記慢測試
@pytest.mark.integration # 標記整合測試
@pytest.mark.skip(reason="TODO")
@pytest.mark.skipif(sys.version_info < (3, 10))
[pytest]
testpaths = tests
python_files = test_*.py
markers =
slow: marks tests as slow
integration: integration tests
addopts = -v --tb=short
這是一個實用的 Python 測試速查工具,覆蓋了 pytest、Mock、Fixtures 等常用測試場景,程式碼示例豐富,分類清晰,方便快速查詢。不過高階功能和最佳實踐指南相對有限,非同步測試部分內容較少。對於日常簡單測試需求來說足夠使用,但如果需要更深入的應用或解決疑難問題,可能還需要參考其他資料補充學習。