Skip to content
This repository has been archived by the owner on Oct 1, 2024. It is now read-only.

fix: [382] not starting another event loop #384

Draft
wants to merge 1 commit into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions ward/_utilities.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import asyncio
import collections
import inspect
from pathlib import Path
import sys
from typing import Any, Callable, Dict, Hashable, Iterable, List, Optional, TypeVar


Expand Down Expand Up @@ -43,3 +45,15 @@ def group_by(items: Iterable[T], key: Callable[[T], H]) -> Dict[H, List[T]]:
for item in items:
groups[key(item)].append(item)
return dict(groups)

def get_current_event_loop() -> asyncio.AbstractEventLoop:
if sys.version_info < (3, 10):
loop = asyncio.get_event_loop()
else:
try:
loop = asyncio.get_running_loop()
except RuntimeError:
loop = asyncio.new_event_loop()

asyncio.set_event_loop(loop)
return loop
4 changes: 2 additions & 2 deletions ward/fixtures.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import asyncio
import inspect
from contextlib import ExitStack, redirect_stderr, redirect_stdout, suppress
from dataclasses import dataclass
Expand All @@ -7,6 +6,7 @@
from pathlib import Path
from typing import Any, AsyncGenerator, Callable, Generator, List, Optional, Union, cast

from ward._utilities import get_current_event_loop
from ward.models import CollectionMetadata, Scope

__all__ = ["fixture", "using", "Fixture", "TeardownResult"]
Expand Down Expand Up @@ -137,7 +137,7 @@ def teardown(self, capture_output: bool) -> "TeardownResult":
next(cast(Generator, self.gen))
elif self.is_async_generator_fixture and self.gen:
awaitable = cast(AsyncGenerator, self.gen).__anext__()
asyncio.run(awaitable)
get_current_event_loop().run_until_complete(awaitable)
except Exception as e:
# Note that with StopIterations being suppressed, we have an issue
# that if a StopIteration occurs in fixture teardown code, it will
Expand Down
9 changes: 4 additions & 5 deletions ward/testing.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import asyncio
import collections
import functools
import inspect
Expand Down Expand Up @@ -31,7 +30,7 @@
_Timer,
is_test_module_name,
)
from ward._utilities import get_absolute_path
from ward._utilities import get_absolute_path, get_current_event_loop
from ward.fixtures import Fixture
from ward.models import CollectionMetadata, Marker, Scope, SkipMarker, XfailMarker

Expand Down Expand Up @@ -197,7 +196,7 @@ def run(self, cache: FixtureCache, dry_run=False) -> "TestResult": # noqa: C901
self.format_description(resolved_args)
if self.is_async_test:
coro = self.fn(**resolved_args)
asyncio.run(coro)
get_current_event_loop().run_until_complete(coro)
else:
self.fn(**resolved_args)
except FixtureError as e:
Expand Down Expand Up @@ -628,9 +627,9 @@ def _resolve_single_arg(
elif fixture.is_async_generator_fixture:
fixture.gen = arg(**args_to_inject)
awaitable = fixture.gen.__anext__() # type: ignore[union-attr]
fixture.resolved_val = asyncio.run(awaitable)
fixture.resolved_val = get_current_event_loop().run_until_complete(awaitable)
elif fixture.is_coroutine_fixture:
fixture.resolved_val = asyncio.run(arg(**args_to_inject))
fixture.resolved_val = get_current_event_loop().run_until_complete(arg(**args_to_inject))
else:
fixture.resolved_val = arg(**args_to_inject)
except (Exception, SystemExit) as e:
Expand Down
Loading