Skip to content

Instantly share code, notes, and snippets.

@malinoff
Created December 9, 2016 06:40
Show Gist options
  • Save malinoff/57e2763c777bc55d048a9fc8ba79c866 to your computer and use it in GitHub Desktop.
Save malinoff/57e2763c777bc55d048a9fc8ba79c866 to your computer and use it in GitHub Desktop.
import asyncio
import pytest
@pytest.hookimpl(hookwrapper=True)
def pytest_fixture_setup(fixturedef, request):
outcome = yield
coro = outcome.result
if asyncio.iscoroutine(coro):
event_loop = request.getfixturevalue('event_loop')
result = event_loop.run_until_complete(coro)
try:
result, finalizer = result
except (TypeError, ValueError):
finalizer = None
cr = fixturedef.cached_result
fixturedef.cached_result = result, cr[1], cr[2]
if finalizer is not None:
fixturedef.addfinalizer(
lambda: event_loop.run_until_complete(finalizer())
)
outcome.result = result
return outcome
pytest test_foo.py -s
============================================================================== test session starts ===============================================================================
platform darwin -- Python 3.5.2, pytest-3.0.5, py-1.4.31, pluggy-0.4.0
rootdir: /Users/malinoff/Projects/opensource/celery/amqproto, inifile:
plugins: cov-2.4.0, asyncio-0.5.0
collected 2 items
test_foo.py ..finalizer called
============================================================================ 2 passed in 0.01 seconds ============================================================================
import pytest
@pytest.fixture()
async def foo():
return 'foo'
@pytest.fixture()
async def foo_with_finalizer():
async def finalizer():
print('finalizer called')
return 'foo', finalizer
def test_foo(foo):
assert foo == 'foo'
def test_foo_with_finalizer(foo_with_finalizer):
assert foo_with_finalizer == 'foo'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment