builtin
Overview
The [builtin](/projects/286/67223) file serves as a centralized documentation hub for **pytest's built-in API and fixtures**. Rather than implementing functionality directly, it primarily provides detailed descriptions of the most commonly used builtin fixtures and APIs offered by pytest, acting as a comprehensive reference guide for users writing tests with pytest.
This file organizes the documentation for pytest's builtin fixtures, explaining their purposes, usage patterns, parameters (where applicable), and examples. It also points users to more detailed API references and specific pytest subsystems such as plugins, marks, and fixtures.
The documentation covers fixtures related to:
Output capturing (
capsys,capfd, etc.)Temporary file and directory handling (
tmpdir,tmp_path, etc.)Logging capture (
caplog)Warning capture (
recwarn)Configuration access (
pytestconfig)Monkeypatching (
monkeypatch)Test result recording (
record_property,record_xml_attribute, etc.)Doctest namespace injection (
doctest_namespace)
Since this file does not contain executable code or class/function definitions, it acts as an extended help page or builtin reference, guiding users to understand and effectively use pytest's builtin fixtures.
Detailed Descriptions of Fixtures and APIs
Below is an elaboration of the documented pytest builtin fixtures and APIs described in this file.
1. cache
Purpose: Provides a persistent cache object that retains state across test runs.
Key Methods:
cache.get(key, default): Retrieve a cached value by key.cache.set(key, value): Store a value in the cache under the given key.
Key Points:
Keys are
/separated strings, typically prefixed by the plugin or app name.Values must be JSON-serializable.
Example:
def test_cache_example(cache): previous_value = cache.get("myplugin/last_run", None) # ... test logic ... cache.set("myplugin/last_run", "2024-06-01")
2. capsys
Purpose: Captures writes to
sys.stdoutandsys.stderras text.Return: A
CaptureFixture[str]instance with methodreadouterr()returning(out, err)strings.Use Case: Test functions that produce output to console.
Example:
def test_output(capsys): print("hello") captured = capsys.readouterr() assert captured.out == "hello\n"
3. capteesys
Purpose: Captures and simultaneously passes through (live-prints)
sys.stdoutandsys.stderras text.Return: A
CaptureFixture[str]instance.Example:
def test_output(capteesys): print("hello") captured = capteesys.readouterr() assert captured.out == "hello\n"
4. capsysbinary
Purpose: Captures writes to
sys.stdoutandsys.stderras bytes.Return: A
CaptureFixture[bytes]instance.Example:
def test_output(capsysbinary): print("hello") captured = capsysbinary.readouterr() assert captured.out == b"hello\n"
5. capfd
Purpose: Captures writes to file descriptors 1 and 2 (stdout and stderr) as text.
Return: A
CaptureFixture[str]instance.Example:
def test_system_echo(capfd): import os os.system('echo "hello"') captured = capfd.readouterr() assert captured.out == "hello\n"
6. capfdbinary
Purpose: Captures writes to file descriptors 1 and 2 as bytes.
Return: A
CaptureFixture[bytes]instance.Example:
def test_system_echo(capfdbinary): import os os.system('echo "hello"') captured = capfdbinary.readouterr() assert captured.out == b"hello\n"
7. doctest_namespace
Scope: Session
Purpose: Provides a dictionary injected into the namespace of doctests.
Usage: Commonly used with autouse fixtures to add modules or variables to doctest environments.
Example:
@pytest.fixture(autouse=True) def add_np(doctest_namespace): import numpy doctest_namespace["np"] = numpy
8. pytestconfig
Scope: Session
Purpose: Provides access to the pytest
Configobject for the active session.Example:
def test_verbosity(pytestconfig): if pytestconfig.get_verbosity() > 0: print("Verbose mode is on")
9. record_property
Purpose: Allows adding custom properties to the current test report.
Usage: Callable with
(name, value).Effect: Properties are included in test reports and can be used by reporters like JUnit XML.
Example:
def test_function(record_property): record_property("example_key", 1)
10. record_xml_attribute
Purpose: Add custom XML attributes to the test's XML tag.
Usage: Callable with
(name, value).
11. record_testsuite_property
Scope: Session
Purpose: Add properties to the root
<testsuite>tag in JUnit XML reports.Usage: Callable with
(name, value).Notes: Does not currently work with
pytest-xdist.Example:
def test_foo(record_testsuite_property): record_testsuite_property("ARCH", "PPC") record_testsuite_property("STORAGE_TYPE", "CEPH")
12. tmpdir_factory
Scope: Session
Purpose: Provides a
TempdirFactoryinstance to create temporary directories shared during the whole test session.
13. tmpdir
Purpose: Provides a temporary directory unique to each test function, represented as a legacy
py.path.localobject.Notes: Usage of
tmp_pathis preferred nowadays.Details: Temporary directories are created under a configurable base temp directory.
Reference: See
temporary directory location and retentionin pytest docs.
14. caplog
Purpose: Access and control logging capture during tests.
Available Attributes:
caplog.messages— list of formatted log messages.caplog.text— formatted log output as string.caplog.records— list oflogging.LogRecordinstances.caplog.record_tuples— list of(logger_name, level, message)tuples.
Methods:
caplog.clear()— clear captured logs.
Use Case: Assert that certain logs were emitted during tests.
15. monkeypatch
Purpose: Convenient fixture for monkeypatching objects, dictionaries, or environment variables.
Key Methods:
setattr(obj, name, value, raising=True)delattr(obj, name, raising=True)setitem(mapping, name, value)delitem(obj, name, raising=True)setenv(name, value, prepend=None)delenv(name, raising=True)syspath_prepend(path)chdir(path)context()— returns a context manager to apply patches temporarily.
Behavior: All changes are reverted after the test or fixture completes.
Example:
def test_env(monkeypatch): monkeypatch.setenv('MYVAR', 'value') assert os.environ['MYVAR'] == 'value'
16. recwarn
Purpose: Fixture that returns a
WarningsRecorderinstance to record all warnings emitted during test execution.Use Case: Test that certain warnings are issued.
See Also: pytest warnings documentation.
17. tmp_path_factory
Scope: Session
Purpose: Provides a
TempPathFactoryinstance for creating temporary directories during the test session.
18. tmp_path
Purpose: Provides a temporary directory unique to each test function, represented as a
pathlib.Pathobject.Notes: Preferred over
tmpdir.Details: Directory created under a configurable base temporary directory.
Implementation Details & Algorithms
This file itself is not an implementation module but a documentation page generated from pytest internals.
Fixtures described here are implemented in various pytest internal modules (e.g.,
_pytest/capture.py,_pytest/tmpdir.py,_pytest/monkeypatch.py, etc.) as indicated by the inline references.Many fixtures provide complex functionality via hooks into pytest's runtime, such as output capturing via patching standard streams, or monkeypatching via careful attribute and environment manipulation with automatic cleanup.
Temporary directory fixtures rely on pytest's temp directory management system, which ensures isolation and cleanup based on configuration.
Logging capture via
caplogintercepts Python logging records emitted during test execution.The
record_propertyand related fixtures interact with pytest's reporting system to enrich test reports with user-defined metadata.The
doctest_namespacefixture integrates with the doctest plugin to inject variables into doctest contexts automatically.
Interactions with Other System Components
pytest Core: These fixtures are tightly integrated with pytest's core test running engine and hook system.
Plugins: Many fixtures and APIs here can be extended or utilized by plugins to enhance test reporting, capturing, and environment management.
Test Reports: Fixtures like
record_propertyandrecord_testsuite_propertyinteract with JUnit XML or other reporting plugins to include additional metadata.Temporary Directory Management:
tmpdir*andtmp_path*fixtures interact with pytest's temp directory lifecycle management.Logging and Warning Capture:
caplogandrecwarnfixtures leverage Python's standard logging and warnings modules to capture and assert behaviors.Monkeypatching: The
monkeypatchfixture facilitates safe environment and object modification, which is essential for isolated test scenarios.Doctest Plugin:
doctest_namespaceinteracts with pytest's doctest subsystem to provide enhanced doctest environments.
Usage Examples Summary
Capturing standard output:
def test_print(capsys): print("hello") captured = capsys.readouterr() assert captured.out == "hello\n"Temporary directory usage:
def test_temp_file(tmp_path): p = tmp_path / "file.txt" p.write_text("hello") assert p.read_text() == "hello"Monkeypatching environment variables:
def test_env(monkeypatch): monkeypatch.setenv('MYVAR', 'value') import os assert os.environ['MYVAR'] == 'value'Recording custom properties for test reporting:
def test_record(record_property): record_property("key", "value")
Mermaid Diagram: pytest Builtin Fixtures Structure
classDiagram
class cache {
+get(key, default)
+set(key, value)
}
class capsys {
+readouterr() : (out:str, err:str)
}
class capteesys {
+readouterr() : (out:str, err:str)
}
class capsysbinary {
+readouterr() : (out:bytes, err:bytes)
}
class capfd {
+readouterr() : (out:str, err:str)
}
class capfdbinary {
+readouterr() : (out:bytes, err:bytes)
}
class doctest_namespace {
<<fixture>>
+dict injected into doctests
}
class pytestconfig {
<<fixture>>
+Config object access
}
class record_property {
+call(name, value)
}
class record_xml_attribute {
+call(name, value)
}
class record_testsuite_property {
+call(name, value)
}
class tmpdir_factory {
<<fixture>>
+TempdirFactory instance
}
class tmpdir {
<<fixture>>
+legacy_path temp directory
}
class tmp_path_factory {
<<fixture>>
+TempPathFactory instance
}
class tmp_path {
<<fixture>>
+pathlib.Path temp directory
}
class caplog {
+messages: list
+text: str
+records: list
+record_tuples: list
+clear()
}
class monkeypatch {
+setattr(obj, name, value, raising)
+delattr(obj, name, raising)
+setitem(mapping, name, value)
+delitem(obj, name, raising)
+setenv(name, value, prepend)
+delenv(name, raising)
+syspath_prepend(path)
+chdir(path)
+context()
}
class recwarn {
+WarningsRecorder instance
}
cache <|-- capsys
capsys <|-- capteesys
capsys <|-- capsysbinary
capfd <|-- capfdbinary
tmpdir_factory <|-- tmpdir
tmp_path_factory <|-- tmp_path
Summary
The [builtin](/projects/286/67223) file is an essential pytest reference document describing builtin fixtures and APIs that facilitate common testing tasks such as output capturing, temporary file management, environment patching, logging, warnings capture, and test metadata recording. It acts as a starting point for pytest users to understand available builtin helpers and how to leverage them in their test suites. The file links to more detailed API references and plugin documentation, ensuring users can explore pytest's rich feature set effectively.
Because it is documentation only, it does not include executable code but comprehensively explains the interfaces provided by pytest core fixtures.