Repository navigation
Expand file tree
/
Copy pathtest_http_api.py
More file actions
369 lines (297 loc) · 13.1 KB
/
Copy pathtest_http_api.py
File metadata and controls
369 lines (297 loc) · 13.1 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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
"""
HTTP API integration tests — uses mock server fixture.
Tests the REST API contract. Uses a lightweight test server with mock backend
(similar to test_server.py) to avoid dependency on external running server.
Run with: pytest tests/test_http_api.py -v
"""
import json
import threading
import urllib.request
import urllib.error
from http.server import HTTPServer
from unittest.mock import MagicMock
import pytest
from ragger_memory import server as server_module
from ragger_memory.server import RaggerHandler
def _find_free_port():
import socket
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind(('127.0.0.1', 0))
return s.getsockname()[1]
@pytest.fixture
def mock_memory():
"""Create a mock RaggerMemory instance with typical responses."""
mem = MagicMock()
mem.count.return_value = 42
mem.is_multi_db = False
mem.store.return_value = "test-123"
mem.search.return_value = {
"results": [
{
"id": "1",
"text": "HTTP API test memory — safe to delete",
"score": 0.92,
"metadata": {"source": "test_http_api", "category": "test"},
"timestamp": "2026-01-01T00:00:00"
}
],
"timing": {"total_ms": 5.0}
}
mem.delete.return_value = True
mem.delete_batch.return_value = 1
return mem
@pytest.fixture
def test_server(mock_memory):
"""Start a test HTTP server with mock backend, auth disabled."""
original_memory = server_module._memory
original_token = server_module._server_token
server_module._memory = mock_memory
server_module._server_token = None # disable auth (single_user + no token)
# Ensure config says single_user=True
from ragger_memory.config import get_config
cfg = get_config()
orig_single_user = cfg.get("single_user", True)
cfg["single_user"] = True
port = _find_free_port()
httpd = HTTPServer(('127.0.0.1', port), RaggerHandler)
thread = threading.Thread(target=httpd.serve_forever, daemon=True)
thread.start()
yield port
httpd.shutdown()
server_module._memory = original_memory
server_module._server_token = original_token
cfg["single_user"] = orig_single_user
def _get(port, path):
url = f"http://127.0.0.1:{port}{path}"
req = urllib.request.Request(url, headers={"Content-Type": "application/json"})
with urllib.request.urlopen(req) as resp:
return resp.status, json.loads(resp.read())
def _post(port, path, body):
url = f"http://127.0.0.1:{port}{path}"
data = json.dumps(body).encode()
req = urllib.request.Request(url, data=data, headers={'Content-Type': 'application/json'})
with urllib.request.urlopen(req) as resp:
return resp.status, json.loads(resp.read())
def _delete(port, path):
url = f"http://127.0.0.1:{port}{path}"
req = urllib.request.Request(url, method="DELETE",
headers={"Content-Type": "application/json"})
with urllib.request.urlopen(req) as resp:
return resp.status, json.loads(resp.read())
def _delete_error(port, path, expected_code=404):
url = f"http://127.0.0.1:{port}{path}"
req = urllib.request.Request(url, method="DELETE",
headers={"Content-Type": "application/json"})
with pytest.raises(urllib.error.HTTPError) as exc_info:
urllib.request.urlopen(req)
assert exc_info.value.code == expected_code
return json.loads(exc_info.value.read())
def _post_error(port, path, body, expected_code=400):
"""POST expecting an error response."""
url = f"http://127.0.0.1:{port}{path}"
data = json.dumps(body).encode()
req = urllib.request.Request(url, data=data, headers={'Content-Type': 'application/json'})
with pytest.raises(urllib.error.HTTPError) as exc_info:
urllib.request.urlopen(req)
assert exc_info.value.code == expected_code
return json.loads(exc_info.value.read())
# =========================================================================
# Health endpoint
# =========================================================================
class TestHealth:
def test_health_returns_ok(self, test_server):
status, data = _get(test_server, "/health")
assert status == 200
assert data["status"] == "ok"
def test_health_has_memory_count(self, test_server):
_, data = _get(test_server, "/health")
assert "memories" in data
assert isinstance(data["memories"], int)
assert data["memories"] == 42
# =========================================================================
# Count endpoint
# =========================================================================
class TestCount:
def test_count_returns_integer(self, test_server):
status, data = _get(test_server, "/count")
assert status == 200
assert "count" in data
assert isinstance(data["count"], int)
assert data["count"] == 42
# =========================================================================
# Store endpoint
# =========================================================================
class TestStore:
def test_store_returns_id(self, test_server, mock_memory):
status, data = _post(test_server, "/store", {
"text": "HTTP API test memory — safe to delete",
"metadata": {"source": "test_http_api", "category": "test"}
})
assert status == 200
assert "id" in data
assert data["id"] == "test-123"
mock_memory.store.assert_called_once()
def test_store_requires_text(self, test_server):
data = _post_error(test_server, "/store", {"metadata": {}}, 400)
assert "error" in data
# =========================================================================
# Search endpoint
# =========================================================================
class TestSearch:
def test_search_returns_results(self, test_server):
status, data = _post(test_server, "/search", {
"query": "test memory",
"limit": 3
})
assert status == 200
assert "results" in data
assert isinstance(data["results"], list)
def test_search_results_have_required_fields(self, test_server):
_, data = _post(test_server, "/search", {"query": "test", "limit": 1})
if data["results"]:
r = data["results"][0]
assert "id" in r
assert "text" in r
assert "score" in r
assert "metadata" in r
assert "timestamp" in r
def test_search_respects_limit(self, test_server, mock_memory):
# Mock should return 1 result regardless of limit
_, data = _post(test_server, "/search", {"query": "test", "limit": 2})
assert len(data["results"]) <= 2
def test_search_has_timing(self, test_server):
_, data = _post(test_server, "/search", {"query": "test", "limit": 1})
assert "timing" in data
def test_search_requires_query(self, test_server):
data = _post_error(test_server, "/search", {"limit": 5}, 400)
assert "error" in data
def test_search_with_collections(self, test_server):
_, data = _post(test_server, "/search", {
"query": "test",
"limit": 3,
"collections": ["memory"]
})
assert "results" in data
def test_search_with_min_score(self, test_server):
_, data = _post(test_server, "/search", {
"query": "test",
"limit": 5,
"min_score": 0.5
})
# Mock returns score 0.92, so should pass
for r in data["results"]:
assert r["score"] >= 0.5
# =========================================================================
# Search by metadata endpoint
# =========================================================================
class TestSearchByMetadata:
def test_search_by_metadata_returns_results(self, test_server, mock_memory):
mock_memory.search_by_metadata.return_value = [
{"id": "m1", "text": "test entry", "metadata": {"category": "fact"},
"timestamp": "2026-01-01T00:00:00"}
]
status, data = _post(test_server, "/search_by_metadata", {
"metadata": {"category": "fact"},
"limit": 5
})
assert status == 200
assert "results" in data
assert len(data["results"]) == 1
mock_memory.search_by_metadata.assert_called_once()
def test_search_by_metadata_requires_metadata(self, test_server):
data = _post_error(test_server, "/search_by_metadata", {"limit": 5}, 400)
assert "error" in data
# =========================================================================
# Delete endpoint
# =========================================================================
class TestDelete:
def test_delete_returns_success(self, test_server, mock_memory):
status, data = _delete(test_server, "/memory/test-123")
assert status == 200
assert data.get("status") == "deleted"
mock_memory.delete.assert_called_once_with("test-123")
def test_delete_not_found(self, test_server, mock_memory):
mock_memory.delete.return_value = False
data = _delete_error(test_server, "/memory/nonexistent", 404)
assert "error" in data
# =========================================================================
# Delete batch endpoint
# =========================================================================
class TestDeleteBatch:
def test_delete_batch_returns_count(self, test_server, mock_memory):
mock_memory.delete_batch.return_value = 3
status, data = _post(test_server, "/delete_batch", {
"ids": ["id1", "id2", "id3"]
})
assert status == 200
assert data["deleted"] == 3
def test_delete_batch_requires_ids(self, test_server):
data = _post_error(test_server, "/delete_batch", {}, 400)
assert "error" in data
# =========================================================================
# Static file serving
# =========================================================================
class TestStaticFiles:
@pytest.fixture
def static_server(self, mock_memory, tmp_path):
"""Server with a temp web root containing test files."""
# Create test web files
(tmp_path / "index.html").write_text("<html><body>test</body></html>")
(tmp_path / "style.css").write_text("body { color: red; }")
(tmp_path / "app.js").write_text("console.log('hi');")
subdir = tmp_path / "sub"
subdir.mkdir()
(subdir / "page.html").write_text("<html>sub</html>")
original_memory = server_module._memory
original_token = server_module._server_token
server_module._memory = mock_memory
server_module._server_token = None
from ragger_memory.config import get_config
cfg = get_config()
orig_single_user = cfg.get("single_user", True)
cfg["single_user"] = True
# Patch _get_web_root to use our temp dir
original_get_web_root = RaggerHandler._get_web_root
RaggerHandler._get_web_root = lambda self: str(tmp_path)
port = _find_free_port()
httpd = HTTPServer(('127.0.0.1', port), RaggerHandler)
thread = threading.Thread(target=httpd.serve_forever, daemon=True)
thread.start()
yield port
httpd.shutdown()
RaggerHandler._get_web_root = original_get_web_root
server_module._memory = original_memory
server_module._server_token = original_token
cfg["single_user"] = orig_single_user
def test_serves_index_at_root(self, static_server):
url = f"http://127.0.0.1:{static_server}/"
with urllib.request.urlopen(url) as resp:
assert resp.status == 200
body = resp.read().decode()
assert "<html>" in body
def test_serves_css(self, static_server):
url = f"http://127.0.0.1:{static_server}/style.css"
with urllib.request.urlopen(url) as resp:
assert resp.status == 200
assert "text/css" in resp.headers.get("Content-Type", "")
def test_serves_js(self, static_server):
url = f"http://127.0.0.1:{static_server}/app.js"
with urllib.request.urlopen(url) as resp:
assert resp.status == 200
body = resp.read().decode()
assert "console.log" in body
def test_serves_subdirectory(self, static_server):
url = f"http://127.0.0.1:{static_server}/sub/page.html"
with urllib.request.urlopen(url) as resp:
assert resp.status == 200
def test_404_nonexistent(self, static_server):
url = f"http://127.0.0.1:{static_server}/nonexistent.xyz"
with pytest.raises(urllib.error.HTTPError) as exc_info:
urllib.request.urlopen(url)
assert exc_info.value.code == 404
def test_no_directory_traversal(self, static_server):
url = f"http://127.0.0.1:{static_server}/../../../etc/passwd"
with pytest.raises(urllib.error.HTTPError) as exc_info:
urllib.request.urlopen(url)
# Should be 404, not serve the file
assert exc_info.value.code in (400, 403, 404)