Coverage for src/zapy/api/v1/api_requests.py: 93%
35 statements
« prev ^ index » next coverage.py v7.4.1, created at 2024-02-10 19:35 +0000
« prev ^ index » next coverage.py v7.4.1, created at 2024-02-10 19:35 +0000
1from typing import Annotated, Any, Self
3from fastapi import APIRouter, BackgroundTasks, Header
4from pydantic import BaseModel
6from zapy.api.deps.socketio import SocketIO
7from zapy.base.exceptions import ZapyError
8from zapy.requests.models import ZapyRequest
9from zapy.requests.requester import RequesterResponse, TestResult, send_request
11api_request_v1 = APIRouter(tags=["v1"])
14class RequestExecResponse(BaseModel):
15 @classmethod
16 def from_wrapper(cls, wrapper: RequesterResponse) -> Self:
17 response = wrapper.response
18 content = response.text
19 return cls(
20 content=content,
21 content_type=response.headers.get("content-type"),
22 headers=dict(response.headers.items()),
23 status=response.status_code,
24 time=response.elapsed.total_seconds(),
25 test_result=wrapper.test_result,
26 )
28 content: str
29 content_type: str
30 headers: dict[str, str]
31 status: int
32 time: float
33 test_result: list[TestResult]
36@api_request_v1.post("/request/exec")
37async def exec_cell(
38 sio: SocketIO,
39 background_tasks: BackgroundTasks,
40 zapy_request: ZapyRequest,
41 x_request_id: Annotated[str | None, Header()] = None,
42) -> RequestExecResponse:
43 def logger(*msg: tuple[Any], sep: str = " ", end: str = "\n") -> None:
44 log_message = sep.join(str(m) for m in msg) + end
45 background_tasks.add_task(sio.emit, f"log:{x_request_id}", log_message)
47 try:
48 response_wrapper = await send_request(
49 zapy_request=zapy_request,
50 logger=logger,
51 )
52 response_exec = RequestExecResponse.from_wrapper(response_wrapper)
53 return response_exec
54 except ZapyError as ex:
55 response = ex.context.get("response")
56 if response: 56 ↛ 57line 56 didn't jump to line 57, because the condition on line 56 was never true
57 response_wrapper = RequesterResponse(response)
58 ex.context["response"] = RequestExecResponse.from_wrapper(response_wrapper)
59 raise