pytest — The Python Testing Framework That Scales
pytest makes it easy to write small tests, yet scales to support complex functional testing. Fixtures, parameterization, plugins, markers, and a rich assertion introspection system. The de facto testing standard for the Python ecosystem.
Agent 可直接安装
这个资产可安装;Agent 先选择当前运行时、检查安装计划,再运行匹配命令。
npx -y tokrepo@latest install 42405aa1-364b-11f1-9bc6-00163e2b0d79 --target codex先 dry-run 确认安装计划,再运行此命令。
What it is
pytest is the de facto standard testing framework for Python. It supports simple unit tests, complex functional tests, fixtures for dependency injection, parameterized test generation, markers, and a rich assertion introspection system that provides detailed failure messages without boilerplate.
pytest is for Python developers at every level -- from solo scripts to large enterprise codebases with thousands of test cases.
The project is actively maintained with regular releases and a growing user community. Documentation covers common use cases, and the open-source nature means you can inspect the source code, contribute fixes, and adapt the tool to your specific requirements.
How it saves time or tokens
pytest eliminates the ceremony required by unittest. No test classes needed, no self.assertEqual calls. A plain function with an assert statement is a valid test. Fixtures compose automatically, parameterize generates test matrices from data, and the plugin ecosystem (1000+ plugins) handles everything from coverage to parallel execution.
How to use
- Install pytest via pip.
- Write test functions in files named
test_*.pyusing plain assert statements. - Run
pytestfrom your project root to discover and execute all tests.
Example
# test_calc.py
def add(a, b):
return a + b
def test_add_integers():
assert add(2, 3) == 5
def test_add_strings():
assert add('hello ', 'world') == 'hello world'
# Fixtures for shared setup
import pytest
@pytest.fixture
def db_connection():
conn = create_connection()
yield conn
conn.close()
def test_query(db_connection):
result = db_connection.execute('SELECT 1')
assert result is not None
# Parameterized tests
@pytest.mark.parametrize('input,expected', [
(1, 2), (2, 4), (3, 6)
])
def test_double(input, expected):
assert input * 2 == expected
Related on TokRepo
- AI Tools for Testing -- Testing tools and frameworks curated on TokRepo
- AI Tools for Coding -- Developer tools for code quality
Common pitfalls
- Test files must follow the
test_*.pynaming convention or pytest will not discover them. Same for test functions: they must start withtest_. - Fixture scope matters. A session-scoped fixture runs once; a function-scoped fixture runs per test. Using the wrong scope causes either slow tests or shared state bugs.
- Importing the module under test with a relative path fails when running pytest from a different directory. Use
pyproject.tomlorconftest.pyto set the Python path correctly.
Before adopting this tool, evaluate whether it fits your team's existing workflow. Read the official documentation thoroughly, and start with a small proof-of-concept rather than a full migration. Community forums, GitHub issues, and Stack Overflow are valuable resources when you encounter edge cases not covered in the documentation.
常见问题
pytest uses plain functions and assert statements instead of test classes and self.assertEqual methods. It provides automatic fixture injection, parameterized tests, and detailed assertion introspection out of the box. unittest requires more boilerplate for the same functionality.
Fixtures are functions decorated with @pytest.fixture that provide setup and teardown logic. They are injected into test functions by name. Fixtures can be scoped to function, class, module, or session level, and they compose automatically.
Install the pytest-xdist plugin with pip install pytest-xdist, then run pytest -n auto to distribute tests across all available CPU cores. This can reduce test suite execution time dramatically on multi-core machines.
Yes. pytest is backwards compatible with unittest. It can discover and run unittest.TestCase subclasses without any modification. You can gradually migrate from unittest to pytest-style tests.
Use the @pytest.mark.parametrize decorator to supply multiple input/output pairs to a single test function. pytest generates a separate test case for each parameter set, with clear reporting on which combination failed.
引用来源 (3)
- pytest GitHub— pytest is the de facto standard Python testing framework
- pytest Documentation— Fixtures, parameterization, and assertion introspection
- pytest Plugin Directory— 1000+ pytest plugins available
讨论
相关资产
WebdriverIO — Next-Gen Browser and Mobile Testing Framework
WebdriverIO is a progressive automation framework for web and mobile testing built on the WebDriver and Chrome DevTools protocols with a rich plugin system.
Kedro — Production-Ready ML Pipeline Framework for Python
Kedro is an open-source Python framework by McKinsey QuantumBlack that applies software engineering best practices to data science and ML pipelines. It provides a standardized project structure, data catalog, and pipeline abstraction that makes experimental code production-ready.
JUnit 5 — The Programmer-Friendly Testing Framework for Java
JUnit 5 is the next generation of the Java testing framework. It provides a modern, extensible architecture with JUnit Platform, JUnit Jupiter, and JUnit Vintage modules for writing and running tests on the JVM.
Hypothesis — Property-Based Testing for Python
Hypothesis is a Python testing library that generates test cases automatically based on specifications you define, finding edge cases that hand-written tests miss.