From 183866a144d866f0970b10ea472aa6144d2f6f92 Mon Sep 17 00:00:00 2001 From: denini08 Date: Tue, 21 Apr 2026 11:28:15 -0300 Subject: [PATCH 1/2] fix: seed random generator to prevent flaky parametrized tests --- testing/pytest/test_employee_pytest.py | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/testing/pytest/test_employee_pytest.py b/testing/pytest/test_employee_pytest.py index b08f2cf..61c2b24 100644 --- a/testing/pytest/test_employee_pytest.py +++ b/testing/pytest/test_employee_pytest.py @@ -30,6 +30,15 @@ def test_pay(employee): assert 2137 == employee.pay +# fixture to ensure reproducible random values +# without seed, random.randint() produces different values each run (flaky tests) +@pytest.fixture(scope="session", autouse=True) +def set_random_seed(): + """make tests reproducible by seeding the random number generator.""" + random.seed(42) + yield + + # test can be parametrized using built-in marker @pytest.mark.parametrize( "given_value, expected_value", From f7bf7a75ff697c9052f0631d2618c56016ac39e1 Mon Sep 17 00:00:00 2001 From: denini08 Date: Tue, 21 Apr 2026 12:18:09 -0300 Subject: [PATCH 2/2] fix: seed before test run to prevent flaky parametrized tests --- testing/pytest/test_employee_pytest.py | 24 ++++++------------------ 1 file changed, 6 insertions(+), 18 deletions(-) diff --git a/testing/pytest/test_employee_pytest.py b/testing/pytest/test_employee_pytest.py index 61c2b24..0c590a3 100644 --- a/testing/pytest/test_employee_pytest.py +++ b/testing/pytest/test_employee_pytest.py @@ -3,6 +3,11 @@ import pytest from employee import Employee +# seeded at import time so parametrize decorator gets deterministic values (avoid ) +# without seed, random.randint() produces different values each run (flaky tests) +_rng = random.Random(42) +_random_test_cases = [(_rng.randint(0, 100),) * 2 for _ in range(9)] + # pytest doesn't require TestCase to inherit from anything class EmployeeTestCase: @@ -30,15 +35,6 @@ def test_pay(employee): assert 2137 == employee.pay -# fixture to ensure reproducible random values -# without seed, random.randint() produces different values each run (flaky tests) -@pytest.fixture(scope="session", autouse=True) -def set_random_seed(): - """make tests reproducible by seeding the random number generator.""" - random.seed(42) - yield - - # test can be parametrized using built-in marker @pytest.mark.parametrize( "given_value, expected_value", @@ -49,15 +45,7 @@ def set_random_seed(): (100, 100), (1999, 1999), (2022, 2022), - tuple([random.randint(0, 100)] * 2), - tuple([random.randint(0, 100)] * 2), - tuple([random.randint(0, 100)] * 2), - tuple([random.randint(0, 100)] * 2), - tuple([random.randint(0, 100)] * 2), - tuple([random.randint(0, 100)] * 2), - tuple([random.randint(0, 100)] * 2), - tuple([random.randint(0, 100)] * 2), - tuple([random.randint(0, 100)] * 2), + *_random_test_cases, ], ) def test_very_simple(given_value, expected_value):