Python Testing

快速掌握 pytest 核心用法,涵盖测试、Mock、参数化、Fixture 及覆盖率。

已扫描
适合谁
Python 开发者、自动化测试工程师
不适合谁
无 Python 基础的初学者、非开发类用户
国内可用性
需网络配置。可能需要网络配置或第三方服务可访问。
安装难度
新手友好(★☆☆)。基于终端操作、依赖、API Key 和本地环境要求的初步判断。

安装与下载

openclaw skills install @afine907/python-testing

Skill 说明

命令、参数、文件名以原文为准

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 详解: [references/pytest.md](references/pytest.md) - 完整 pytest 用法
  • Mock 和 Patch: [references/mocking.md](references/mocking.md) - unittest.mock 详解
  • Fixtures: [references/fixtures.md](references/fixtures.md) - fixture 高级用法
  • 异步测试: [references/async.md](references/async.md) - pytest-asyncio
  • 覆盖率: [references/coverage.md](references/coverage.md) - pytest-cov 配置

常用标记

@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/
A
@afine907

已收录 1 个 Skill

相关推荐