pytest-rng: Reproducible Randomness for Pytest Tests
pytest-rng is a pytest plugin that provides fixtures to manage and inject reproducible randomness into your tests. It offers a `random.Random` instance (`rng`), a factory to create new instances (`rng_factory`), and access to the current seed (`rng_seed`). Version `1.0.0` is current, and it maintains a stable release cadence for a core pytest plugin, focusing on test stability.
Common errors
-
AttributeError: 'module' object has no attribute 'rng'
cause Attempting to import `rng` directly from the `pytest_rng` package.fix`rng` is a pytest fixture. Do not import it. Instead, declare it as an argument in your test function: `def test_my_feature(rng): ...` -
pytest: error: unrecognized arguments: --rng-seed
cause The `pytest-rng` plugin is not installed or not active in the pytest environment.fixEnsure `pytest-rng` is installed in your testing environment: `pip install pytest-rng`. If running in a virtual environment, make sure it's active. This error can also occur if pytest itself is not installed. -
Tests are still producing non-reproducible random numbers despite `pytest-rng` being installed.
cause The global `random` module or other unseeded random sources are being used instead of the `rng` fixture.fixEnsure all calls to generate randomness within your tests explicitly use the `rng` fixture (e.g., `rng.randint()`, `rng.random()`) instead of `random.randint()` or other global or external randomness functions.
Warnings
- breaking The configuration option for setting the seed changed significantly in v1.0.0.
- gotcha `pytest-rng` does not automatically patch the global `random` module or other randomness sources.
- gotcha Interactions with other randomness libraries (e.g., NumPy's `numpy.random`, `os.urandom`) are not managed by `pytest-rng`.
Install
-
pip install pytest-rng
Imports
- rng
from pytest_rng import rng
def test_my_feature(rng): value = rng.randint(1, 100)
Quickstart
# test_example.py
import os
def test_random_sequence(rng):
"""
Demonstrates using the rng fixture for reproducible randomness.
Run with: pytest test_example.py --rng-seed=123
With --rng-seed=123, rng.randint(1, 100) will consistently be 42
on the first call. (This is for demonstration and might vary with versions).
"""
# Use the rng fixture, which is a seeded random.Random instance
assert isinstance(rng.randint(1, 100), int)
assert isinstance(rng.random(), float)
# Example of running the test with a specific seed to get reproducible results:
# To run this specific test with a consistent seed:
# pytest test_example.py --rng-seed=123