-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtest_api.py
More file actions
1678 lines (1313 loc) · 68.2 KB
/
test_api.py
File metadata and controls
1678 lines (1313 loc) · 68.2 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
"""Unit tests for CodeRAGAPI initialization and factory methods.
These tests verify:
1. CodeRAGAPI __init__ - different configuration options
2. _create_embedding_model - factory for embedding backends
3. _generate_collection_name (module-level) - collection name generation logic
All tests mock external dependencies to avoid loading real models.
"""
import tempfile
from pathlib import Path
from unittest.mock import MagicMock, PropertyMock, patch
import pytest
from code_rag.api import CodeRAGAPI, generate_collection_name
# ============================================================================
# generate_collection_name Tests
# ============================================================================
class TestGenerateCollectionName:
"""Tests for the generate_collection_name function."""
def test_generates_consistent_name_for_same_path(self):
"""Test that same path always generates the same collection name."""
path = "/home/user/myproject"
name1 = generate_collection_name(path)
name2 = generate_collection_name(path)
assert name1 == name2
def test_different_paths_generate_different_names(self):
"""Test that different paths generate different collection names."""
name1 = generate_collection_name("/home/user/project1")
name2 = generate_collection_name("/home/user/project2")
assert name1 != name2
def test_name_starts_with_codebase_prefix(self):
"""Test that generated names have the expected prefix."""
name = generate_collection_name("/some/path")
assert name.startswith("codebase_")
def test_name_has_consistent_length(self):
"""Test that generated names have consistent length (prefix + 16 char hash)."""
name = generate_collection_name("/any/path")
# "codebase_" is 9 chars + 16 char hash = 25 chars
assert len(name) == 25
def test_resolves_relative_paths(self):
"""Test that relative paths are resolved to absolute paths."""
with tempfile.TemporaryDirectory() as temp_dir:
# Create a subdirectory
subdir = Path(temp_dir) / "subdir"
subdir.mkdir()
# Get absolute path name
abs_name = generate_collection_name(str(subdir))
# Test with different relative path representations
# would resolve to same absolute path
assert abs_name.startswith("codebase_")
def test_handles_trailing_slashes(self):
"""Test that trailing slashes don't affect the result after resolve."""
# Note: Path.resolve() normalizes trailing slashes
path1 = "/home/user/project"
path2 = "/home/user/project/"
name1 = generate_collection_name(path1)
name2 = generate_collection_name(path2)
# Both should resolve to same path
assert name1 == name2
# ============================================================================
# CodeRAGAPI.__init__ Tests
# ============================================================================
class TestCodeRAGAPIInit:
"""Tests for CodeRAGAPI initialization."""
@pytest.fixture
def mock_dependencies(self):
"""Mock all external dependencies for CodeRAGAPI init."""
with (
patch("code_rag.api.SentenceTransformerEmbedding") as mock_st,
patch("code_rag.api.ChromaDatabase") as mock_chroma,
patch("code_rag.api.QdrantDatabase") as mock_qdrant,
patch("code_rag.api.CrossEncoderReranker") as mock_reranker,
patch("code_rag.api.Config") as mock_config,
):
# Setup mock config
mock_config_instance = MagicMock()
mock_config_instance.get_database_path.return_value = "/tmp/test-db"
mock_config_instance.is_shared_server_enabled.return_value = False
mock_config_instance.get_shared_server_port.return_value = 8199
mock_config_instance.get_reranker_model.return_value = (
"jinaai/jina-reranker-v3"
)
mock_config_instance.get_model_idle_timeout.return_value = 1800
mock_config.return_value = mock_config_instance
# Setup mock embedding model
mock_embedding = MagicMock()
mock_embedding.get_embedding_dimension.return_value = 384
mock_st.return_value = mock_embedding
# Setup mock databases
mock_chroma_instance = MagicMock()
mock_chroma.return_value = mock_chroma_instance
mock_qdrant_instance = MagicMock()
mock_qdrant.return_value = mock_qdrant_instance
# Setup mock reranker
mock_reranker_instance = MagicMock()
mock_reranker.return_value = mock_reranker_instance
yield {
"SentenceTransformerEmbedding": mock_st,
"ChromaDatabase": mock_chroma,
"QdrantDatabase": mock_qdrant,
"CrossEncoderReranker": mock_reranker,
"Config": mock_config,
"config_instance": mock_config_instance,
"embedding_instance": mock_embedding,
"chroma_instance": mock_chroma_instance,
"qdrant_instance": mock_qdrant_instance,
"reranker_instance": mock_reranker_instance,
}
def test_default_initialization(self, mock_dependencies):
"""Test CodeRAGAPI initializes with default parameters."""
api = CodeRAGAPI()
assert api.database_type == "chroma"
assert api.embedding_model_name == "sentence-transformers/all-MiniLM-L6-v2"
assert api.reranker_enabled is True
assert api.reranker_multiplier == 2
assert api.lazy_load_models is False
def test_custom_database_type_chroma(self, mock_dependencies):
"""Test initialization with chroma database."""
api = CodeRAGAPI(database_type="chroma")
mock_dependencies["ChromaDatabase"].assert_called_once()
mock_dependencies["QdrantDatabase"].assert_not_called()
assert api.database_type == "chroma"
def test_custom_database_type_qdrant(self, mock_dependencies):
"""Test initialization with qdrant database."""
api = CodeRAGAPI(database_type="qdrant")
mock_dependencies["QdrantDatabase"].assert_called_once()
assert api.database_type == "qdrant"
def test_custom_database_path(self, mock_dependencies):
"""Test initialization with custom database path."""
custom_path = "/custom/db/path"
api = CodeRAGAPI(database_path=custom_path)
assert api.database_path == custom_path
mock_dependencies["ChromaDatabase"].assert_called_with(
persist_directory=custom_path
)
def test_default_database_path_from_config(self, mock_dependencies):
"""Test database path falls back to config default."""
api = CodeRAGAPI()
assert api.database_path == "/tmp/test-db"
mock_dependencies["config_instance"].get_database_path.assert_called()
def test_custom_embedding_model(self, mock_dependencies):
"""Test initialization with custom embedding model."""
custom_model = "custom/embedding-model"
api = CodeRAGAPI(embedding_model=custom_model)
assert api.embedding_model_name == custom_model
mock_dependencies["SentenceTransformerEmbedding"].assert_called_with(
custom_model, lazy_load=False, idle_timeout=1800
)
def test_reranker_disabled(self, mock_dependencies):
"""Test initialization with reranker disabled."""
api = CodeRAGAPI(reranker_enabled=False)
assert api.reranker_enabled is False
assert api.reranker is None
mock_dependencies["CrossEncoderReranker"].assert_not_called()
def test_reranker_enabled_default(self, mock_dependencies):
"""Test reranker is enabled by default."""
api = CodeRAGAPI()
assert api.reranker_enabled is True
mock_dependencies["CrossEncoderReranker"].assert_called_once()
def test_custom_reranker_model(self, mock_dependencies):
"""Test initialization with custom reranker model."""
custom_model = "custom/reranker-model"
api = CodeRAGAPI(reranker_model=custom_model)
mock_dependencies["CrossEncoderReranker"].assert_called_with(
custom_model, lazy_load=False, idle_timeout=1800
)
def test_reranker_multiplier(self, mock_dependencies):
"""Test initialization with custom reranker multiplier."""
api = CodeRAGAPI(reranker_multiplier=5)
assert api.reranker_multiplier == 5
def test_lazy_load_models_enabled(self, mock_dependencies):
"""Test initialization with lazy loading enabled."""
api = CodeRAGAPI(lazy_load_models=True)
assert api.lazy_load_models is True
mock_dependencies["SentenceTransformerEmbedding"].assert_called_with(
"sentence-transformers/all-MiniLM-L6-v2", lazy_load=True, idle_timeout=1800
)
def test_session_state_initialized(self, mock_dependencies):
"""Test that session state is properly initialized."""
api = CodeRAGAPI()
assert api._indexed_paths == set()
assert api._active_collection is None
assert api._metadata_indices == {}
class TestCodeRAGAPIInitSharedServer:
"""Tests for CodeRAGAPI initialization with shared server mode."""
def test_uses_http_embedding_when_shared_server_enabled(self):
"""Test that HTTP embedding is used when shared server is enabled."""
with (
patch("code_rag.api.SentenceTransformerEmbedding") as mock_st,
patch("code_rag.api.ChromaDatabase") as mock_chroma,
patch("code_rag.api.CrossEncoderReranker") as mock_reranker,
patch("code_rag.api.Config") as mock_config,
patch(
"code_rag.embeddings.http_embedding.HttpEmbedding"
) as mock_http_embed,
):
# Setup mock config for shared server mode
mock_config_instance = MagicMock()
mock_config_instance.get_database_path.return_value = "/tmp/test-db"
mock_config_instance.is_shared_server_enabled.return_value = True
mock_config_instance.get_shared_server_port.return_value = 9999
mock_config_instance.get_reranker_model.return_value = (
"jinaai/jina-reranker-v3"
)
mock_config_instance.get_model_idle_timeout.return_value = 1800
mock_config.return_value = mock_config_instance
# Setup mock HTTP embedding
mock_http_embed_instance = MagicMock()
mock_http_embed_instance.get_embedding_dimension.return_value = 384
mock_http_embed_instance.client_id = "test-client-id"
mock_http_embed.return_value = mock_http_embed_instance
# Setup mock database
mock_chroma_instance = MagicMock()
mock_chroma.return_value = mock_chroma_instance
api = CodeRAGAPI(reranker_enabled=False)
assert api._use_shared_server is True
# SentenceTransformerEmbedding should NOT be called in shared server mode
mock_st.assert_not_called()
# HttpEmbedding should be called with the port
mock_http_embed.assert_called_with(port=9999)
def test_shared_server_port_from_config(self):
"""Test that shared server port is read from config."""
with (
patch("code_rag.api.SentenceTransformerEmbedding") as mock_st,
patch("code_rag.api.ChromaDatabase") as mock_chroma,
patch("code_rag.api.CrossEncoderReranker") as mock_reranker,
patch("code_rag.api.Config") as mock_config,
patch(
"code_rag.embeddings.http_embedding.HttpEmbedding"
) as mock_http_embed,
):
# Setup mock config for shared server mode
mock_config_instance = MagicMock()
mock_config_instance.get_database_path.return_value = "/tmp/test-db"
mock_config_instance.is_shared_server_enabled.return_value = True
mock_config_instance.get_shared_server_port.return_value = 7777
mock_config_instance.get_reranker_model.return_value = (
"jinaai/jina-reranker-v3"
)
mock_config_instance.get_model_idle_timeout.return_value = 1800
mock_config.return_value = mock_config_instance
# Setup mock HTTP embedding
mock_http_embed_instance = MagicMock()
mock_http_embed_instance.get_embedding_dimension.return_value = 384
mock_http_embed.return_value = mock_http_embed_instance
# Setup mock database
mock_chroma_instance = MagicMock()
mock_chroma.return_value = mock_chroma_instance
api = CodeRAGAPI(reranker_enabled=False)
assert api._shared_server_port == 7777
# ============================================================================
# CodeRAGAPI._create_embedding_model Tests
# ============================================================================
class TestCreateEmbeddingModel:
"""Tests for CodeRAGAPI._create_embedding_model factory method."""
@pytest.fixture
def api_with_mocks(self):
"""Create a CodeRAGAPI instance with mocked components for testing _create_embedding_model."""
with (
patch("code_rag.api.SentenceTransformerEmbedding") as mock_st,
patch("code_rag.api.LiteLLMEmbedding") as mock_litellm,
patch("code_rag.api.ChromaDatabase") as mock_chroma,
patch("code_rag.api.CrossEncoderReranker") as mock_reranker,
patch("code_rag.api.Config") as mock_config,
):
# Setup mock config
mock_config_instance = MagicMock()
mock_config_instance.get_database_path.return_value = "/tmp/test-db"
mock_config_instance.is_shared_server_enabled.return_value = False
mock_config_instance.get_shared_server_port.return_value = 8199
mock_config_instance.get_reranker_model.return_value = (
"jinaai/jina-reranker-v3"
)
mock_config_instance.get_model_idle_timeout.return_value = 1800
mock_config.return_value = mock_config_instance
# Setup mock embedding model
mock_embedding = MagicMock()
mock_embedding.get_embedding_dimension.return_value = 384
mock_st.return_value = mock_embedding
mock_litellm.return_value = mock_embedding
# Setup mock database
mock_chroma_instance = MagicMock()
mock_chroma.return_value = mock_chroma_instance
# Setup mock reranker
mock_reranker_instance = MagicMock()
mock_reranker.return_value = mock_reranker_instance
api = CodeRAGAPI(reranker_enabled=False)
yield {
"api": api,
"SentenceTransformerEmbedding": mock_st,
"LiteLLMEmbedding": mock_litellm,
"config_instance": mock_config_instance,
}
def test_creates_sentence_transformer_for_local_model(self, api_with_mocks):
"""Test that SentenceTransformerEmbedding is created for local models."""
api = api_with_mocks["api"]
mock_st = api_with_mocks["SentenceTransformerEmbedding"]
# Reset mock to clear initialization call
mock_st.reset_mock()
api._create_embedding_model("sentence-transformers/all-MiniLM-L6-v2")
mock_st.assert_called_once_with(
"sentence-transformers/all-MiniLM-L6-v2", lazy_load=False, idle_timeout=1800
)
def test_creates_litellm_for_openai_text_embedding(self, api_with_mocks):
"""Test that LiteLLMEmbedding is created for OpenAI text-embedding models."""
api = api_with_mocks["api"]
mock_litellm = api_with_mocks["LiteLLMEmbedding"]
mock_litellm.reset_mock()
api._create_embedding_model("text-embedding-3-small")
mock_litellm.assert_called_once_with(
"text-embedding-3-small", idle_timeout=1800
)
def test_creates_litellm_for_openai_prefix(self, api_with_mocks):
"""Test that LiteLLMEmbedding is created for openai/ prefixed models."""
api = api_with_mocks["api"]
mock_litellm = api_with_mocks["LiteLLMEmbedding"]
mock_litellm.reset_mock()
api._create_embedding_model("openai/text-embedding-ada-002")
mock_litellm.assert_called_once_with(
"openai/text-embedding-ada-002", idle_timeout=1800
)
def test_creates_litellm_for_azure_prefix(self, api_with_mocks):
"""Test that LiteLLMEmbedding is created for azure/ prefixed models."""
api = api_with_mocks["api"]
mock_litellm = api_with_mocks["LiteLLMEmbedding"]
mock_litellm.reset_mock()
api._create_embedding_model("azure/text-embedding-3-small")
mock_litellm.assert_called_once_with(
"azure/text-embedding-3-small", idle_timeout=1800
)
def test_creates_litellm_for_vertex_ai_prefix(self, api_with_mocks):
"""Test that LiteLLMEmbedding is created for vertex_ai/ prefixed models."""
api = api_with_mocks["api"]
mock_litellm = api_with_mocks["LiteLLMEmbedding"]
mock_litellm.reset_mock()
api._create_embedding_model("vertex_ai/text-embedding-004")
mock_litellm.assert_called_once_with(
"vertex_ai/text-embedding-004", idle_timeout=1800
)
def test_creates_litellm_for_cohere_prefix(self, api_with_mocks):
"""Test that LiteLLMEmbedding is created for cohere/ prefixed models."""
api = api_with_mocks["api"]
mock_litellm = api_with_mocks["LiteLLMEmbedding"]
mock_litellm.reset_mock()
api._create_embedding_model("cohere/embed-english-v3.0")
mock_litellm.assert_called_once_with(
"cohere/embed-english-v3.0", idle_timeout=1800
)
def test_creates_litellm_for_bedrock_prefix(self, api_with_mocks):
"""Test that LiteLLMEmbedding is created for bedrock/ prefixed models."""
api = api_with_mocks["api"]
mock_litellm = api_with_mocks["LiteLLMEmbedding"]
mock_litellm.reset_mock()
api._create_embedding_model("bedrock/amazon.titan-embed-text-v1")
mock_litellm.assert_called_once_with(
"bedrock/amazon.titan-embed-text-v1", idle_timeout=1800
)
def test_creates_sentence_transformer_for_unknown_prefix(self, api_with_mocks):
"""Test that SentenceTransformerEmbedding is created for unknown prefixes."""
api = api_with_mocks["api"]
mock_st = api_with_mocks["SentenceTransformerEmbedding"]
mock_st.reset_mock()
api._create_embedding_model("nomic-ai/CodeRankEmbed")
mock_st.assert_called_once_with(
"nomic-ai/CodeRankEmbed", lazy_load=False, idle_timeout=1800
)
def test_lazy_load_passed_to_sentence_transformer(self, api_with_mocks):
"""Test that lazy_load parameter is correctly passed."""
api = api_with_mocks["api"]
mock_st = api_with_mocks["SentenceTransformerEmbedding"]
mock_st.reset_mock()
api._create_embedding_model("some-local-model", lazy_load=True)
mock_st.assert_called_once_with(
"some-local-model", lazy_load=True, idle_timeout=1800
)
class TestCreateEmbeddingModelSharedServer:
"""Tests for _create_embedding_model with shared server mode."""
def test_creates_http_embedding_when_shared_server_enabled(self):
"""Test that HttpEmbedding is created when shared server is enabled."""
with (
patch("code_rag.api.SentenceTransformerEmbedding") as mock_st,
patch("code_rag.api.ChromaDatabase") as mock_chroma,
patch("code_rag.api.CrossEncoderReranker") as mock_reranker,
patch("code_rag.api.Config") as mock_config,
patch(
"code_rag.embeddings.http_embedding.HttpEmbedding"
) as mock_http_embed,
):
# Setup mock config for shared server mode
mock_config_instance = MagicMock()
mock_config_instance.get_database_path.return_value = "/tmp/test-db"
mock_config_instance.is_shared_server_enabled.return_value = True
mock_config_instance.get_shared_server_port.return_value = 9999
mock_config_instance.get_reranker_model.return_value = (
"jinaai/jina-reranker-v3"
)
mock_config_instance.get_model_idle_timeout.return_value = 1800
mock_config.return_value = mock_config_instance
# Setup mock HTTP embedding
mock_http_embed_instance = MagicMock()
mock_http_embed_instance.get_embedding_dimension.return_value = 384
mock_http_embed.return_value = mock_http_embed_instance
# Setup mock database
mock_chroma_instance = MagicMock()
mock_chroma.return_value = mock_chroma_instance
api = CodeRAGAPI(reranker_enabled=False)
# HttpEmbedding should have been called during init
mock_http_embed.assert_called_with(port=9999)
# SentenceTransformerEmbedding should NOT have been called
mock_st.assert_not_called()
# ============================================================================
# CodeRAGAPI._create_database Tests
# ============================================================================
class TestCreateDatabase:
"""Tests for CodeRAGAPI._create_database factory method."""
@pytest.fixture
def api_instance(self):
"""Create a minimal CodeRAGAPI instance for testing _create_database."""
with (
patch("code_rag.api.SentenceTransformerEmbedding") as mock_st,
patch("code_rag.api.ChromaDatabase") as mock_chroma,
patch("code_rag.api.CrossEncoderReranker") as mock_reranker,
patch("code_rag.api.Config") as mock_config,
):
mock_config_instance = MagicMock()
mock_config_instance.get_database_path.return_value = "/tmp/test-db"
mock_config_instance.is_shared_server_enabled.return_value = False
mock_config_instance.get_shared_server_port.return_value = 8199
mock_config_instance.get_reranker_model.return_value = (
"jinaai/jina-reranker-v3"
)
mock_config_instance.get_model_idle_timeout.return_value = 1800
mock_config.return_value = mock_config_instance
mock_embedding = MagicMock()
mock_embedding.get_embedding_dimension.return_value = 384
mock_st.return_value = mock_embedding
mock_chroma.return_value = MagicMock()
api = CodeRAGAPI(reranker_enabled=False)
yield api
def test_creates_chroma_database(self, api_instance):
"""Test that ChromaDatabase is created for 'chroma' type."""
with patch("code_rag.api.ChromaDatabase") as mock_chroma:
mock_chroma.return_value = MagicMock()
result = api_instance._create_database("chroma", "/test/path")
mock_chroma.assert_called_with(persist_directory="/test/path")
def test_creates_qdrant_database(self, api_instance):
"""Test that QdrantDatabase is created for 'qdrant' type."""
with patch("code_rag.api.QdrantDatabase") as mock_qdrant:
mock_qdrant.return_value = MagicMock()
result = api_instance._create_database("qdrant", "/test/path")
mock_qdrant.assert_called_with(persist_directory="/test/path")
def test_raises_for_unsupported_database_type(self, api_instance):
"""Test that ValueError is raised for unsupported database types."""
with pytest.raises(ValueError, match="Unsupported database type: invalid"):
api_instance._create_database("invalid", "/test/path")
# ============================================================================
# CodeRAGAPI Error Handling Tests
# ============================================================================
class TestCodeRAGAPIErrorHandling:
"""Tests for error handling during CodeRAGAPI initialization."""
def test_reranker_failure_disables_reranker(self):
"""Test that reranker initialization failure gracefully disables reranker."""
with (
patch("code_rag.api.SentenceTransformerEmbedding") as mock_st,
patch("code_rag.api.ChromaDatabase") as mock_chroma,
patch("code_rag.api.CrossEncoderReranker") as mock_reranker,
patch("code_rag.api.Config") as mock_config,
):
mock_config_instance = MagicMock()
mock_config_instance.get_database_path.return_value = "/tmp/test-db"
mock_config_instance.is_shared_server_enabled.return_value = False
mock_config_instance.get_shared_server_port.return_value = 8199
mock_config_instance.get_reranker_model.return_value = (
"jinaai/jina-reranker-v3"
)
mock_config_instance.get_model_idle_timeout.return_value = 1800
mock_config.return_value = mock_config_instance
mock_embedding = MagicMock()
mock_embedding.get_embedding_dimension.return_value = 384
mock_st.return_value = mock_embedding
mock_chroma.return_value = MagicMock()
# Make reranker initialization fail
mock_reranker.side_effect = RuntimeError("Failed to load reranker model")
# Should not raise - just disables reranker
api = CodeRAGAPI(reranker_enabled=True)
assert api.reranker is None
# ============================================================================
# CodeRAGAPI.search Tests
# ============================================================================
class TestCodeRAGAPISearch:
"""Tests for CodeRAGAPI.search method."""
@pytest.fixture
def mock_api(self):
"""Create a CodeRAGAPI instance with mocked components for search tests."""
with (
patch("code_rag.api.SentenceTransformerEmbedding") as mock_st,
patch("code_rag.api.ChromaDatabase") as mock_chroma,
patch("code_rag.api.CrossEncoderReranker") as mock_reranker,
patch("code_rag.api.Config") as mock_config,
):
# Setup mock config
mock_config_instance = MagicMock()
mock_config_instance.get_database_path.return_value = "/tmp/test-db"
mock_config_instance.is_shared_server_enabled.return_value = False
mock_config_instance.get_shared_server_port.return_value = 8199
mock_config_instance.get_reranker_model.return_value = (
"jinaai/jina-reranker-v3"
)
mock_config_instance.get_model_idle_timeout.return_value = 1800
mock_config.return_value = mock_config_instance
# Setup mock embedding model
mock_embedding = MagicMock()
mock_embedding.get_embedding_dimension.return_value = 384
mock_embedding.embed_query.return_value = [0.1] * 384
mock_embedding.embed.return_value = [0.1] * 384
mock_st.return_value = mock_embedding
# Setup mock database with sample results
mock_chroma_instance = MagicMock()
mock_chroma_instance.query.return_value = {
"documents": [["def hello():\n print('world')"]],
"metadatas": [
[
{
"file_path": "/test/hello.py",
"chunk_index": 0,
"total_chunks": 1,
"start_line": 1,
"end_line": 2,
"function_name": "hello",
"symbol_type": "function",
}
]
],
"distances": [[0.1]],
}
mock_chroma.return_value = mock_chroma_instance
# Setup mock reranker
mock_reranker_instance = MagicMock()
mock_reranker_instance.rerank.return_value = [(0, 0.95)]
mock_reranker.return_value = mock_reranker_instance
api = CodeRAGAPI()
api._active_collection = "test_collection"
yield {
"api": api,
"embedding": mock_embedding,
"database": mock_chroma_instance,
"reranker": mock_reranker_instance,
}
def test_search_requires_active_collection(self, mock_api):
"""Test that search raises error when no collection is active."""
api = mock_api["api"]
api._active_collection = None
with pytest.raises(ValueError, match="No collection specified"):
api.search("test query")
def test_search_uses_specified_collection(self, mock_api):
"""Test that search uses specified collection over active collection."""
api = mock_api["api"]
api._active_collection = "default_collection"
# Should not raise
api.search("test query", collection_name="specific_collection")
def test_search_generates_query_embedding(self, mock_api):
"""Test that search generates embedding for query."""
api = mock_api["api"]
mock_embedding = mock_api["embedding"]
api.search("find authentication code")
mock_embedding.embed_query.assert_called_with("find authentication code")
def test_search_returns_formatted_results(self, mock_api):
"""Test that search returns properly formatted results."""
api = mock_api["api"]
results = api.search("hello function", rerank=False)
assert len(results) == 1
assert results[0]["content"] == "def hello():\n print('world')"
assert results[0]["file_path"] == "/test/hello.py"
assert results[0]["chunk_index"] == 0
assert results[0]["function_name"] == "hello"
assert "similarity" in results[0]
def test_search_with_reranking_enabled(self, mock_api):
"""Test search with reranking enabled."""
api = mock_api["api"]
mock_reranker = mock_api["reranker"]
results = api.search("hello function", rerank=True)
mock_reranker.rerank.assert_called_once()
# Reranker score should be used as similarity
assert results[0]["similarity"] == 0.95
def test_search_with_reranking_disabled(self, mock_api):
"""Test search with reranking disabled."""
api = mock_api["api"]
mock_reranker = mock_api["reranker"]
results = api.search("hello function", rerank=False)
mock_reranker.rerank.assert_not_called()
# Similarity should be calculated from distance
assert results[0]["similarity"] == 0.9 # 1 - 0.1 distance
def test_search_with_custom_n_results(self, mock_api):
"""Test search respects n_results parameter."""
api = mock_api["api"]
mock_db = mock_api["database"]
api.search("test query", n_results=10, rerank=False)
mock_db.query.assert_called()
call_args = mock_db.query.call_args
assert call_args[1]["n_results"] == 10
def test_search_with_reranker_multiplier(self, mock_api):
"""Test search uses reranker multiplier for initial retrieval."""
api = mock_api["api"]
api.reranker_multiplier = 3
mock_db = mock_api["database"]
api.search("test query", n_results=5, rerank=True)
mock_db.query.assert_called()
call_args = mock_db.query.call_args
# Should retrieve 5 * 3 = 15 results for reranking
assert call_args[1]["n_results"] == 15
def test_search_with_custom_reranker_multiplier(self, mock_api):
"""Test search uses custom reranker multiplier when provided."""
api = mock_api["api"]
api.reranker_multiplier = 2 # Default
mock_db = mock_api["database"]
api.search("test query", n_results=5, rerank=True, reranker_multiplier=4)
mock_db.query.assert_called()
call_args = mock_db.query.call_args
# Should use custom multiplier: 5 * 4 = 20
assert call_args[1]["n_results"] == 20
def test_search_with_file_type_filter(self, mock_api):
"""Test search filters results by file type."""
api = mock_api["api"]
mock_db = mock_api["database"]
# Setup multiple results with different file types
mock_db.query.return_value = {
"documents": [["py content", "js content", "md content"]],
"metadatas": [
[
{"file_path": "/test/file.py", "chunk_index": 0, "total_chunks": 1},
{"file_path": "/test/file.js", "chunk_index": 0, "total_chunks": 1},
{"file_path": "/test/file.md", "chunk_index": 0, "total_chunks": 1},
]
],
"distances": [[0.1, 0.2, 0.3]],
}
results = api.search("test query", file_types=[".py"], rerank=False)
# Should only return Python file
assert len(results) == 1
assert results[0]["file_path"] == "/test/file.py"
def test_search_with_include_paths_filter(self, mock_api):
"""Test search filters results by path patterns."""
api = mock_api["api"]
mock_db = mock_api["database"]
mock_db.query.return_value = {
"documents": [["src content", "test content", "docs content"]],
"metadatas": [
[
{
"file_path": "/project/src/main.py",
"chunk_index": 0,
"total_chunks": 1,
},
{
"file_path": "/project/tests/test_main.py",
"chunk_index": 0,
"total_chunks": 1,
},
{
"file_path": "/project/docs/readme.md",
"chunk_index": 0,
"total_chunks": 1,
},
]
],
"distances": [[0.1, 0.2, 0.3]],
}
results = api.search("test query", include_paths=["src/"], rerank=False)
# Should only return file from src/
assert len(results) == 1
assert "src/main.py" in results[0]["file_path"]
def test_search_empty_results(self, mock_api):
"""Test search handles empty results gracefully."""
api = mock_api["api"]
mock_db = mock_api["database"]
mock_db.query.return_value = {
"documents": [[]],
"metadatas": [[]],
"distances": [[]],
}
results = api.search("nonexistent query")
assert results == []
def test_search_reranker_failure_fallback(self, mock_api):
"""Test search falls back to original results when reranker fails."""
api = mock_api["api"]
mock_reranker = mock_api["reranker"]
# Make reranker fail
mock_reranker.rerank.side_effect = RuntimeError("Reranker failed")
# Should not raise, should return results from original database query
results = api.search("test query", rerank=True)
assert len(results) == 1
# Results should still be returned (fallback to original distance)
# Note: similarity calculation still uses reranker path since reranker is not None
assert results[0]["content"] == "def hello():\n print('world')"
class TestCodeRAGAPISearchIdentifierBoosting:
"""Tests for identifier-based boosting in search."""
@pytest.fixture
def mock_api_with_results(self):
"""Create API with multiple search results for boosting tests."""
with (
patch("code_rag.api.SentenceTransformerEmbedding") as mock_st,
patch("code_rag.api.ChromaDatabase") as mock_chroma,
patch("code_rag.api.CrossEncoderReranker") as mock_reranker,
patch("code_rag.api.Config") as mock_config,
):
mock_config_instance = MagicMock()
mock_config_instance.get_database_path.return_value = "/tmp/test-db"
mock_config_instance.is_shared_server_enabled.return_value = False
mock_config_instance.get_shared_server_port.return_value = 8199
mock_config_instance.get_reranker_model.return_value = (
"jinaai/jina-reranker-v3"
)
mock_config_instance.get_model_idle_timeout.return_value = 1800
mock_config.return_value = mock_config_instance
mock_embedding = MagicMock()
mock_embedding.get_embedding_dimension.return_value = 384
mock_embedding.embed_query.return_value = [0.1] * 384
mock_st.return_value = mock_embedding
# Multiple results - one containing the identifier, one not
mock_chroma_instance = MagicMock()
mock_chroma_instance.query.return_value = {
"documents": [
[
"def process_data(): pass", # Does not contain "getUserName"
"def getUserName(): return name", # Contains the identifier
]
],
"metadatas": [
[
{
"file_path": "/test/a.py",
"chunk_index": 0,
"total_chunks": 1,
},
{
"file_path": "/test/b.py",
"chunk_index": 0,
"total_chunks": 1,
},
]
],
"distances": [[0.2, 0.3]], # First result is closer in vector space
}
mock_chroma.return_value = mock_chroma_instance
mock_reranker_instance = MagicMock()
mock_reranker.return_value = mock_reranker_instance
api = CodeRAGAPI(reranker_enabled=False)
api._active_collection = "test_collection"
yield {
"api": api,
"database": mock_chroma_instance,
}
def test_search_boosts_identifier_matches(self, mock_api_with_results):
"""Test that search boosts results containing query identifiers."""
api = mock_api_with_results["api"]
# Query contains a camelCase identifier
# Use rerank=False since we're testing identifier boosting, not reranking
results = api.search("getUserName function", n_results=2, rerank=False)
# Result containing "getUserName" should be boosted
boosted_result = next(r for r in results if "getUserName" in r["content"])
non_boosted = next(r for r in results if "getUserName" not in r["content"])
assert boosted_result["boosted"] is True
assert non_boosted["boosted"] is False
def test_search_marks_unboosted_results(self, mock_api_with_results):
"""Test that results without identifier matches are marked as not boosted."""
api = mock_api_with_results["api"]
# Query without identifiers
results = api.search("find some code", n_results=2)
# All results should not be boosted
for result in results:
assert result["boosted"] is False
# ============================================================================
# CodeRAGAPI.index_codebase Tests
# ============================================================================
class TestCodeRAGAPIIndexCodebase:
"""Tests for CodeRAGAPI.index_codebase method."""
@pytest.fixture
def mock_api_for_indexing(self):
"""Create a CodeRAGAPI instance with mocked components for indexing tests."""