| 119 | logging.info("Server started") |
| 120 | |
| 121 | def run( |
| 122 | self, start_signal: queue.SimpleQueue, exception_queue: queue.SimpleQueue, key: str, handler: CommandHandler |
| 123 | ): |
| 124 | stop_signal: Optional[asyncio.Queue] = None |
| 125 | |
| 126 | async def handle_request(request): |
| 127 | command = request.match_info["cmd"] |
| 128 | request_key = request.headers["HQ_TEST_KEY"] |
| 129 | assert request_key == key |
| 130 | |
| 131 | logging.info(f"Received request: {request}, command: {command}") |
| 132 | input = await extract_mock_input(request, command) |
| 133 | try: |
| 134 | resp = await handler.handle_command(input) |
| 135 | except ManagerException as e: |
| 136 | # This exception should not be propagated within tests, and should be returned |
| 137 | # in stderr of the manager response instead. |
| 138 | resp = response_error(stderr=str(e)) |
| 139 | assert isinstance(resp, CommandOutput) |
| 140 | |
| 141 | resp = { |
| 142 | "stdout": resp.stdout, |
| 143 | "stderr": resp.stderr, |
| 144 | "code": resp.code, |
| 145 | } |
| 146 | return web.json_response(resp) |
| 147 | |
| 148 | @web.middleware |
| 149 | async def handle_error(request, handler): |
| 150 | """ |
| 151 | Make sure that if any exception is thrown, we propagate it to the tests. |
| 152 | """ |
| 153 | nonlocal stop_signal |
| 154 | try: |
| 155 | return await handler(request) |
| 156 | except BaseException as e: |
| 157 | stop_signal.put_nowait(e) |
| 158 | return response_error() |
| 159 | |
| 160 | app = web.Application(middlewares=[handle_error]) |
| 161 | app.add_routes( |
| 162 | [ |
| 163 | web.post("/{cmd}", handle_request), |
| 164 | ] |
| 165 | ) |
| 166 | |
| 167 | async def body(): |
| 168 | """ |
| 169 | On Python <3.10, asyncio.Queue cannot be created outside an event loop. |
| 170 | That is why it is created in such a complicated way here. |
| 171 | """ |
| 172 | nonlocal stop_signal |
| 173 | stop_signal = asyncio.Queue() |
| 174 | |
| 175 | logging.info("Starting mock server") |
| 176 | runner = web.AppRunner(app) |
| 177 | await runner.setup() |
| 178 | |