pytest-stub
raw JSON → 1.1.0 verified Mon Apr 27 auth: no python
pytest-stub is a plugin for the pytest framework that allows you to conveniently stub packages, modules, attributes, and functions for testing purposes. Version 1.1.0 is actively maintained. Release cadence is low, with occasional updates.
pip install pytest-stub Common errors
error AttributeError: module 'pytest_stub' has no attribute 'stub' ↓
cause Outdated version of pytest-stub (<1.0) or incorrect import: the `stub` function may not exist in older versions.
fix
Upgrade to latest:
pip install --upgrade pytest-stub and import from pytest_stub import stub. error TypeError: 'str' object is not callable ↓
cause Attempting to call the stub object (returned from stub() context manager) directly instead of using `.return_value`.
fix
Access the mock object via the context variable and set
.return_value: e.g., with stub('x') as m: m.return_value = 1. Warnings
gotcha Do not use `stub` in a global context; always use as a context manager or fixture. Otherwise stubs may persist across tests. ↓
fix Use `with stub('...') as m:` inside a test or fixture.
gotcha The stub target must be an importable path; e.g., 'package.module.attr'. Stubbing builtins (like 'print') does not work because builtins are not modules. ↓
fix Only stub attributes reachable via a module path.
Imports
- stub wrong
import pytest_stubcorrectfrom pytest_stub import stub
Quickstart
import pytest
from pytest_stub import stub
@pytest.fixture
def stubbed_random():
with stub('random.randint') as m:
m.return_value = 42
yield
def test_random(stubbed_random):
import random
assert random.randint(1, 10) == 42