Fixtures¶
Capture all log records. |
|
Capture stdout and stderr. |
|
Change the current working dir to the given path. |
|
Execute the given callback when leaving the test function. |
|
Delete attribute of an object for the duration of test. |
|
Enter the context manager, return its result, and exit the context when leaving the test function. |
|
Forbid network connections during the test. |
|
Get the path to the root directory of the project. |
|
Get a pytest fixture by its name. |
|
Get meta information about the currently running test. |
|
Create a temporary directory. |
|
Patch attributes of objects for the duration of test. |
|
Restore the current state of the mapping after leaving the test. |
|
Record all warnings (emitted using |
|
Patch an attribute for the duration of test. |
- pytypest.fixtures.capture_logs() LogCaptureFixture ¶
Capture all log records.
A wrapper around caplog pytest fixture.
import logging cap = capture_logs() logging.warning('oh hi mark') record = cap.records[-1] assert record.message == 'oh hi mark'
- pytypest.fixtures.capture_std(*, binary: bool = False, fd: bool = False) CaptureFixture ¶
Capture stdout and stderr.
A wrapper around capsys, capfd, capsysbinary, and capfdbinary pytest fixtures.
cap = capture_std() print('hello') captured = cap.readouterr() assert captured.out.rstrip() == 'hello'
- pytypest.fixtures.chdir(path: Path | str) Iterator[None] ¶
Change the current working dir to the given path.
Similar to pytest.MonkeyPatch.chdir.
chdir('/')
- pytypest.fixtures.defer(callback: Callable[[], object]) Iterator[None] ¶
Execute the given callback when leaving the test function.
It’s a nice way to clean up after a test function without creating a fixture or a context manager.
Similar to pytest.FixtureRequest.addfinalizer.
stream = open('some-file.txt') defer(stream.close)
- pytypest.fixtures.delattr(target: object | str, name: str, *, must_exist: bool = True) Iterator[None] ¶
Delete attribute of an object for the duration of test.
A wrapper around pytest.MonkeyPatch.delattr.
The target can be either the object to patch or the full import path to the object. The target can be any object, including modules, classes, methods, and functions.
delattr(logging, 'info')
- pytypest.fixtures.enter_context(manager: AbstractContextManager[T]) Iterator[T] ¶
Enter the context manager, return its result, and exit the context when leaving the test function.
It’s a bit imilar to contextlib.ExitStack in a sense that it helps to keep code indentation low when entering multiple context managers.
stream = enter_context(open('some_file'))
- pytypest.fixtures.forbid_networking(*, allowed: Sequence[tuple[str, int]] = ()) Iterator[None] ¶
Forbid network connections during the test.
This fixture is a good candidate for
pytypest.autouse()
.The allowed argument accepts a sequence of (host, port) pairs to which connections should still be allowed.
forbid_networking(allowed=[('example.com', 443)])
- pytypest.fixtures.get_project_root() Path ¶
Get the path to the root directory of the project.
root = get_project_root() assert (root / 'pyproject.toml').exists()
https://docs.pytest.org/en/7.1.x/reference/customize.html#finding-the-rootdir
- pytypest.fixtures.get_pytest_fixture(name: str) Any ¶
Get a pytest fixture by its name.
A wrapper around pytest.FixtureRequest.getfixturevalue.
This is useful for using fixtures from third-party pytest plugins. All built-in pytest fixtures already have a convenient wrapper in pytypest.
For example, get
event_loop
fixture from pytest-asyncio:from asyncio import AbstractEventLoop loop: AbstractEventLoop = get_pytest_fixture('event_loop')
- pytypest.fixtures.get_request() FixtureRequest ¶
Get meta information about the currently running test.
A wrapper around request pytest fixture.
request = get_request() verbosity = request.config.getoption("verbose") if verbosity > 0: ...
- pytypest.fixtures.make_temp_dir(basename: str | None = None, numbered: bool = True) Path ¶
Create a temporary directory.
A wrapper around tmp_path and tmp_path_factory pytest fixtures.
- Parameters:
basename – if specified, the created directory will have this name.
numbered – if True (default), ensure the directory is unique by adding a numbered suffix greater than any existing one.
dir_path = fixtures.make_temp_dir() file_path = dir_path / 'example.py' file_path.write_text('1 + 2') ... content = file_path.read_text() assert content == '1 + 2'
- pytypest.fixtures.monkeypatch() Iterator[MonkeyPatch] ¶
Patch attributes of objects for the duration of test.
A wrapper around monkeypatch pytest fixture.
Usually, you don’t need to use this fixture directly. The preferred way to patch things is using
pytypest.fixtures.setattr()
,pytypest.fixtures.delattr()
, andpytypest.fixtures.preserve_mapping()
.
- pytypest.fixtures.preserve_mapping(target: MutableMapping) Iterator[None] ¶
Restore the current state of the mapping after leaving the test.
After calling the fixture, you can safely modify the given mapping, and these changes will be reverted before the next test starts.
It’s not a deep copy, though. If you modify a list inside of the mapping, that modification will escape the test.
import sys preserve_mapping(sys.modules) sys.modules['requests'] = Mock()
- pytypest.fixtures.record_warnings() WarningsRecorder ¶
Record all warnings (emitted using
warnings
module).A wrapper around recwarn pytest fixture.
import warnings rec = fixtures.record_warnings() warnings.warn('oh hi mark', UserWarning) w = rec.pop(UserWarning) assert str(w.message) == 'oh hi mark'
- pytypest.fixtures.setattr(target: object | str, name: str, value: object, *, must_exist: bool = True) Iterator[None] ¶
Patch an attribute for the duration of test.
A wrapper around pytest.MonkeyPatch.setattr.
The target can be either the object to patch or the full import path to the object. The target can be any object, including modules, classes, methods, and functions.
from unittest.mock import Mock mock = Mock() setattr('logging', 'info', mock)