Spaces:
Running
Running
import pytest | |
from fastapi.testclient import TestClient | |
from app.api import app | |
# Mock the most_similar function for testing | |
def mock_most_similar(query, n): | |
if query == "error": | |
raise Exception("Test exception") | |
return [[0.9, "Result 1"], [0.8, "Result 2"]][:n] | |
# Initialize the FastAPI test client | |
client = TestClient(app) | |
def setup_mock_search_engine(): | |
# Replace the app's search engine with a mock that uses the mock_most_similar function | |
app.state.search_engine = type( | |
"MockSearchEngine", | |
(object,), | |
{"most_similar": mock_most_similar} | |
) | |
def test_search_valid_input(): | |
response = client.get("/search", params={"query": "test", "n": 2}) | |
assert response.status_code == 200 | |
assert response.json() == { | |
"query": "test", | |
"results": [[0.9, "Result 1"], [0.8, "Result 2"]] | |
} | |
def test_search_empty_query(): | |
response = client.get("/search", params={"query": "", "n": 2}) | |
assert response.status_code == 400 | |
assert response.json()["detail"] == "Query cannot be empty." | |
def test_search_invalid_n(): | |
response = client.get("/search", params={"query": "test", "n": 0}) | |
assert response.status_code == 422 | |
def test_search_engine_error(): | |
response = client.get("/search", params={"query": "error", "n": 2}) | |
assert response.status_code == 500 | |
assert "An unexpected error occurred: Test exception" in response.json()["detail"] | |
def test_search_no_engine(): | |
app.state.search_engine = None # Simulate uninitialized search engine | |
response = client.get("/search", params={"query": "test", "n": 2}) | |
assert response.status_code == 500 | |
assert response.json()["detail"] == "Search engine not initialized." | |