Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion CHANGELOG.rst
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,17 @@ Changelog
Unreleased
----------

* Removed the random state caching, which would grow without bound, leaking memory in long test runs.
* Remove the random state caching, which would grow without bound, leaking memory in long test runs.
The caching was added to slightly speed up re-using the same (final) seed, but since the final seed is now different for each test, it has no effect.

`PR #690 <https://github.com/pytest-dev/pytest-randomly/issues/687>`__.

* Modify Numpy seed restriction, replacing hashing with a modulo operation.
The extra work to hash is unnecessary now that we generate a final seed per test with CRC32.
This change saves ~500ns per test when Numpy is installed.

`PR #691 <https://github.com/pytest-dev/pytest-randomly/issues/691>`__.

4.0.0 (2025-09-10)
------------------

Expand Down
17 changes: 3 additions & 14 deletions src/pytest_randomly/__init__.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
from __future__ import annotations

import argparse
import hashlib
import random
import sys
from functools import lru_cache
Expand Down Expand Up @@ -160,8 +159,7 @@ def _reseed(config: Config, offset: int = 0) -> int:
baker_random.setstate(random_state)

if have_numpy: # pragma: no branch
numpy_seed = _truncate_seed_for_numpy(seed)
np_random.seed(numpy_seed)
np_random.seed(seed % 2**32)

if entrypoint_reseeds is None:
eps = entry_points(group="pytest_randomly.random_seeder")
Expand All @@ -172,15 +170,6 @@ def _reseed(config: Config, offset: int = 0) -> int:
return seed


def _truncate_seed_for_numpy(seed: int) -> int:
seed = abs(seed)
if seed <= 2**32 - 1:
return seed

seed_bytes = seed.to_bytes(seed.bit_length(), "big")
return int.from_bytes(hashlib.sha512(seed_bytes).digest()[: 32 // 8], "big")


def pytest_report_header(config: Config) -> str:
seed = config.getoption("randomly_seed")
_reseed(config)
Expand All @@ -189,7 +178,7 @@ def pytest_report_header(config: Config) -> str:

def pytest_runtest_setup(item: Item) -> None:
if item.config.getoption("randomly_reset_seed"):
_reseed(item.config, _crc32(item.nodeid) - 1)
_reseed(item.config, (_crc32(item.nodeid) - 1) % 2**32)


def pytest_runtest_call(item: Item) -> None:
Expand All @@ -199,7 +188,7 @@ def pytest_runtest_call(item: Item) -> None:

def pytest_runtest_teardown(item: Item) -> None:
if item.config.getoption("randomly_reset_seed"):
_reseed(item.config, _crc32(item.nodeid) + 1)
_reseed(item.config, (_crc32(item.nodeid) + 1) % 2**32)


@hookimpl(tryfirst=True)
Expand Down