Skip to content

Commit

Permalink
Setup default loop in test utilities (#2804)
Browse files Browse the repository at this point in the history
* Make set_event_loop(loop) for pytest runners

* Code cleanup

* Update docs

* Add versionchanged

* Add changelog
  • Loading branch information
asvetlov authored Mar 7, 2018
1 parent 20928e1 commit 5853890
Show file tree
Hide file tree
Showing 5 changed files with 27 additions and 3 deletions.
3 changes: 3 additions & 0 deletions CHANGES/2804.feature
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Install a test event loop as default by
``asyncio.set_event_loop()``. The change affects aiohttp test utils
but backward compatibility is not broken for 99.99% of use cases.
2 changes: 1 addition & 1 deletion aiohttp/pytest_plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -203,8 +203,8 @@ def loop(loop_factory, fast, loop_debug):
with loop_context(loop_factory, fast=fast) as _loop:
if loop_debug:
_loop.set_debug(True) # pragma: no cover
asyncio.set_event_loop(_loop)
yield _loop
asyncio.set_event_loop(None)


@pytest.fixture
Expand Down
2 changes: 1 addition & 1 deletion aiohttp/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -410,7 +410,7 @@ def setup_test_loop(loop_factory=asyncio.new_event_loop):
once they are done with the loop.
"""
loop = loop_factory()
asyncio.set_event_loop(None)
asyncio.set_event_loop(loop)
if sys.platform != "win32":
policy = asyncio.get_event_loop_policy()
watcher = asyncio.SafeChildWatcher()
Expand Down
14 changes: 14 additions & 0 deletions docs/testing.rst
Original file line number Diff line number Diff line change
Expand Up @@ -788,6 +788,20 @@ Utilities
The caller should also call teardown_test_loop, once they are done
with the loop.

.. note::

As side effect the function changes asyncio *default loop* by
:func:`asyncio.set_event_loop` call.

Previous default loop is not restored.

It should not be a problem for test suite: every test expects a
new test loop instance anyway.

.. versionchanged:: 3.1

The function installs a created event loop as *default*.

.. function:: teardown_test_loop(loop)

Teardown and cleanup an event_loop created by setup_test_loop.
Expand Down
9 changes: 8 additions & 1 deletion tests/test_loop.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,4 +29,11 @@ async def on_startup_hook(self, app):

@unittest_run_loop
async def test_on_startup_hook(self):
assert self.startup_loop is not None
self.assertIsNotNone(self.startup_loop)

def test_default_loop(self):
self.assertIs(self.loop, asyncio.get_event_loop())


def test_default_loop(loop):
assert asyncio.get_event_loop() is loop

0 comments on commit 5853890

Please sign in to comment.