-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_search_route.py
More file actions
289 lines (228 loc) · 11.4 KB
/
Copy pathtest_search_route.py
File metadata and controls
289 lines (228 loc) · 11.4 KB
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
"""
Tests for the /search route.
Tests cover:
- Unit tests: mock search_docs, assert HTML with results, empty query handling
- Integration tests: initialized index, hit /search?q=health, assert results in HTML
- Index unavailable → graceful message
- Empty results → "No results found"
"""
from unittest.mock import MagicMock, patch
import pytest
from httpx import ASGITransport, AsyncClient
from docs_server.main import app
from docs_server.mcp.search import SearchResult
# =============================================================================
# FIXTURES
# =============================================================================
@pytest.fixture
def temp_docs_root(tmp_path):
"""Create a temporary docs directory with sample markdown files."""
docs_dir = tmp_path / "docs"
docs_dir.mkdir()
(docs_dir / "index.md").write_text("# Welcome\n\nHome page.")
(docs_dir / "sidebar.md").write_text("# Nav\n\n* [Home](index.md)")
(docs_dir / "topbar.md").write_text("# Top\n\n## right\n* [Link](index.md)")
api_dir = docs_dir / "api"
api_dir.mkdir()
(api_dir / "endpoints.md").write_text(
"# API Endpoints\n\n## GET /health\n\nHealth check.\n\n## Rate Limiting\n\nRate limiting at 120/min."
)
features_dir = docs_dir / "features"
features_dir.mkdir()
(features_dir / "mcp.md").write_text("# MCP\n\nMCP enables LLM integration. Health monitoring.")
return docs_dir
@pytest.fixture
def temp_cache_root(tmp_path):
"""Create a temporary cache directory."""
cache_dir = tmp_path / "cache"
cache_dir.mkdir()
return cache_dir
@pytest.fixture
async def initialized_index(temp_docs_root, temp_cache_root):
"""Create an initialized search index with test documents."""
from docs_server.mcp.indexer import SearchIndexManager
with patch("docs_server.mcp.indexer.settings") as mock_settings:
mock_settings.DOCS_ROOT = temp_docs_root
mock_settings.CACHE_ROOT = temp_cache_root
mock_settings.DEBUG = False
mock_settings.MCP_MAX_SEARCH_RESULTS = 10
mock_settings.MCP_SNIPPET_LENGTH = 200
manager = SearchIndexManager()
manager._docs_root = temp_docs_root
manager._index_path = temp_cache_root / "mcp" / "whoosh"
manager._metadata_path = temp_cache_root / "mcp" / "metadata.json"
await manager.initialize(force_rebuild=True)
yield manager
manager.shutdown()
# =============================================================================
# UNIT TESTS (mocked search_docs)
# =============================================================================
class TestSearchRouteUnit:
"""Unit tests with mocked search_docs."""
@pytest.mark.asyncio
async def test_search_returns_html_with_results(self, temp_docs_root):
"""GET /search?q=test returns HTML containing search results."""
mock_results = [
SearchResult(
path="api/endpoints.md",
title="API Endpoints",
snippet="Health check endpoint",
score=2.5,
category="api",
)
]
with (
patch("docs_server.main.settings") as mock_settings,
patch("docs_server.mcp.search_docs", return_value=mock_results),
):
mock_settings.DOCS_ROOT = temp_docs_root
mock_settings.MCP_ENABLED = True
with patch("docs_server.mcp.get_index_manager") as mock_get_mgr:
mock_mgr = MagicMock()
mock_mgr.is_initialized = True
mock_get_mgr.return_value = mock_mgr
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
response = await client.get("/search?q=test")
assert response.status_code == 200
assert "text/html" in response.headers.get("content-type", "")
html = response.text
assert "API Endpoints" in html
assert "api/endpoints.md" in html or "/api/endpoints.html" in html
@pytest.mark.asyncio
async def test_search_empty_query_shows_search_page(self, temp_docs_root):
"""GET /search with empty q shows search page without results."""
with (
patch("docs_server.main.settings") as mock_settings,
):
mock_settings.DOCS_ROOT = temp_docs_root
mock_settings.MCP_ENABLED = True
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
response = await client.get("/search?q=")
response_ws = await client.get("/search?q= ")
assert response.status_code == 200
assert response_ws.status_code == 200
assert "search-page" in response.text
assert "search-page-results" in response.text
@pytest.mark.asyncio
async def test_search_index_unavailable_graceful_message(self, temp_docs_root):
"""When index unavailable, show graceful message."""
with (
patch("docs_server.main.settings") as mock_settings,
patch("docs_server.mcp.get_index_manager") as mock_get_mgr,
):
mock_settings.DOCS_ROOT = temp_docs_root
mock_settings.MCP_ENABLED = True
mock_mgr = MagicMock()
mock_mgr.is_initialized = False
mock_get_mgr.return_value = mock_mgr
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
response = await client.get("/search?q=health")
assert response.status_code == 200
assert "Search will be available once the index is built" in response.text
@pytest.mark.asyncio
async def test_search_empty_results_no_results_found(self, temp_docs_root):
"""When search returns no results, show 'No results found'."""
with (
patch("docs_server.main.settings") as mock_settings,
patch("docs_server.mcp.search_docs", return_value=[]),
patch("docs_server.mcp.get_index_manager") as mock_get_mgr,
):
mock_settings.DOCS_ROOT = temp_docs_root
mock_settings.MCP_ENABLED = True
mock_mgr = MagicMock()
mock_mgr.is_initialized = True
mock_get_mgr.return_value = mock_mgr
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
response = await client.get("/search?q=xyznonexistent")
assert response.status_code == 200
assert "No results found" in response.text
assert "xyznonexistent" in response.text
# =============================================================================
# JSON SEARCH EDGE CASES
# =============================================================================
class TestSearchJsonEdgeCases:
"""JSON format edge cases for /search?format=json."""
@pytest.mark.asyncio
async def test_search_json_empty_query_returns_empty(self, temp_docs_root):
"""GET /search?format=json with empty q returns empty JSON payload."""
with patch("docs_server.main.settings") as mock_settings:
mock_settings.DOCS_ROOT = temp_docs_root
mock_settings.MCP_ENABLED = True
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
response = await client.get("/search?q=&format=json")
response_ws = await client.get("/search?q= &format=json")
assert response.status_code == 200
assert response_ws.status_code == 200
data = response.json()
assert data == {"query": "", "count": 0, "results": [], "html": ""}
@pytest.mark.asyncio
async def test_search_json_mcp_disabled_returns_unavailable(self, temp_docs_root):
"""GET /search?format=json when MCP disabled returns 'Search is not available'."""
with patch("docs_server.main.settings") as mock_settings:
mock_settings.DOCS_ROOT = temp_docs_root
mock_settings.MCP_ENABLED = False
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
response = await client.get("/search?q=test&format=json")
assert response.status_code == 200
data = response.json()
assert data["query"] == "test"
assert data["count"] == 0
assert "Search is not available" in data["html"]
@pytest.mark.asyncio
async def test_search_json_index_unavailable_returns_graceful_message(self, temp_docs_root):
"""GET /search?format=json when index not initialized returns graceful message."""
with (
patch("docs_server.main.settings") as mock_settings,
patch("docs_server.mcp.get_index_manager") as mock_get_mgr,
):
mock_settings.DOCS_ROOT = temp_docs_root
mock_settings.MCP_ENABLED = True
mock_mgr = MagicMock()
mock_mgr.is_initialized = False
mock_get_mgr.return_value = mock_mgr
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
response = await client.get("/search?q=health&format=json")
assert response.status_code == 200
data = response.json()
assert data["query"] == "health"
assert data["count"] == 0
assert "Search will be available once the index is built" in data["html"]
# =============================================================================
# INTEGRATION TESTS (real index)
# =============================================================================
class TestSearchRouteIntegration:
"""Integration tests with initialized index."""
@pytest.mark.asyncio
async def test_search_q_health_returns_results(self, temp_docs_root, temp_cache_root, initialized_index):
"""GET /search?q=health returns HTML with results when index is initialized."""
with (
patch("docs_server.main.settings") as mock_settings,
patch("docs_server.mcp.get_index_manager", return_value=initialized_index),
):
mock_settings.DOCS_ROOT = temp_docs_root
mock_settings.MCP_ENABLED = True
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
response = await client.get("/search?q=health")
assert response.status_code == 200
html = response.text
assert "search-page" in html
# api/endpoints.md contains "Health check" - should be in results
assert "health" in html.lower() or "Health" in html or "endpoints" in html.lower()
@pytest.mark.asyncio
async def test_search_json_format_returns_json(self, temp_docs_root, temp_cache_root, initialized_index):
"""GET /search?q=health&format=json returns JSON with results."""
with (
patch("docs_server.main.settings") as mock_settings,
patch("docs_server.mcp.get_index_manager", return_value=initialized_index),
):
mock_settings.DOCS_ROOT = temp_docs_root
mock_settings.MCP_ENABLED = True
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
response = await client.get("/search?q=health&format=json")
assert response.status_code == 200
data = response.json()
assert "query" in data
assert "count" in data
assert "results" in data
assert "html" in data
assert data["query"] == "health"