Skip to content

Support for "yield" fixtures #16

Closed

Description

@njsmith

Pytest allows fixtures to contain a yield, and do both setup and teardown:

@pytest.fixture
def http_server():
    server = start_server()
    yield
    server.stop()

We should support this for async fixtures.

It looks like the way Pytest does this is that when it calls a fixture function (in _pytest.fixtures.call_fixture_func), and it detects that the function is a generator, then it calls request.addfinalizer to make sure the cleanup happens.

I don't think this works for us... I guess what we would need to do is to do a second pass over the the fixture tree to call some AsyncFixture.cleanup method, and then implement that for fixtures that are async generators?

Ugh, Pytest is so confusing and complicated.

Activity

  1. touilleMan commented on Dec 11, 2017

    @touilleMan
    Member

    I think we can implement this in the _bootstrap_fixture_and_run_test function:

    async def _bootstrap_fixture_and_run_test(**kwargs):
        async_funcs, async_generators = extract_async_generators(kwargs)
    
        kwargs = await _resolve_coroutine_fixtures_in(async_funcs)
    
        for key, agen in async_generators.items():
            kwargs[key] = await agen.asend(None)
    
        await testfunc(**kwargs)
    
        for key, agen in async_generators.items():
            try:
                await agen.asend(None)
            except StopAsyncIteration:
                pass
            else:
                raise RuntimeError('%s fixture has more than one yield !' % key)
  2. touilleMan commented on Dec 11, 2017

    @touilleMan
    Member

    Well only trouble in my example is if the async generator fixture contains itself async fixtures.
    I think we can solve this by customizing _install_coroutine_fixture_if_needed to make it install CoroutineFixture for regular async fixture and a new AsyncGeneratorFixture which resolve method would only resolve the fixture's fixtures and return the async generator function ready to be used (i.e. with a partial or a wrapper function injecting it parameter fixtures).

  3. njsmith commented on Dec 11, 2017

    @njsmith
    MemberAuthor

    Yeah, the problem is that in general async generator fixtures could appear anywhere in the fixture DAG, so whatever we do with them is going to need to somehow involve a recursion over that DAG.

  4. touilleMan commented on Dec 15, 2017

    @touilleMan
    Member

    implemented in #17

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions