-
Notifications
You must be signed in to change notification settings - Fork 642
Expand file tree
/
Copy pathtest_memory_controller.py
More file actions
2704 lines (2333 loc) · 109 KB
/
test_memory_controller.py
File metadata and controls
2704 lines (2333 loc) · 109 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
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Memory Controller API Test Script
Verify input and output structures of all endpoints under /api/v0/memories
Usage:
# Run all tests
python tests/test_memory_controller.py
# Specify API address
python tests/test_memory_controller.py --base-url http://localhost:1995
# Specify test user
python tests/test_memory_controller.py --base-url http://dev-server:1995 --user-id test_user_123
# Test by category (batch execution)
python tests/test_memory_controller.py --test-method fetch # Run all fetch tests
python tests/test_memory_controller.py --test-method retrieve # Run all retrieve/search tests
python tests/test_memory_controller.py --test-method search # Same as retrieve
python tests/test_memory_controller.py --test-method memorize # Run memorization tests
python tests/test_memory_controller.py --test-method meta # Run metadata tests
# Test a specific method
python tests/test_memory_controller.py --test-method fetch_episodic
python tests/test_memory_controller.py --test-method fetch_atomic_fact
python tests/test_memory_controller.py --test-method fetch_group_filter
python tests/test_memory_controller.py --test-method fetch_time_range
python tests/test_memory_controller.py --test-method fetch_combined_filters
python tests/test_memory_controller.py --test-method fetch_all_types
python tests/test_memory_controller.py --test-method search_keyword
# Test all methods except certain ones (parameters separated by commas)
python tests/test_memory_controller.py --except-test-method memorize
python tests/test_memory_controller.py --except-test-method memorize,fetch_episodic
python tests/test_memory_controller.py --except-test-method save_meta,patch_meta
# Disable sync mode (use background mode)
python tests/test_memory_controller.py --sync-mode false
"""
import argparse
import json
from zoneinfo import ZoneInfo
import uuid
from datetime import datetime, timedelta
import requests
class MemoryControllerTester:
"""Memory Controller API Test Class"""
# Default tenant information
DEFAULT_ORGANIZATION_ID = "test_memory_api_organization"
DEFAULT_SPACE_ID = "test_memory_api_space"
DEFAULT_HASH_KEY = "test_memory_api_hash_key"
def __init__(
self,
base_url: str,
user_id: str,
group_id: str,
organization_id: str = None,
space_id: str = None,
hash_key: str = None,
timeout: int = 180,
sync_mode: bool = True,
):
"""
Initialize tester
Args:
base_url: API base URL
user_id: Test user ID
group_id: Test group ID
organization_id: Organization ID (default: test_memory_api_organization)
space_id: Space ID (default: test_memory_api_space)
hash_key: Hash key (default: test_memory_api_hash_key)
timeout: Request timeout in seconds, default 180 seconds (3 minutes)
sync_mode: Whether to enable sync mode (default: True, server default is also True so param is only sent when False)
"""
self.base_url = base_url
self.api_prefix = "/api/v0/memories"
self.user_id = user_id
self.group_id = group_id
self.organization_id = organization_id or self.DEFAULT_ORGANIZATION_ID
self.space_id = space_id or self.DEFAULT_SPACE_ID
self.hash_key = hash_key or self.DEFAULT_HASH_KEY
self.timeout = timeout
self.sync_mode = sync_mode
def get_tenant_headers(self) -> dict:
"""
Get tenant-related request headers
Returns:
dict: Dictionary containing X-Organization-Id, X-Space-Id, and optional X-Hash-Key
"""
headers = {
"X-Organization-Id": self.organization_id,
"X-Space-Id": self.space_id,
}
if self.hash_key:
headers["X-Hash-Key"] = self.hash_key
return headers
def init_database(self) -> bool:
"""
Initialize tenant database
Call /internal/tenant/init-db endpoint to initialize database.
Returns:
bool: Whether initialization was successful
"""
url = f"{self.base_url}/internal/tenant/init-db"
headers = self.get_tenant_headers()
print("\n" + "=" * 80)
print(" Initialize Tenant Database")
print("=" * 80)
print(f"📍 URL: POST {url}")
print(
f"📤 Tenant Info: organization_id={self.organization_id}, space_id={self.space_id}"
)
print(
f"📤 Request Headers: {json.dumps(headers, indent=2, ensure_ascii=False)}"
)
try:
response = requests.post(url, headers=headers, timeout=self.timeout)
print(f"\n📥 Response Status Code: {response.status_code}")
response_json = response.json()
print("📥 Response Data:")
print(json.dumps(response_json, indent=2, ensure_ascii=False))
if response.status_code == 200 and response_json.get("success"):
print(
f"\n✅ Database initialization successful: tenant_id={response_json.get('tenant_id')}"
)
return True
else:
print(
f"\n⚠️ Database initialization returned: {response_json.get('message', 'Unknown')}"
)
# Continue even if failed, possibly database already exists
return True
except Exception as e: # noqa: BLE001
print(f"\n❌ Database initialization failed: {e}")
return False
def print_section(self, title: str):
"""Print section separator"""
print("\n" + "=" * 80)
print(f" {title}")
print("=" * 80)
def _get_sync_mode_params(self) -> dict:
"""
Get query parameters for sync mode
Returns:
dict: Dictionary containing sync_mode parameter only when sync_mode is False
(sync_mode=true is the server default, no need to send explicitly)
"""
if not self.sync_mode:
return {"sync_mode": "false"}
return {}
def call_post_api(self, endpoint: str, data: dict):
"""
Call POST API and print results
Args:
endpoint: API endpoint
data: Request data
Returns:
(status_code, response_json)
"""
# If it's the memorize endpoint and sender is not provided, generate one randomly
if endpoint == "" and "sender" not in data:
data["sender"] = f"user_{uuid.uuid4().hex[:12]}"
print(f"⚠️ Sender not provided, auto-generated: {data['sender']}")
url = f"{self.base_url}{self.api_prefix}{endpoint}"
headers = self.get_tenant_headers()
params = self._get_sync_mode_params()
print(f"\n📍 URL: POST {url}")
if params:
print(f"📤 Query Parameters: {params}")
print("📤 Request Data:")
print(json.dumps(data, indent=2, ensure_ascii=False))
try:
response = requests.post(
url, json=data, headers=headers, params=params, timeout=self.timeout
)
print(f"\n📥 Response Status Code: {response.status_code}")
print("📥 Response Data:")
response_json = response.json()
print(json.dumps(response_json, indent=2, ensure_ascii=False))
return response.status_code, response_json
except (
Exception
) as e: # noqa: BLE001 Need to catch all exceptions to ensure script continues
print(f"\n❌ Request failed: {e}")
return None, None
def call_get_api(self, endpoint: str, params: dict = None):
"""
Call GET API and print results
Args:
endpoint: API endpoint
params: Query parameters
Returns:
(status_code, response_json)
"""
url = f"{self.base_url}{self.api_prefix}{endpoint}"
headers = self.get_tenant_headers()
# Merge sync mode parameters
merged_params = self._get_sync_mode_params()
if params:
merged_params.update(params)
print(f"\n📍 URL: GET {url}")
if merged_params:
print("📤 Query Parameters:")
print(json.dumps(merged_params, indent=2, ensure_ascii=False))
try:
response = requests.get(
url, params=merged_params, headers=headers, timeout=self.timeout
)
print(f"\n📥 Response Status Code: {response.status_code}")
print("📥 Response Data:")
response_json = response.json()
print(json.dumps(response_json, indent=2, ensure_ascii=False))
return response.status_code, response_json
except (
Exception
) as e: # noqa: BLE001 Need to catch all exceptions to ensure script continues
print(f"\n❌ Request failed: {e}")
return None, None
def call_get_with_body_api(self, endpoint: str, data: dict):
"""
Call GET API (with body) and print results
Although uncommon, some search interfaces (e.g., Elasticsearch) use GET + body to pass complex parameters
Args:
endpoint: API endpoint
data: Request data (placed in body)
Returns:
(status_code, response_json)
"""
url = f"{self.base_url}{self.api_prefix}{endpoint}"
headers = self.get_tenant_headers()
params = self._get_sync_mode_params()
print(f"\n📍 URL: GET {url} (with body)")
if params:
print(f"📤 Query Parameters: {params}")
print("📤 Request Data:")
print(json.dumps(data, indent=2, ensure_ascii=False))
try:
# GET request with body (requests library supports this, though not common)
response = requests.request(
"GET",
url,
json=data,
headers=headers,
params=params,
timeout=self.timeout,
)
print(f"\n📥 Response Status Code: {response.status_code}")
print("📥 Response Data:")
response_json = response.json()
print(json.dumps(response_json, indent=2, ensure_ascii=False))
return response.status_code, response_json
except (
Exception
) as e: # noqa: BLE001 Need to catch all exceptions to ensure script continues
print(f"\n❌ Request failed: {e}")
return None, None
def call_patch_api(self, endpoint: str, data: dict):
"""
Call PATCH API and print results
Args:
endpoint: API endpoint
data: Request data
Returns:
(status_code, response_json)
"""
url = f"{self.base_url}{self.api_prefix}{endpoint}"
headers = self.get_tenant_headers()
params = self._get_sync_mode_params()
print(f"\n📍 URL: PATCH {url}")
if params:
print(f"📤 Query Parameters: {params}")
print("📤 Request Data:")
print(json.dumps(data, indent=2, ensure_ascii=False))
try:
response = requests.patch(
url, json=data, headers=headers, params=params, timeout=self.timeout
)
print(f"\n📥 Response Status Code: {response.status_code}")
print("📥 Response Data:")
response_json = response.json()
print(json.dumps(response_json, indent=2, ensure_ascii=False))
return response.status_code, response_json
except (
Exception
) as e: # noqa: BLE001 Need to catch all exceptions to ensure script continues
print(f"\n❌ Request failed: {e}")
return None, None
def test_memorize_single_message(self):
"""Test 1: POST /api/v0/memories - Store conversation memory (send multiple messages to trigger boundary detection)"""
self.print_section("Test 1: POST /api/v0/memories - Store Conversation Memory")
# Prepare a simple conversation to simulate user and assistant interaction
# Sending multiple messages can trigger boundary detection and extract memories
base_time = datetime.now(ZoneInfo("UTC"))
# Generate unique message ID prefix for this test run to avoid duplicate detection
msg_prefix = uuid.uuid4().hex[:8]
# Build conversation sequence, triggering boundary detection through:
# 1. First scenario: Discussion about coffee preferences (4 messages)
# 2. Second scenario: Start new topic (trigger boundary via time gap + topic switch)
messages = [
# Scenario 1: Discuss coffee preferences (complete conversation episode)
{
"group_id": self.group_id,
"message_id": f"msg_{msg_prefix}_001",
"create_time": base_time.isoformat(),
"sender": self.user_id,
"sender_name": "Test User",
"content": "I recently want to develop a habit of drinking coffee, do you have any suggestions?",
"refer_list": [],
},
{
"group_id": self.group_id,
"message_id": f"msg_{msg_prefix}_002",
"create_time": (base_time + timedelta(seconds=30)).isoformat(),
"sender": "assistant_001",
"sender_name": "AI Assistant",
"content": "Of course! Coffee comes in many varieties, from strong espresso to mild Americano. You can choose based on your taste. I suggest starting with Americano.",
"role": "assistant",
"refer_list": [],
},
{
"group_id": self.group_id,
"message_id": f"msg_{msg_prefix}_003",
"create_time": (base_time + timedelta(minutes=1)).isoformat(),
"sender": self.user_id,
"sender_name": "Test User",
"content": "I like drinking Americano, no sugar, no milk, the stronger the better.",
"refer_list": [],
},
{
"group_id": self.group_id,
"message_id": f"msg_{msg_prefix}_004",
"create_time": (
base_time + timedelta(minutes=1, seconds=30)
).isoformat(),
"sender": "assistant_001",
"sender_name": "AI Assistant",
"content": "I understand your preference! Black Americano can fully experience the flavor of coffee beans. I suggest choosing dark roasted beans for a stronger taste.",
"role": "assistant",
"refer_list": [],
},
# Scenario 2: Start new topic (trigger boundary via longer time gap + topic switch)
# According to boundary detection rules: time gap over 4 hours and content unrelated will trigger boundary
{
"group_id": self.group_id,
"message_id": f"msg_{msg_prefix}_005",
"create_time": (base_time + timedelta(hours=24)).isoformat(),
"sender": self.user_id,
"sender_name": "Test User",
"content": "By the way, how is the weekend project progressing?",
"role": "user",
"refer_list": [],
},
{
"group_id": self.group_id,
"message_id": f"msg_{msg_prefix}_006",
"create_time": (
base_time + timedelta(hours=24, seconds=30)
).isoformat(),
"sender": "assistant_001",
"sender_name": "AI Assistant",
"content": "The project is progressing smoothly, main features are 80% complete, expected to submit for testing next week.",
"refer_list": [],
},
]
# Send messages one by one
print("\n📨 Starting to send conversation sequence...")
print(
"💡 Strategy Explanation: First 4 messages form complete scenario 1 (coffee preference discussion)"
)
print(
"💡 5th message triggers boundary detection via 5-hour time gap + new topic"
)
print("💡 This ensures memory from scenario 1 is successfully extracted")
last_response = None
for i, msg in enumerate(messages, 1):
if i == 5:
print(
f"\n🔄 --- Scenario Switch: Sending message {i}/{len(messages)} (triggering boundary) ---"
)
else:
print(f"\n--- Sending message {i}/{len(messages)} ---")
status_code, response = self.call_post_api("", msg)
# Verify each message is successfully processed
assert (
status_code == 200
), f"Message {i} status code should be 200, actual: {status_code}"
assert response.get("status") == "ok", f"Message {i} status should be ok"
last_response = response
# Use the response from the last message for validation
status_code = 200
response = last_response
# Assert: Validate result structure
print("\n📊 Validating conversation memory extraction results...")
assert "result" in response, "Successful response should contain result field"
result = response["result"]
assert "saved_memories" in result, "result should contain saved_memories field"
assert "count" in result, "result should contain count field"
assert "status_info" in result, "result should contain status_info field"
# Validate saved_memories is a list
assert isinstance(
result["saved_memories"], list
), "saved_memories should be a list"
assert result["count"] >= 0, "count should be >= 0"
assert result["status_info"] in [
"accumulated",
"extracted",
], "status_info should be accumulated or extracted"
# If there are extracted memories, validate each memory's structure
if result["count"] > 0:
print(f"\n✅ Successfully extracted {result['count']} memories!")
print(
f"✅ Boundary detection successful: triggered by time gap (5 hours) + topic switch"
)
for idx, memory in enumerate(result["saved_memories"], 1):
assert isinstance(memory, dict), f"Memory {idx} should be a dictionary"
# Note: Different memory types may have different field structures
# Here only basic field existence is validated
memory_type = memory.get('memory_type', 'unknown')
summary = memory.get('summary', memory.get('content', 'no summary'))[
:50
]
print(f" Memory {idx}: {memory_type} - {summary}...")
else:
print(
f"\n⚠️ Messages accumulated, waiting for boundary detection (status_info: {result['status_info']})"
)
print(
f" Sent {len(messages)} messages, but boundary detection conditions may not be met"
)
print(
f" 💡 Tip: Boundary detection requires one of the following conditions:"
)
print(
f" 1. Cross-day (new message date differs from previous message)"
)
print(f" 2. Long interruption (over 4 hours) + topic switch")
print(f" 3. Clear scene/topic switch signal")
print(f"\n✅ Memorize Test Completed")
return status_code, response
def test_fetch_episodic(self):
"""Test 2: GET /api/v0/memories - Fetch user episodic memory (episodic_memory type, pass parameters via body)
Tests multiple scenarios:
1. Only user_id (group_id NOT provided in request)
2. user_id + group_id=None (explicitly null)
3. user_id + group_id="" (explicitly empty string)
4. user_id + group_id both have valid values
5. user_id="__all__" + valid group_id
"""
self.print_section("Test 2: GET /api/v0/memories - Fetch User Episodic Memory")
# Scenario 1: Only user_id, group_id NOT provided (parameter doesn't exist)
print("\n--- Scenario 1: Only user_id (group_id NOT provided) ---")
data = {
"user_id": self.user_id,
"memory_type": "episodic_memory",
"limit": 10,
"offset": 0,
# group_id is NOT in the request at all
}
status_code, response = self.call_get_with_body_api("", data)
# Assert: Precisely validate response structure
assert status_code == 200, f"Status code should be 200, actual: {status_code}"
assert (
response.get("status") == "ok"
), f"Status should be ok, actual: {response.get('status')}"
assert "result" in response, "Response should contain result field"
result = response["result"]
assert "memories" in result, "result should contain memories field"
assert "total_count" in result, "result should contain total_count field"
assert "has_more" in result, "result should contain has_more field"
assert "metadata" in result, "result should contain metadata field"
# Validate data types
assert isinstance(result["memories"], list), "memories should be a list"
assert result["total_count"] >= 0, "total_count should be >= 0"
assert isinstance(result["has_more"], bool), "has_more should be boolean"
# Validate metadata structure
metadata = result["metadata"]
assert isinstance(metadata, dict), "metadata should be a dictionary"
assert "source" in metadata, "metadata should contain source field"
assert "user_id" in metadata, "metadata should contain user_id field"
assert "memory_type" in metadata, "metadata should contain memory_type field"
assert metadata.get("user_id") == self.user_id, "metadata user_id should match"
# If there are memories, deeply validate structure
if result["total_count"] > 0 and len(result["memories"]) > 0:
for idx, memory in enumerate(result["memories"]):
assert isinstance(memory, dict), f"Memory {idx} should be a dictionary"
assert "user_id" in memory, f"Memory {idx} should contain user_id"
assert "timestamp" in memory, f"Memory {idx} should contain timestamp"
assert (
memory.get("user_id") == self.user_id
), f"Memory {idx} user_id should match"
print(
f"✅ Scenario 1 successful, returned {result['total_count']} episodic memories"
)
else:
print(
f"✅ Scenario 1 successful, returned {result['total_count']} episodic memories"
)
# Scenario 2: user_id + group_id=None (explicitly null)
print("\n--- Scenario 2: user_id + group_id=None (explicitly null) ---")
data = {
"user_id": self.user_id,
"group_id": None, # Explicitly set to None
"memory_type": "episodic_memory",
"limit": 10,
"offset": 0,
}
status_code, response = self.call_get_with_body_api("", data)
assert status_code == 200, f"Status code should be 200, actual: {status_code}"
assert response.get("status") == "ok", f"Status should be ok"
result = response["result"]
# Validate that returned memories have null or empty group_id
if result["total_count"] > 0 and len(result["memories"]) > 0:
for idx, memory in enumerate(result["memories"]):
group_id_value = memory.get("group_id")
assert group_id_value in (
None,
"",
), f"Memory {idx} group_id should be None or empty string, actual: {group_id_value}"
print(
f"✅ Scenario 2 successful, returned {result['total_count']} episodic memories with null/empty group_id"
)
else:
print(
f"✅ Scenario 2 successful, returned {result['total_count']} episodic memories"
)
# Scenario 3: user_id + group_id="" (explicitly empty string)
print("\n--- Scenario 3: user_id + group_id='' (explicitly empty string) ---")
data = {
"user_id": self.user_id,
"group_id": "", # Explicitly set to empty string
"memory_type": "episodic_memory",
"limit": 10,
"offset": 0,
}
status_code, response = self.call_get_with_body_api("", data)
assert status_code == 200, f"Status code should be 200, actual: {status_code}"
assert response.get("status") == "ok", f"Status should be ok"
result = response["result"]
# Validate that returned memories have null or empty group_id
if result["total_count"] > 0 and len(result["memories"]) > 0:
for idx, memory in enumerate(result["memories"]):
group_id_value = memory.get("group_id")
assert group_id_value in (
None,
"",
), f"Memory {idx} group_id should be None or empty string, actual: {group_id_value}"
print(
f"✅ Scenario 3 successful, returned {result['total_count']} episodic memories with null/empty group_id"
)
else:
print(
f"✅ Scenario 3 successful, returned {result['total_count']} episodic memories"
)
# Scenario 4: user_id + group_id both have valid values
print("\n--- Scenario 4: user_id + group_id both have valid values ---")
data = {
"user_id": self.user_id,
"group_id": self.group_id,
"memory_type": "episodic_memory",
"limit": 10,
"offset": 0,
}
status_code, response = self.call_get_with_body_api("", data)
assert status_code == 200, f"Status code should be 200, actual: {status_code}"
assert response.get("status") == "ok", f"Status should be ok"
result = response["result"]
# Validate metadata includes both user_id and group_id
metadata = result["metadata"]
assert metadata.get("user_id") == self.user_id, "metadata user_id should match"
assert (
metadata.get("group_id") == self.group_id
), "metadata group_id should match"
# Validate that returned memories have the requested group_id
if result["total_count"] > 0 and len(result["memories"]) > 0:
for idx, memory in enumerate(result["memories"]):
assert (
memory.get("group_id") == self.group_id
), f"Memory {idx} group_id should be {self.group_id}, actual: {memory.get('group_id')}"
assert (
memory.get("user_id") == self.user_id
), f"Memory {idx} user_id should be {self.user_id}, actual: {memory.get('user_id')}"
print(
f"✅ Scenario 4 successful, returned {result['total_count']} episodic memories with matching filters"
)
else:
print(
f"✅ Scenario 4 successful, returned {result['total_count']} episodic memories"
)
# Scenario 5: user_id="__all__" + valid group_id
print("\n--- Scenario 5: user_id='__all__' + valid group_id ---")
data = {
"user_id": "__all__",
"group_id": self.group_id,
"memory_type": "episodic_memory",
"limit": 10,
"offset": 0,
}
status_code, response = self.call_get_with_body_api("", data)
assert status_code == 200, f"Status code should be 200, actual: {status_code}"
assert response.get("status") == "ok", f"Status should be ok"
result = response["result"]
# Validate metadata includes group_id
metadata = result["metadata"]
assert (
metadata.get("group_id") == self.group_id
), "metadata group_id should match"
# Validate that returned memories have the requested group_id
if result["total_count"] > 0 and len(result["memories"]) > 0:
for idx, memory in enumerate(result["memories"]):
assert (
memory.get("group_id") == self.group_id
), f"Memory {idx} group_id should be {self.group_id}, actual: {memory.get('group_id')}"
print(
f"✅ Scenario 5 successful, returned {result['total_count']} episodic memories with group_id={self.group_id}"
)
else:
print(
f"✅ Scenario 5 successful, returned {result['total_count']} episodic memories"
)
return status_code, response
def test_fetch_foresight(self):
"""Test 3: GET /api/v0/memories - Fetch foresight (foresight type, pass parameters via body)
Tests multiple scenarios:
1. Only user_id (group_id NOT provided in request)
2. user_id + group_id=None (explicitly null)
3. user_id + group_id="" (explicitly empty string)
4. user_id + group_id both have valid values
5. user_id="__all__" + valid group_id
"""
self.print_section("Test 3: GET /api/v0/memories - Fetch Foresight")
# Scenario 1: Only user_id, group_id NOT provided (parameter doesn't exist)
print("\n--- Scenario 1: Only user_id (group_id NOT provided) ---")
data = {
"user_id": self.user_id,
"memory_type": "foresight",
"limit": 10,
"offset": 0,
# group_id is NOT in the request at all
}
status_code, response = self.call_get_with_body_api("", data)
# Assert: Precisely validate response structure
assert status_code == 200, f"Status code should be 200, actual: {status_code}"
assert (
response.get("status") == "ok"
), f"Status should be ok, actual: {response.get('status')}"
assert "result" in response, "Response should contain result field"
result = response["result"]
assert "memories" in result, "result should contain memories field"
assert "total_count" in result, "result should contain total_count field"
assert "has_more" in result, "result should contain has_more field"
assert "metadata" in result, "result should contain metadata field"
# Validate data types
assert isinstance(result["memories"], list), "memories should be a list"
assert result["total_count"] >= 0, "total_count should be >= 0"
assert isinstance(result["has_more"], bool), "has_more should be boolean"
# Validate metadata structure
metadata = result["metadata"]
assert isinstance(metadata, dict), "metadata should be a dictionary"
assert "source" in metadata, "metadata should contain source field"
assert "user_id" in metadata, "metadata should contain user_id field"
assert "memory_type" in metadata, "metadata should contain memory_type field"
assert metadata.get("user_id") == self.user_id, "metadata user_id should match"
# If there are memories, deeply validate structure
if result["total_count"] > 0 and len(result["memories"]) > 0:
for idx, memory in enumerate(result["memories"]):
assert isinstance(memory, dict), f"Memory {idx} should be a dictionary"
assert "content" in memory, f"Memory {idx} should contain content"
assert (
"parent_type" in memory
), f"Memory {idx} should contain parent_type"
assert "parent_id" in memory, f"Memory {idx} should contain parent_id"
# Foresight user_id may be None (group scenario), so not enforced
print(
f"✅ Scenario 1 successful, returned {result['total_count']} foresights"
)
else:
print(
f"✅ Scenario 1 successful, returned {result['total_count']} foresights"
)
# Scenario 2: user_id + group_id=None (explicitly null)
print("\n--- Scenario 2: user_id + group_id=None (explicitly null) ---")
data = {
"user_id": self.user_id,
"group_id": None, # Explicitly set to None
"memory_type": "foresight",
"limit": 10,
"offset": 0,
}
status_code, response = self.call_get_with_body_api("", data)
assert status_code == 200, f"Status code should be 200, actual: {status_code}"
assert response.get("status") == "ok", f"Status should be ok"
result = response["result"]
# Validate that returned memories have null or empty group_id
if result["total_count"] > 0 and len(result["memories"]) > 0:
for idx, memory in enumerate(result["memories"]):
group_id_value = memory.get("group_id")
assert group_id_value in (
None,
"",
), f"Memory {idx} group_id should be None or empty string, actual: {group_id_value}"
print(
f"✅ Scenario 2 successful, returned {result['total_count']} foresights with null/empty group_id"
)
else:
print(
f"✅ Scenario 2 successful, returned {result['total_count']} foresights"
)
# Scenario 3: user_id + group_id="" (explicitly empty string)
print("\n--- Scenario 3: user_id + group_id='' (explicitly empty string) ---")
data = {
"user_id": self.user_id,
"group_id": "", # Explicitly set to empty string
"memory_type": "foresight",
"limit": 10,
"offset": 0,
}
status_code, response = self.call_get_with_body_api("", data)
assert status_code == 200, f"Status code should be 200, actual: {status_code}"
assert response.get("status") == "ok", f"Status should be ok"
result = response["result"]
# Validate that returned memories have null or empty group_id
if result["total_count"] > 0 and len(result["memories"]) > 0:
for idx, memory in enumerate(result["memories"]):
group_id_value = memory.get("group_id")
assert group_id_value in (
None,
"",
), f"Memory {idx} group_id should be None or empty string, actual: {group_id_value}"
print(
f"✅ Scenario 3 successful, returned {result['total_count']} foresights with null/empty group_id"
)
else:
print(
f"✅ Scenario 3 successful, returned {result['total_count']} foresights"
)
# Scenario 4: user_id + group_id both have valid values
print("\n--- Scenario 4: user_id + group_id both have valid values ---")
data = {
"user_id": self.user_id,
"group_id": self.group_id,
"memory_type": "foresight",
"limit": 10,
"offset": 0,
}
status_code, response = self.call_get_with_body_api("", data)
assert status_code == 200, f"Status code should be 200, actual: {status_code}"
assert response.get("status") == "ok", f"Status should be ok"
result = response["result"]
# Validate metadata includes both user_id and group_id
metadata = result["metadata"]
assert metadata.get("user_id") == self.user_id, "metadata user_id should match"
assert (
metadata.get("group_id") == self.group_id
), "metadata group_id should match"
# Validate that returned memories have the requested group_id
# Note: foresight user_id may be None in some cases, so only validate group_id
if result["total_count"] > 0 and len(result["memories"]) > 0:
for idx, memory in enumerate(result["memories"]):
assert (
memory.get("group_id") == self.group_id
), f"Memory {idx} group_id should be {self.group_id}, actual: {memory.get('group_id')}"
print(
f"✅ Scenario 4 successful, returned {result['total_count']} foresights with group_id={self.group_id}"
)
else:
print(
f"✅ Scenario 4 successful, returned {result['total_count']} foresights"
)
# Scenario 5: user_id="__all__" + valid group_id
print("\n--- Scenario 5: user_id='__all__' + valid group_id ---")
data = {
"user_id": "__all__",
"group_id": self.group_id,
"memory_type": "foresight",
"limit": 10,
"offset": 0,
}
status_code, response = self.call_get_with_body_api("", data)
assert status_code == 200, f"Status code should be 200, actual: {status_code}"
assert response.get("status") == "ok", f"Status should be ok"
result = response["result"]
# Validate metadata includes group_id
metadata = result["metadata"]
assert (
metadata.get("group_id") == self.group_id
), "metadata group_id should match"
# Validate that returned memories have the requested group_id
if result["total_count"] > 0 and len(result["memories"]) > 0:
for idx, memory in enumerate(result["memories"]):
assert (
memory.get("group_id") == self.group_id
), f"Memory {idx} group_id should be {self.group_id}, actual: {memory.get('group_id')}"
print(
f"✅ Scenario 5 successful, returned {result['total_count']} foresights with group_id={self.group_id}"
)
else:
print(
f"✅ Scenario 5 successful, returned {result['total_count']} foresights"
)
return status_code, response
def test_fetch_atomic_fact(self):
"""Test 4: GET /api/v0/memories - Fetch user atomic fact (atomic_fact type, pass parameters via body)
Tests multiple scenarios:
1. Only user_id (group_id NOT provided in request)
2. user_id + group_id=None (explicitly null)
3. user_id + group_id="" (explicitly empty string)
4. user_id + group_id both have valid values
5. user_id="__all__" + valid group_id
"""
self.print_section("Test 4: GET /api/v0/memories - Fetch User Atomic Fact")
# Scenario 1: Only user_id, group_id NOT provided (parameter doesn't exist)
print("\n--- Scenario 1: Only user_id (group_id NOT provided) ---")
data = {
"user_id": self.user_id,
"memory_type": "atomic_fact",
"limit": 10,
"offset": 0,
# group_id is NOT in the request at all
}
status_code, response = self.call_get_with_body_api("", data)
# Assert: Precisely validate response structure
assert status_code == 200, f"Status code should be 200, actual: {status_code}"
assert (
response.get("status") == "ok"
), f"Status should be ok, actual: {response.get('status')}"
assert "result" in response, "Response should contain result field"
result = response["result"]
assert "memories" in result, "result should contain memories field"
assert "total_count" in result, "result should contain total_count field"
assert "has_more" in result, "result should contain has_more field"
assert "metadata" in result, "result should contain metadata field"
# Validate data types
assert isinstance(result["memories"], list), "memories should be a list"
assert result["total_count"] >= 0, "total_count should be >= 0"
assert isinstance(result["has_more"], bool), "has_more should be boolean"
# Validate metadata structure
metadata = result["metadata"]
assert isinstance(metadata, dict), "metadata should be a dictionary"
assert "source" in metadata, "metadata should contain source field"
assert "user_id" in metadata, "metadata should contain user_id field"
assert "memory_type" in metadata, "metadata should contain memory_type field"
assert metadata.get("user_id") == self.user_id, "metadata user_id should match"
# If there are atomic facts, deeply validate structure
if result["total_count"] > 0 and len(result["memories"]) > 0:
for idx, memory in enumerate(result["memories"]):
assert isinstance(memory, dict), f"Memory {idx} should be a dictionary"
assert (
"atomic_fact" in memory
), f"Memory {idx} should contain atomic_fact"
assert "timestamp" in memory, f"Memory {idx} should contain timestamp"
assert "user_id" in memory, f"Memory {idx} should contain user_id"
assert (
memory.get("user_id") == self.user_id
), f"Memory {idx} user_id should match"
print(
f"✅ Scenario 1 successful, returned {result['total_count']} atomic facts"
)
else:
print(
f"✅ Scenario 1 successful, returned {result['total_count']} atomic facts"
)
# Scenario 2: user_id + group_id=None (explicitly null)
print("\n--- Scenario 2: user_id + group_id=None (explicitly null) ---")
data = {
"user_id": self.user_id,
"group_id": None, # Explicitly set to None
"memory_type": "atomic_fact",
"limit": 10,
"offset": 0,
}
status_code, response = self.call_get_with_body_api("", data)
assert status_code == 200, f"Status code should be 200, actual: {status_code}"
assert response.get("status") == "ok", f"Status should be ok"
result = response["result"]
# Validate that returned memories have null or empty group_id