pytest-randomly
Pytest-randomly is a pytest plugin that randomly orders tests and controls the random seed. Its primary purpose is to help identify and prevent inter-test dependencies and 'flaky' tests by ensuring tests do not rely on a specific execution order. It also resets the global `random.seed()` at the start of each test and can manage the random states of several other libraries. The current version is 4.0.1, and the project is actively maintained.
Warnings
- gotcha While pytest-randomly shuffles test order and resets the global `random.seed()` before each test, multiple calls to `random` *within a single test function* will produce the same sequence if run with the same overall test session seed. This is by design for reproducibility of a failing test run. If truly unique random sequences per invocation within a single test are desired, the test itself needs to manage its random state more granularly or explicitly disable `pytest-randomly`'s seed reset for that test using `--randomly-dont-reset-seed`.
- gotcha If you use other randomness generators in third-party packages (not explicitly supported by pytest-randomly out-of-the-box, e.g., `factory-boy`, `Faker`, `Model Bakery`, `NumPy`), their random states might not be reset by default, leading to inconsistent test results. You can check the documentation for a list of currently supported libraries.
- gotcha When using `pytest-randomly` with other plugins that affect test collection or ordering, such as `pytest-order`, ensure their configurations do not conflict. For example, `pytest-order` can be used to fix the order of specific tests while still allowing `pytest-randomly` to randomize others.
- gotcha Using the `--random-order-bucket=global` option (which shuffles all tests completely without regard to module or class boundaries) can significantly increase test run times if you have class-scoped or module-scoped fixtures with expensive setup/teardown. This is because these fixtures might be initialized and torn down multiple times as tests from different scopes interleave.
Install
-
pip install pytest-randomly
Imports
- pytest_randomly
This is a pytest plugin and is automatically loaded. Direct imports for its core functionality are not typically needed. Advanced users can register entry points for custom random seeders via 'pytest_randomly.random_seeder'.
Quickstart
import random
def test_first_random():
print(f"\nTest 1 random: {random.randint(1, 100)}")
assert True
def test_second_random():
print(f"\nTest 2 random: {random.randint(1, 100)}")
assert True
# To run this, save as test_example.py and execute in your terminal:
# pytest -s test_example.py
# To reproduce a run, use the seed printed in the output, e.g.:
# pytest -s test_example.py --randomly-seed=123456789