def wrapper(*args, **kwargs): # type: ignore[no-untyped-def]
request = kwargs["request"] if strip_request: del kwargs["request"]
# if neither the fixture nor the test use the 'loop' fixture, # 'getfixturevalue' will fail because the test is not parameterized # (this can be removed someday if 'loop' is no longer parameterized) if"loop"notin request.fixturenames: raise Exception( "Asynchronous fixtures must depend on the 'loop' fixture or " "be used in tests depending from it."
)
_loop = request.getfixturevalue("loop")
if is_async_gen: # for async generators, we need to advance the generator once, # then advance it again in a finalizer
gen = func(*args, **kwargs)
@contextlib.contextmanager def _runtime_warning_context(): # type: ignore[no-untyped-def] """Context manager which checks for RuntimeWarnings.
This exists specifically to
avoid "coroutine 'X' was never awaited" warnings being missed.
If RuntimeWarnings occur in the context a RuntimeError is raised. """ with warnings.catch_warnings(record=True) as _warnings: yield
rw = [ "{w.filename}:{w.lineno}:{w.message}".format(w=w) for w in _warnings if w.category == RuntimeWarning
] if rw: raise RuntimeError( "{} Runtime Warning{},\n{}".format(
len(rw), ""if len(rw) == 1 else"s", "\n".join(rw)
)
)
Sets up and tears down a loop unless one is passed in via the loop
argument when it's passed straight through. """ if loop: # loop already exists, pass it straight through yield loop else: # this shadows loop_context's standard behavior
loop = setup_test_loop() yield loop
teardown_test_loop(loop, fast=fast)
def pytest_pycollect_makeitem(collector, name, obj): # type: ignore[no-untyped-def] """Fix pytest collecting for coroutines.""" if collector.funcnamefilter(name) and asyncio.iscoroutinefunction(obj): return list(collector._genfunctions(name, obj))
def pytest_pyfunc_call(pyfuncitem): # type: ignore[no-untyped-def] """Run coroutines in an event loop instead of a normal function call."""
fast = pyfuncitem.config.getoption("--aiohttp-fast") if asyncio.iscoroutinefunction(pyfuncitem.function):
existing_loop = pyfuncitem.funcargs.get( "proactor_loop"
) or pyfuncitem.funcargs.get("loop", None) with _runtime_warning_context(): with _passthrough_loop_context(existing_loop, fast=fast) as _loop:
testargs = {
arg: pyfuncitem.funcargs[arg] for arg in pyfuncitem._fixtureinfo.argnames
}
_loop.run_until_complete(pyfuncitem.obj(**testargs))
if uvloop isnotNone: # pragma: no cover
avail_factories["uvloop"] = uvloop.EventLoopPolicy
if loops == "all":
loops = "pyloop,uvloop?"
factories = {} # type: ignore[var-annotated] for name in loops.split(","):
required = not name.endswith("?")
name = name.strip(" ?") if name notin avail_factories: # pragma: no cover if required: raise ValueError( "Unknown loop '%s', available loops: %s"
% (name, list(factories.keys()))
) else: continue
factories[name] = avail_factories[name]
metafunc.parametrize( "loop_factory", list(factories.values()), ids=list(factories.keys())
)
@pytest.fixture def loop(loop_factory, fast, loop_debug): # type: ignore[no-untyped-def] """Return an instance of the event loop."""
policy = loop_factory()
asyncio.set_event_loop_policy(policy) with loop_context(fast=fast) as _loop: if loop_debug:
_loop.set_debug(True) # pragma: no cover
asyncio.set_event_loop(_loop) yield _loop
@pytest.fixture def aiohttp_unused_port() -> Callable[[], int]: """Return a port that is unused on the current host.""" return _unused_port
@pytest.fixture def aiohttp_server(loop: asyncio.AbstractEventLoop) -> Iterator[AiohttpServer]: """Factory to create a TestServer instance, given an app.
aiohttp_server(app, **kwargs) """
servers = []
async def go(
app: Application, *, port: Optional[int] = None, **kwargs: Any
) -> TestServer:
server = TestServer(app, port=port)
await server.start_server(loop=loop, **kwargs)
servers.append(server) return server
yield go
async def finalize() -> None: while servers:
await servers.pop().close()
@pytest.fixture def aiohttp_raw_server(loop: asyncio.AbstractEventLoop) -> Iterator[AiohttpRawServer]: """Factory to create a RawTestServer instance, given a web handler.
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.