Send value back to fixtures?
Hi everyone,
I was wondering if it is possible to send() a value back to an Iterator fixture (defined using yield)?
From what I tried, it seems that pytest always sends None. It makes sens that the user cannot really decide when to start the tearout phase (which could be triggered by naive sending), but could it be possible to have tests analyze return value, which could be a dict with fixture/value pairs, and then pytest would still orchestrate the teardowns as it usually does, but while sending values in the right order?
This would for exmaple be used as follows:
def test_func(check_capture_fixture):
# .....
return {"check_capture_fixture": False}
make it so that check_capture_fixture knows it recieved False, and could disable its usual tearout for example.
Maybe there's a more natural way to do that, in which case I'm curious.
All the best! Élie
Fixtures may not be controlled from tests
If control is needed use a manager or factory pattern
Tests are not allowed to change the basic setup teardown flow
Custom apis are allowed to do that
One way I would do this is to make check_capture_fixture return an object, so tests can communicate with it:
@dataclass
class CaptureChecker:
check: bool = True
def check_something(self) -> None: ...
@pytest.fixture
def check_capture_fixture() -> Iterator[CaptureChecker]:
checker = CaptureChecker()
yield checker
if checker.check:
checker.check_something()
def test_func(check_capture_fixture: CaptureChecker) -> None:
...
check_capture_fixture.check = False
Ok yes, I think this very reasonable, thanks! (I'll close on monday at work unless done before)
Thanks again for your answers, I will close since you provided a quick workaround.
May I ask though if/why you think this is not a good feature idea in principle? I'm a bit curious. Thanks!
May I ask though if/why you think this is not a good feature idea in principle? I'm a bit curious.
IMHO: Because it's an entirely non-obvious (if not outright confusing) solution to a very rare problem.
Thanks for the feedback 👍