File size: 1,853 Bytes
45b4689
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
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)


@pytest.fixture(autouse=True)
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}
    )


@pytest.mark.unit
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"]]
    }


@pytest.mark.unit
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."


@pytest.mark.unit
def test_search_invalid_n():
    response = client.get("/search", params={"query": "test", "n": 0})
    assert response.status_code == 422


@pytest.mark.unit
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"]


@pytest.mark.unit
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."