Created
September 17, 2024 22:43
-
-
Save voidus/af267f7e87f9683b75e8bc1e6ead9628 to your computer and use it in GitHub Desktop.
The pytest factoryboy integration we need
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from typing import assert_never | |
from uuid import uuid4 | |
from factory import random as factory_random | |
from pytest import ( | |
CallInfo, | |
Item, | |
StashKey, | |
hookimpl, | |
) | |
def pytest_addoption(parser): | |
parser.addoption("--seed", action="store", help="seed to use for faker") | |
randomness_seed_stash_key = StashKey[str]() | |
@hookimpl(tryfirst=True) | |
def pytest_runtest_setup(item: Item): | |
match item.config.getoption("--seed"): | |
case None: | |
seed = uuid4().hex | |
case str() as s: | |
seed = s | |
case x: | |
assert_never(x) # type: ignore | |
factory_random.reseed_random(seed) | |
item.stash[randomness_seed_stash_key] = seed | |
@hookimpl(wrapper=True) | |
def pytest_runtest_makereport(item: Item, call: CallInfo): | |
report = yield | |
if report.failed and (seed := item.stash.get(randomness_seed_stash_key, None)): | |
report.sections.append( | |
( | |
"Re-run with same random seed", | |
f"pytest {item.nodeid} --seed={seed} to re-run with the same randomness", | |
) | |
) | |
return report |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Update: just use pytest-randomly