Skip to content

Instantly share code, notes, and snippets.

@voidus
Created September 17, 2024 22:43
Show Gist options
  • Save voidus/af267f7e87f9683b75e8bc1e6ead9628 to your computer and use it in GitHub Desktop.
Save voidus/af267f7e87f9683b75e8bc1e6ead9628 to your computer and use it in GitHub Desktop.
The pytest factoryboy integration we need
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
@voidus
Copy link
Author

voidus commented Oct 2, 2024

Update: just use pytest-randomly

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment