From 97a08937e9c7647553e6535b55efebfac1f3e883 Mon Sep 17 00:00:00 2001 From: Adam Johnson Date: Mon, 20 Apr 2026 13:50:13 +0100 Subject: [PATCH] Fix a crash with Faker installed and plugin disabled Fixes #718. --- CHANGELOG.rst | 4 ++++ src/pytest_randomly/__init__.py | 17 ++++++++++++----- tests/test_pytest_randomly.py | 12 ++++++++++++ 3 files changed, 28 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.rst b/CHANGELOG.rst index 07ea4d0..f396c02 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -2,6 +2,10 @@ Changelog ========= +* Fix a crash with Faker installed when explicitly enabling and disabling the plugin (via ``-p randomly -p no:randomly``). + + Thanks to mojosan77 for the report in `Issue #718 `__. + * Drop Python 3.9 support. 4.0.1 (2025-09-12) diff --git a/src/pytest_randomly/__init__.py b/src/pytest_randomly/__init__.py index d4de74c..1888f87 100644 --- a/src/pytest_randomly/__init__.py +++ b/src/pytest_randomly/__init__.py @@ -265,8 +265,15 @@ def _crc32(string: str) -> int: if have_faker: # pragma: no branch @fixture(autouse=True) - def faker_seed(pytestconfig: Config, request: SubRequest) -> int: - result: int = pytestconfig.getoption("randomly_seed") + _crc32( - request.node.nodeid - ) - return result + def faker_seed(pytestconfig: Config, request: SubRequest) -> Any: + from faker.contrib.pytest.plugin import DEFAULT_SEED + + seed = pytestconfig.getoption("randomly_seed") + if seed in ("default", "last"): + # pytest-randomly has been imported but disabled, so + # pytest_configure hasn't run to set the seed. Fall back to + # Faker's default seed. + return DEFAULT_SEED + else: + result: int = seed + _crc32(request.node.nodeid) + return result diff --git a/tests/test_pytest_randomly.py b/tests/test_pytest_randomly.py index 7d41a15..2846688 100644 --- a/tests/test_pytest_randomly.py +++ b/tests/test_pytest_randomly.py @@ -633,6 +633,18 @@ def test_two(faker): out.assert_outcomes(passed=2) +def test_faker_enabled_disabled(monkeypatch, ourtester): + ourtester.makepyfile( + test_one=""" + def test_one(faker): + assert faker.name() == 'Norma Fisher' + """ + ) + + out = ourtester.runpytest("-p", "randomly", "-p", "no:randomly") + out.assert_outcomes(passed=1) + + def test_model_bakery(ourtester): """ Check the Model Bakery random generator is reset between tests.