Python Testing

👤 afine907 📦 v1.0.0 ⭐ 4.4 ⬇️ 824 下載
💻 開發程式設計 免費

📖 技能介紹


name: python-testing description: Python 測試速查。當需要:(1) 執行 pytest 測試 (2) 使用 mock/patch (3) 引數化測試 (4) fixtures (5) 非同步測試 (6) 覆蓋率測試時使用。

小蔥技能站7w4.net每天更新,海量AI技能等你發現。


Python Testing

Python 測試框架核心用法速查。

快速參考

pytest 基礎

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

Mock

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

Fixture

@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.ini 配置

[pytest]
testpaths = tests
python_files = test_*.py
markers =
    slow: marks tests as slow
    integration: integration tests
addopts = -v --tb=short

文件

  • pytest: https://docs.pytest.org/
  • pytest-cov: https://pytest-cov.readthedocs.io/

🤖 AI 評測

這是一個實用的 Python 測試速查工具,覆蓋了 pytest、Mock、Fixtures 等常用測試場景,程式碼示例豐富,分類清晰,方便快速查詢。不過高階功能和最佳實踐指南相對有限,非同步測試部分內容較少。對於日常簡單測試需求來說足夠使用,但如果需要更深入的應用或解決疑難問題,可能還需要參考其他資料補充學習。

📊 多維度評分

適應性3.9
規範性4.4
有效性4.7
可靠性4.4
可信度4.5

📁 包含檔案 (7 個)

📄 SKILL.md 2.2 KB
📄 _meta.json 133 B
📄 references/async.md 1.1 KB
📄 references/coverage.md 830 B
📄 references/fixtures.md 1.6 KB
📄 references/mocking.md 2.4 KB
📄 references/pytest.md 2.2 KB