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