Debian Codegraph @

third_party/python/aiohttp/aiohttp/pytest_plugin.py

raw
1 import asyncio
2 import contextlib
3 import inspect
4 import warnings
5 from typing import (
6 Any,
7 Awaitable,
8 Callable,
9 Dict,
10 Iterator,
11 Optional,
12 Protocol,
13 Type,
14 Union,
15 )
16
17 import pytest
18
19 from .test_utils import (
20 BaseTestServer,
21 RawTestServer,
22 TestClient,
23 TestServer,
24 loop_context,
25 setup_test_loop,
26 teardown_test_loop,
27 unused_port as _unused_port,
28 )
29 from .web import Application
30 from .web_protocol import _RequestHandler
31
32 try:
33 import uvloop
34 except ImportError: # pragma: no cover
35 uvloop = None # type: ignore[assignment]
36
37
38 class AiohttpClient(Protocol):
39 def __call__(
40 self,
41 __param: Union[Application, BaseTestServer],
42 *,
43 server_kwargs: Optional[Dict[str, Any]] = None,
44 **kwargs: Any
45 ) -> Awaitable[TestClient]: ...
46
47
48 class AiohttpServer(Protocol):
49 def __call__(
50 self, app: Application, *, port: Optional[int] = None, **kwargs: Any
51 ) -> Awaitable[TestServer]: ...
52
53
54 class AiohttpRawServer(Protocol):
55 def __call__(
56 self, handler: _RequestHandler, *, port: Optional[int] = None, **kwargs: Any
57 ) -> Awaitable[RawTestServer]: ...
58
59
60 def pytest_addoption(parser): # type: ignore[no-untyped-def]
61 parser.addoption(
62 "--aiohttp-fast",
63 action="store_true",
64 default=False,
65 help="run tests faster by disabling extra checks",
66 )
67 parser.addoption(
68 "--aiohttp-loop",
69 action="store",
70 default="pyloop",
71 help="run tests with specific loop: pyloop, uvloop or all",
72 )
73 parser.addoption(
74 "--aiohttp-enable-loop-debug",
75 action="store_true",
76 default=False,
77 help="enable event loop debug mode",
78 )
79
80
81 def pytest_fixture_setup(fixturedef): # type: ignore[no-untyped-def]
82 """Set up pytest fixture.
83
84 Allow fixtures to be coroutines. Run coroutine fixtures in an event loop.
85 """
86 func = fixturedef.func
87
88 if inspect.isasyncgenfunction(func):
89 # async generator fixture
90 is_async_gen = True
91 elif asyncio.iscoroutinefunction(func):
92 # regular async fixture
93 is_async_gen = False
94 else:
95 # not an async fixture, nothing to do
96 return
97
98 strip_request = False
99 if "request" not in fixturedef.argnames:
100 fixturedef.argnames += ("request",)
101 strip_request = True
102
103 def wrapper(*args, **kwargs): # type: ignore[no-untyped-def]
104 request = kwargs["request"]
105 if strip_request:
106 del kwargs["request"]
107
108 # if neither the fixture nor the test use the 'loop' fixture,
109 # 'getfixturevalue' will fail because the test is not parameterized
110 # (this can be removed someday if 'loop' is no longer parameterized)
111 if "loop" not in request.fixturenames:
112 raise Exception(
113 "Asynchronous fixtures must depend on the 'loop' fixture or "
114 "be used in tests depending from it."
115 )
116
117 _loop = request.getfixturevalue("loop")
118
119 if is_async_gen:
120 # for async generators, we need to advance the generator once,
121 # then advance it again in a finalizer
122 gen = func(*args, **kwargs)
123
124 def finalizer(): # type: ignore[no-untyped-def]
125 try:
126 return _loop.run_until_complete(gen.__anext__())
127 except StopAsyncIteration:
128 pass
129
130 request.addfinalizer(finalizer)
131 return _loop.run_until_complete(gen.__anext__())
132 else:
133 return _loop.run_until_complete(func(*args, **kwargs))
134
135 fixturedef.func = wrapper
136
137
138 @pytest.fixture
139 def fast(request): # type: ignore[no-untyped-def]
140 """--fast config option"""
141 return request.config.getoption("--aiohttp-fast")
142
143
144 @pytest.fixture
145 def loop_debug(request): # type: ignore[no-untyped-def]
146 """--enable-loop-debug config option"""
147 return request.config.getoption("--aiohttp-enable-loop-debug")
148
149
150 @contextlib.contextmanager
151 def _runtime_warning_context(): # type: ignore[no-untyped-def]
152 """Context manager which checks for RuntimeWarnings.
153
154 This exists specifically to
155 avoid "coroutine 'X' was never awaited" warnings being missed.
156
157 If RuntimeWarnings occur in the context a RuntimeError is raised.
158 """
159 with warnings.catch_warnings(record=True) as _warnings:
160 yield
161 rw = [
162 "{w.filename}:{w.lineno}:{w.message}".format(w=w)
163 for w in _warnings
164 if w.category == RuntimeWarning
165 ]
166 if rw:
167 raise RuntimeError(
168 "{} Runtime Warning{},\n{}".format(
169 len(rw), "" if len(rw) == 1 else "s", "\n".join(rw)
170 )
171 )
172
173
174 @contextlib.contextmanager
175 def _passthrough_loop_context(loop, fast=False): # type: ignore[no-untyped-def]
176 """Passthrough loop context.
177
178 Sets up and tears down a loop unless one is passed in via the loop
179 argument when it's passed straight through.
180 """
181 if loop:
182 # loop already exists, pass it straight through
183 yield loop
184 else:
185 # this shadows loop_context's standard behavior
186 loop = setup_test_loop()
187 yield loop
188 teardown_test_loop(loop, fast=fast)
189
190
191 def pytest_pycollect_makeitem(collector, name, obj): # type: ignore[no-untyped-def]
192 """Fix pytest collecting for coroutines."""
193 if collector.funcnamefilter(name) and asyncio.iscoroutinefunction(obj):
194 return list(collector._genfunctions(name, obj))
195
196
197 def pytest_pyfunc_call(pyfuncitem): # type: ignore[no-untyped-def]
198 """Run coroutines in an event loop instead of a normal function call."""
199 fast = pyfuncitem.config.getoption("--aiohttp-fast")
200 if asyncio.iscoroutinefunction(pyfuncitem.function):
201 existing_loop = pyfuncitem.funcargs.get(
202 "proactor_loop"
203 ) or pyfuncitem.funcargs.get("loop", None)
204 with _runtime_warning_context():
205 with _passthrough_loop_context(existing_loop, fast=fast) as _loop:
206 testargs = {
207 arg: pyfuncitem.funcargs[arg]
208 for arg in pyfuncitem._fixtureinfo.argnames
209 }
210 _loop.run_until_complete(pyfuncitem.obj(**testargs))
211
212 return True
213
214
215 def pytest_generate_tests(metafunc): # type: ignore[no-untyped-def]
216 if "loop_factory" not in metafunc.fixturenames:
217 return
218
219 loops = metafunc.config.option.aiohttp_loop
220 avail_factories: Dict[str, Type[asyncio.AbstractEventLoopPolicy]]
221 avail_factories = {"pyloop": asyncio.DefaultEventLoopPolicy}
222
223 if uvloop is not None: # pragma: no cover
224 avail_factories["uvloop"] = uvloop.EventLoopPolicy
225
226 if loops == "all":
227 loops = "pyloop,uvloop?"
228
229 factories = {} # type: ignore[var-annotated]
230 for name in loops.split(","):
231 required = not name.endswith("?")
232 name = name.strip(" ?")
233 if name not in avail_factories: # pragma: no cover
234 if required:
235 raise ValueError(
236 "Unknown loop '%s', available loops: %s"
237 % (name, list(factories.keys()))
238 )
239 else:
240 continue
241 factories[name] = avail_factories[name]
242 metafunc.parametrize(
243 "loop_factory", list(factories.values()), ids=list(factories.keys())
244 )
245
246
247 @pytest.fixture
248 def loop(loop_factory, fast, loop_debug): # type: ignore[no-untyped-def]
249 """Return an instance of the event loop."""
250 policy = loop_factory()
251 asyncio.set_event_loop_policy(policy)
252 with loop_context(fast=fast) as _loop:
253 if loop_debug:
254 _loop.set_debug(True) # pragma: no cover
255 asyncio.set_event_loop(_loop)
256 yield _loop
257
258
259 @pytest.fixture
260 def proactor_loop(): # type: ignore[no-untyped-def]
261 policy = asyncio.WindowsProactorEventLoopPolicy() # type: ignore[attr-defined]
262 asyncio.set_event_loop_policy(policy)
263
264 with loop_context(policy.new_event_loop) as _loop:
265 asyncio.set_event_loop(_loop)
266 yield _loop
267
268
269 @pytest.fixture
270 def unused_port(aiohttp_unused_port: Callable[[], int]) -> Callable[[], int]:
271 warnings.warn(
272 "Deprecated, use aiohttp_unused_port fixture instead",
273 DeprecationWarning,
274 stacklevel=2,
275 )
276 return aiohttp_unused_port
277
278
279 @pytest.fixture
280 def aiohttp_unused_port() -> Callable[[], int]:
281 """Return a port that is unused on the current host."""
282 return _unused_port
283
284
285 @pytest.fixture
286 def aiohttp_server(loop: asyncio.AbstractEventLoop) -> Iterator[AiohttpServer]:
287 """Factory to create a TestServer instance, given an app.
288
289 aiohttp_server(app, **kwargs)
290 """
291 servers = []
292
293 async def go(
294 app: Application, *, port: Optional[int] = None, **kwargs: Any
295 ) -> TestServer:
296 server = TestServer(app, port=port)
297 await server.start_server(loop=loop, **kwargs)
298 servers.append(server)
299 return server
300
301 yield go
302
303 async def finalize() -> None:
304 while servers:
305 await servers.pop().close()
306
307 loop.run_until_complete(finalize())
308
309
310 @pytest.fixture
311 def test_server(aiohttp_server): # type: ignore[no-untyped-def] # pragma: no cover
312 warnings.warn(
313 "Deprecated, use aiohttp_server fixture instead",
314 DeprecationWarning,
315 stacklevel=2,
316 )
317 return aiohttp_server
318
319
320 @pytest.fixture
321 def aiohttp_raw_server(loop: asyncio.AbstractEventLoop) -> Iterator[AiohttpRawServer]:
322 """Factory to create a RawTestServer instance, given a web handler.
323
324 aiohttp_raw_server(handler, **kwargs)
325 """
326 servers = []
327
328 async def go(
329 handler: _RequestHandler, *, port: Optional[int] = None, **kwargs: Any
330 ) -> RawTestServer:
331 server = RawTestServer(handler, port=port)
332 await server.start_server(loop=loop, **kwargs)
333 servers.append(server)
334 return server
335
336 yield go
337
338 async def finalize() -> None:
339 while servers:
340 await servers.pop().close()
341
342 loop.run_until_complete(finalize())
343
344
345 @pytest.fixture
346 def raw_test_server( # type: ignore[no-untyped-def] # pragma: no cover
347 aiohttp_raw_server,
348 ):
349 warnings.warn(
350 "Deprecated, use aiohttp_raw_server fixture instead",
351 DeprecationWarning,
352 stacklevel=2,
353 )
354 return aiohttp_raw_server
355
356
357 @pytest.fixture
358 def aiohttp_client(
359 loop: asyncio.AbstractEventLoop,
360 ) -> Iterator[AiohttpClient]:
361 """Factory to create a TestClient instance.
362
363 aiohttp_client(app, **kwargs)
364 aiohttp_client(server, **kwargs)
365 aiohttp_client(raw_server, **kwargs)
366 """
367 clients = []
368
369 async def go(
370 __param: Union[Application, BaseTestServer],
371 *args: Any,
372 server_kwargs: Optional[Dict[str, Any]] = None,
373 **kwargs: Any
374 ) -> TestClient:
375
376 if isinstance(__param, Callable) and not isinstance( # type: ignore[arg-type]
377 __param, (Application, BaseTestServer)
378 ):
379 __param = __param(loop, *args, **kwargs)
380 kwargs = {}
381 else:
382 assert not args, "args should be empty"
383
384 if isinstance(__param, Application):
385 server_kwargs = server_kwargs or {}
386 server = TestServer(__param, loop=loop, **server_kwargs)
387 client = TestClient(server, loop=loop, **kwargs)
388 elif isinstance(__param, BaseTestServer):
389 client = TestClient(__param, loop=loop, **kwargs)
390 else:
391 raise ValueError("Unknown argument type: %r" % type(__param))
392
393 await client.start_server()
394 clients.append(client)
395 return client
396
397 yield go
398
399 async def finalize() -> None:
400 while clients:
401 await clients.pop().close()
402
403 loop.run_until_complete(finalize())
404
405
406 @pytest.fixture
407 def test_client(aiohttp_client): # type: ignore[no-untyped-def] # pragma: no cover
408 warnings.warn(
409 "Deprecated, use aiohttp_client fixture instead",
410 DeprecationWarning,
411 stacklevel=2,
412 )
413 return aiohttp_client