Skip to content

Commit 51d986c

Browse files
alblascoTinche
authored andcommitted
To solve test cases that fail:
Even_loop() fixture properly closes the loop (but as explained below this is not enough to reset behaviour): ``` @pytest.fixture def event_loop(request): """Create an instance of the default event loop for each test case.""" loop = asyncio.get_event_loop_policy().new_event_loop() yield loop loop.close() ``` Subsequent calls to asyncio.get_event_loop() returns the previous closed loop, instead of providing a new loop. This is due to (https://github.com/python/cpython/blob/3.8/Lib/asyncio/events.py#L634) variable _set_called is True, and so even when loop is None, then no new_event_loop is created [I really don´t know the reason of this _set_called behaviour]. The best solution I have found is to set_event_loop_policy(None). This completely resets global variable and so any subsequent call to asyncio.get_event_loop() provides a new event_loop. I have included this in the pytest hook (pytest_fixture_post_finalizer), that is called after fixture teardowns. Note: Same behaviour can be done modifying event_loop() fixture, but I have discarded it as this would force users that have overwritten even_loop fixture to modify its implementation: ``` @pytest.fixture def event_loop(request): """Create an instance of the default event loop for each test case.""" loop = asyncio.get_event_loop_policy().new_event_loop() yield loop loop.close() asyncio.set_event_loop_policy(None) ```
1 parent f97e900 commit 51d986c

File tree

1 file changed

+8
-0
lines changed

1 file changed

+8
-0
lines changed

pytest_asyncio/plugin.py

+8
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,14 @@ def get_and_strip_from(self, name, data_dict):
7272
del data_dict[name]
7373
return result
7474

75+
@pytest.hookimpl(trylast=True)
76+
def pytest_fixture_post_finalizer(fixturedef, request):
77+
"""Called after fixture teardown"""
78+
if fixturedef.argname == "event_loop":
79+
# Set empty loop policy, so that subsequent get_event_loop() provides a new loop
80+
asyncio.set_event_loop_policy(None)
81+
82+
7583

7684
@pytest.hookimpl(hookwrapper=True)
7785
def pytest_fixture_setup(fixturedef, request):

0 commit comments

Comments
 (0)