Skip to content

Commit 5853890

Browse files
authored
Setup default loop in test utilities (#2804)
* Make set_event_loop(loop) for pytest runners * Code cleanup * Update docs * Add versionchanged * Add changelog
1 parent 20928e1 commit 5853890

File tree

5 files changed

+27
-3
lines changed

5 files changed

+27
-3
lines changed

CHANGES/2804.feature

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Install a test event loop as default by
2+
``asyncio.set_event_loop()``. The change affects aiohttp test utils
3+
but backward compatibility is not broken for 99.99% of use cases.

aiohttp/pytest_plugin.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -203,8 +203,8 @@ def loop(loop_factory, fast, loop_debug):
203203
with loop_context(loop_factory, fast=fast) as _loop:
204204
if loop_debug:
205205
_loop.set_debug(True) # pragma: no cover
206+
asyncio.set_event_loop(_loop)
206207
yield _loop
207-
asyncio.set_event_loop(None)
208208

209209

210210
@pytest.fixture

aiohttp/test_utils.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -410,7 +410,7 @@ def setup_test_loop(loop_factory=asyncio.new_event_loop):
410410
once they are done with the loop.
411411
"""
412412
loop = loop_factory()
413-
asyncio.set_event_loop(None)
413+
asyncio.set_event_loop(loop)
414414
if sys.platform != "win32":
415415
policy = asyncio.get_event_loop_policy()
416416
watcher = asyncio.SafeChildWatcher()

docs/testing.rst

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -788,6 +788,20 @@ Utilities
788788
The caller should also call teardown_test_loop, once they are done
789789
with the loop.
790790

791+
.. note::
792+
793+
As side effect the function changes asyncio *default loop* by
794+
:func:`asyncio.set_event_loop` call.
795+
796+
Previous default loop is not restored.
797+
798+
It should not be a problem for test suite: every test expects a
799+
new test loop instance anyway.
800+
801+
.. versionchanged:: 3.1
802+
803+
The function installs a created event loop as *default*.
804+
791805
.. function:: teardown_test_loop(loop)
792806

793807
Teardown and cleanup an event_loop created by setup_test_loop.

tests/test_loop.py

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,4 +29,11 @@ async def on_startup_hook(self, app):
2929

3030
@unittest_run_loop
3131
async def test_on_startup_hook(self):
32-
assert self.startup_loop is not None
32+
self.assertIsNotNone(self.startup_loop)
33+
34+
def test_default_loop(self):
35+
self.assertIs(self.loop, asyncio.get_event_loop())
36+
37+
38+
def test_default_loop(loop):
39+
assert asyncio.get_event_loop() is loop

0 commit comments

Comments
 (0)