test_utils.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676
  1. """Utilities shared by tests."""
  2. import asyncio
  3. import contextlib
  4. import functools
  5. import gc
  6. import inspect
  7. import os
  8. import socket
  9. import sys
  10. import unittest
  11. from abc import ABC, abstractmethod
  12. from types import TracebackType
  13. from typing import TYPE_CHECKING, Any, Callable, Iterator, List, Optional, Type, Union
  14. from unittest import mock
  15. from multidict import CIMultiDict, CIMultiDictProxy
  16. from yarl import URL
  17. import aiohttp
  18. from aiohttp.client import (
  19. ClientResponse,
  20. _RequestContextManager,
  21. _WSRequestContextManager,
  22. )
  23. from . import ClientSession, hdrs
  24. from .abc import AbstractCookieJar
  25. from .client_reqrep import ClientResponse
  26. from .client_ws import ClientWebSocketResponse
  27. from .helpers import sentinel
  28. from .http import HttpVersion, RawRequestMessage
  29. from .signals import Signal
  30. from .web import (
  31. Application,
  32. AppRunner,
  33. BaseRunner,
  34. Request,
  35. Server,
  36. ServerRunner,
  37. SockSite,
  38. UrlMappingMatchInfo,
  39. )
  40. from .web_protocol import _RequestHandler
  41. if TYPE_CHECKING: # pragma: no cover
  42. from ssl import SSLContext
  43. else:
  44. SSLContext = None
  45. REUSE_ADDRESS = os.name == "posix" and sys.platform != "cygwin"
  46. def get_unused_port_socket(host: str) -> socket.socket:
  47. return get_port_socket(host, 0)
  48. def get_port_socket(host: str, port: int) -> socket.socket:
  49. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  50. if REUSE_ADDRESS:
  51. # Windows has different semantics for SO_REUSEADDR,
  52. # so don't set it. Ref:
  53. # https://docs.microsoft.com/en-us/windows/win32/winsock/using-so-reuseaddr-and-so-exclusiveaddruse
  54. s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  55. s.bind((host, port))
  56. return s
  57. def unused_port() -> int:
  58. """Return a port that is unused on the current host."""
  59. with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
  60. s.bind(("127.0.0.1", 0))
  61. return s.getsockname()[1]
  62. class BaseTestServer(ABC):
  63. __test__ = False
  64. def __init__(
  65. self,
  66. *,
  67. scheme: Union[str, object] = sentinel,
  68. loop: Optional[asyncio.AbstractEventLoop] = None,
  69. host: str = "127.0.0.1",
  70. port: Optional[int] = None,
  71. skip_url_asserts: bool = False,
  72. **kwargs: Any,
  73. ) -> None:
  74. self._loop = loop
  75. self.runner = None # type: Optional[BaseRunner]
  76. self._root = None # type: Optional[URL]
  77. self.host = host
  78. self.port = port
  79. self._closed = False
  80. self.scheme = scheme
  81. self.skip_url_asserts = skip_url_asserts
  82. async def start_server(
  83. self, loop: Optional[asyncio.AbstractEventLoop] = None, **kwargs: Any
  84. ) -> None:
  85. if self.runner:
  86. return
  87. self._loop = loop
  88. self._ssl = kwargs.pop("ssl", None)
  89. self.runner = await self._make_runner(**kwargs)
  90. await self.runner.setup()
  91. if not self.port:
  92. self.port = 0
  93. _sock = get_port_socket(self.host, self.port)
  94. self.host, self.port = _sock.getsockname()[:2]
  95. site = SockSite(self.runner, sock=_sock, ssl_context=self._ssl)
  96. await site.start()
  97. server = site._server
  98. assert server is not None
  99. sockets = server.sockets
  100. assert sockets is not None
  101. self.port = sockets[0].getsockname()[1]
  102. if self.scheme is sentinel:
  103. if self._ssl:
  104. scheme = "https"
  105. else:
  106. scheme = "http"
  107. self.scheme = scheme
  108. self._root = URL(f"{self.scheme}://{self.host}:{self.port}")
  109. @abstractmethod # pragma: no cover
  110. async def _make_runner(self, **kwargs: Any) -> BaseRunner:
  111. pass
  112. def make_url(self, path: str) -> URL:
  113. assert self._root is not None
  114. url = URL(path)
  115. if not self.skip_url_asserts:
  116. assert not url.is_absolute()
  117. return self._root.join(url)
  118. else:
  119. return URL(str(self._root) + path)
  120. @property
  121. def started(self) -> bool:
  122. return self.runner is not None
  123. @property
  124. def closed(self) -> bool:
  125. return self._closed
  126. @property
  127. def handler(self) -> Server:
  128. # for backward compatibility
  129. # web.Server instance
  130. runner = self.runner
  131. assert runner is not None
  132. assert runner.server is not None
  133. return runner.server
  134. async def close(self) -> None:
  135. """Close all fixtures created by the test client.
  136. After that point, the TestClient is no longer usable.
  137. This is an idempotent function: running close multiple times
  138. will not have any additional effects.
  139. close is also run when the object is garbage collected, and on
  140. exit when used as a context manager.
  141. """
  142. if self.started and not self.closed:
  143. assert self.runner is not None
  144. await self.runner.cleanup()
  145. self._root = None
  146. self.port = None
  147. self._closed = True
  148. def __enter__(self) -> None:
  149. raise TypeError("Use async with instead")
  150. def __exit__(
  151. self,
  152. exc_type: Optional[Type[BaseException]],
  153. exc_value: Optional[BaseException],
  154. traceback: Optional[TracebackType],
  155. ) -> None:
  156. # __exit__ should exist in pair with __enter__ but never executed
  157. pass # pragma: no cover
  158. async def __aenter__(self) -> "BaseTestServer":
  159. await self.start_server(loop=self._loop)
  160. return self
  161. async def __aexit__(
  162. self,
  163. exc_type: Optional[Type[BaseException]],
  164. exc_value: Optional[BaseException],
  165. traceback: Optional[TracebackType],
  166. ) -> None:
  167. await self.close()
  168. class TestServer(BaseTestServer):
  169. def __init__(
  170. self,
  171. app: Application,
  172. *,
  173. scheme: Union[str, object] = sentinel,
  174. host: str = "127.0.0.1",
  175. port: Optional[int] = None,
  176. **kwargs: Any,
  177. ):
  178. self.app = app
  179. super().__init__(scheme=scheme, host=host, port=port, **kwargs)
  180. async def _make_runner(self, **kwargs: Any) -> BaseRunner:
  181. return AppRunner(self.app, **kwargs)
  182. class RawTestServer(BaseTestServer):
  183. def __init__(
  184. self,
  185. handler: _RequestHandler,
  186. *,
  187. scheme: Union[str, object] = sentinel,
  188. host: str = "127.0.0.1",
  189. port: Optional[int] = None,
  190. **kwargs: Any,
  191. ) -> None:
  192. self._handler = handler
  193. super().__init__(scheme=scheme, host=host, port=port, **kwargs)
  194. async def _make_runner(self, debug: bool = True, **kwargs: Any) -> ServerRunner:
  195. srv = Server(self._handler, loop=self._loop, debug=debug, **kwargs)
  196. return ServerRunner(srv, debug=debug, **kwargs)
  197. class TestClient:
  198. """
  199. A test client implementation.
  200. To write functional tests for aiohttp based servers.
  201. """
  202. __test__ = False
  203. def __init__(
  204. self,
  205. server: BaseTestServer,
  206. *,
  207. cookie_jar: Optional[AbstractCookieJar] = None,
  208. loop: Optional[asyncio.AbstractEventLoop] = None,
  209. **kwargs: Any,
  210. ) -> None:
  211. if not isinstance(server, BaseTestServer):
  212. raise TypeError(
  213. "server must be TestServer " "instance, found type: %r" % type(server)
  214. )
  215. self._server = server
  216. self._loop = loop
  217. if cookie_jar is None:
  218. cookie_jar = aiohttp.CookieJar(unsafe=True, loop=loop)
  219. self._session = ClientSession(loop=loop, cookie_jar=cookie_jar, **kwargs)
  220. self._closed = False
  221. self._responses = [] # type: List[ClientResponse]
  222. self._websockets = [] # type: List[ClientWebSocketResponse]
  223. async def start_server(self) -> None:
  224. await self._server.start_server(loop=self._loop)
  225. @property
  226. def host(self) -> str:
  227. return self._server.host
  228. @property
  229. def port(self) -> Optional[int]:
  230. return self._server.port
  231. @property
  232. def server(self) -> BaseTestServer:
  233. return self._server
  234. @property
  235. def app(self) -> Application:
  236. return getattr(self._server, "app", None)
  237. @property
  238. def session(self) -> ClientSession:
  239. """An internal aiohttp.ClientSession.
  240. Unlike the methods on the TestClient, client session requests
  241. do not automatically include the host in the url queried, and
  242. will require an absolute path to the resource.
  243. """
  244. return self._session
  245. def make_url(self, path: str) -> URL:
  246. return self._server.make_url(path)
  247. async def _request(self, method: str, path: str, **kwargs: Any) -> ClientResponse:
  248. resp = await self._session.request(method, self.make_url(path), **kwargs)
  249. # save it to close later
  250. self._responses.append(resp)
  251. return resp
  252. def request(self, method: str, path: str, **kwargs: Any) -> _RequestContextManager:
  253. """Routes a request to tested http server.
  254. The interface is identical to aiohttp.ClientSession.request,
  255. except the loop kwarg is overridden by the instance used by the
  256. test server.
  257. """
  258. return _RequestContextManager(self._request(method, path, **kwargs))
  259. def get(self, path: str, **kwargs: Any) -> _RequestContextManager:
  260. """Perform an HTTP GET request."""
  261. return _RequestContextManager(self._request(hdrs.METH_GET, path, **kwargs))
  262. def post(self, path: str, **kwargs: Any) -> _RequestContextManager:
  263. """Perform an HTTP POST request."""
  264. return _RequestContextManager(self._request(hdrs.METH_POST, path, **kwargs))
  265. def options(self, path: str, **kwargs: Any) -> _RequestContextManager:
  266. """Perform an HTTP OPTIONS request."""
  267. return _RequestContextManager(self._request(hdrs.METH_OPTIONS, path, **kwargs))
  268. def head(self, path: str, **kwargs: Any) -> _RequestContextManager:
  269. """Perform an HTTP HEAD request."""
  270. return _RequestContextManager(self._request(hdrs.METH_HEAD, path, **kwargs))
  271. def put(self, path: str, **kwargs: Any) -> _RequestContextManager:
  272. """Perform an HTTP PUT request."""
  273. return _RequestContextManager(self._request(hdrs.METH_PUT, path, **kwargs))
  274. def patch(self, path: str, **kwargs: Any) -> _RequestContextManager:
  275. """Perform an HTTP PATCH request."""
  276. return _RequestContextManager(self._request(hdrs.METH_PATCH, path, **kwargs))
  277. def delete(self, path: str, **kwargs: Any) -> _RequestContextManager:
  278. """Perform an HTTP PATCH request."""
  279. return _RequestContextManager(self._request(hdrs.METH_DELETE, path, **kwargs))
  280. def ws_connect(self, path: str, **kwargs: Any) -> _WSRequestContextManager:
  281. """Initiate websocket connection.
  282. The api corresponds to aiohttp.ClientSession.ws_connect.
  283. """
  284. return _WSRequestContextManager(self._ws_connect(path, **kwargs))
  285. async def _ws_connect(self, path: str, **kwargs: Any) -> ClientWebSocketResponse:
  286. ws = await self._session.ws_connect(self.make_url(path), **kwargs)
  287. self._websockets.append(ws)
  288. return ws
  289. async def close(self) -> None:
  290. """Close all fixtures created by the test client.
  291. After that point, the TestClient is no longer usable.
  292. This is an idempotent function: running close multiple times
  293. will not have any additional effects.
  294. close is also run on exit when used as a(n) (asynchronous)
  295. context manager.
  296. """
  297. if not self._closed:
  298. for resp in self._responses:
  299. resp.close()
  300. for ws in self._websockets:
  301. await ws.close()
  302. await self._session.close()
  303. await self._server.close()
  304. self._closed = True
  305. def __enter__(self) -> None:
  306. raise TypeError("Use async with instead")
  307. def __exit__(
  308. self,
  309. exc_type: Optional[Type[BaseException]],
  310. exc: Optional[BaseException],
  311. tb: Optional[TracebackType],
  312. ) -> None:
  313. # __exit__ should exist in pair with __enter__ but never executed
  314. pass # pragma: no cover
  315. async def __aenter__(self) -> "TestClient":
  316. await self.start_server()
  317. return self
  318. async def __aexit__(
  319. self,
  320. exc_type: Optional[Type[BaseException]],
  321. exc: Optional[BaseException],
  322. tb: Optional[TracebackType],
  323. ) -> None:
  324. await self.close()
  325. class AioHTTPTestCase(unittest.TestCase):
  326. """A base class to allow for unittest web applications using
  327. aiohttp.
  328. Provides the following:
  329. * self.client (aiohttp.test_utils.TestClient): an aiohttp test client.
  330. * self.loop (asyncio.BaseEventLoop): the event loop in which the
  331. application and server are running.
  332. * self.app (aiohttp.web.Application): the application returned by
  333. self.get_application()
  334. Note that the TestClient's methods are asynchronous: you have to
  335. execute function on the test client using asynchronous methods.
  336. """
  337. async def get_application(self) -> Application:
  338. """
  339. This method should be overridden
  340. to return the aiohttp.web.Application
  341. object to test.
  342. """
  343. return self.get_app()
  344. def get_app(self) -> Application:
  345. """Obsolete method used to constructing web application.
  346. Use .get_application() coroutine instead
  347. """
  348. raise RuntimeError("Did you forget to define get_application()?")
  349. def setUp(self) -> None:
  350. self.loop = setup_test_loop()
  351. self.app = self.loop.run_until_complete(self.get_application())
  352. self.server = self.loop.run_until_complete(self.get_server(self.app))
  353. self.client = self.loop.run_until_complete(self.get_client(self.server))
  354. self.loop.run_until_complete(self.client.start_server())
  355. self.loop.run_until_complete(self.setUpAsync())
  356. async def setUpAsync(self) -> None:
  357. pass
  358. def tearDown(self) -> None:
  359. self.loop.run_until_complete(self.tearDownAsync())
  360. self.loop.run_until_complete(self.client.close())
  361. teardown_test_loop(self.loop)
  362. async def tearDownAsync(self) -> None:
  363. pass
  364. async def get_server(self, app: Application) -> TestServer:
  365. """Return a TestServer instance."""
  366. return TestServer(app, loop=self.loop)
  367. async def get_client(self, server: TestServer) -> TestClient:
  368. """Return a TestClient instance."""
  369. return TestClient(server, loop=self.loop)
  370. def unittest_run_loop(func: Any, *args: Any, **kwargs: Any) -> Any:
  371. """A decorator dedicated to use with asynchronous methods of an
  372. AioHTTPTestCase.
  373. Handles executing an asynchronous function, using
  374. the self.loop of the AioHTTPTestCase.
  375. """
  376. @functools.wraps(func, *args, **kwargs)
  377. def new_func(self: Any, *inner_args: Any, **inner_kwargs: Any) -> Any:
  378. return self.loop.run_until_complete(func(self, *inner_args, **inner_kwargs))
  379. return new_func
  380. _LOOP_FACTORY = Callable[[], asyncio.AbstractEventLoop]
  381. @contextlib.contextmanager
  382. def loop_context(
  383. loop_factory: _LOOP_FACTORY = asyncio.new_event_loop, fast: bool = False
  384. ) -> Iterator[asyncio.AbstractEventLoop]:
  385. """A contextmanager that creates an event_loop, for test purposes.
  386. Handles the creation and cleanup of a test loop.
  387. """
  388. loop = setup_test_loop(loop_factory)
  389. yield loop
  390. teardown_test_loop(loop, fast=fast)
  391. def setup_test_loop(
  392. loop_factory: _LOOP_FACTORY = asyncio.new_event_loop,
  393. ) -> asyncio.AbstractEventLoop:
  394. """Create and return an asyncio.BaseEventLoop
  395. instance.
  396. The caller should also call teardown_test_loop,
  397. once they are done with the loop.
  398. """
  399. loop = loop_factory()
  400. try:
  401. module = loop.__class__.__module__
  402. skip_watcher = "uvloop" in module
  403. except AttributeError: # pragma: no cover
  404. # Just in case
  405. skip_watcher = True
  406. asyncio.set_event_loop(loop)
  407. if sys.platform != "win32" and not skip_watcher:
  408. policy = asyncio.get_event_loop_policy()
  409. watcher = asyncio.SafeChildWatcher()
  410. watcher.attach_loop(loop)
  411. with contextlib.suppress(NotImplementedError):
  412. policy.set_child_watcher(watcher)
  413. return loop
  414. def teardown_test_loop(loop: asyncio.AbstractEventLoop, fast: bool = False) -> None:
  415. """Teardown and cleanup an event_loop created
  416. by setup_test_loop.
  417. """
  418. closed = loop.is_closed()
  419. if not closed:
  420. loop.call_soon(loop.stop)
  421. loop.run_forever()
  422. loop.close()
  423. if not fast:
  424. gc.collect()
  425. asyncio.set_event_loop(None)
  426. def _create_app_mock() -> mock.MagicMock:
  427. def get_dict(app: Any, key: str) -> Any:
  428. return app.__app_dict[key]
  429. def set_dict(app: Any, key: str, value: Any) -> None:
  430. app.__app_dict[key] = value
  431. app = mock.MagicMock()
  432. app.__app_dict = {}
  433. app.__getitem__ = get_dict
  434. app.__setitem__ = set_dict
  435. app._debug = False
  436. app.on_response_prepare = Signal(app)
  437. app.on_response_prepare.freeze()
  438. return app
  439. def _create_transport(sslcontext: Optional[SSLContext] = None) -> mock.Mock:
  440. transport = mock.Mock()
  441. def get_extra_info(key: str) -> Optional[SSLContext]:
  442. if key == "sslcontext":
  443. return sslcontext
  444. else:
  445. return None
  446. transport.get_extra_info.side_effect = get_extra_info
  447. return transport
  448. def make_mocked_request(
  449. method: str,
  450. path: str,
  451. headers: Any = None,
  452. *,
  453. match_info: Any = sentinel,
  454. version: HttpVersion = HttpVersion(1, 1),
  455. closing: bool = False,
  456. app: Any = None,
  457. writer: Any = sentinel,
  458. protocol: Any = sentinel,
  459. transport: Any = sentinel,
  460. payload: Any = sentinel,
  461. sslcontext: Optional[SSLContext] = None,
  462. client_max_size: int = 1024 ** 2,
  463. loop: Any = ...,
  464. ) -> Request:
  465. """Creates mocked web.Request testing purposes.
  466. Useful in unit tests, when spinning full web server is overkill or
  467. specific conditions and errors are hard to trigger.
  468. """
  469. task = mock.Mock()
  470. if loop is ...:
  471. loop = mock.Mock()
  472. loop.create_future.return_value = ()
  473. if version < HttpVersion(1, 1):
  474. closing = True
  475. if headers:
  476. headers = CIMultiDictProxy(CIMultiDict(headers))
  477. raw_hdrs = tuple(
  478. (k.encode("utf-8"), v.encode("utf-8")) for k, v in headers.items()
  479. )
  480. else:
  481. headers = CIMultiDictProxy(CIMultiDict())
  482. raw_hdrs = ()
  483. chunked = "chunked" in headers.get(hdrs.TRANSFER_ENCODING, "").lower()
  484. message = RawRequestMessage(
  485. method,
  486. path,
  487. version,
  488. headers,
  489. raw_hdrs,
  490. closing,
  491. False,
  492. False,
  493. chunked,
  494. URL(path),
  495. )
  496. if app is None:
  497. app = _create_app_mock()
  498. if transport is sentinel:
  499. transport = _create_transport(sslcontext)
  500. if protocol is sentinel:
  501. protocol = mock.Mock()
  502. protocol.transport = transport
  503. if writer is sentinel:
  504. writer = mock.Mock()
  505. writer.write_headers = make_mocked_coro(None)
  506. writer.write = make_mocked_coro(None)
  507. writer.write_eof = make_mocked_coro(None)
  508. writer.drain = make_mocked_coro(None)
  509. writer.transport = transport
  510. protocol.transport = transport
  511. protocol.writer = writer
  512. if payload is sentinel:
  513. payload = mock.Mock()
  514. req = Request(
  515. message, payload, protocol, writer, task, loop, client_max_size=client_max_size
  516. )
  517. match_info = UrlMappingMatchInfo(
  518. {} if match_info is sentinel else match_info, mock.Mock()
  519. )
  520. match_info.add_app(app)
  521. req._match_info = match_info
  522. return req
  523. def make_mocked_coro(
  524. return_value: Any = sentinel, raise_exception: Any = sentinel
  525. ) -> Any:
  526. """Creates a coroutine mock."""
  527. async def mock_coro(*args: Any, **kwargs: Any) -> Any:
  528. if raise_exception is not sentinel:
  529. raise raise_exception
  530. if not inspect.isawaitable(return_value):
  531. return return_value
  532. await return_value
  533. return mock.Mock(wraps=mock_coro)