-
Notifications
You must be signed in to change notification settings - Fork 188
Expand file tree
/
Copy pathtest_config.py
More file actions
1540 lines (1213 loc) · 66.1 KB
/
test_config.py
File metadata and controls
1540 lines (1213 loc) · 66.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
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
"""Test configuration management."""
import tempfile
import pytest
from datetime import datetime
from typing import Any, cast
from basic_memory.config import (
BasicMemoryConfig,
ConfigManager,
ProjectEntry,
ProjectMode,
default_fastembed_cache_dir,
resolve_data_dir,
)
from pathlib import Path
def _migrate_legacy_projects(data: dict[str, Any]) -> dict[str, Any]:
return cast(dict[str, Any], cast(Any, BasicMemoryConfig.migrate_legacy_projects)(data))
class TestBasicMemoryConfig:
"""Test BasicMemoryConfig behavior with BASIC_MEMORY_HOME environment variable."""
def test_default_behavior_without_basic_memory_home(self, config_home, monkeypatch):
"""Test that config uses default path when BASIC_MEMORY_HOME is not set."""
# Ensure BASIC_MEMORY_HOME is not set
monkeypatch.delenv("BASIC_MEMORY_HOME", raising=False)
config = BasicMemoryConfig()
# Should use the default path (home/basic-memory)
expected_path = config_home / "basic-memory"
assert Path(config.projects["main"].path) == expected_path
assert config.default_project == "main"
def test_respects_basic_memory_home_environment_variable(self, config_home, monkeypatch):
"""Test that config respects BASIC_MEMORY_HOME environment variable."""
custom_path = config_home / "app" / "data"
monkeypatch.setenv("BASIC_MEMORY_HOME", str(custom_path))
config = BasicMemoryConfig()
# Should use the custom path from environment variable
assert Path(config.projects["main"].path) == custom_path
def test_model_post_init_respects_basic_memory_home_creates_main(
self, config_home, monkeypatch
):
"""Test that model_post_init creates main project with BASIC_MEMORY_HOME when missing and no other projects."""
custom_path = config_home / "custom" / "memory" / "path"
monkeypatch.setenv("BASIC_MEMORY_HOME", str(custom_path))
# Create config without main project
config = BasicMemoryConfig()
# model_post_init should have added main project with BASIC_MEMORY_HOME
assert "main" in config.projects
assert Path(config.projects["main"].path) == custom_path
def test_model_post_init_respects_basic_memory_home_sets_non_main_default(
self, config_home, monkeypatch
):
"""Test that model_post_init does not create main project with BASIC_MEMORY_HOME when another project exists."""
custom_path = config_home / "custom" / "memory" / "path"
monkeypatch.setenv("BASIC_MEMORY_HOME", str(custom_path))
# Create config without main project
other_path = config_home / "some" / "path"
config = BasicMemoryConfig(projects={"other": {"path": str(other_path)}})
# model_post_init should not add main project with BASIC_MEMORY_HOME
assert "main" not in config.projects
assert Path(config.projects["other"].path) == other_path
assert config.default_project == "other"
def test_model_post_init_fallback_without_basic_memory_home(self, config_home, monkeypatch):
"""Test that model_post_init can set a non-main default when BASIC_MEMORY_HOME is not set."""
# Ensure BASIC_MEMORY_HOME is not set
monkeypatch.delenv("BASIC_MEMORY_HOME", raising=False)
# Create config without main project
other_path = config_home / "some" / "path"
config = BasicMemoryConfig(projects={"other": {"path": str(other_path)}})
# model_post_init should not add main project, but "other" should now be the default
assert "main" not in config.projects
assert Path(config.projects["other"].path) == other_path
assert config.default_project == "other"
def test_basic_memory_home_with_relative_path(self, config_home, monkeypatch):
"""Test that BASIC_MEMORY_HOME works with relative paths."""
relative_path = "relative/memory/path"
monkeypatch.setenv("BASIC_MEMORY_HOME", relative_path)
config = BasicMemoryConfig()
# Should normalize to platform-native path format
assert Path(config.projects["main"].path) == Path(relative_path)
def test_basic_memory_home_overrides_existing_main_project(self, config_home, monkeypatch):
"""Test that BASIC_MEMORY_HOME is not used when a map is passed in the constructor."""
custom_path = str(config_home / "override" / "memory" / "path")
monkeypatch.setenv("BASIC_MEMORY_HOME", custom_path)
# Try to create config with a different main project path
original_path = str(config_home / "original" / "path")
config = BasicMemoryConfig(projects={"main": {"path": original_path}})
# The default_factory should override with BASIC_MEMORY_HOME value
# Note: This tests the current behavior where default_factory takes precedence
assert config.projects["main"].path == original_path
def test_app_database_path_uses_custom_config_dir(self, tmp_path, monkeypatch):
"""Default SQLite DB should live under BASIC_MEMORY_CONFIG_DIR when set."""
custom_config_dir = tmp_path / "instance-a" / "state"
monkeypatch.setenv("BASIC_MEMORY_CONFIG_DIR", str(custom_config_dir))
config = BasicMemoryConfig(projects={"main": {"path": str(tmp_path / "project")}})
assert config.data_dir_path == custom_config_dir
assert config.app_database_path == custom_config_dir / "memory.db"
assert config.app_database_path.exists()
def test_app_database_path_defaults_to_home_data_dir(self, config_home, monkeypatch):
"""Without BASIC_MEMORY_CONFIG_DIR, default DB stays at ~/.basic-memory/memory.db."""
monkeypatch.delenv("BASIC_MEMORY_CONFIG_DIR", raising=False)
config = BasicMemoryConfig()
assert config.data_dir_path == config_home / ".basic-memory"
assert config.app_database_path == config_home / ".basic-memory" / "memory.db"
def test_semantic_embedding_cache_dir_field_stays_none_by_default(
self, config_home, monkeypatch
):
"""The raw config field stays None so it isn't persisted into config.json.
Resolution to a concrete path happens in embedding_provider_factory at
provider construction time, so ``BASIC_MEMORY_CONFIG_DIR`` and
``FASTEMBED_CACHE_PATH`` changes take effect on every run instead of
being frozen by the first save. See #741.
"""
monkeypatch.delenv("BASIC_MEMORY_CONFIG_DIR", raising=False)
monkeypatch.delenv("FASTEMBED_CACHE_PATH", raising=False)
config = BasicMemoryConfig()
assert config.semantic_embedding_cache_dir is None
def test_semantic_embedding_cache_dir_not_persisted_in_model_dump(
self, config_home, monkeypatch
):
"""model_dump must not bake a resolved cache path into config.json.
Regression guard for #741: persisting the default would freeze stale
paths when users later change BASIC_MEMORY_CONFIG_DIR or
FASTEMBED_CACHE_PATH.
"""
monkeypatch.delenv("BASIC_MEMORY_CONFIG_DIR", raising=False)
monkeypatch.delenv("FASTEMBED_CACHE_PATH", raising=False)
dumped = BasicMemoryConfig().model_dump(mode="json")
assert dumped["semantic_embedding_cache_dir"] is None
def test_semantic_embedding_cache_dir_explicit_user_value_preserved(
self, config_home, monkeypatch
):
"""An explicit user override still round-trips through model_dump."""
monkeypatch.delenv("BASIC_MEMORY_CONFIG_DIR", raising=False)
monkeypatch.delenv("FASTEMBED_CACHE_PATH", raising=False)
config = BasicMemoryConfig(semantic_embedding_cache_dir="/custom/explicit/path")
assert config.semantic_embedding_cache_dir == "/custom/explicit/path"
assert (
config.model_dump(mode="json")["semantic_embedding_cache_dir"]
== "/custom/explicit/path"
)
def test_explicit_default_project_preserved(self, config_home, monkeypatch):
"""Test that a valid explicit default_project is not overwritten by model_post_init."""
monkeypatch.delenv("BASIC_MEMORY_HOME", raising=False)
config = BasicMemoryConfig(
projects={
"alpha": {"path": str(config_home / "alpha")},
"beta": {"path": str(config_home / "beta")},
},
default_project="beta",
)
assert config.default_project == "beta"
def test_invalid_default_project_corrected(self, config_home, monkeypatch):
"""Test that an invalid default_project is corrected to the first project."""
monkeypatch.delenv("BASIC_MEMORY_HOME", raising=False)
config = BasicMemoryConfig(
projects={
"alpha": {"path": str(config_home / "alpha")},
"beta": {"path": str(config_home / "beta")},
},
default_project="nonexistent",
)
assert config.default_project == "alpha"
def test_no_default_project_key_uses_first_project(self, config_home, monkeypatch):
"""Test that config without default_project key sets it to the first project."""
monkeypatch.delenv("BASIC_MEMORY_HOME", raising=False)
# Simulate loading a config file that has no default_project key —
# the field default (None) kicks in, and model_post_init resolves it
config = BasicMemoryConfig(
projects={
"research": {"path": str(config_home / "research")},
"notes": {"path": str(config_home / "notes")},
},
)
assert config.default_project == "research"
def test_empty_string_default_project_corrected(self, config_home, monkeypatch):
"""Test that an empty-string default_project is corrected to the first project."""
monkeypatch.delenv("BASIC_MEMORY_HOME", raising=False)
config = BasicMemoryConfig(
projects={
"alpha": {"path": str(config_home / "alpha")},
},
default_project="",
)
# Empty string is not in projects, so model_post_init corrects it
assert config.default_project == "alpha"
def test_single_project_default_always_matches(self, config_home, monkeypatch):
"""Test that a config with one project always resolves default_project to it."""
monkeypatch.delenv("BASIC_MEMORY_HOME", raising=False)
config = BasicMemoryConfig(
projects={"only": {"path": str(config_home / "only")}},
)
assert config.default_project == "only"
def test_stale_default_project_loaded_from_file(self, config_home, monkeypatch):
"""Test that a config file with a stale default_project is corrected on load."""
import json
import basic_memory.config
monkeypatch.delenv("BASIC_MEMORY_HOME", raising=False)
config_manager = ConfigManager()
config_manager.config_dir = config_home / ".basic-memory"
config_manager.config_file = config_manager.config_dir / "config.json"
config_manager.config_dir.mkdir(parents=True, exist_ok=True)
# Write a config file where default_project references a removed project
config_data = {
"projects": {
"research": {"path": str(config_home / "research")},
"notes": {"path": str(config_home / "notes")},
},
"default_project": "deleted-project",
}
config_manager.config_file.write_text(json.dumps(config_data, indent=2))
basic_memory.config._CONFIG_CACHE = None
basic_memory.config._CONFIG_MTIME = None
basic_memory.config._CONFIG_SIZE = None
loaded = config_manager.load_config()
assert loaded.default_project == "research"
def test_config_file_without_default_project_key(self, config_home, monkeypatch):
"""Test that a config file with no default_project key resolves dynamically."""
import json
import basic_memory.config
monkeypatch.delenv("BASIC_MEMORY_HOME", raising=False)
config_manager = ConfigManager()
config_manager.config_dir = config_home / ".basic-memory"
config_manager.config_file = config_manager.config_dir / "config.json"
config_manager.config_dir.mkdir(parents=True, exist_ok=True)
# Write a config file that deliberately omits default_project
config_data = {
"projects": {
"work": {"path": str(config_home / "work")},
"personal": {"path": str(config_home / "personal")},
},
}
config_manager.config_file.write_text(json.dumps(config_data, indent=2))
basic_memory.config._CONFIG_CACHE = None
basic_memory.config._CONFIG_MTIME = None
basic_memory.config._CONFIG_SIZE = None
loaded = config_manager.load_config()
assert loaded.default_project == "work"
class TestDataDirHelpers:
"""Module-level helpers that resolve the Basic Memory data directory."""
def test_resolve_data_dir_defaults_to_home_dot_basic_memory(self, config_home, monkeypatch):
"""Without BASIC_MEMORY_CONFIG_DIR, resolver returns ~/.basic-memory."""
monkeypatch.delenv("BASIC_MEMORY_CONFIG_DIR", raising=False)
assert resolve_data_dir() == config_home / ".basic-memory"
def test_resolve_data_dir_honors_config_dir_env(self, tmp_path, monkeypatch):
"""BASIC_MEMORY_CONFIG_DIR overrides the default location."""
custom = tmp_path / "elsewhere"
monkeypatch.setenv("BASIC_MEMORY_CONFIG_DIR", str(custom))
assert resolve_data_dir() == custom
def test_default_fastembed_cache_dir_uses_data_dir(self, config_home, monkeypatch):
"""Default cache path is a subdir of the Basic Memory data dir."""
monkeypatch.delenv("BASIC_MEMORY_CONFIG_DIR", raising=False)
monkeypatch.delenv("FASTEMBED_CACHE_PATH", raising=False)
assert default_fastembed_cache_dir() == str(
config_home / ".basic-memory" / "fastembed_cache"
)
def test_default_fastembed_cache_dir_env_override(self, tmp_path, monkeypatch):
"""FASTEMBED_CACHE_PATH is preferred when set."""
custom = tmp_path / "custom-cache"
monkeypatch.setenv("FASTEMBED_CACHE_PATH", str(custom))
monkeypatch.setenv("BASIC_MEMORY_CONFIG_DIR", str(tmp_path / "state"))
assert default_fastembed_cache_dir() == str(custom)
def test_default_fastembed_cache_dir_never_falls_back_to_tmp(self, config_home, monkeypatch):
"""Regression guard for #741: default must not point at /tmp/fastembed_cache."""
monkeypatch.delenv("BASIC_MEMORY_CONFIG_DIR", raising=False)
monkeypatch.delenv("FASTEMBED_CACHE_PATH", raising=False)
resolved = default_fastembed_cache_dir()
assert "/tmp/fastembed_cache" not in resolved
assert not resolved.startswith(tempfile.gettempdir())
class TestConfigManager:
"""Test ConfigManager functionality."""
@pytest.fixture
def temp_config_manager(self):
"""Create a ConfigManager with temporary config file."""
with tempfile.TemporaryDirectory() as temp_dir:
temp_path = Path(temp_dir)
# Create a test ConfigManager instance
config_manager = ConfigManager()
# Override config paths to use temp directory
config_manager.config_dir = temp_path / "basic-memory"
config_manager.config_file = config_manager.config_dir / "config.yaml"
config_manager.config_dir.mkdir(parents=True, exist_ok=True)
# Create initial config with test projects
test_config = BasicMemoryConfig(
default_project="main",
projects={
"main": {"path": str(temp_path / "main")},
"test-project": {"path": str(temp_path / "test")},
"special-chars": {
"path": str(temp_path / "special")
}, # This will be the config key for "Special/Chars"
},
)
config_manager.save_config(test_config)
yield config_manager
def test_set_default_project_with_exact_name_match(self, temp_config_manager):
"""Test set_default_project when project name matches config key exactly."""
config_manager = temp_config_manager
# Set default to a project that exists with exact name match
config_manager.set_default_project("test-project")
# Verify the config was updated
config = config_manager.load_config()
assert config.default_project == "test-project"
def test_set_default_project_with_permalink_lookup(self, temp_config_manager):
"""Test set_default_project when input needs permalink normalization."""
config_manager = temp_config_manager
# Simulate a project that was created with special characters
# The config key would be the permalink, but user might type the original name
# First add a project with original name that gets normalized
config = config_manager.load_config()
config.projects["special-chars-project"] = ProjectEntry(path=str(Path("/tmp/special")))
config_manager.save_config(config)
# Now test setting default using a name that will normalize to the config key
config_manager.set_default_project(
"Special Chars Project"
) # This should normalize to "special-chars-project"
# Verify the config was updated with the correct config key
updated_config = config_manager.load_config()
assert updated_config.default_project == "special-chars-project"
def test_set_default_project_uses_canonical_name(self, temp_config_manager):
"""Test that set_default_project uses the canonical config key, not user input."""
config_manager = temp_config_manager
# Add a project with a config key that differs from user input
config = config_manager.load_config()
config.projects["my-test-project"] = ProjectEntry(path=str(Path("/tmp/mytest")))
config_manager.save_config(config)
# Set default using input that will match but is different from config key
config_manager.set_default_project("My Test Project") # Should find "my-test-project"
# Verify that the canonical config key is used, not the user input
updated_config = config_manager.load_config()
assert updated_config.default_project == "my-test-project"
# Should NOT be the user input
assert updated_config.default_project != "My Test Project"
def test_set_default_project_nonexistent_project(self, temp_config_manager):
"""Test set_default_project raises ValueError for nonexistent project."""
config_manager = temp_config_manager
with pytest.raises(ValueError, match="Project 'nonexistent' not found"):
config_manager.set_default_project("nonexistent")
def test_disable_permalinks_flag_default(self):
"""Test that disable_permalinks flag defaults to False."""
config = BasicMemoryConfig()
assert config.disable_permalinks is False
def test_disable_permalinks_flag_can_be_enabled(self):
"""Test that disable_permalinks flag can be set to True."""
config = BasicMemoryConfig(disable_permalinks=True)
assert config.disable_permalinks is True
def test_ensure_frontmatter_on_sync_flag_default(self):
"""Test that ensure_frontmatter_on_sync defaults to True."""
config = BasicMemoryConfig()
assert config.ensure_frontmatter_on_sync is True
def test_ensure_frontmatter_on_sync_flag_can_be_disabled(self):
"""Test that ensure_frontmatter_on_sync can be set to False."""
config = BasicMemoryConfig(ensure_frontmatter_on_sync=False)
assert config.ensure_frontmatter_on_sync is False
def test_permalinks_include_project_flag_default(self):
"""Test that permalinks_include_project defaults to True."""
config = BasicMemoryConfig()
assert config.permalinks_include_project is True
def test_permalinks_include_project_flag_can_be_disabled(self):
"""Test that permalinks_include_project can be set to False."""
config = BasicMemoryConfig(permalinks_include_project=False)
assert config.permalinks_include_project is False
def test_config_manager_respects_custom_config_dir(self, monkeypatch):
"""Test that ConfigManager respects BASIC_MEMORY_CONFIG_DIR environment variable."""
with tempfile.TemporaryDirectory() as temp_dir:
custom_config_dir = Path(temp_dir) / "custom" / "config"
monkeypatch.setenv("BASIC_MEMORY_CONFIG_DIR", str(custom_config_dir))
config_manager = ConfigManager()
# Verify config_dir is set to the custom path
assert config_manager.config_dir == custom_config_dir
# Verify config_file is in the custom directory
assert config_manager.config_file == custom_config_dir / "config.json"
# Verify the directory was created
assert config_manager.config_dir.exists()
def test_config_manager_default_without_custom_config_dir(self, config_home, monkeypatch):
"""Test that ConfigManager uses default location when BASIC_MEMORY_CONFIG_DIR is not set."""
monkeypatch.delenv("BASIC_MEMORY_CONFIG_DIR", raising=False)
config_manager = ConfigManager()
# Should use default location
assert config_manager.config_dir == config_home / ".basic-memory"
assert config_manager.config_file == config_home / ".basic-memory" / "config.json"
def test_remove_project_with_exact_name_match(self, temp_config_manager):
"""Test remove_project when project name matches config key exactly."""
config_manager = temp_config_manager
# Verify project exists
config = config_manager.load_config()
assert "test-project" in config.projects
# Remove the project with exact name match
config_manager.remove_project("test-project")
# Verify the project was removed
config = config_manager.load_config()
assert "test-project" not in config.projects
def test_remove_project_with_permalink_lookup(self, temp_config_manager):
"""Test remove_project when input needs permalink normalization."""
config_manager = temp_config_manager
# Add a project with normalized key
config = config_manager.load_config()
config.projects["special-chars-project"] = ProjectEntry(path=str(Path("/tmp/special")))
config_manager.save_config(config)
# Remove using a name that will normalize to the config key
config_manager.remove_project(
"Special Chars Project"
) # This should normalize to "special-chars-project"
# Verify the project was removed using the correct config key
updated_config = config_manager.load_config()
assert "special-chars-project" not in updated_config.projects
def test_remove_project_uses_canonical_name(self, temp_config_manager):
"""Test that remove_project uses the canonical config key, not user input."""
config_manager = temp_config_manager
# Add a project with a config key that differs from user input
config = config_manager.load_config()
config.projects["my-test-project"] = ProjectEntry(path=str(Path("/tmp/mytest")))
config_manager.save_config(config)
# Remove using input that will match but is different from config key
config_manager.remove_project("My Test Project") # Should find "my-test-project"
# Verify that the canonical config key was removed
updated_config = config_manager.load_config()
assert "my-test-project" not in updated_config.projects
def test_remove_project_nonexistent_project(self, temp_config_manager):
"""Test remove_project raises ValueError for nonexistent project."""
config_manager = temp_config_manager
with pytest.raises(ValueError, match="Project 'nonexistent' not found"):
config_manager.remove_project("nonexistent")
def test_remove_project_cannot_remove_default(self, temp_config_manager):
"""Test remove_project raises ValueError when trying to remove default project."""
config_manager = temp_config_manager
# Try to remove the default project
with pytest.raises(ValueError, match="Cannot remove the default project"):
config_manager.remove_project("main")
def test_config_project_entry_cloud_sync_defaults(self, temp_config_manager):
"""Test that ProjectEntry cloud sync fields default to None/False."""
config_manager = temp_config_manager
config = config_manager.load_config()
entry = config.projects["main"]
assert entry.local_sync_path is None
assert entry.bisync_initialized is False
assert entry.last_sync is None
def test_save_and_load_config_with_cloud_sync_fields(self):
"""Test that config with cloud sync fields can be saved and loaded."""
with tempfile.TemporaryDirectory() as temp_dir:
temp_path = Path(temp_dir)
config_manager = ConfigManager()
config_manager.config_dir = temp_path / "basic-memory"
config_manager.config_file = config_manager.config_dir / "config.json"
config_manager.config_dir.mkdir(parents=True, exist_ok=True)
# Create config with cloud sync fields on a project entry
now = datetime.now()
test_config = BasicMemoryConfig(
projects={
"main": {"path": str(temp_path / "main")},
"research": {
"path": str(temp_path / "research"),
"mode": "cloud",
"local_sync_path": str(temp_path / "research-local"),
"last_sync": now.isoformat(),
"bisync_initialized": True,
},
},
)
config_manager.save_config(test_config)
# Load and verify
loaded_config = config_manager.load_config()
assert "research" in loaded_config.projects
entry = loaded_config.projects["research"]
assert entry.local_sync_path == str(temp_path / "research-local")
assert entry.bisync_initialized is True
assert entry.last_sync == now
def test_add_cloud_sync_to_existing_project(self):
"""Test adding cloud sync fields to an existing project entry."""
with tempfile.TemporaryDirectory() as temp_dir:
temp_path = Path(temp_dir)
config_manager = ConfigManager()
config_manager.config_dir = temp_path / "basic-memory"
config_manager.config_file = config_manager.config_dir / "config.json"
config_manager.config_dir.mkdir(parents=True, exist_ok=True)
# Create initial config without cloud sync fields
initial_config = BasicMemoryConfig(projects={"main": {"path": str(temp_path / "main")}})
config_manager.save_config(initial_config)
# Load, modify, and save
config = config_manager.load_config()
assert config.projects["main"].local_sync_path is None
config.projects["main"].local_sync_path = str(temp_path / "work-local")
config_manager.save_config(config)
# Reload and verify persistence
reloaded_config = config_manager.load_config()
assert reloaded_config.projects["main"].local_sync_path == str(temp_path / "work-local")
assert reloaded_config.projects["main"].bisync_initialized is False
def test_backward_compatibility_loading_old_format_config(self):
"""Test that old config files with Dict[str, str] projects can be loaded and migrated."""
with tempfile.TemporaryDirectory() as temp_dir:
temp_path = Path(temp_dir)
config_manager = ConfigManager()
config_manager.config_dir = temp_path / "basic-memory"
config_manager.config_file = config_manager.config_dir / "config.json"
config_manager.config_dir.mkdir(parents=True, exist_ok=True)
# Manually write old-style config with Dict[str, str] projects
import json
old_config_data = {
"env": "dev",
"projects": {"main": str(temp_path / "main")},
"default_project": "main",
"log_level": "INFO",
}
config_manager.config_file.write_text(json.dumps(old_config_data, indent=2))
# Clear the config cache to ensure we load from the temp file
import basic_memory.config
basic_memory.config._CONFIG_CACHE = None
basic_memory.config._CONFIG_MTIME = None
basic_memory.config._CONFIG_SIZE = None
# Should load successfully with migration to ProjectEntry
config = config_manager.load_config()
assert isinstance(config.projects["main"], ProjectEntry)
assert config.projects["main"].path == str(temp_path / "main")
assert config.projects["main"].mode == ProjectMode.LOCAL
def test_backward_compatibility_migrates_project_modes_and_cloud_projects(self):
"""Test that old config with project_modes and cloud_projects is migrated."""
with tempfile.TemporaryDirectory() as temp_dir:
temp_path = Path(temp_dir)
config_manager = ConfigManager()
config_manager.config_dir = temp_path / "basic-memory"
config_manager.config_file = config_manager.config_dir / "config.json"
config_manager.config_dir.mkdir(parents=True, exist_ok=True)
import json
old_config_data = {
"env": "dev",
"projects": {
"main": str(temp_path / "main"),
"research": str(temp_path / "research"),
},
"default_project": "main",
"project_modes": {"research": "cloud"},
"cloud_projects": {
"research": {
"local_path": str(temp_path / "research-local"),
"bisync_initialized": True,
"last_sync": "2026-02-06T17:36:38",
}
},
}
config_manager.config_file.write_text(json.dumps(old_config_data, indent=2))
import basic_memory.config
basic_memory.config._CONFIG_CACHE = None
basic_memory.config._CONFIG_MTIME = None
basic_memory.config._CONFIG_SIZE = None
config = config_manager.load_config()
# Verify migration
assert config.projects["research"].mode == ProjectMode.CLOUD
assert config.projects["research"].local_sync_path == str(temp_path / "research-local")
assert config.projects["research"].bisync_initialized is True
assert config.projects["main"].mode == ProjectMode.LOCAL
def test_legacy_cloud_mode_key_is_stripped_on_normalization_save(self):
"""Legacy cloud_mode should be removed from config.json after load/save normalization."""
with tempfile.TemporaryDirectory() as temp_dir:
temp_path = Path(temp_dir)
config_manager = ConfigManager()
config_manager.config_dir = temp_path / "basic-memory"
config_manager.config_file = config_manager.config_dir / "config.json"
config_manager.config_dir.mkdir(parents=True, exist_ok=True)
import json
legacy_config = {
"env": "dev",
"projects": {"main": str(temp_path / "main")},
"default_project": "main",
"cloud_mode": True,
}
config_manager.config_file.write_text(json.dumps(legacy_config, indent=2))
import basic_memory.config
basic_memory.config._CONFIG_CACHE = None
basic_memory.config._CONFIG_MTIME = None
basic_memory.config._CONFIG_SIZE = None
loaded = config_manager.load_config()
assert isinstance(loaded, BasicMemoryConfig)
raw = json.loads(config_manager.config_file.read_text(encoding="utf-8"))
assert "cloud_mode" not in raw
def test_migration_creates_backup_of_old_config(self):
"""Config migration should create a .bak backup before overwriting."""
with tempfile.TemporaryDirectory() as temp_dir:
temp_path = Path(temp_dir)
config_manager = ConfigManager()
config_manager.config_dir = temp_path / "basic-memory"
config_manager.config_file = config_manager.config_dir / "config.json"
config_manager.config_dir.mkdir(parents=True, exist_ok=True)
import json
old_config_data = {
"env": "dev",
"projects": {"main": str(temp_path / "main")},
"default_project": "main",
}
config_manager.config_file.write_text(json.dumps(old_config_data, indent=2))
original_content = config_manager.config_file.read_text()
import basic_memory.config
basic_memory.config._CONFIG_CACHE = None
basic_memory.config._CONFIG_MTIME = None
basic_memory.config._CONFIG_SIZE = None
config_manager.load_config()
# Backup should exist with the original content
backup_path = config_manager.config_file.with_suffix(".json.bak")
assert backup_path.exists(), "Migration should create a backup file"
assert backup_path.read_text() == original_content
def test_no_backup_when_config_is_current_format(self):
"""No backup should be created when config is already in the current format."""
with tempfile.TemporaryDirectory() as temp_dir:
temp_path = Path(temp_dir)
config_manager = ConfigManager()
config_manager.config_dir = temp_path / "basic-memory"
config_manager.config_file = config_manager.config_dir / "config.json"
config_manager.config_dir.mkdir(parents=True, exist_ok=True)
import json
# Write config in the current ProjectEntry format — no migration needed
current_config_data = {
"env": "dev",
"projects": {"main": {"path": str(temp_path / "main"), "mode": "local"}},
"default_project": "main",
}
config_manager.config_file.write_text(json.dumps(current_config_data, indent=2))
import basic_memory.config
basic_memory.config._CONFIG_CACHE = None
basic_memory.config._CONFIG_MTIME = None
basic_memory.config._CONFIG_SIZE = None
config_manager.load_config()
backup_path = config_manager.config_file.with_suffix(".json.bak")
assert not backup_path.exists(), "No backup should be created for current-format config"
class TestPlatformNativePathSeparators:
"""Test that config uses platform-native path separators."""
def test_project_paths_use_platform_native_separators_in_config(self, monkeypatch):
"""Test that project paths use platform-native separators when created."""
import platform
with tempfile.TemporaryDirectory() as temp_dir:
temp_path = Path(temp_dir)
# Set up ConfigManager with temp directory
config_manager = ConfigManager()
config_manager.config_dir = temp_path / "basic-memory"
config_manager.config_file = config_manager.config_dir / "config.json"
config_manager.config_dir.mkdir(parents=True, exist_ok=True)
# Create a project path
project_path = temp_path / "my" / "project"
project_path.mkdir(parents=True, exist_ok=True)
# Add project via ConfigManager
config = BasicMemoryConfig(projects={})
config.projects["test-project"] = ProjectEntry(path=str(project_path))
config_manager.save_config(config)
# Read the raw JSON file
import json
config_data = json.loads(config_manager.config_file.read_text())
# Verify path uses platform-native separators
saved_path = config_data["projects"]["test-project"]["path"]
# On Windows, should have backslashes; on Unix, forward slashes
if platform.system() == "Windows":
# Windows paths should contain backslashes
assert "\\" in saved_path or ":" in saved_path # C:\\ or \\UNC
assert "/" not in saved_path.replace(":/", "") # Exclude drive letter
else:
# Unix paths should use forward slashes
assert "/" in saved_path
# Should not force POSIX on non-Windows
assert saved_path == str(project_path)
def test_add_project_uses_platform_native_separators(self, monkeypatch):
"""Test that ConfigManager.add_project() uses platform-native separators."""
import platform
with tempfile.TemporaryDirectory() as temp_dir:
temp_path = Path(temp_dir)
# Set up ConfigManager
config_manager = ConfigManager()
config_manager.config_dir = temp_path / "basic-memory"
config_manager.config_file = config_manager.config_dir / "config.json"
config_manager.config_dir.mkdir(parents=True, exist_ok=True)
# Initialize with empty projects
initial_config = BasicMemoryConfig(projects={})
config_manager.save_config(initial_config)
# Add project
project_path = temp_path / "new" / "project"
config_manager.add_project("new-project", str(project_path))
# Load and verify
config = config_manager.load_config()
saved_path = config.projects["new-project"].path
# Verify platform-native separators
if platform.system() == "Windows":
assert "\\" in saved_path or ":" in saved_path
else:
assert "/" in saved_path
assert saved_path == str(project_path)
def test_add_project_never_creates_directory(self):
"""Test that ConfigManager.add_project() is pure config management — no mkdir.
Directory creation is delegated to ProjectService via FileService, which
supports both local and cloud (S3) backends.
"""
with tempfile.TemporaryDirectory() as temp_dir:
temp_path = Path(temp_dir)
config_manager = ConfigManager()
config_manager.config_dir = temp_path / "basic-memory"
config_manager.config_file = config_manager.config_dir / "config.json"
config_manager.config_dir.mkdir(parents=True, exist_ok=True)
initial_config = BasicMemoryConfig(projects={})
config_manager.save_config(initial_config)
# Use a path that does not exist — ConfigManager should not create it
nonexistent_path = str(temp_path / "nonexistent" / "project")
config_manager.add_project("test-project", nonexistent_path)
# Check directory does NOT exist right after add_project(),
# before load_config() which triggers the model validator
assert not Path(nonexistent_path).exists()
# Verify project was persisted in config
config = config_manager.load_config()
assert "test-project" in config.projects
assert config.projects["test-project"].path == nonexistent_path
def test_model_post_init_uses_platform_native_separators(self, config_home, monkeypatch):
"""Test that model_post_init uses platform-native separators."""
import platform
monkeypatch.delenv("BASIC_MEMORY_HOME", raising=False)
# Create config without projects (triggers model_post_init to add main)
config = BasicMemoryConfig(projects={})
# Verify main project path uses platform-native separators
main_path = config.projects["main"].path
if platform.system() == "Windows":
# Windows: should have backslashes or drive letter
assert "\\" in main_path or ":" in main_path
else:
# Unix: should have forward slashes
assert "/" in main_path
class TestSemanticSearchConfig:
"""Test semantic search configuration options."""
def test_semantic_search_enabled_defaults_to_true_when_semantic_modules_are_available(
self, monkeypatch
):
"""Semantic search defaults on when fastembed and sqlite_vec are importable."""
import basic_memory.config as config_module
monkeypatch.delenv("BASIC_MEMORY_SEMANTIC_SEARCH_ENABLED", raising=False)
monkeypatch.setattr(
config_module.importlib.util,
"find_spec",
lambda name: object() if name in {"fastembed", "sqlite_vec"} else None,
)
config = BasicMemoryConfig()
assert config.semantic_search_enabled is True
def test_semantic_search_enabled_defaults_to_false_when_any_semantic_module_is_unavailable(
self, monkeypatch
):
"""Semantic search defaults off when required semantic modules are missing."""
import basic_memory.config as config_module
monkeypatch.delenv("BASIC_MEMORY_SEMANTIC_SEARCH_ENABLED", raising=False)
monkeypatch.setattr(
config_module.importlib.util,
"find_spec",
lambda name: object() if name == "fastembed" else None,
)
config = BasicMemoryConfig()
assert config.semantic_search_enabled is False
def test_semantic_search_enabled_env_var_overrides_dependency_default(self, monkeypatch):
"""Environment overrides should win over dependency-based defaults."""
import basic_memory.config as config_module
monkeypatch.setattr(config_module.importlib.util, "find_spec", lambda name: None)
monkeypatch.setenv("BASIC_MEMORY_SEMANTIC_SEARCH_ENABLED", "true")
enabled = BasicMemoryConfig()
assert enabled.semantic_search_enabled is True
monkeypatch.setenv("BASIC_MEMORY_SEMANTIC_SEARCH_ENABLED", "false")
disabled = BasicMemoryConfig()
assert disabled.semantic_search_enabled is False
def test_semantic_embedding_dimensions_defaults_to_none(self):
"""Dimensions should default to None, letting the provider choose."""
config = BasicMemoryConfig()
assert config.semantic_embedding_dimensions is None
def test_semantic_embedding_dimensions_can_be_set(self):
"""Explicit dimensions should be stored on the config object."""
config = BasicMemoryConfig(semantic_embedding_dimensions=1536)
assert config.semantic_embedding_dimensions == 1536
def test_semantic_postgres_prepare_concurrency_defaults_to_4(self):
"""Postgres prepare concurrency should default to a conservative window of 4."""
config = BasicMemoryConfig()
assert config.semantic_postgres_prepare_concurrency == 4
def test_semantic_postgres_prepare_concurrency_validation(self):
"""Postgres prepare concurrency must stay within the bounded safe range."""
config = BasicMemoryConfig(semantic_postgres_prepare_concurrency=8)
assert config.semantic_postgres_prepare_concurrency == 8
with pytest.raises(Exception):
BasicMemoryConfig(semantic_postgres_prepare_concurrency=0)
with pytest.raises(Exception):
BasicMemoryConfig(semantic_postgres_prepare_concurrency=17)
def test_semantic_search_enabled_description_mentions_both_backends(self):