|
| 1 | +from copy import deepcopy |
| 2 | +from dataclasses import dataclass |
| 3 | +from inspect import isawaitable |
| 4 | +from typing import Awaitable, Callable |
| 5 | + |
| 6 | +from aiohttp import web |
| 7 | + |
| 8 | + |
| 9 | +@dataclass |
| 10 | +class MockData: |
| 11 | + method: str # the method we replace |
| 12 | + path: str # the API path we are replacing |
| 13 | + response: ( |
| 14 | + web.Response |
| 15 | + | Callable[[web.Request], web.Response | Awaitable[web.Response]] |
| 16 | + ) |
| 17 | + |
| 18 | + |
| 19 | +class WebServiceMock: |
| 20 | + """ |
| 21 | + A mock web service with a single API handle. |
| 22 | + Intended use: |
| 23 | + 1. Start aiohttp_server with a universal route to the handle |
| 24 | + 2. Add real APIs via add_mock_data |
| 25 | + """ |
| 26 | + |
| 27 | + def __init__(self): |
| 28 | + self._mock_data: list[MockData] = [] |
| 29 | + self._call_info = {} |
| 30 | + |
| 31 | + async def handle(self, request: web.Request) -> web.Response: |
| 32 | + """ |
| 33 | + The method searches for a mock among the registered MockData, |
| 34 | + stores the request information, and returns a mock response. |
| 35 | + """ |
| 36 | + for mock in self._mock_data: |
| 37 | + if ( |
| 38 | + mock.method.lower() == request.method.lower() |
| 39 | + and mock.path == request.path |
| 40 | + ): |
| 41 | + await self._save_request(mock.method, mock.path, request) |
| 42 | + if isinstance(mock.response, web.Response): |
| 43 | + return deepcopy(mock.response) |
| 44 | + else: |
| 45 | + response = mock.response(request) |
| 46 | + if isawaitable(response): |
| 47 | + return await response |
| 48 | + else: |
| 49 | + return response |
| 50 | + |
| 51 | + raise Exception( |
| 52 | + f"Mock with method={request.method} " |
| 53 | + f"and url={request.path} not found" |
| 54 | + ) |
| 55 | + |
| 56 | + def add_mock_data(self, mock_data: MockData) -> list[dict[str, any]]: |
| 57 | + """Saves a new mock and returns a reference to the call history""" |
| 58 | + self._mock_data.append(mock_data) |
| 59 | + |
| 60 | + url_data = self._call_info.get(mock_data.path) or {} |
| 61 | + method_data = url_data.get(mock_data.method) or [] |
| 62 | + url_data[mock_data.method] = method_data |
| 63 | + self._call_info[mock_data.path] = url_data |
| 64 | + return self._call_info[mock_data.path][mock_data.method] |
| 65 | + |
| 66 | + async def _save_request( |
| 67 | + self, method: str, path: str, request: web.Request |
| 68 | + ) -> None: |
| 69 | + data = {"headers": request.headers} |
| 70 | + if request.can_read_body: |
| 71 | + if request.content_type == "application/json": |
| 72 | + data["json"] = await request.json() |
| 73 | + if request.content_type == "text/plain": |
| 74 | + data["text"] = await request.text() |
| 75 | + |
| 76 | + self._call_info[path][method].append(data) |
0 commit comments