-
-
Notifications
You must be signed in to change notification settings - Fork 154
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #1028 from nolar/manage-uvloop-in-tests
Manage uvloop's loops & policies properly in tests
- Loading branch information
Showing
2 changed files
with
75 additions
and
37 deletions.
There are no files selected for viewing
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
import asyncio | ||
import contextlib | ||
from typing import Generator, Optional | ||
|
||
|
||
@contextlib.contextmanager | ||
def proper_loop(suggested_loop: Optional[asyncio.AbstractEventLoop] = None) -> Generator[None, None, None]: | ||
""" | ||
Ensure that we have the proper loop, either suggested or properly managed. | ||
A "properly managed" loop is the one we own and therefore close. | ||
If ``uvloop`` is installed, it is used. | ||
Otherwise, the event loop policy remains unaffected. | ||
This loop manager is usually used in CLI only, not deeper than that; | ||
i.e. not even in ``kopf.run()``, since uvloop is only auto-managed for CLI. | ||
""" | ||
original_policy = asyncio.get_event_loop_policy() | ||
if suggested_loop is None: # the pure CLI use, not a KopfRunner or other code | ||
try: | ||
import uvloop | ||
except ImportError: | ||
pass | ||
else: | ||
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) | ||
|
||
try: | ||
yield | ||
|
||
finally: | ||
try: | ||
import uvloop | ||
except ImportError: | ||
pass | ||
else: | ||
asyncio.set_event_loop_policy(original_policy) |
This file contains 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