← 返回
未分类

Python Testing

Python 测试速查。当需要:(1) 运行 pytest 测试 (2) 使用 mock/patch (3) 参数化测试 (4) fixtures (5) 异步测试 (6) 覆盖率测试时使用。
Python 测试速查:运行 pytest、使用 mock/patch、参数化、fixtures、异步、覆盖率测试。
afine907
未分类 clawhub v1.0.0 1 版本 100000 Key: 无需
★ 0
Stars
📥 305
下载
💾 2
安装
1
版本
#latest

概述

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/

版本历史

共 1 个版本

  • v1.0.0 当前
    2026-05-21 15:24 安全 安全

安全检测

腾讯云安全 (Keen)

安全,无风险
查看报告

腾讯云安全 (Sanbu)

安全,无风险
查看报告

🔗 相关推荐

Linux Ops

afine907
Linux运维速查:进程管理、日志分析、网络诊断、性能监控、用户管理。
★ 0 📥 266

Commit Diff Analyzer

afine907
分析两次 Git 提交之间的代码变更。用户提供两个提交 ID 时使用,用于了解两者之间的改动,包括文件修改等。
★ 0 📥 254

AI Commit Message Generator

afine907
分析暂存的更改并自动生成语义化的提交信息。读取 git diff --staged,分析代码更改,生成符合约定的提交信息。
★ 0 📥 263