python-pytest-ops
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChinesePython pytest Patterns
Python pytest 测试模式
Modern pytest patterns for effective testing.
用于高效测试的现代pytest模式。
Basic Test Structure
基础测试结构
python
import pytest
def test_basic():
"""Simple assertion test."""
assert 1 + 1 == 2
def test_with_description():
"""Descriptive name and docstring."""
result = calculate_total([1, 2, 3])
assert result == 6, "Sum should equal 6"python
import pytest
def test_basic():
"""Simple assertion test."""
assert 1 + 1 == 2
def test_with_description():
"""Descriptive name and docstring."""
result = calculate_total([1, 2, 3])
assert result == 6, "Sum should equal 6"Fixtures
Fixture
python
import pytest
@pytest.fixture
def sample_user():
"""Create test user."""
return {"id": 1, "name": "Test User"}
@pytest.fixture
def db_connection():
"""Fixture with setup and teardown."""
conn = create_connection()
yield conn
conn.close()
def test_user(sample_user):
"""Fixtures injected by name."""
assert sample_user["name"] == "Test User"python
import pytest
@pytest.fixture
def sample_user():
"""Create test user."""
return {"id": 1, "name": "Test User"}
@pytest.fixture
def db_connection():
"""Fixture with setup and teardown."""
conn = create_connection()
yield conn
conn.close()
def test_user(sample_user):
"""Fixtures injected by name."""
assert sample_user["name"] == "Test User"Fixture Scopes
Fixture 作用域
python
@pytest.fixture(scope="function") # Default - per test
@pytest.fixture(scope="class") # Per test class
@pytest.fixture(scope="module") # Per test file
@pytest.fixture(scope="session") # Entire test runpython
@pytest.fixture(scope="function") # Default - per test
@pytest.fixture(scope="class") # Per test class
@pytest.fixture(scope="module") # Per test file
@pytest.fixture(scope="session") # Entire test runParametrize
参数化测试
python
@pytest.mark.parametrize("input,expected", [
(1, 2),
(2, 4),
(3, 6),
])
def test_double(input, expected):
assert double(input) == expectedpython
@pytest.mark.parametrize("input,expected", [
(1, 2),
(2, 4),
(3, 6),
])
def test_double(input, expected):
assert double(input) == expectedMultiple parameters
Multiple parameters
@pytest.mark.parametrize("x", [1, 2])
@pytest.mark.parametrize("y", [10, 20])
def test_multiply(x, y): # 4 test combinations
assert x * y > 0
undefined@pytest.mark.parametrize("x", [1, 2])
@pytest.mark.parametrize("y", [10, 20])
def test_multiply(x, y): # 4 test combinations
assert x * y > 0
undefinedException Testing
异常测试
python
def test_raises():
with pytest.raises(ValueError) as exc_info:
raise ValueError("Invalid input")
assert "Invalid" in str(exc_info.value)
def test_raises_match():
with pytest.raises(ValueError, match=r".*[Ii]nvalid.*"):
raise ValueError("Invalid input")python
def test_raises():
with pytest.raises(ValueError) as exc_info:
raise ValueError("Invalid input")
assert "Invalid" in str(exc_info.value)
def test_raises_match():
with pytest.raises(ValueError, match=r".*[Ii]nvalid.*"):
raise ValueError("Invalid input")Markers
标记器
python
@pytest.mark.skip(reason="Not implemented yet")
def test_future_feature():
pass
@pytest.mark.skipif(sys.platform == "win32", reason="Unix only")
def test_unix_feature():
pass
@pytest.mark.xfail(reason="Known bug")
def test_buggy():
assert broken_function() == expected
@pytest.mark.slow
def test_performance():
"""Custom marker - register in pytest.ini."""
passpython
@pytest.mark.skip(reason="Not implemented yet")
def test_future_feature():
pass
@pytest.mark.skipif(sys.platform == "win32", reason="Unix only")
def test_unix_feature():
pass
@pytest.mark.xfail(reason="Known bug")
def test_buggy():
assert broken_function() == expected
@pytest.mark.slow
def test_performance():
"""Custom marker - register in pytest.ini."""
passMocking
模拟测试
python
from unittest.mock import Mock, patch, MagicMock
def test_with_mock():
mock_api = Mock()
mock_api.get.return_value = {"status": "ok"}
result = mock_api.get("/endpoint")
assert result["status"] == "ok"
@patch("module.external_api")
def test_with_patch(mock_api):
mock_api.return_value = {"data": []}
result = function_using_api()
mock_api.assert_called_once()python
from unittest.mock import Mock, patch, MagicMock
def test_with_mock():
mock_api = Mock()
mock_api.get.return_value = {"status": "ok"}
result = mock_api.get("/endpoint")
assert result["status"] == "ok"
@patch("module.external_api")
def test_with_patch(mock_api):
mock_api.return_value = {"data": []}
result = function_using_api()
mock_api.assert_called_once()pytest-mock (Recommended)
pytest-mock(推荐用法)
python
def test_with_mocker(mocker):
mock_api = mocker.patch("module.api_call")
mock_api.return_value = {"success": True}
result = process_data()
assert result["success"]python
def test_with_mocker(mocker):
mock_api = mocker.patch("module.api_call")
mock_api.return_value = {"success": True}
result = process_data()
assert result["success"]conftest.py
conftest.py 配置
python
undefinedpython
undefinedtests/conftest.py - Shared fixtures
tests/conftest.py - Shared fixtures
import pytest
@pytest.fixture(scope="session")
def app():
"""Application fixture available to all tests."""
return create_app(testing=True)
@pytest.fixture
def client(app):
"""Test client fixture."""
return app.test_client()
undefinedimport pytest
@pytest.fixture(scope="session")
def app():
"""Application fixture available to all tests."""
return create_app(testing=True)
@pytest.fixture
def client(app):
"""Test client fixture."""
return app.test_client()
undefinedQuick Reference
快速参考
| Command | Description |
|---|---|
| Run all tests |
| Verbose output |
| Stop on first failure |
| Run matching tests |
| Run marked tests |
| Rerun last failed |
| Coverage report |
| Parallel (pytest-xdist) |
| 命令 | 描述 |
|---|---|
| 运行所有测试 |
| 详细输出 |
| 首次失败后停止 |
| 运行匹配名称的测试 |
| 运行标记为slow的测试 |
| 重新运行上次失败的测试 |
| 生成覆盖率报告 |
| 并行运行测试(需pytest-xdist) |
Additional Resources
额外资源
- - Factory fixtures, autouse, conftest patterns
./references/fixtures-advanced.md - - Mock, patch, MagicMock, side_effect
./references/mocking-patterns.md - - pytest-asyncio patterns
./references/async-testing.md - - pytest-cov, branch coverage, reports
./references/coverage-strategies.md - - Database fixtures, API testing, testcontainers
./references/integration-testing.md - - Hypothesis framework, strategies, shrinking
./references/property-testing.md - - Test pyramid, organization, isolation strategies
./references/test-architecture.md
- - 工厂Fixture、自动使用、conftest模式
./references/fixtures-advanced.md - - Mock、patch、MagicMock、side_effect
./references/mocking-patterns.md - - pytest-asyncio 模式
./references/async-testing.md - - pytest-cov、分支覆盖率、报告
./references/coverage-strategies.md - - 数据库Fixture、API测试、testcontainers
./references/integration-testing.md - - Hypothesis框架、策略、简化
./references/property-testing.md - - 测试金字塔、组织、隔离策略
./references/test-architecture.md
Scripts
脚本
- - Run tests with recommended options
./scripts/run-tests.sh - - Generate conftest.py boilerplate
./scripts/generate-conftest.sh
- - 使用推荐选项运行测试
./scripts/run-tests.sh - - 生成conftest.py 模板代码
./scripts/generate-conftest.sh
Assets
资源文件
- - Recommended pytest configuration
./assets/pytest.ini.template - - Common fixture patterns
./assets/conftest.py.template
- - 推荐的pytest配置
./assets/pytest.ini.template - - 常见Fixture模式
./assets/conftest.py.template
See Also
另请参阅
Related Skills:
- - Type-safe test code
python-typing-ops - - Async test patterns (pytest-asyncio)
python-async-ops
Testing specific frameworks:
- - TestClient, API testing
python-fastapi-ops - - Database fixtures, transactions
python-database-ops
相关技能:
- - 类型安全的测试代码
python-typing-ops - - 异步测试模式(pytest-asyncio)
python-async-ops
特定框架测试:
- - TestClient、API测试
python-fastapi-ops - - 数据库Fixture、事务
python-database-ops