ac-user-auth / tests /utils /helpers.py
MukeshKapoor25's picture
first commit
70f8e84
import json
from fastapi.testclient import TestClient
from unittest.mock import AsyncMock
def create_mock_request(collection_name: str):
"""
Create a mock request object with a collection name.
Args:
collection_name (str): The collection name to set in the request's state.
Returns:
MockRequest: A mock FastAPI request object with state.
"""
class MockRequest:
state = type("State", (), {"collection_name": collection_name})
return MockRequest()
def load_test_data(file_path: str):
"""
Load test data from a JSON file.
Args:
file_path (str): Path to the JSON file containing test data.
Returns:
dict: Parsed JSON data as a dictionary.
"""
with open(file_path, "r") as file:
return json.load(file)
def assert_response(response, expected_status_code: int, expected_body: dict = None):
"""
Assert a response object for status code and body content.
Args:
response (TestClient.Response): The response object to validate.
expected_status_code (int): The expected HTTP status code.
expected_body (dict, optional): The expected response body. Defaults to None.
"""
assert response.status_code == expected_status_code, f"Expected {expected_status_code}, got {response.status_code}"
if expected_body:
assert response.json() == expected_body, f"Expected {expected_body}, got {response.json()}"
def mock_async_function(return_value=None, side_effect=None):
"""
Create a mock for an async function.
Args:
return_value: The value the mock should return when awaited.
side_effect: A function or exception to raise when the mock is called.
Returns:
AsyncMock: A mocked async function.
"""
mock_func = AsyncMock()
if return_value is not None:
mock_func.return_value = return_value
if side_effect is not None:
mock_func.side_effect = side_effect
return mock_func
def simulate_test_client_request(client: TestClient, method: str, url: str, json_body: dict = None):
"""
Simulate a request using FastAPI's TestClient.
Args:
client (TestClient): The FastAPI TestClient instance.
method (str): HTTP method (GET, POST, PUT, DELETE).
url (str): The endpoint URL to test.
json_body (dict, optional): JSON payload for the request. Defaults to None.
Returns:
Response: The response object from the request.
"""
if method.upper() == "POST":
return client.post(url, json=json_body)
elif method.upper() == "GET":
return client.get(url)
elif method.upper() == "PUT":
return client.put(url, json=json_body)
elif method.upper() == "DELETE":
return client.delete(url)
else:
raise ValueError(f"Unsupported HTTP method: {method}")