pytest-rng: Reproducible Randomness for Pytest Tests

1.0.0 · active · verified Fri Apr 17

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

Warnings

Install

Imports

Quickstart

Create a test file (e.g., `test_example.py`) and define a test function that accepts the `rng` fixture. To observe reproducibility, run `pytest` with the `--rng-seed` CLI option, for instance: `pytest --rng-seed=123`.

# 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

view raw JSON →