From 6a88c98949828b762cf45864c1a9766f6d516623 Mon Sep 17 00:00:00 2001 From: Helena Adamkova <58051865+Ellenn-A@users.noreply.github.com> Date: Mon, 20 May 2024 13:14:43 +0100 Subject: [PATCH] test restructure --- app/main.py | 84 ++---------- app/routes/posts.py | 171 ++++++++++++++++++------- extra/helper.py | 26 ---- extra/test_2.py | 30 ----- poetry.lock | 16 +-- pyproject.toml | 1 - tests/conftest.py | 82 +++++++++++- tests/test_drcp_event_handler.py | 212 +++++++++++++++++++++++++++++++ tests/test_endpoints.py | 96 -------------- tests/test_post_query.py | 53 ++++++++ tests/test_receive_response.py | 51 ++++++++ 11 files changed, 531 insertions(+), 291 deletions(-) delete mode 100644 extra/helper.py delete mode 100644 extra/test_2.py create mode 100644 tests/test_drcp_event_handler.py delete mode 100644 tests/test_endpoints.py create mode 100644 tests/test_post_query.py create mode 100644 tests/test_receive_response.py diff --git a/app/main.py b/app/main.py index ad3f11a..4e0f733 100644 --- a/app/main.py +++ b/app/main.py @@ -1,77 +1,15 @@ -from typing import Optional, List, Any -from datetime import datetime -from enum import IntEnum, StrEnum -import requests -from fastapi import FastAPI, HTTPException -from uagents import Model -import httpx +from fastapi import FastAPI +from routes import router as api_router -veritableUrl = "http://localhost:3010" -peerUrl="http://localhost:3001/api" - -class TestRequest(Model): - message: str - -class DrpcRequestObject(Model): - jsonrpc: str - method: str - params: Optional[List | object] - id: Optional[str| int ] - -class DrpcErrorCode(IntEnum): - METHOD_NOT_FOUND = -32601, # make all stuff inside enums lowercase - PARSE_ERROR = -32700, - INVALID_REQUEST = -32600, - INVALID_PARAMS = -32602, - INTERNAL_ERROR = -32603, - SERVER_ERROR = -32000, - -class DrpcResponseError(Model): - code: DrpcErrorCode - message: str - data: Optional[Any] - -class DrpcResponseObject(Model): - jsonrpc: str - result: Optional[Any] - error: Optional[DrpcResponseError] - id: Optional[str| int ] - -class DrpcRole(StrEnum): - Client = 'client', - Server = 'server', - -class DrpcState(StrEnum): - RequestSent = 'request-sent', - RequestReceived = 'request-received', - Completed = 'completed', - -class Query(Model): - message: dict - -# RPC Response example -# --> {"jsonrpc": "2.0", "method": "subtract", "params": [23, 42], "id": 2} -# <-- {"jsonrpc": "2.0", "result": -19, "id": 2} -class Response(Model): - message: dict - -class DrpcEvent(Model): - createdAt: datetime - request: Optional[DrpcRequestObject| List[DrpcRequestObject]] - response: Optional[DrpcResponseObject] - connectionId: str - role: DrpcRole - state: DrpcState - threadId: str - id:str - _tags:dict - -app = FastAPI() +def get_application() -> FastAPI: + """ + Controller to setup the application and return an Application + instance to Uvicorn. + """ + application = FastAPI() + application.include_router(api_router) + return application - -# def start(): -# uvicorn.run(app, host="0.0.0.0", port=8000) -# if __name__ == "__main__": -# start() \ No newline at end of file +app = get_application() diff --git a/app/routes/posts.py b/app/routes/posts.py index 5aaa77d..a46f103 100644 --- a/app/routes/posts.py +++ b/app/routes/posts.py @@ -1,70 +1,147 @@ from fastapi import APIRouter,HTTPException +from typing import Optional, List, Any +from datetime import datetime +from enum import IntEnum, StrEnum from fastapi.responses import JSONResponse from pydantic import BaseModel import httpx +import requests +from uagents import Model veritableUrl = "http://localhost:3010" +peerUrl="http://localhost:3001/api" + class Query(BaseModel): message: dict +class DrpcRequestObject(Model): + jsonrpc: str + method: str + params: Optional[List | object] + id: Optional[str| int ] + +class DrpcErrorCode(IntEnum): + method_not_found = -32601, + parse_error = -32700, + invalid_request = -32600, + invalid_params = -32602, + internal_error = -32603, + server_error = -32000, + +class DrpcResponseError(Model): + code: DrpcErrorCode + message: str + data: Optional[Any] + +class DrpcResponseObject(Model): + jsonrpc: str + result: Optional[Any] + error: Optional[DrpcResponseError] + id: Optional[str| int ] + +class DrpcRole(StrEnum): + Client = 'client', + Server = 'server', + +class DrpcState(StrEnum): + RequestSent = 'request-sent', + RequestReceived = 'request-received', + Completed = 'completed', + +class Query(Model): + message: dict + +# RPC Response example +# --> {"jsonrpc": "2.0", "method": "subtract", "params": [23, 42], "id": 2} +# <-- {"jsonrpc": "2.0", "result": -19, "id": 2} +class Response(Model): + message: dict + +class DrpcEvent(Model): + createdAt: datetime + request: Optional[DrpcRequestObject| List[DrpcRequestObject]] + response: Optional[DrpcResponseObject] + connectionId: str + role: DrpcRole + state: DrpcState + threadId: str + id:str + _tags:dict + router = APIRouter() async def postToVeritable(req:Query)-> JSONResponse: - req_dict = dict(req) - async with httpx.AsyncClient() as client: - response = await client.post(f"{veritableUrl}/drcp/request", json=req_dict) - return response - + async with httpx.AsyncClient() as client: + response = await client.post(f"{veritableUrl}/drcp/request", json=req) + return [response.status, response.json()] +async def postResponseToVeritable(req: Response)-> JSONResponse: + async with httpx.AsyncClient() as client: + response = client.post(f"{veritableUrl}/drcp/response", json=req) + return [response.status, response.json()] +async def peerReceivesResponse(req: DrpcEvent) -> JSONResponse: + async with httpx.AsyncClient() as client: + response = await client.post(f"{peerUrl}/receive-response", json=req) + return [response.status, response.json()] +async def peerReceivesQuery(req: DrpcEvent) -> JSONResponse: + async with httpx.AsyncClient() as client: + response =await client.post(f"{peerUrl}/receive-query", json=req) + return [response.status, response.json()] + @router.post("/send-query", name="test-name",status_code=202) async def send_query(req: Query): # need to define Query try: response = await postToVeritable(req) - if response.status_code != 202: - print("Error:", response.status_code) - return response.json() + if response[0] != '202': + raise ValueError("Response status is not 202") + return response except Exception as e: raise HTTPException(status_code=500, detail=str(e)) - - -# @app.post("/webhooks/drpc") #from veritable cloudagent # need to pay attention to responseState changed and request state changed -# async def drpc_event_handler(req: DrpcEvent): -# try: -# req_dict = dict(req) -# req_dict['createdAt'] = req_dict['createdAt'].isoformat() - -# # Convert DrpcRequestObject object to a dictionary -# if req_dict['request']: -# req_dict['request'] = dict(req_dict['request']) +@router.post("/webhooks/drpc", name="webhooks-drpc",status_code=200) #from veritable cloudagent to peerAPI +async def drpc_event_handler(req: DrpcEvent): + try: + req_dict = dict(req) + req_dict['createdAt'] = req_dict['createdAt'].isoformat() + # Convert DrpcRequestObject object to a dictionary + if req_dict['request']: + req_dict['request'] = dict(req_dict['request']) -# # Convert DrpcResponseObject object to a dictionary -# if req_dict['response']: -# req_dict['response'] = dict(req_dict['response']) -# # Convert DrpcResponseError object to a dictionary -# if req_dict['response']['error']: -# req_dict['response']['error'] = dict(req_dict['response']['error']) -# if req_dict['role']=='client': -# # respond to the peer API -# response = requests.post(f"{peerUrl}/receive-response", json=req_dict) -# print('in request') -# if req_dict['role']=='server': -# response = requests.post(f"{peerUrl}/receive-query", json=req_dict) -# if response.status_code != 200: -# print("Error:", response.status_code) -# return response -# except Exception as e: -# raise HTTPException(status_code=500, detail=str(e)) -# @app.post("/receive-response") ## this receives response from chainvine and it forwards info to veritable -# async def receive_response(resp: Response): #basic RPC response -# try: -# req_dict = dict(resp) -# # relay stuff to the drcp/response in veritable -# response = requests.post(f"{veritableUrl}/drcp/response", json=req_dict) -# if response.status_code != 200: -# print("Error:", response.status_code) -# return response -# except Exception as e: -# raise HTTPException(status_code=500, detail=str(e)) \ No newline at end of file + # Convert DrpcResponseObject object to a dictionary + if req_dict['response']: + req_dict['response'] = dict(req_dict['response']) + # Convert DrpcResponseError object to a dictionary + if req_dict['response']['error']: + req_dict['response']['error'] = dict(req_dict['response']['error']) + request_check = req_dict['request'] + response_check = req_dict['response'] + role_check = req_dict['role'] + if request_check and response_check: + raise ValueError("JSON body cannot contain both 'request' and 'response'") + if request_check and role_check != 'server': + raise ValueError("If 'request' is present, 'role' must be 'server'") + if response_check and role_check != 'client': + raise ValueError("If 'response' is present, 'role' must be 'client'") + if role_check =='client': + response =await peerReceivesResponse(req_dict) + elif role_check =='server': + response = await peerReceivesQuery(req_dict) + else: + raise ValueError("Error in request body.") + if response[0] != '200': + raise ValueError("Response status is not 200") + return response + except Exception as e: + raise HTTPException(status_code=500, detail=str(e)) + +@router.post("/receive-response", name="receive-response",status_code=200) ## this receives response from chainvine and it forwards info to veritable +async def receive_response(resp: Response): #basic RPC response + try: + response = await postResponseToVeritable(resp) + if response[0] != '200': + raise ValueError("Response status is not 200") + return response + except Exception as e: + raise HTTPException(status_code=500, detail=str(e)) \ No newline at end of file diff --git a/extra/helper.py b/extra/helper.py deleted file mode 100644 index 07b8348..0000000 --- a/extra/helper.py +++ /dev/null @@ -1,26 +0,0 @@ -# from fastapi import FastAPI, HTTPException, Depends -# import httpx -# from typing import Any -# from pydantic import BaseModel - -# veritableUrl = "http://localhost:3010" -# peerUrl = "http://localhost:3001/api" - -# app = FastAPI() -# class Query(BaseModel): -# message: dict - -# def get_http_client() -> httpx.AsyncClient: -# return httpx.AsyncClient() - -# @app.post("/send-query") -# async def send_query(req: Query, http_client: httpx.AsyncClient = Depends(get_http_client)): -# try: -# response = await http_client.post(f"{veritableUrl}/drcp/request", json=req) -# if response.status_code != 202: -# print("Error:", response.status_code) -# return response.json() -# except Exception as e: -# raise HTTPException(status_code=500, detail=str(e)) - -# # Other endpoints ... diff --git a/extra/test_2.py b/extra/test_2.py deleted file mode 100644 index 6329ecc..0000000 --- a/extra/test_2.py +++ /dev/null @@ -1,30 +0,0 @@ -# import pytest -# from fastapi.testclient import TestClient -# from unittest.mock import AsyncMock, patch -# from extra.main import app, get_http_client -# import httpx -# veritableUrl = "http://localhost:3010" -# client = TestClient(app) - -# @pytest.fixture -# def mock_http_client(): -# mock = AsyncMock(httpx.AsyncClient) -# with patch('app.main.get_http_client', return_value=mock): -# yield mock - -# def test_send_query(mock_http_client): -# # Mock the post method to return a response with status code 202 -# mock_http_client.post.return_value = AsyncMock(status_code=202, json=lambda: {"success": True}) - -# # Make a POST request to the /send-query endpoint -# response = client.post("/send-query", json={"message": {"content": "some test message"}}) - -# # Assert the response status code and JSON content -# assert response.status_code == 202 -# assert response.json() == {"success": True} - -# # Assert that the mock post method was called with the correct arguments -# mock_http_client.post.assert_called_once_with( -# f"{veritableUrl}/drcp/request", -# json={"message": {"content": "some test message"}} -# ) diff --git a/poetry.lock b/poetry.lock index f694ec6..5896bcf 100644 --- a/poetry.lock +++ b/poetry.lock @@ -1537,20 +1537,6 @@ requests = ">=2.22,<3" [package.extras] fixture = ["fixtures"] -[[package]] -name = "respx" -version = "0.21.1" -description = "A utility for mocking out the Python HTTPX and HTTP Core libraries." -optional = false -python-versions = ">=3.7" -files = [ - {file = "respx-0.21.1-py2.py3-none-any.whl", hash = "sha256:05f45de23f0c785862a2c92a3e173916e8ca88e4caad715dd5f68584d6053c20"}, - {file = "respx-0.21.1.tar.gz", hash = "sha256:0bd7fe21bfaa52106caa1223ce61224cf30786985f17c63c5d71eff0307ee8af"}, -] - -[package.dependencies] -httpx = ">=0.21.0" - [[package]] name = "rich" version = "13.7.1" @@ -2216,4 +2202,4 @@ multidict = ">=4.0" [metadata] lock-version = "2.0" python-versions = "~3.12" -content-hash = "d091483b1836ce1631cc9f4c312ffbf16b05e270e420e1f49adb2ed2e26dfd7b" +content-hash = "da01fc9db9ad90ce70577402c50b78b13337c7a8e03eb6a34f98944bb7df246d" diff --git a/pyproject.toml b/pyproject.toml index 184dc9c..ba7c5be 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -21,7 +21,6 @@ flake8 = "^7.0.0" httpx = "^0.27.0" asgi-lifespan = "^2.1.0" pytest-asyncio = "^0.23.6" -respx = "^0.21.1" [tool.poetry.group.dev.dependencies] diff --git a/tests/conftest.py b/tests/conftest.py index fbf1431..e00eae3 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -2,7 +2,7 @@ from fastapi import FastAPI from asgi_lifespan import LifespanManager import pytest_asyncio -from httpx import AsyncClient, ASGITransport +from httpx import AsyncClient @pytest.fixture def app() -> FastAPI: @@ -29,7 +29,7 @@ async def client(app: FastAPI) -> AsyncClient: @pytest.fixture -def test_forward_query_success_mock_202(mocker) -> None: +def test_post_query_success_mock_202(mocker) -> None: """ Test return data for the 202 response from veritable when forwarding a query. """ @@ -39,4 +39,80 @@ def test_forward_query_success_mock_202(mocker) -> None: "202", {}, ], - ) \ No newline at end of file + ) + +@pytest.fixture +def test_receive_response_success_mock_200(mocker) -> None: + """ + Test return data for the 200 receive response forwarding to veritable. + """ + mocker.patch( + "routes.posts.postResponseToVeritable", + return_value=[ + "200", + {}, + ], + ) +@pytest.fixture +def test_receive_response_fail_mock_500(mocker) -> None: + """ + Test return data for the 500 receive response forwarding to veritable. + """ + mocker.patch( + "routes.posts.postResponseToVeritable", + return_value=[ + "500", + {}, + ], + ) + +@pytest.fixture +def test_drcp_event_handler_response_success_mock_200(mocker) -> None: + """ + Test return data for forwarding data from the "/webhooks/drpc" endpoint to /receive-response endpoint in peerAPI. + """ + mocker.patch( + "routes.posts.peerReceivesResponse", + return_value=[ + "200", + {}, + ], + ) +@pytest.fixture +def test_drcp_event_handler_query_success_mock_200(mocker) -> None: + """ + Test return data for forwarding data from the "/webhooks/drpc" endpoint to /receive-query endpoint in peerAPI. + """ + mocker.patch( + "routes.posts.peerReceivesQuery", + return_value=[ + "200", + {}, + ], + ) + +@pytest.fixture +def test_drcp_event_handler_query_fail_mock_500(mocker) -> None: + """ + Test failed return data for forwarding data from the "/webhooks/drpc" endpoint to /receive-query endpoint in peerAPI. + """ + mocker.patch( + "routes.posts.peerReceivesQuery", + return_value=[ + "500", + {}, + ], + ) +@pytest.fixture +def test_post_query_fail_mock_500(mocker) -> None: + """ + Test return data for 500 response from veritable when forwarding a query. + """ + mocker.patch( + "routes.posts.postToVeritable", + return_value=[ + "500", + {}, + ], + ) + \ No newline at end of file diff --git a/tests/test_drcp_event_handler.py b/tests/test_drcp_event_handler.py new file mode 100644 index 0000000..da60b3c --- /dev/null +++ b/tests/test_drcp_event_handler.py @@ -0,0 +1,212 @@ +from fastapi import FastAPI, status +from httpx import AsyncClient +import pytest +pytestmark = pytest.mark.asyncio + + +# happy path tests +async def test_drcp_event_handler_response( + app: FastAPI, + client: AsyncClient, + test_drcp_event_handler_response_success_mock_200, +) -> None: + """ + ... + """ + payload = { + "createdAt": "2024-05-20T08:51:21.630Z", + "response": { + "jsonrpc": "string", + "result": "string", + "error": { + "code": -32601, + "message": "string", + "data": "string" + }, + "id": "string" + }, + "connectionId": "string", + "role": "client", + "state": "request-sent", + "threadId": "string", + "id": "string" +} + response_pat = await client.post( + app.url_path_for("webhooks-drpc"), + json=payload, + ) + assert response_pat.status_code == status.HTTP_200_OK + +async def test_drcp_event_handler_query( + app: FastAPI, + client: AsyncClient, + test_drcp_event_handler_query_success_mock_200, +) -> None: + """ + ... + """ + payload = { + "createdAt": "2024-05-20T08:51:21.630Z", + "request": { + "jsonrpc": "string", + "method": "string", + "params": [ + "string" + ], + "id": "string" + }, + "connectionId": "string", + "role": "server", + "state": "request-sent", + "threadId": "string", + "id": "string" +} + response_pat = await client.post( + app.url_path_for("webhooks-drpc"), + json=payload, + ) + assert response_pat.status_code == status.HTTP_200_OK + + # Sad path tests +async def test_receive_response_422( + app: FastAPI, + client: AsyncClient, +) -> None: + """ + ... + """ + payload = {"some":"wrong body"} + response_pat = await client.post( + app.url_path_for("webhooks-drpc"), + json=payload, + ) + assert response_pat.status_code == status.HTTP_422_UNPROCESSABLE_ENTITY + +async def test_receive_response_500( + app: FastAPI, + client: AsyncClient, +) -> None: + """ + ... + """ + payload = { + "createdAt": "2024-05-20T08:51:21.630Z", + "request": { + "jsonrpc": "string", + "method": "string", + "params": [ + "string" + ], + "id": "string" + }, + "response": { + "jsonrpc": "string", + "result": "string", + "error": { + "code": -32601, + "message": "string", + "data": "string" + }, + "id": "string" + }, + "connectionId": "string", + "role": "client", + "state": "request-sent", + "threadId": "string", + "id": "string" +} + response_pat = await client.post( + app.url_path_for("webhooks-drpc"), + json=payload, + ) + assert response_pat.status_code == status.HTTP_500_INTERNAL_SERVER_ERROR + +async def test_drcp_event_handler_query_wrong_role( + app: FastAPI, + client: AsyncClient, +) -> None: + """ + ... + """ + payload = { + "createdAt": "2024-05-20T08:51:21.630Z", + "request": { + "jsonrpc": "string", + "method": "string", + "params": [ + "string" + ], + "id": "string" + }, + "connectionId": "string", + "role": "client", + "state": "request-sent", + "threadId": "string", + "id": "string" +} + response_pat = await client.post( + app.url_path_for("webhooks-drpc"), + json=payload, + ) + assert response_pat.status_code == status.HTTP_500_INTERNAL_SERVER_ERROR + +async def test_drcp_event_handler_response_wrong_role( + app: FastAPI, + client: AsyncClient, +) -> None: + """ + ... + """ + payload = { + "createdAt": "2024-05-20T08:51:21.630Z", + "response": { + "jsonrpc": "string", + "result": "string", + "error": { + "code": -32601, + "message": "string", + "data": "string" + }, + "id": "string" + }, + "connectionId": "string", + "role": "server", + "state": "request-sent", + "threadId": "string", + "id": "string" +} + response_pat = await client.post( + app.url_path_for("webhooks-drpc"), + json=payload, + ) + assert response_pat.status_code == status.HTTP_500_INTERNAL_SERVER_ERROR + +async def test_drcp_event_handler_query_fail_500( + app: FastAPI, + client: AsyncClient, + test_drcp_event_handler_query_fail_mock_500, +) -> None: + """ + ... + """ + payload = { + "createdAt": "2024-05-20T08:51:21.630Z", + "request": { + "jsonrpc": "string", + "method": "string", + "params": [ + "string" + ], + "id": "string" + }, + "connectionId": "string", + "role": "server", + "state": "request-sent", + "threadId": "string", + "id": "string" +} + response_pat = await client.post( + app.url_path_for("webhooks-drpc"), + json=payload, + ) + assert response_pat.status_code == status.HTTP_500_INTERNAL_SERVER_ERROR \ No newline at end of file diff --git a/tests/test_endpoints.py b/tests/test_endpoints.py deleted file mode 100644 index 6971b36..0000000 --- a/tests/test_endpoints.py +++ /dev/null @@ -1,96 +0,0 @@ -from fastapi import FastAPI, status -from httpx import AsyncClient -from unittest.mock import MagicMock, Mock, patch - - -import pytest - - - -pytestmark = pytest.mark.asyncio - -veritableUrl = "http://localhost:3010" -peerUrl="http://localhost:3001/api" - - -async def test_post_query( - app: FastAPI, - client: AsyncClient, - test_forward_query_success_mock_202, -) -> None: - """ - ... - """ - payload = {"message":{"content": "some test message"}} - response_pat = await client.post( - app.url_path_for("test-name"), - json=payload, - ) - print(response_pat.json()) - assert response_pat.status_code == status.HTTP_202_ACCEPTED - - - - -# def test_send_query(): -# def mockJson(): -# return {} -# mockClient = Mock() -# mockClient.status_code = 202 -# mockClient.json = mockJson - -# class AsyncContextManager: -# async def __aenter__(self): -# return self -# async def __aexit__(self, exc_type, exc, tb): -# pass -# async def post(self, url): -# return mockClient - -# patch('app.main.httpx.AsyncClient', new=MagicMock(AsyncContextManager)) -# client = TestClient(app) -# payload = {"message":{"content": "some test message"}} -# response = client.post("/send-query",json=payload) -# print(type(response)) -# print(response.json()) - -# @pytest.fixture -# def mocked_api(): -# with respx.mock(base_url=veritableUrl) as respx_mock: -# respx_mock.post("/drcp/request", content=[], alias="list_users") -# ... -# yield respx_mock - -# def test_list_users(mocked_api): -# client = TestClient(app) -# payload = {"message":{"content": "some test message"}} -# response = client.post("/send-query",json=payload) -# request = mocked_api["list_users"] -# assert request.called -# assert response.json() == [] - -# return_value=httpx.Response(202) -# @respx.mock -# async def test_example(): -# my_route = respx.post(f"{veritableUrl}/drcp/request").respond(json={"some":"data"}) -# client = TestClient(app) -# payload = {"message":{"content": "some test message"}} -# response =await client.post("/send-query",json=payload) -# # response = httpx.get("https://foo.bar/") -# print(response) -# assert my_route.called -# assert response.status_code == 202 -# @pytest.mark.asyncio -# def test_send_query(): - -# with respx.mock: -# request = respx.post( -# f"{veritableUrl}/drcp/request", json = {} -# ) - -# client = TestClient(app) -# payload = {"message":{"content": "some test message"}} -# response = client.post("/send-query",json=payload) -# print(type(response)) -# print(response.json()) - diff --git a/tests/test_post_query.py b/tests/test_post_query.py new file mode 100644 index 0000000..30e5f2f --- /dev/null +++ b/tests/test_post_query.py @@ -0,0 +1,53 @@ +from fastapi import FastAPI, status +from httpx import AsyncClient +import pytest +pytestmark = pytest.mark.asyncio + + +# happy path tests +async def test_post_query( + app: FastAPI, + client: AsyncClient, + test_post_query_success_mock_202, +) -> None: + """ + ... + """ + payload = {"message":{"content": "some test message"}} + response_pat = await client.post( + app.url_path_for("test-name"), + json=payload, + ) + assert response_pat.status_code == status.HTTP_202_ACCEPTED + +# sad path tests + +async def test_post_query_wrong_body( + app: FastAPI, + client: AsyncClient, +) -> None: + """ + ... + """ + payload = {"wrongBody":{}} + response_pat = await client.post( + app.url_path_for("test-name"), + json=payload, + ) + assert response_pat.status_code == status.HTTP_422_UNPROCESSABLE_ENTITY + +async def test_post_query_failed_500( + app: FastAPI, + client: AsyncClient, + test_post_query_fail_mock_500, +) -> None: + """ + ... + """ + payload = {"message":{"content": "some test message"}} + response_pat = await client.post( + app.url_path_for("test-name"), + json=payload, + ) + assert response_pat.status_code == status.HTTP_500_INTERNAL_SERVER_ERROR + \ No newline at end of file diff --git a/tests/test_receive_response.py b/tests/test_receive_response.py new file mode 100644 index 0000000..81f00a2 --- /dev/null +++ b/tests/test_receive_response.py @@ -0,0 +1,51 @@ +from fastapi import FastAPI, status +from httpx import AsyncClient +import pytest +pytestmark = pytest.mark.asyncio + + +# happy path tests + +async def test_receive_response( + app: FastAPI, + client: AsyncClient, + test_receive_response_success_mock_200, +) -> None: + """ + ... + """ + payload = {"message":{"content": "some test message"}} + response_pat = await client.post( + app.url_path_for("receive-response"), + json=payload, + ) + assert response_pat.status_code == status.HTTP_200_OK + + + # Sad path tests + +async def test_receive_response_fail_500( + app: FastAPI, + client: AsyncClient, + test_receive_response_fail_mock_500, +) -> None: + """ + ... + """ + payload = {"message":{"content": "some test message"}} + response_pat = await client.post( + app.url_path_for("receive-response"), + json=payload, + ) + assert response_pat.status_code == status.HTTP_500_INTERNAL_SERVER_ERROR + + + + + + + + + + +