forked from basicmachines-co/basic-memory
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_knowledge_router.py
More file actions
1323 lines (1115 loc) · 44.8 KB
/
test_knowledge_router.py
File metadata and controls
1323 lines (1115 loc) · 44.8 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
"""Tests for knowledge graph API routes."""
from urllib.parse import quote
import pytest
from httpx import AsyncClient
from basic_memory.schemas import (
Entity,
EntityResponse,
)
from basic_memory.schemas.search import SearchItemType, SearchResponse
from basic_memory.utils import normalize_newlines
@pytest.mark.asyncio
async def test_create_entity(client: AsyncClient, file_service, project_url):
"""Should create entity successfully."""
data = {
"title": "TestEntity",
"folder": "test",
"entity_type": "test",
"content": "TestContent",
"project": "Test Project Context",
}
# Create an entity
print(f"Requesting with data: {data}")
# Use the permalink version of the project name in the path
response = await client.post(f"{project_url}/knowledge/entities", json=data)
# Print response for debugging
print(f"Response status: {response.status_code}")
print(f"Response content: {response.text}")
# Verify creation
assert response.status_code == 200
entity = EntityResponse.model_validate(response.json())
assert entity.permalink == "test/test-entity"
assert entity.file_path == "test/TestEntity.md"
assert entity.entity_type == data["entity_type"]
assert entity.content_type == "text/markdown"
# Verify file has new content but preserved metadata
file_path = file_service.get_entity_path(entity)
file_content, _ = await file_service.read_file(file_path)
assert data["content"] in file_content
@pytest.mark.asyncio
async def test_create_entity_observations_relations(client: AsyncClient, file_service, project_url):
"""Should create entity successfully."""
data = {
"title": "TestEntity",
"folder": "test",
"content": """
# TestContent
## Observations
- [note] This is notable #tag1 (testing)
- related to [[SomeOtherThing]]
""",
}
# Create an entity
response = await client.post(f"{project_url}/knowledge/entities", json=data)
# Verify creation
assert response.status_code == 200
entity = EntityResponse.model_validate(response.json())
assert entity.permalink == "test/test-entity"
assert entity.file_path == "test/TestEntity.md"
assert entity.entity_type == "note"
assert entity.content_type == "text/markdown"
assert len(entity.observations) == 1
assert entity.observations[0].category == "note"
assert entity.observations[0].content == "This is notable #tag1"
assert entity.observations[0].tags == ["tag1"]
assert entity.observations[0].context == "testing"
assert len(entity.relations) == 1
assert entity.relations[0].relation_type == "related to"
assert entity.relations[0].from_id == "test/test-entity"
assert entity.relations[0].to_id is None
# Verify file has new content but preserved metadata
file_path = file_service.get_entity_path(entity)
file_content, _ = await file_service.read_file(file_path)
assert data["content"].strip() in file_content
@pytest.mark.asyncio
async def test_relation_resolution_after_creation(client: AsyncClient, project_url):
"""Test that relation resolution works after creating entities and handles exceptions gracefully."""
# Create first entity with unresolved relation
entity1_data = {
"title": "EntityOne",
"folder": "test",
"entity_type": "test",
"content": "This entity references [[EntityTwo]]",
}
response1 = await client.put(
f"{project_url}/knowledge/entities/test/entity-one", json=entity1_data
)
assert response1.status_code == 201
entity1 = response1.json()
# Verify relation exists but is unresolved
assert len(entity1["relations"]) == 1
assert entity1["relations"][0]["to_id"] is None
assert entity1["relations"][0]["to_name"] == "EntityTwo"
# Create the referenced entity
entity2_data = {
"title": "EntityTwo",
"folder": "test",
"entity_type": "test",
"content": "This is the referenced entity",
}
response2 = await client.put(
f"{project_url}/knowledge/entities/test/entity-two", json=entity2_data
)
assert response2.status_code == 201
# Verify the original entity's relation was resolved
response_check = await client.get(f"{project_url}/knowledge/entities/test/entity-one")
assert response_check.status_code == 200
updated_entity1 = response_check.json()
# The relation should now be resolved via the automatic resolution after entity creation
resolved_relations = [r for r in updated_entity1["relations"] if r["to_id"] is not None]
assert (
len(resolved_relations) >= 0
) # May or may not be resolved immediately depending on timing
@pytest.mark.asyncio
async def test_relation_resolution_exception_handling(client: AsyncClient, project_url):
"""Test that relation resolution exceptions are handled gracefully."""
import unittest.mock
# Create an entity that would trigger relation resolution
entity_data = {
"title": "ExceptionTest",
"folder": "test",
"entity_type": "test",
"content": "This entity has a [[Relation]]",
}
# Mock the sync service to raise an exception during relation resolution
# We'll patch at the module level where it's imported
with unittest.mock.patch(
"basic_memory.api.routers.knowledge_router.SyncServiceDep",
side_effect=lambda: unittest.mock.AsyncMock(),
) as mock_sync_service_dep:
# Configure the mock sync service to raise an exception
mock_sync_service = unittest.mock.AsyncMock()
mock_sync_service.resolve_relations.side_effect = Exception("Sync service failed")
mock_sync_service_dep.return_value = mock_sync_service
# This should still succeed even though relation resolution fails
response = await client.put(
f"{project_url}/knowledge/entities/test/exception-test", json=entity_data
)
assert response.status_code == 201
entity = response.json()
# Verify the entity was still created successfully
assert entity["title"] == "ExceptionTest"
assert len(entity["relations"]) == 1 # Relation should still be there, just unresolved
@pytest.mark.asyncio
async def test_get_entity_by_permalink(client: AsyncClient, project_url):
"""Should retrieve an entity by path ID."""
# First create an entity
data = {"title": "TestEntity", "folder": "test", "entity_type": "test"}
response = await client.post(f"{project_url}/knowledge/entities", json=data)
assert response.status_code == 200
data = response.json()
# Now get it by permalink
permalink = data["permalink"]
response = await client.get(f"{project_url}/knowledge/entities/{permalink}")
# Verify retrieval
assert response.status_code == 200
entity = response.json()
assert entity["file_path"] == "test/TestEntity.md"
assert entity["entity_type"] == "test"
assert entity["permalink"] == "test/test-entity"
@pytest.mark.asyncio
async def test_get_entity_by_file_path(client: AsyncClient, project_url):
"""Should retrieve an entity by path ID."""
# First create an entity
data = {"title": "TestEntity", "folder": "test", "entity_type": "test"}
response = await client.post(f"{project_url}/knowledge/entities", json=data)
assert response.status_code == 200
data = response.json()
# Now get it by path
file_path = data["file_path"]
response = await client.get(f"{project_url}/knowledge/entities/{file_path}")
# Verify retrieval
assert response.status_code == 200
entity = response.json()
assert entity["file_path"] == "test/TestEntity.md"
assert entity["entity_type"] == "test"
assert entity["permalink"] == "test/test-entity"
@pytest.mark.asyncio
async def test_get_entities(client: AsyncClient, project_url):
"""Should open multiple entities by path IDs."""
# Create a few entities with different names
await client.post(
f"{project_url}/knowledge/entities",
json={"title": "AlphaTest", "folder": "", "entity_type": "test"},
)
await client.post(
f"{project_url}/knowledge/entities",
json={"title": "BetaTest", "folder": "", "entity_type": "test"},
)
# Open nodes by path IDs
response = await client.get(
f"{project_url}/knowledge/entities?permalink=alpha-test&permalink=beta-test",
)
# Verify results
assert response.status_code == 200
data = response.json()
assert len(data["entities"]) == 2
entity_0 = data["entities"][0]
assert entity_0["title"] == "AlphaTest"
assert entity_0["file_path"] == "AlphaTest.md"
assert entity_0["entity_type"] == "test"
assert entity_0["permalink"] == "alpha-test"
entity_1 = data["entities"][1]
assert entity_1["title"] == "BetaTest"
assert entity_1["file_path"] == "BetaTest.md"
assert entity_1["entity_type"] == "test"
assert entity_1["permalink"] == "beta-test"
@pytest.mark.asyncio
async def test_delete_entity(client: AsyncClient, project_url):
"""Test DELETE /knowledge/entities with path ID."""
# Create test entity
entity_data = {"file_path": "TestEntity", "entity_type": "test"}
await client.post(f"{project_url}/knowledge/entities", json=entity_data)
# Test deletion
response = await client.post(
f"{project_url}/knowledge/entities/delete", json={"permalinks": ["test-entity"]}
)
assert response.status_code == 200
assert response.json() == {"deleted": True}
# Verify entity is gone
permalink = quote("test/TestEntity")
response = await client.get(f"{project_url}/knowledge/entities/{permalink}")
assert response.status_code == 404
@pytest.mark.asyncio
async def test_delete_single_entity(client: AsyncClient, project_url):
"""Test DELETE /knowledge/entities with path ID."""
# Create test entity
entity_data = {"title": "TestEntity", "folder": "", "entity_type": "test"}
await client.post(f"{project_url}/knowledge/entities", json=entity_data)
# Test deletion
response = await client.delete(f"{project_url}/knowledge/entities/test-entity")
assert response.status_code == 200
assert response.json() == {"deleted": True}
# Verify entity is gone
permalink = quote("test/TestEntity")
response = await client.get(f"{project_url}/knowledge/entities/{permalink}")
assert response.status_code == 404
@pytest.mark.asyncio
async def test_delete_single_entity_by_title(client: AsyncClient, project_url):
"""Test DELETE /knowledge/entities with file path."""
# Create test entity
entity_data = {"title": "TestEntity", "folder": "", "entity_type": "test"}
response = await client.post(f"{project_url}/knowledge/entities", json=entity_data)
assert response.status_code == 200
data = response.json()
# Test deletion
response = await client.delete(f"{project_url}/knowledge/entities/TestEntity")
assert response.status_code == 200
assert response.json() == {"deleted": True}
# Verify entity is gone
file_path = quote(data["file_path"])
response = await client.get(f"{project_url}/knowledge/entities/{file_path}")
assert response.status_code == 404
@pytest.mark.asyncio
async def test_delete_single_entity_not_found(client: AsyncClient, project_url):
"""Test DELETE /knowledge/entities with path ID."""
# Test deletion
response = await client.delete(f"{project_url}/knowledge/entities/test-not-found")
assert response.status_code == 200
assert response.json() == {"deleted": False}
@pytest.mark.asyncio
async def test_delete_entity_bulk(client: AsyncClient, project_url):
"""Test bulk entity deletion using path IDs."""
# Create test entities
await client.post(
f"{project_url}/knowledge/entities", json={"file_path": "Entity1", "entity_type": "test"}
)
await client.post(
f"{project_url}/knowledge/entities", json={"file_path": "Entity2", "entity_type": "test"}
)
# Test deletion
response = await client.post(
f"{project_url}/knowledge/entities/delete", json={"permalinks": ["Entity1", "Entity2"]}
)
assert response.status_code == 200
assert response.json() == {"deleted": True}
# Verify entities are gone
for name in ["Entity1", "Entity2"]:
permalink = quote(f"{name}")
response = await client.get(f"{project_url}/knowledge/entities/{permalink}")
assert response.status_code == 404
@pytest.mark.asyncio
async def test_delete_nonexistent_entity(client: AsyncClient, project_url):
"""Test deleting a nonexistent entity by path ID."""
response = await client.post(
f"{project_url}/knowledge/entities/delete", json={"permalinks": ["non_existent"]}
)
assert response.status_code == 200
assert response.json() == {"deleted": True}
@pytest.mark.asyncio
async def test_entity_indexing(client: AsyncClient, project_url):
"""Test entity creation includes search indexing."""
# Create entity
response = await client.post(
f"{project_url}/knowledge/entities",
json={
"title": "SearchTest",
"folder": "",
"entity_type": "test",
"observations": ["Unique searchable observation"],
},
)
assert response.status_code == 200
# Verify it's searchable
search_response = await client.post(
f"{project_url}/search/",
json={"text": "search", "entity_types": [SearchItemType.ENTITY.value]},
)
assert search_response.status_code == 200
search_result = SearchResponse.model_validate(search_response.json())
assert len(search_result.results) == 1
assert search_result.results[0].permalink == "search-test"
assert search_result.results[0].type == SearchItemType.ENTITY.value
@pytest.mark.asyncio
async def test_entity_delete_indexing(client: AsyncClient, project_url):
"""Test deleted entities are removed from search index."""
# Create entity
response = await client.post(
f"{project_url}/knowledge/entities",
json={
"title": "DeleteTest",
"folder": "",
"entity_type": "test",
"observations": ["Searchable observation that should be removed"],
},
)
assert response.status_code == 200
entity = response.json()
# Verify it's initially searchable
search_response = await client.post(
f"{project_url}/search/",
json={"text": "delete", "entity_types": [SearchItemType.ENTITY.value]},
)
search_result = SearchResponse.model_validate(search_response.json())
assert len(search_result.results) == 1
# Delete entity
delete_response = await client.post(
f"{project_url}/knowledge/entities/delete", json={"permalinks": [entity["permalink"]]}
)
assert delete_response.status_code == 200
# Verify it's no longer searchable
search_response = await client.post(
f"{project_url}/search/", json={"text": "delete", "types": [SearchItemType.ENTITY.value]}
)
search_result = SearchResponse.model_validate(search_response.json())
assert len(search_result.results) == 0
@pytest.mark.asyncio
async def test_update_entity_basic(client: AsyncClient, project_url):
"""Test basic entity field updates."""
# Create initial entity
response = await client.post(
f"{project_url}/knowledge/entities",
json={
"title": "test",
"folder": "",
"entity_type": "test",
"content": "Initial summary",
"entity_metadata": {"status": "draft"},
},
)
entity_response = response.json()
# Update fields
entity = Entity(**entity_response, folder="")
entity.entity_metadata["status"] = "final"
entity.content = "Updated summary"
response = await client.put(
f"{project_url}/knowledge/entities/{entity.permalink}", json=entity.model_dump()
)
assert response.status_code == 200
updated = response.json()
# Verify updates
assert updated["entity_metadata"]["status"] == "final" # Preserved
response = await client.get(f"{project_url}/resource/{updated['permalink']}?content=true")
# raw markdown content
fetched = response.text
assert "Updated summary" in fetched
@pytest.mark.asyncio
async def test_update_entity_content(client: AsyncClient, project_url):
"""Test updating content for different entity types."""
# Create a note entity
response = await client.post(
f"{project_url}/knowledge/entities",
json={"title": "test-note", "folder": "", "entity_type": "note", "summary": "Test note"},
)
note = response.json()
# Update fields
entity = Entity(**note, folder="")
entity.content = "# Updated Note\n\nNew content."
response = await client.put(
f"{project_url}/knowledge/entities/{note['permalink']}", json=entity.model_dump()
)
assert response.status_code == 200
updated = response.json()
# Verify through get request to check file
response = await client.get(f"{project_url}/resource/{updated['permalink']}?content=true")
# raw markdown content
fetched = response.text
assert "# Updated Note" in fetched
assert "New content" in fetched
@pytest.mark.asyncio
async def test_update_entity_type_conversion(client: AsyncClient, project_url):
"""Test converting between note and knowledge types."""
# Create a note
note_data = {
"title": "test-note",
"folder": "",
"entity_type": "note",
"summary": "Test note",
"content": "# Test Note\n\nInitial content.",
}
response = await client.post(f"{project_url}/knowledge/entities", json=note_data)
note = response.json()
# Update fields
entity = Entity(**note, folder="")
entity.entity_type = "test"
response = await client.put(
f"{project_url}/knowledge/entities/{note['permalink']}", json=entity.model_dump()
)
assert response.status_code == 200
updated = response.json()
# Verify conversion
assert updated["entity_type"] == "test"
# Get latest to verify file format
response = await client.get(f"{project_url}/knowledge/entities/{updated['permalink']}")
knowledge = response.json()
assert knowledge.get("content") is None
@pytest.mark.asyncio
async def test_update_entity_metadata(client: AsyncClient, project_url):
"""Test updating entity metadata."""
# Create entity
data = {
"title": "test",
"folder": "",
"entity_type": "test",
"entity_metadata": {"status": "draft"},
}
response = await client.post(f"{project_url}/knowledge/entities", json=data)
entity_response = response.json()
# Update fields
entity = Entity(**entity_response, folder="")
entity.entity_metadata["status"] = "final"
entity.entity_metadata["reviewed"] = True
# Update metadata
response = await client.put(
f"{project_url}/knowledge/entities/{entity.permalink}", json=entity.model_dump()
)
assert response.status_code == 200
updated = response.json()
# Verify metadata was merged, not replaced
assert updated["entity_metadata"]["status"] == "final"
assert updated["entity_metadata"]["reviewed"] in (True, "True")
@pytest.mark.asyncio
async def test_update_entity_not_found_does_create(client: AsyncClient, project_url):
"""Test updating non-existent entity does a create"""
data = {
"title": "nonexistent",
"folder": "",
"entity_type": "test",
"observations": ["First observation", "Second observation"],
}
entity = Entity(**data)
response = await client.put(
f"{project_url}/knowledge/entities/nonexistent", json=entity.model_dump()
)
assert response.status_code == 201
@pytest.mark.asyncio
async def test_update_entity_incorrect_permalink(client: AsyncClient, project_url):
"""Test updating non-existent entity does a create"""
data = {
"title": "Test Entity",
"folder": "",
"entity_type": "test",
"observations": ["First observation", "Second observation"],
}
entity = Entity(**data)
response = await client.put(
f"{project_url}/knowledge/entities/nonexistent", json=entity.model_dump()
)
assert response.status_code == 400
@pytest.mark.asyncio
async def test_update_entity_search_index(client: AsyncClient, project_url):
"""Test search index is updated after entity changes."""
# Create entity
data = {
"title": "test",
"folder": "",
"entity_type": "test",
"content": "Initial searchable content",
}
response = await client.post(f"{project_url}/knowledge/entities", json=data)
entity_response = response.json()
# Update fields
entity = Entity(**entity_response, folder="")
entity.content = "Updated with unique sphinx marker"
response = await client.put(
f"{project_url}/knowledge/entities/{entity.permalink}", json=entity.model_dump()
)
assert response.status_code == 200
# Search should find new content
search_response = await client.post(
f"{project_url}/search/",
json={"text": "sphinx marker", "entity_types": [SearchItemType.ENTITY.value]},
)
results = search_response.json()["results"]
assert len(results) == 1
assert results[0]["permalink"] == entity.permalink
# PATCH edit entity endpoint tests
@pytest.mark.asyncio
async def test_edit_entity_append(client: AsyncClient, project_url):
"""Test appending content to an entity via PATCH endpoint."""
# Create test entity
response = await client.post(
f"{project_url}/knowledge/entities",
json={
"title": "Test Note",
"folder": "test",
"entity_type": "note",
"content": "Original content",
},
)
assert response.status_code == 200
entity = response.json()
# Edit entity with append operation
response = await client.patch(
f"{project_url}/knowledge/entities/{entity['permalink']}",
json={"operation": "append", "content": "Appended content"},
)
if response.status_code != 200:
print(f"PATCH failed with status {response.status_code}")
print(f"Response content: {response.text}")
assert response.status_code == 200
updated = response.json()
# Verify content was appended by reading the file
response = await client.get(f"{project_url}/resource/{updated['permalink']}?content=true")
file_content = response.text
assert "Original content" in file_content
assert "Appended content" in file_content
assert file_content.index("Original content") < file_content.index("Appended content")
@pytest.mark.asyncio
async def test_edit_entity_prepend(client: AsyncClient, project_url):
"""Test prepending content to an entity via PATCH endpoint."""
# Create test entity
response = await client.post(
f"{project_url}/knowledge/entities",
json={
"title": "Test Note",
"folder": "test",
"entity_type": "note",
"content": "Original content",
},
)
assert response.status_code == 200
entity = response.json()
# Edit entity with prepend operation
response = await client.patch(
f"{project_url}/knowledge/entities/{entity['permalink']}",
json={"operation": "prepend", "content": "Prepended content"},
)
if response.status_code != 200:
print(f"PATCH prepend failed with status {response.status_code}")
print(f"Response content: {response.text}")
assert response.status_code == 200
updated = response.json()
# Verify the entire file content structure
response = await client.get(f"{project_url}/resource/{updated['permalink']}?content=true")
file_content = response.text
# Expected content with frontmatter preserved and content prepended to body
expected_content = normalize_newlines("""---
title: Test Note
type: note
permalink: test/test-note
---
Prepended content
Original content""")
assert file_content.strip() == expected_content.strip()
@pytest.mark.asyncio
async def test_edit_entity_find_replace(client: AsyncClient, project_url):
"""Test find and replace operation via PATCH endpoint."""
# Create test entity
response = await client.post(
f"{project_url}/knowledge/entities",
json={
"title": "Test Note",
"folder": "test",
"entity_type": "note",
"content": "This is old content that needs updating",
},
)
assert response.status_code == 200
entity = response.json()
# Edit entity with find_replace operation
response = await client.patch(
f"{project_url}/knowledge/entities/{entity['permalink']}",
json={"operation": "find_replace", "content": "new content", "find_text": "old content"},
)
assert response.status_code == 200
updated = response.json()
# Verify content was replaced
response = await client.get(f"{project_url}/resource/{updated['permalink']}?content=true")
file_content = response.text
assert "old content" not in file_content
assert "This is new content that needs updating" in file_content
@pytest.mark.asyncio
async def test_edit_entity_find_replace_with_expected_replacements(
client: AsyncClient, project_url
):
"""Test find and replace with expected_replacements parameter."""
# Create test entity with repeated text
response = await client.post(
f"{project_url}/knowledge/entities",
json={
"title": "Sample Note",
"folder": "docs",
"entity_type": "note",
"content": "The word banana appears here. Another banana word here.",
},
)
assert response.status_code == 200
entity = response.json()
# Edit entity with find_replace operation, expecting 2 replacements
response = await client.patch(
f"{project_url}/knowledge/entities/{entity['permalink']}",
json={
"operation": "find_replace",
"content": "apple",
"find_text": "banana",
"expected_replacements": 2,
},
)
assert response.status_code == 200
updated = response.json()
# Verify both instances were replaced
response = await client.get(f"{project_url}/resource/{updated['permalink']}?content=true")
file_content = response.text
assert "The word apple appears here. Another apple word here." in file_content
@pytest.mark.asyncio
async def test_edit_entity_replace_section(client: AsyncClient, project_url):
"""Test replacing a section via PATCH endpoint."""
# Create test entity with sections
content = """# Main Title
## Section 1
Original section 1 content
## Section 2
Original section 2 content"""
response = await client.post(
f"{project_url}/knowledge/entities",
json={
"title": "Sample Note",
"folder": "docs",
"entity_type": "note",
"content": content,
},
)
assert response.status_code == 200
entity = response.json()
# Edit entity with replace_section operation
response = await client.patch(
f"{project_url}/knowledge/entities/{entity['permalink']}",
json={
"operation": "replace_section",
"content": "New section 1 content",
"section": "## Section 1",
},
)
assert response.status_code == 200
updated = response.json()
# Verify section was replaced
response = await client.get(f"{project_url}/resource/{updated['permalink']}?content=true")
file_content = response.text
assert "New section 1 content" in file_content
assert "Original section 1 content" not in file_content
assert "Original section 2 content" in file_content # Other sections preserved
@pytest.mark.asyncio
async def test_edit_entity_not_found(client: AsyncClient, project_url):
"""Test editing a non-existent entity returns 400."""
response = await client.patch(
f"{project_url}/knowledge/entities/non-existent",
json={"operation": "append", "content": "content"},
)
assert response.status_code == 400
assert "Entity not found" in response.json()["detail"]
@pytest.mark.asyncio
async def test_edit_entity_invalid_operation(client: AsyncClient, project_url):
"""Test editing with invalid operation returns 400."""
# Create test entity
response = await client.post(
f"{project_url}/knowledge/entities",
json={
"title": "Test Note",
"folder": "test",
"entity_type": "note",
"content": "Original content",
},
)
assert response.status_code == 200
entity = response.json()
# Try invalid operation
response = await client.patch(
f"{project_url}/knowledge/entities/{entity['permalink']}",
json={"operation": "invalid_operation", "content": "content"},
)
assert response.status_code == 422
assert "invalid_operation" in response.json()["detail"][0]["input"]
@pytest.mark.asyncio
async def test_edit_entity_find_replace_missing_find_text(client: AsyncClient, project_url):
"""Test find_replace without find_text returns 400."""
# Create test entity
response = await client.post(
f"{project_url}/knowledge/entities",
json={
"title": "Test Note",
"folder": "test",
"entity_type": "note",
"content": "Original content",
},
)
assert response.status_code == 200
entity = response.json()
# Try find_replace without find_text
response = await client.patch(
f"{project_url}/knowledge/entities/{entity['permalink']}",
json={"operation": "find_replace", "content": "new content"},
)
assert response.status_code == 400
assert "find_text is required" in response.json()["detail"]
@pytest.mark.asyncio
async def test_edit_entity_replace_section_missing_section(client: AsyncClient, project_url):
"""Test replace_section without section parameter returns 400."""
# Create test entity
response = await client.post(
f"{project_url}/knowledge/entities",
json={
"title": "Test Note",
"folder": "test",
"entity_type": "note",
"content": "Original content",
},
)
assert response.status_code == 200
entity = response.json()
# Try replace_section without section
response = await client.patch(
f"{project_url}/knowledge/entities/{entity['permalink']}",
json={"operation": "replace_section", "content": "new content"},
)
assert response.status_code == 400
assert "section is required" in response.json()["detail"]
@pytest.mark.asyncio
async def test_edit_entity_find_replace_not_found(client: AsyncClient, project_url):
"""Test find_replace when text is not found returns 400."""
# Create test entity
response = await client.post(
f"{project_url}/knowledge/entities",
json={
"title": "Test Note",
"folder": "test",
"entity_type": "note",
"content": "This is some content",
},
)
assert response.status_code == 200
entity = response.json()
# Try to replace text that doesn't exist
response = await client.patch(
f"{project_url}/knowledge/entities/{entity['permalink']}",
json={"operation": "find_replace", "content": "new content", "find_text": "nonexistent"},
)
assert response.status_code == 400
assert "Text to replace not found" in response.json()["detail"]
@pytest.mark.asyncio
async def test_edit_entity_find_replace_wrong_expected_count(client: AsyncClient, project_url):
"""Test find_replace with wrong expected_replacements count returns 400."""
# Create test entity with repeated text
response = await client.post(
f"{project_url}/knowledge/entities",
json={
"title": "Sample Note",
"folder": "docs",
"entity_type": "note",
"content": "The word banana appears here. Another banana word here.",
},
)
assert response.status_code == 200
entity = response.json()
# Try to replace with wrong expected count
response = await client.patch(
f"{project_url}/knowledge/entities/{entity['permalink']}",
json={
"operation": "find_replace",
"content": "replacement",
"find_text": "banana",
"expected_replacements": 1, # Wrong - there are actually 2
},
)
assert response.status_code == 400
assert "Expected 1 occurrences" in response.json()["detail"]
assert "but found 2" in response.json()["detail"]
@pytest.mark.asyncio
async def test_edit_entity_search_reindex(client: AsyncClient, project_url):
"""Test that edited entities are reindexed for search."""
# Create test entity
response = await client.post(
f"{project_url}/knowledge/entities",
json={
"title": "Search Test",
"folder": "test",
"entity_type": "note",
"content": "Original searchable content",
},
)
assert response.status_code == 200
entity = response.json()
# Edit the entity
response = await client.patch(
f"{project_url}/knowledge/entities/{entity['permalink']}",
json={"operation": "append", "content": " with unique zebra marker"},
)
assert response.status_code == 200
# Search should find the new content
search_response = await client.post(
f"{project_url}/search/",
json={"text": "zebra marker", "entity_types": ["entity"]},
)
results = search_response.json()["results"]
assert len(results) == 1
assert results[0]["permalink"] == entity["permalink"]
# Move entity endpoint tests
@pytest.mark.asyncio
async def test_move_entity_success(client: AsyncClient, project_url):
"""Test successfully moving an entity to a new location."""
# Create test entity
response = await client.post(
f"{project_url}/knowledge/entities",
json={
"title": "TestNote",
"folder": "source",
"entity_type": "note",
"content": "Test content",