diff --git a/pytest_asyncio/plugin.py b/pytest_asyncio/plugin.py index 309bdf76..a99e9ec3 100644 --- a/pytest_asyncio/plugin.py +++ b/pytest_asyncio/plugin.py @@ -129,7 +129,12 @@ async def setup(): if kw not in request.keywords: continue policy = asyncio.get_event_loop_policy() - old_loop = policy.get_event_loop() + try: + old_loop = policy.get_event_loop() + except RuntimeError as exc: + if 'no current event loop' not in str(exc): + raise + old_loop = None policy.set_event_loop(loop) fixturedef.addfinalizer(lambda: policy.set_event_loop(old_loop)) diff --git a/tests/test_simple.py b/tests/test_simple.py index 35995d97..152d88f1 100644 --- a/tests/test_simple.py +++ b/tests/test_simple.py @@ -7,7 +7,7 @@ @asyncio.coroutine -def async_coro(loop): +def async_coro(loop=None): """A very simple coroutine.""" yield from asyncio.sleep(0, loop=loop) return 'ok' @@ -143,3 +143,18 @@ def test_asyncio_marker_method(self, event_loop): """Test the asyncio pytest marker in a Test class.""" ret = yield from async_coro(event_loop) assert ret == 'ok' + + +class TestUnexistingLoop: + @pytest.fixture + def remove_loop(self): + old_loop = asyncio.get_event_loop() + asyncio.set_event_loop(None) + yield + asyncio.set_event_loop(old_loop) + + @pytest.mark.asyncio + def test_asyncio_marker_without_loop(self, remove_loop): + """Test the asyncio pytest marker in a Test class.""" + ret = yield from async_coro() + assert ret == 'ok'