Last active
May 8, 2019 08:57
-
-
Save ties/21d75aa31c399e6c9a100232d040f214 to your computer and use it in GitHub Desktop.
Tests basic assumptions about running event loops.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Tests basic assumptions about running event loops. | |
Gets and compares the result of `get_event_loop` with `get_running_loop` before | |
and after setting it to None. | |
A more strict situation than in the documentation holds (for Python 3.7.3), | |
given default event loop policy: | |
`get_event_loop` returns the same result after setting the event loop to None, | |
when ran from a coroutine. | |
Outside coroutines it raises an RuntimeError | |
""" | |
import asyncio | |
async def test_async() -> None: | |
loop_1 = asyncio.get_event_loop() | |
asyncio.set_event_loop(None) | |
running_loop = asyncio.get_running_loop() | |
assert loop_1 == running_loop | |
asyncio.set_event_loop(None) | |
loop_2 = asyncio.get_event_loop() | |
assert loop_1 == loop_2 == running_loop | |
print("Done, all passed.") | |
# restore | |
asyncio.set_event_loop(loop_1) | |
def test_non_async() -> None: | |
loop_1 = asyncio.get_event_loop() | |
assert loop_1 is not None | |
print("There is a default event loop") | |
print("And there is no running loop:") | |
try: | |
asyncio.get_running_loop() | |
print("Unreachable") | |
except RuntimeError as err: | |
print("No running loop outside coroutine, exception:", err) | |
asyncio.set_event_loop(None) | |
print("After `set_event_loop(None)`, getting the loop raises a " | |
"RuntimeError when not in a coroutine") | |
try: | |
asyncio.get_event_loop() | |
print("Unreachable") | |
except RuntimeError as err: | |
print("RuntimeError:", err) | |
# restore | |
asyncio.set_event_loop(loop_1) | |
LOOP = asyncio.get_event_loop() | |
LOOP.run_until_complete(test_async()) | |
test_non_async() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment