pytest icon indicating copy to clipboard operation
pytest copied to clipboard

Send value back to fixtures?

Open ego-thales opened this issue 6 months ago • 3 comments

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

ego-thales avatar Jun 13 '25 12:06 ego-thales

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

RonnyPfannschmidt avatar Jun 13 '25 15:06 RonnyPfannschmidt

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   

nicoddemus avatar Jun 13 '25 17:06 nicoddemus

Ok yes, I think this very reasonable, thanks! (I'll close on monday at work unless done before)

eliegoudout avatar Jun 15 '25 08:06 eliegoudout

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!

ego-thales avatar Jun 16 '25 08:06 ego-thales

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.

The-Compiler avatar Jun 18 '25 15:06 The-Compiler

Thanks for the feedback 👍

ego-thales avatar Jun 19 '25 07:06 ego-thales