| 1 |
"""Utilities shared by tests.""" |
| 2 |
|
| 3 |
import asyncio |
| 4 |
import contextlib |
| 5 |
import gc |
| 6 |
import inspect |
| 7 |
import ipaddress |
| 8 |
import os |
| 9 |
import socket |
| 10 |
import sys |
| 11 |
import warnings |
| 12 |
from abc import ABC, abstractmethod |
| 13 |
from types import TracebackType |
| 14 |
from typing import TYPE_CHECKING, Any, Callable, Iterator, List, Optional, Type, cast |
| 15 |
from unittest import IsolatedAsyncioTestCase, mock |
| 16 |
|
| 17 |
from aiosignal import Signal |
| 18 |
from multidict import CIMultiDict, CIMultiDictProxy |
| 19 |
from yarl import URL |
| 20 |
|
| 21 |
import aiohttp |
| 22 |
from aiohttp.client import ( |
| 23 |
_RequestContextManager, |
| 24 |
_RequestOptions, |
| 25 |
_WSRequestContextManager, |
| 26 |
) |
| 27 |
|
| 28 |
from . import ClientSession, hdrs |
| 29 |
from .abc import AbstractCookieJar |
| 30 |
from .client_reqrep import ClientResponse |
| 31 |
from .client_ws import ClientWebSocketResponse |
| 32 |
from .helpers import sentinel |
| 33 |
from .http import HttpVersion, RawRequestMessage |
| 34 |
from .streams import EMPTY_PAYLOAD, StreamReader |
| 35 |
from .typedefs import StrOrURL |
| 36 |
from .web import ( |
| 37 |
Application, |
| 38 |
AppRunner, |
| 39 |
BaseRunner, |
| 40 |
Request, |
| 41 |
Server, |
| 42 |
ServerRunner, |
| 43 |
SockSite, |
| 44 |
UrlMappingMatchInfo, |
| 45 |
) |
| 46 |
from .web_protocol import _RequestHandler |
| 47 |
|
| 48 |
if TYPE_CHECKING: |
| 49 |
from ssl import SSLContext |
| 50 |
else: |
| 51 |
SSLContext = None |
| 52 |
|
| 53 |
if sys.version_info >= (3, 11) and TYPE_CHECKING: |
| 54 |
from typing import Unpack |
| 55 |
|
| 56 |
REUSE_ADDRESS = os.name == "posix" and sys.platform != "cygwin" |
| 57 |
|
| 58 |
|
| 59 |
def get_unused_port_socket( |
| 60 |
host: str, family: socket.AddressFamily = socket.AF_INET |
| 61 |
) -> socket.socket: |
| 62 |
return get_port_socket(host, 0, family) |
| 63 |
|
| 64 |
|
| 65 |
def get_port_socket( |
| 66 |
host: str, port: int, family: socket.AddressFamily |
| 67 |
) -> socket.socket: |
| 68 |
s = socket.socket(family, socket.SOCK_STREAM) |
| 69 |
if REUSE_ADDRESS: |
| 70 |
# Windows has different semantics for SO_REUSEADDR, |
| 71 |
# so don't set it. Ref: |
| 72 |
# https://docs.microsoft.com/en-us/windows/win32/winsock/using-so-reuseaddr-and-so-exclusiveaddruse |
| 73 |
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) |
| 74 |
s.bind((host, port)) |
| 75 |
return s |
| 76 |
|
| 77 |
|
| 78 |
def unused_port() -> int: |
| 79 |
"""Return a port that is unused on the current host.""" |
| 80 |
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: |
| 81 |
s.bind(("127.0.0.1", 0)) |
| 82 |
return cast(int, s.getsockname()[1]) |
| 83 |
|
| 84 |
|
| 85 |
class BaseTestServer(ABC): |
| 86 |
__test__ = False |
| 87 |
|
| 88 |
def __init__( |
| 89 |
self, |
| 90 |
*, |
| 91 |
scheme: str = "", |
| 92 |
loop: Optional[asyncio.AbstractEventLoop] = None, |
| 93 |
host: str = "127.0.0.1", |
| 94 |
port: Optional[int] = None, |
| 95 |
skip_url_asserts: bool = False, |
| 96 |
socket_factory: Callable[ |
| 97 |
[str, int, socket.AddressFamily], socket.socket |
| 98 |
] = get_port_socket, |
| 99 |
**kwargs: Any, |
| 100 |
) -> None: |
| 101 |
self._loop = loop |
| 102 |
self.runner: Optional[BaseRunner] = None |
| 103 |
self._root: Optional[URL] = None |
| 104 |
self.host = host |
| 105 |
self.port = port |
| 106 |
self._closed = False |
| 107 |
self.scheme = scheme |
| 108 |
self.skip_url_asserts = skip_url_asserts |
| 109 |
self.socket_factory = socket_factory |
| 110 |
|
| 111 |
async def start_server( |
| 112 |
self, loop: Optional[asyncio.AbstractEventLoop] = None, **kwargs: Any |
| 113 |
) -> None: |
| 114 |
if self.runner: |
| 115 |
return |
| 116 |
self._loop = loop |
| 117 |
self._ssl = kwargs.pop("ssl", None) |
| 118 |
self.runner = await self._make_runner(handler_cancellation=True, **kwargs) |
| 119 |
await self.runner.setup() |
| 120 |
if not self.port: |
| 121 |
self.port = 0 |
| 122 |
absolute_host = self.host |
| 123 |
try: |
| 124 |
version = ipaddress.ip_address(self.host).version |
| 125 |
except ValueError: |
| 126 |
version = 4 |
| 127 |
if version == 6: |
| 128 |
absolute_host = f"[{self.host}]" |
| 129 |
family = socket.AF_INET6 if version == 6 else socket.AF_INET |
| 130 |
_sock = self.socket_factory(self.host, self.port, family) |
| 131 |
self.host, self.port = _sock.getsockname()[:2] |
| 132 |
site = SockSite(self.runner, sock=_sock, ssl_context=self._ssl) |
| 133 |
await site.start() |
| 134 |
server = site._server |
| 135 |
assert server is not None |
| 136 |
sockets = server.sockets # type: ignore[attr-defined] |
| 137 |
assert sockets is not None |
| 138 |
self.port = sockets[0].getsockname()[1] |
| 139 |
if not self.scheme: |
| 140 |
self.scheme = "https" if self._ssl else "http" |
| 141 |
self._root = URL(f"{self.scheme}://{absolute_host}:{self.port}") |
| 142 |
|
| 143 |
@abstractmethod # pragma: no cover |
| 144 |
async def _make_runner(self, **kwargs: Any) -> BaseRunner: |
| 145 |
pass |
| 146 |
|
| 147 |
def make_url(self, path: StrOrURL) -> URL: |
| 148 |
assert self._root is not None |
| 149 |
url = URL(path) |
| 150 |
if not self.skip_url_asserts: |
| 151 |
assert not url.absolute |
| 152 |
return self._root.join(url) |
| 153 |
else: |
| 154 |
return URL(str(self._root) + str(path)) |
| 155 |
|
| 156 |
@property |
| 157 |
def started(self) -> bool: |
| 158 |
return self.runner is not None |
| 159 |
|
| 160 |
@property |
| 161 |
def closed(self) -> bool: |
| 162 |
return self._closed |
| 163 |
|
| 164 |
@property |
| 165 |
def handler(self) -> Server: |
| 166 |
# for backward compatibility |
| 167 |
# web.Server instance |
| 168 |
runner = self.runner |
| 169 |
assert runner is not None |
| 170 |
assert runner.server is not None |
| 171 |
return runner.server |
| 172 |
|
| 173 |
async def close(self) -> None: |
| 174 |
"""Close all fixtures created by the test client. |
| 175 |
|
| 176 |
After that point, the TestClient is no longer usable. |
| 177 |
|
| 178 |
This is an idempotent function: running close multiple times |
| 179 |
will not have any additional effects. |
| 180 |
|
| 181 |
close is also run when the object is garbage collected, and on |
| 182 |
exit when used as a context manager. |
| 183 |
|
| 184 |
""" |
| 185 |
if self.started and not self.closed: |
| 186 |
assert self.runner is not None |
| 187 |
await self.runner.cleanup() |
| 188 |
self._root = None |
| 189 |
self.port = None |
| 190 |
self._closed = True |
| 191 |
|
| 192 |
def __enter__(self) -> None: |
| 193 |
raise TypeError("Use async with instead") |
| 194 |
|
| 195 |
def __exit__( |
| 196 |
self, |
| 197 |
exc_type: Optional[Type[BaseException]], |
| 198 |
exc_value: Optional[BaseException], |
| 199 |
traceback: Optional[TracebackType], |
| 200 |
) -> None: |
| 201 |
# __exit__ should exist in pair with __enter__ but never executed |
| 202 |
pass # pragma: no cover |
| 203 |
|
| 204 |
async def __aenter__(self) -> "BaseTestServer": |
| 205 |
await self.start_server(loop=self._loop) |
| 206 |
return self |
| 207 |
|
| 208 |
async def __aexit__( |
| 209 |
self, |
| 210 |
exc_type: Optional[Type[BaseException]], |
| 211 |
exc_value: Optional[BaseException], |
| 212 |
traceback: Optional[TracebackType], |
| 213 |
) -> None: |
| 214 |
await self.close() |
| 215 |
|
| 216 |
|
| 217 |
class TestServer(BaseTestServer): |
| 218 |
def __init__( |
| 219 |
self, |
| 220 |
app: Application, |
| 221 |
*, |
| 222 |
scheme: str = "", |
| 223 |
host: str = "127.0.0.1", |
| 224 |
port: Optional[int] = None, |
| 225 |
**kwargs: Any, |
| 226 |
): |
| 227 |
self.app = app |
| 228 |
super().__init__(scheme=scheme, host=host, port=port, **kwargs) |
| 229 |
|
| 230 |
async def _make_runner(self, **kwargs: Any) -> BaseRunner: |
| 231 |
return AppRunner(self.app, **kwargs) |
| 232 |
|
| 233 |
|
| 234 |
class RawTestServer(BaseTestServer): |
| 235 |
def __init__( |
| 236 |
self, |
| 237 |
handler: _RequestHandler, |
| 238 |
*, |
| 239 |
scheme: str = "", |
| 240 |
host: str = "127.0.0.1", |
| 241 |
port: Optional[int] = None, |
| 242 |
**kwargs: Any, |
| 243 |
) -> None: |
| 244 |
self._handler = handler |
| 245 |
super().__init__(scheme=scheme, host=host, port=port, **kwargs) |
| 246 |
|
| 247 |
async def _make_runner(self, debug: bool = True, **kwargs: Any) -> ServerRunner: |
| 248 |
srv = Server(self._handler, loop=self._loop, debug=debug, **kwargs) |
| 249 |
return ServerRunner(srv, debug=debug, **kwargs) |
| 250 |
|
| 251 |
|
| 252 |
class TestClient: |
| 253 |
""" |
| 254 |
A test client implementation. |
| 255 |
|
| 256 |
To write functional tests for aiohttp based servers. |
| 257 |
|
| 258 |
""" |
| 259 |
|
| 260 |
__test__ = False |
| 261 |
|
| 262 |
def __init__( |
| 263 |
self, |
| 264 |
server: BaseTestServer, |
| 265 |
*, |
| 266 |
cookie_jar: Optional[AbstractCookieJar] = None, |
| 267 |
loop: Optional[asyncio.AbstractEventLoop] = None, |
| 268 |
**kwargs: Any, |
| 269 |
) -> None: |
| 270 |
if not isinstance(server, BaseTestServer): |
| 271 |
raise TypeError( |
| 272 |
"server must be TestServer " "instance, found type: %r" % type(server) |
| 273 |
) |
| 274 |
self._server = server |
| 275 |
self._loop = loop |
| 276 |
if cookie_jar is None: |
| 277 |
cookie_jar = aiohttp.CookieJar(unsafe=True, loop=loop) |
| 278 |
self._session = ClientSession(loop=loop, cookie_jar=cookie_jar, **kwargs) |
| 279 |
self._closed = False |
| 280 |
self._responses: List[ClientResponse] = [] |
| 281 |
self._websockets: List[ClientWebSocketResponse] = [] |
| 282 |
|
| 283 |
async def start_server(self) -> None: |
| 284 |
await self._server.start_server(loop=self._loop) |
| 285 |
|
| 286 |
@property |
| 287 |
def host(self) -> str: |
| 288 |
return self._server.host |
| 289 |
|
| 290 |
@property |
| 291 |
def port(self) -> Optional[int]: |
| 292 |
return self._server.port |
| 293 |
|
| 294 |
@property |
| 295 |
def server(self) -> BaseTestServer: |
| 296 |
return self._server |
| 297 |
|
| 298 |
@property |
| 299 |
def app(self) -> Optional[Application]: |
| 300 |
return cast(Optional[Application], getattr(self._server, "app", None)) |
| 301 |
|
| 302 |
@property |
| 303 |
def session(self) -> ClientSession: |
| 304 |
"""An internal aiohttp.ClientSession. |
| 305 |
|
| 306 |
Unlike the methods on the TestClient, client session requests |
| 307 |
do not automatically include the host in the url queried, and |
| 308 |
will require an absolute path to the resource. |
| 309 |
|
| 310 |
""" |
| 311 |
return self._session |
| 312 |
|
| 313 |
def make_url(self, path: StrOrURL) -> URL: |
| 314 |
return self._server.make_url(path) |
| 315 |
|
| 316 |
async def _request( |
| 317 |
self, method: str, path: StrOrURL, **kwargs: Any |
| 318 |
) -> ClientResponse: |
| 319 |
resp = await self._session.request(method, self.make_url(path), **kwargs) |
| 320 |
# save it to close later |
| 321 |
self._responses.append(resp) |
| 322 |
return resp |
| 323 |
|
| 324 |
if sys.version_info >= (3, 11) and TYPE_CHECKING: |
| 325 |
|
| 326 |
def request( |
| 327 |
self, method: str, path: StrOrURL, **kwargs: Unpack[_RequestOptions] |
| 328 |
) -> _RequestContextManager: ... |
| 329 |
|
| 330 |
def get( |
| 331 |
self, |
| 332 |
path: StrOrURL, |
| 333 |
**kwargs: Unpack[_RequestOptions], |
| 334 |
) -> _RequestContextManager: ... |
| 335 |
|
| 336 |
def options( |
| 337 |
self, |
| 338 |
path: StrOrURL, |
| 339 |
**kwargs: Unpack[_RequestOptions], |
| 340 |
) -> _RequestContextManager: ... |
| 341 |
|
| 342 |
def head( |
| 343 |
self, |
| 344 |
path: StrOrURL, |
| 345 |
**kwargs: Unpack[_RequestOptions], |
| 346 |
) -> _RequestContextManager: ... |
| 347 |
|
| 348 |
def post( |
| 349 |
self, |
| 350 |
path: StrOrURL, |
| 351 |
**kwargs: Unpack[_RequestOptions], |
| 352 |
) -> _RequestContextManager: ... |
| 353 |
|
| 354 |
def put( |
| 355 |
self, |
| 356 |
path: StrOrURL, |
| 357 |
**kwargs: Unpack[_RequestOptions], |
| 358 |
) -> _RequestContextManager: ... |
| 359 |
|
| 360 |
def patch( |
| 361 |
self, |
| 362 |
path: StrOrURL, |
| 363 |
**kwargs: Unpack[_RequestOptions], |
| 364 |
) -> _RequestContextManager: ... |
| 365 |
|
| 366 |
def delete( |
| 367 |
self, |
| 368 |
path: StrOrURL, |
| 369 |
**kwargs: Unpack[_RequestOptions], |
| 370 |
) -> _RequestContextManager: ... |
| 371 |
|
| 372 |
else: |
| 373 |
|
| 374 |
def request( |
| 375 |
self, method: str, path: StrOrURL, **kwargs: Any |
| 376 |
) -> _RequestContextManager: |
| 377 |
"""Routes a request to tested http server. |
| 378 |
|
| 379 |
The interface is identical to aiohttp.ClientSession.request, |
| 380 |
except the loop kwarg is overridden by the instance used by the |
| 381 |
test server. |
| 382 |
|
| 383 |
""" |
| 384 |
return _RequestContextManager(self._request(method, path, **kwargs)) |
| 385 |
|
| 386 |
def get(self, path: StrOrURL, **kwargs: Any) -> _RequestContextManager: |
| 387 |
"""Perform an HTTP GET request.""" |
| 388 |
return _RequestContextManager(self._request(hdrs.METH_GET, path, **kwargs)) |
| 389 |
|
| 390 |
def post(self, path: StrOrURL, **kwargs: Any) -> _RequestContextManager: |
| 391 |
"""Perform an HTTP POST request.""" |
| 392 |
return _RequestContextManager(self._request(hdrs.METH_POST, path, **kwargs)) |
| 393 |
|
| 394 |
def options(self, path: StrOrURL, **kwargs: Any) -> _RequestContextManager: |
| 395 |
"""Perform an HTTP OPTIONS request.""" |
| 396 |
return _RequestContextManager( |
| 397 |
self._request(hdrs.METH_OPTIONS, path, **kwargs) |
| 398 |
) |
| 399 |
|
| 400 |
def head(self, path: StrOrURL, **kwargs: Any) -> _RequestContextManager: |
| 401 |
"""Perform an HTTP HEAD request.""" |
| 402 |
return _RequestContextManager(self._request(hdrs.METH_HEAD, path, **kwargs)) |
| 403 |
|
| 404 |
def put(self, path: StrOrURL, **kwargs: Any) -> _RequestContextManager: |
| 405 |
"""Perform an HTTP PUT request.""" |
| 406 |
return _RequestContextManager(self._request(hdrs.METH_PUT, path, **kwargs)) |
| 407 |
|
| 408 |
def patch(self, path: StrOrURL, **kwargs: Any) -> _RequestContextManager: |
| 409 |
"""Perform an HTTP PATCH request.""" |
| 410 |
return _RequestContextManager( |
| 411 |
self._request(hdrs.METH_PATCH, path, **kwargs) |
| 412 |
) |
| 413 |
|
| 414 |
def delete(self, path: StrOrURL, **kwargs: Any) -> _RequestContextManager: |
| 415 |
"""Perform an HTTP PATCH request.""" |
| 416 |
return _RequestContextManager( |
| 417 |
self._request(hdrs.METH_DELETE, path, **kwargs) |
| 418 |
) |
| 419 |
|
| 420 |
def ws_connect(self, path: StrOrURL, **kwargs: Any) -> _WSRequestContextManager: |
| 421 |
"""Initiate websocket connection. |
| 422 |
|
| 423 |
The api corresponds to aiohttp.ClientSession.ws_connect. |
| 424 |
|
| 425 |
""" |
| 426 |
return _WSRequestContextManager(self._ws_connect(path, **kwargs)) |
| 427 |
|
| 428 |
async def _ws_connect( |
| 429 |
self, path: StrOrURL, **kwargs: Any |
| 430 |
) -> ClientWebSocketResponse: |
| 431 |
ws = await self._session.ws_connect(self.make_url(path), **kwargs) |
| 432 |
self._websockets.append(ws) |
| 433 |
return ws |
| 434 |
|
| 435 |
async def close(self) -> None: |
| 436 |
"""Close all fixtures created by the test client. |
| 437 |
|
| 438 |
After that point, the TestClient is no longer usable. |
| 439 |
|
| 440 |
This is an idempotent function: running close multiple times |
| 441 |
will not have any additional effects. |
| 442 |
|
| 443 |
close is also run on exit when used as a(n) (asynchronous) |
| 444 |
context manager. |
| 445 |
|
| 446 |
""" |
| 447 |
if not self._closed: |
| 448 |
for resp in self._responses: |
| 449 |
resp.close() |
| 450 |
for ws in self._websockets: |
| 451 |
await ws.close() |
| 452 |
await self._session.close() |
| 453 |
await self._server.close() |
| 454 |
self._closed = True |
| 455 |
|
| 456 |
def __enter__(self) -> None: |
| 457 |
raise TypeError("Use async with instead") |
| 458 |
|
| 459 |
def __exit__( |
| 460 |
self, |
| 461 |
exc_type: Optional[Type[BaseException]], |
| 462 |
exc: Optional[BaseException], |
| 463 |
tb: Optional[TracebackType], |
| 464 |
) -> None: |
| 465 |
# __exit__ should exist in pair with __enter__ but never executed |
| 466 |
pass # pragma: no cover |
| 467 |
|
| 468 |
async def __aenter__(self) -> "TestClient": |
| 469 |
await self.start_server() |
| 470 |
return self |
| 471 |
|
| 472 |
async def __aexit__( |
| 473 |
self, |
| 474 |
exc_type: Optional[Type[BaseException]], |
| 475 |
exc: Optional[BaseException], |
| 476 |
tb: Optional[TracebackType], |
| 477 |
) -> None: |
| 478 |
await self.close() |
| 479 |
|
| 480 |
|
| 481 |
class AioHTTPTestCase(IsolatedAsyncioTestCase): |
| 482 |
"""A base class to allow for unittest web applications using aiohttp. |
| 483 |
|
| 484 |
Provides the following: |
| 485 |
|
| 486 |
* self.client (aiohttp.test_utils.TestClient): an aiohttp test client. |
| 487 |
* self.loop (asyncio.BaseEventLoop): the event loop in which the |
| 488 |
application and server are running. |
| 489 |
* self.app (aiohttp.web.Application): the application returned by |
| 490 |
self.get_application() |
| 491 |
|
| 492 |
Note that the TestClient's methods are asynchronous: you have to |
| 493 |
execute function on the test client using asynchronous methods. |
| 494 |
""" |
| 495 |
|
| 496 |
async def get_application(self) -> Application: |
| 497 |
"""Get application. |
| 498 |
|
| 499 |
This method should be overridden |
| 500 |
to return the aiohttp.web.Application |
| 501 |
object to test. |
| 502 |
""" |
| 503 |
return self.get_app() |
| 504 |
|
| 505 |
def get_app(self) -> Application: |
| 506 |
"""Obsolete method used to constructing web application. |
| 507 |
|
| 508 |
Use .get_application() coroutine instead. |
| 509 |
""" |
| 510 |
raise RuntimeError("Did you forget to define get_application()?") |
| 511 |
|
| 512 |
async def asyncSetUp(self) -> None: |
| 513 |
self.loop = asyncio.get_running_loop() |
| 514 |
return await self.setUpAsync() |
| 515 |
|
| 516 |
async def setUpAsync(self) -> None: |
| 517 |
self.app = await self.get_application() |
| 518 |
self.server = await self.get_server(self.app) |
| 519 |
self.client = await self.get_client(self.server) |
| 520 |
|
| 521 |
await self.client.start_server() |
| 522 |
|
| 523 |
async def asyncTearDown(self) -> None: |
| 524 |
return await self.tearDownAsync() |
| 525 |
|
| 526 |
async def tearDownAsync(self) -> None: |
| 527 |
await self.client.close() |
| 528 |
|
| 529 |
async def get_server(self, app: Application) -> TestServer: |
| 530 |
"""Return a TestServer instance.""" |
| 531 |
return TestServer(app, loop=self.loop) |
| 532 |
|
| 533 |
async def get_client(self, server: TestServer) -> TestClient: |
| 534 |
"""Return a TestClient instance.""" |
| 535 |
return TestClient(server, loop=self.loop) |
| 536 |
|
| 537 |
|
| 538 |
def unittest_run_loop(func: Any, *args: Any, **kwargs: Any) -> Any: |
| 539 |
""" |
| 540 |
A decorator dedicated to use with asynchronous AioHTTPTestCase test methods. |
| 541 |
|
| 542 |
In 3.8+, this does nothing. |
| 543 |
""" |
| 544 |
warnings.warn( |
| 545 |
"Decorator `@unittest_run_loop` is no longer needed in aiohttp 3.8+", |
| 546 |
DeprecationWarning, |
| 547 |
stacklevel=2, |
| 548 |
) |
| 549 |
return func |
| 550 |
|
| 551 |
|
| 552 |
_LOOP_FACTORY = Callable[[], asyncio.AbstractEventLoop] |
| 553 |
|
| 554 |
|
| 555 |
@contextlib.contextmanager |
| 556 |
def loop_context( |
| 557 |
loop_factory: _LOOP_FACTORY = asyncio.new_event_loop, fast: bool = False |
| 558 |
) -> Iterator[asyncio.AbstractEventLoop]: |
| 559 |
"""A contextmanager that creates an event_loop, for test purposes. |
| 560 |
|
| 561 |
Handles the creation and cleanup of a test loop. |
| 562 |
""" |
| 563 |
loop = setup_test_loop(loop_factory) |
| 564 |
yield loop |
| 565 |
teardown_test_loop(loop, fast=fast) |
| 566 |
|
| 567 |
|
| 568 |
def setup_test_loop( |
| 569 |
loop_factory: _LOOP_FACTORY = asyncio.new_event_loop, |
| 570 |
) -> asyncio.AbstractEventLoop: |
| 571 |
"""Create and return an asyncio.BaseEventLoop instance. |
| 572 |
|
| 573 |
The caller should also call teardown_test_loop, |
| 574 |
once they are done with the loop. |
| 575 |
""" |
| 576 |
loop = loop_factory() |
| 577 |
asyncio.set_event_loop(loop) |
| 578 |
return loop |
| 579 |
|
| 580 |
|
| 581 |
def teardown_test_loop(loop: asyncio.AbstractEventLoop, fast: bool = False) -> None: |
| 582 |
"""Teardown and cleanup an event_loop created by setup_test_loop.""" |
| 583 |
closed = loop.is_closed() |
| 584 |
if not closed: |
| 585 |
loop.call_soon(loop.stop) |
| 586 |
loop.run_forever() |
| 587 |
loop.close() |
| 588 |
|
| 589 |
if not fast: |
| 590 |
gc.collect() |
| 591 |
|
| 592 |
asyncio.set_event_loop(None) |
| 593 |
|
| 594 |
|
| 595 |
def _create_app_mock() -> mock.MagicMock: |
| 596 |
def get_dict(app: Any, key: str) -> Any: |
| 597 |
return app.__app_dict[key] |
| 598 |
|
| 599 |
def set_dict(app: Any, key: str, value: Any) -> None: |
| 600 |
app.__app_dict[key] = value |
| 601 |
|
| 602 |
app = mock.MagicMock(spec=Application) |
| 603 |
app.__app_dict = {} |
| 604 |
app.__getitem__ = get_dict |
| 605 |
app.__setitem__ = set_dict |
| 606 |
|
| 607 |
app._debug = False |
| 608 |
app.on_response_prepare = Signal(app) |
| 609 |
app.on_response_prepare.freeze() |
| 610 |
return app |
| 611 |
|
| 612 |
|
| 613 |
def _create_transport(sslcontext: Optional[SSLContext] = None) -> mock.Mock: |
| 614 |
transport = mock.Mock() |
| 615 |
|
| 616 |
def get_extra_info(key: str) -> Optional[SSLContext]: |
| 617 |
if key == "sslcontext": |
| 618 |
return sslcontext |
| 619 |
else: |
| 620 |
return None |
| 621 |
|
| 622 |
transport.get_extra_info.side_effect = get_extra_info |
| 623 |
return transport |
| 624 |
|
| 625 |
|
| 626 |
def make_mocked_request( |
| 627 |
method: str, |
| 628 |
path: str, |
| 629 |
headers: Any = None, |
| 630 |
*, |
| 631 |
match_info: Any = sentinel, |
| 632 |
version: HttpVersion = HttpVersion(1, 1), |
| 633 |
closing: bool = False, |
| 634 |
app: Any = None, |
| 635 |
writer: Any = sentinel, |
| 636 |
protocol: Any = sentinel, |
| 637 |
transport: Any = sentinel, |
| 638 |
payload: StreamReader = EMPTY_PAYLOAD, |
| 639 |
sslcontext: Optional[SSLContext] = None, |
| 640 |
client_max_size: int = 1024**2, |
| 641 |
loop: Any = ..., |
| 642 |
) -> Request: |
| 643 |
"""Creates mocked web.Request testing purposes. |
| 644 |
|
| 645 |
Useful in unit tests, when spinning full web server is overkill or |
| 646 |
specific conditions and errors are hard to trigger. |
| 647 |
""" |
| 648 |
task = mock.Mock() |
| 649 |
if loop is ...: |
| 650 |
# no loop passed, try to get the current one if |
| 651 |
# its is running as we need a real loop to create |
| 652 |
# executor jobs to be able to do testing |
| 653 |
# with a real executor |
| 654 |
try: |
| 655 |
loop = asyncio.get_running_loop() |
| 656 |
except RuntimeError: |
| 657 |
loop = mock.Mock() |
| 658 |
loop.create_future.return_value = () |
| 659 |
|
| 660 |
if version < HttpVersion(1, 1): |
| 661 |
closing = True |
| 662 |
|
| 663 |
if headers: |
| 664 |
headers = CIMultiDictProxy(CIMultiDict(headers)) |
| 665 |
raw_hdrs = tuple( |
| 666 |
(k.encode("utf-8"), v.encode("utf-8")) for k, v in headers.items() |
| 667 |
) |
| 668 |
else: |
| 669 |
headers = CIMultiDictProxy(CIMultiDict()) |
| 670 |
raw_hdrs = () |
| 671 |
|
| 672 |
chunked = "chunked" in headers.get(hdrs.TRANSFER_ENCODING, "").lower() |
| 673 |
|
| 674 |
message = RawRequestMessage( |
| 675 |
method, |
| 676 |
path, |
| 677 |
version, |
| 678 |
headers, |
| 679 |
raw_hdrs, |
| 680 |
closing, |
| 681 |
None, |
| 682 |
False, |
| 683 |
chunked, |
| 684 |
URL(path), |
| 685 |
) |
| 686 |
if app is None: |
| 687 |
app = _create_app_mock() |
| 688 |
|
| 689 |
if transport is sentinel: |
| 690 |
transport = _create_transport(sslcontext) |
| 691 |
|
| 692 |
if protocol is sentinel: |
| 693 |
protocol = mock.Mock() |
| 694 |
protocol.transport = transport |
| 695 |
|
| 696 |
if writer is sentinel: |
| 697 |
writer = mock.Mock() |
| 698 |
writer.write_headers = make_mocked_coro(None) |
| 699 |
writer.write = make_mocked_coro(None) |
| 700 |
writer.write_eof = make_mocked_coro(None) |
| 701 |
writer.drain = make_mocked_coro(None) |
| 702 |
writer.transport = transport |
| 703 |
|
| 704 |
protocol.transport = transport |
| 705 |
protocol.writer = writer |
| 706 |
|
| 707 |
req = Request( |
| 708 |
message, payload, protocol, writer, task, loop, client_max_size=client_max_size |
| 709 |
) |
| 710 |
|
| 711 |
match_info = UrlMappingMatchInfo( |
| 712 |
{} if match_info is sentinel else match_info, mock.Mock() |
| 713 |
) |
| 714 |
match_info.add_app(app) |
| 715 |
req._match_info = match_info |
| 716 |
|
| 717 |
return req |
| 718 |
|
| 719 |
|
| 720 |
def make_mocked_coro( |
| 721 |
return_value: Any = sentinel, raise_exception: Any = sentinel |
| 722 |
) -> Any: |
| 723 |
"""Creates a coroutine mock.""" |
| 724 |
|
| 725 |
async def mock_coro(*args: Any, **kwargs: Any) -> Any: |
| 726 |
if raise_exception is not sentinel: |
| 727 |
raise raise_exception |
| 728 |
if not inspect.isawaitable(return_value): |
| 729 |
return return_value |
| 730 |
await return_value |
| 731 |
|
| 732 |
return mock.Mock(wraps=mock_coro) |