-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtest_embeddings.py
More file actions
1262 lines (939 loc) · 46.7 KB
/
test_embeddings.py
File metadata and controls
1262 lines (939 loc) · 46.7 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
"""Comprehensive tests for the embedding modules.
These tests verify:
1. HTTPEmbedding server management and request handling
2. LiteLLMEmbedding initialization and embedding generation
3. OpenAIEmbedding initialization and embedding generation
4. SentenceTransformerEmbedding model loading, caching, and idle timeout
All tests mock external dependencies to avoid real HTTP requests and model loading.
"""
import gc
import json
import tempfile
import threading
import time
from pathlib import Path
from unittest.mock import MagicMock, Mock, PropertyMock, mock_open, patch
import numpy as np
import pytest
import requests
# ============================================================================
# HTTPEmbedding Tests
# ============================================================================
class TestHttpEmbeddingInit:
"""Tests for HTTPEmbedding initialization."""
@pytest.fixture
def mock_server_running(self):
"""Mock a running server."""
with patch("requests.get") as mock_get, patch("requests.post") as mock_post:
# Health check returns 200
mock_get.return_value = Mock(status_code=200)
mock_post.return_value = Mock(status_code=200)
yield mock_get, mock_post
@pytest.fixture
def temp_cache_dir(self):
"""Provide a temporary cache directory."""
with tempfile.TemporaryDirectory() as temp_dir:
yield temp_dir
def test_init_connects_to_running_server(self, mock_server_running, temp_cache_dir):
"""Test that initialization connects to an already running server."""
mock_get, mock_post = mock_server_running
with (
patch(
"code_rag.embeddings.http_embedding.get_server_info_path"
) as mock_info_path,
patch(
"code_rag.embeddings.http_embedding.get_server_log_path"
) as mock_log_path,
):
# Server info file doesn't exist
mock_info_path.return_value = Path(temp_cache_dir) / "embedding_server.json"
mock_log_path.return_value = Path(temp_cache_dir) / "embedding_server.log"
from code_rag.embeddings.http_embedding import HttpEmbedding
embedding = HttpEmbedding(port=8199)
assert embedding.port == 8199
assert embedding.base_url == "http://127.0.0.1:8199"
assert embedding.client_id is not None
# Cleanup
embedding._cleanup()
def test_init_reads_port_from_server_info(
self, mock_server_running, temp_cache_dir
):
"""Test that initialization reads actual port from server info file."""
mock_get, mock_post = mock_server_running
# Create server info file with different port
info_path = Path(temp_cache_dir) / "embedding_server.json"
info_path.write_text(json.dumps({"port": 9999}))
with (
patch(
"code_rag.embeddings.http_embedding.get_server_info_path"
) as mock_info_path,
patch(
"code_rag.embeddings.http_embedding.get_server_log_path"
) as mock_log_path,
):
mock_info_path.return_value = info_path
mock_log_path.return_value = Path(temp_cache_dir) / "embedding_server.log"
from code_rag.embeddings.http_embedding import HttpEmbedding
embedding = HttpEmbedding(port=8199)
# Should have switched to the port from the info file
assert embedding.port == 9999
assert embedding.base_url == "http://127.0.0.1:9999"
# Cleanup
embedding._cleanup()
class TestHttpEmbeddingServerManagement:
"""Tests for HTTPEmbedding server spawning and health checks."""
def test_is_server_running_returns_true_when_healthy(self):
"""Test _is_server_running returns True when server responds with 200."""
with (
patch("requests.get") as mock_get,
patch("requests.post") as mock_post,
patch(
"code_rag.embeddings.http_embedding.get_server_info_path"
) as mock_info_path,
patch(
"code_rag.embeddings.http_embedding.get_server_log_path"
) as mock_log_path,
):
mock_get.return_value = Mock(status_code=200)
mock_post.return_value = Mock(status_code=200)
with tempfile.TemporaryDirectory() as temp_dir:
mock_info_path.return_value = Path(temp_dir) / "embedding_server.json"
mock_log_path.return_value = Path(temp_dir) / "embedding_server.log"
from code_rag.embeddings.http_embedding import HttpEmbedding
embedding = HttpEmbedding()
assert embedding._is_server_running() is True
embedding._cleanup()
def test_is_server_running_returns_false_on_connection_error(self):
"""Test _is_server_running returns False when connection fails."""
with (
patch("requests.get") as mock_get,
patch("requests.post") as mock_post,
patch(
"code_rag.embeddings.http_embedding.get_server_info_path"
) as mock_info_path,
patch(
"code_rag.embeddings.http_embedding.get_server_log_path"
) as mock_log_path,
patch.object(
__import__(
"code_rag.embeddings.http_embedding", fromlist=["HttpEmbedding"]
).HttpEmbedding,
"_spawn_server",
) as mock_spawn,
):
# First call succeeds (init), subsequent calls fail
mock_get.side_effect = [Mock(status_code=200), requests.ConnectionError()]
mock_post.return_value = Mock(status_code=200)
with tempfile.TemporaryDirectory() as temp_dir:
mock_info_path.return_value = Path(temp_dir) / "embedding_server.json"
mock_log_path.return_value = Path(temp_dir) / "embedding_server.log"
from code_rag.embeddings.http_embedding import HttpEmbedding
embedding = HttpEmbedding()
assert embedding._is_server_running() is False
embedding._cleanup()
def test_is_server_running_returns_false_on_timeout(self):
"""Test _is_server_running returns False when request times out."""
with (
patch("requests.get") as mock_get,
patch("requests.post") as mock_post,
patch(
"code_rag.embeddings.http_embedding.get_server_info_path"
) as mock_info_path,
patch(
"code_rag.embeddings.http_embedding.get_server_log_path"
) as mock_log_path,
):
# First call succeeds (init), subsequent calls timeout
mock_get.side_effect = [Mock(status_code=200), requests.Timeout()]
mock_post.return_value = Mock(status_code=200)
with tempfile.TemporaryDirectory() as temp_dir:
mock_info_path.return_value = Path(temp_dir) / "embedding_server.json"
mock_log_path.return_value = Path(temp_dir) / "embedding_server.log"
from code_rag.embeddings.http_embedding import HttpEmbedding
embedding = HttpEmbedding()
assert embedding._is_server_running() is False
embedding._cleanup()
class TestHttpEmbeddingHeartbeat:
"""Tests for HTTPEmbedding heartbeat functionality."""
def test_heartbeat_thread_starts(self):
"""Test that heartbeat thread is started on initialization."""
with (
patch("requests.get") as mock_get,
patch("requests.post") as mock_post,
patch(
"code_rag.embeddings.http_embedding.get_server_info_path"
) as mock_info_path,
patch(
"code_rag.embeddings.http_embedding.get_server_log_path"
) as mock_log_path,
):
mock_get.return_value = Mock(status_code=200)
mock_post.return_value = Mock(status_code=200)
with tempfile.TemporaryDirectory() as temp_dir:
mock_info_path.return_value = Path(temp_dir) / "embedding_server.json"
mock_log_path.return_value = Path(temp_dir) / "embedding_server.log"
from code_rag.embeddings.http_embedding import HttpEmbedding
embedding = HttpEmbedding()
assert embedding._heartbeat_thread is not None
assert embedding._heartbeat_thread.is_alive()
embedding._cleanup()
def test_heartbeat_stops_on_cleanup(self):
"""Test that heartbeat thread stops on cleanup."""
with (
patch("requests.get") as mock_get,
patch("requests.post") as mock_post,
patch(
"code_rag.embeddings.http_embedding.get_server_info_path"
) as mock_info_path,
patch(
"code_rag.embeddings.http_embedding.get_server_log_path"
) as mock_log_path,
):
mock_get.return_value = Mock(status_code=200)
mock_post.return_value = Mock(status_code=200)
with tempfile.TemporaryDirectory() as temp_dir:
mock_info_path.return_value = Path(temp_dir) / "embedding_server.json"
mock_log_path.return_value = Path(temp_dir) / "embedding_server.log"
from code_rag.embeddings.http_embedding import HttpEmbedding
embedding = HttpEmbedding()
heartbeat_thread = embedding._heartbeat_thread
embedding._cleanup()
# Give thread time to stop
time.sleep(0.1)
assert not heartbeat_thread.is_alive()
class TestHttpEmbeddingRequests:
"""Tests for HTTPEmbedding embedding requests."""
@pytest.fixture
def mock_http_embedding(self):
"""Provide a mocked HTTPEmbedding instance."""
with (
patch("requests.get") as mock_get,
patch("requests.post") as mock_post,
patch(
"code_rag.embeddings.http_embedding.get_server_info_path"
) as mock_info_path,
patch(
"code_rag.embeddings.http_embedding.get_server_log_path"
) as mock_log_path,
):
mock_get.return_value = Mock(status_code=200)
mock_post.return_value = Mock(status_code=200, json=lambda: {})
with tempfile.TemporaryDirectory() as temp_dir:
mock_info_path.return_value = Path(temp_dir) / "embedding_server.json"
mock_log_path.return_value = Path(temp_dir) / "embedding_server.log"
from code_rag.embeddings.http_embedding import HttpEmbedding
embedding = HttpEmbedding()
yield embedding, mock_post
embedding._cleanup()
def test_embed_single_text(self, mock_http_embedding):
"""Test embedding a single text."""
embedding, mock_post = mock_http_embedding
expected_embedding = [0.1, 0.2, 0.3, 0.4, 0.5]
mock_post.return_value = Mock(
status_code=200, json=lambda: {"embeddings": [expected_embedding]}
)
mock_post.return_value.raise_for_status = Mock()
result = embedding.embed("test text")
assert result == expected_embedding
def test_embed_query(self, mock_http_embedding):
"""Test embedding a query."""
embedding, mock_post = mock_http_embedding
expected_embedding = [0.5, 0.4, 0.3, 0.2, 0.1]
mock_post.return_value = Mock(
status_code=200, json=lambda: {"embedding": expected_embedding}
)
mock_post.return_value.raise_for_status = Mock()
result = embedding.embed_query("search query")
assert result == expected_embedding
def test_embed_batch(self, mock_http_embedding):
"""Test embedding multiple texts in batch."""
embedding, mock_post = mock_http_embedding
expected_embeddings = [[0.1, 0.2, 0.3], [0.4, 0.5, 0.6], [0.7, 0.8, 0.9]]
mock_post.return_value = Mock(
status_code=200, json=lambda: {"embeddings": expected_embeddings}
)
mock_post.return_value.raise_for_status = Mock()
result = embedding.embed_batch(["text1", "text2", "text3"])
assert result == expected_embeddings
def test_get_embedding_dimension(self, mock_http_embedding):
"""Test getting embedding dimension."""
embedding, mock_post = mock_http_embedding
mock_post.return_value = Mock(status_code=200, json=lambda: {"dimension": 384})
mock_post.return_value.raise_for_status = Mock()
result = embedding.get_embedding_dimension()
assert result == 384
class TestHttpEmbeddingRetry:
"""Tests for HTTPEmbedding retry logic."""
def test_request_retries_on_connection_error(self):
"""Test that requests retry once on connection error."""
with (
patch("requests.get") as mock_get,
patch("requests.post") as mock_post,
patch(
"code_rag.embeddings.http_embedding.get_server_info_path"
) as mock_info_path,
patch(
"code_rag.embeddings.http_embedding.get_server_log_path"
) as mock_log_path,
):
# Health checks succeed
mock_get.return_value = Mock(status_code=200)
success_response = Mock(status_code=200)
success_response.json.return_value = {"embeddings": [[0.1, 0.2, 0.3]]}
success_response.raise_for_status = Mock()
# Initial mock for server initialization
mock_post.return_value = Mock(status_code=200)
with tempfile.TemporaryDirectory() as temp_dir:
mock_info_path.return_value = Path(temp_dir) / "embedding_server.json"
mock_log_path.return_value = Path(temp_dir) / "embedding_server.log"
from code_rag.embeddings.http_embedding import HttpEmbedding
embedding = HttpEmbedding()
# Now set up retry scenario using a callable side_effect
call_count = [0]
def post_side_effect(*args, **kwargs):
url = args[0] if args else kwargs.get("url", "")
# Allow heartbeat and disconnect calls to succeed
if "/heartbeat" in url or "/disconnect" in url:
return Mock(status_code=200)
# First embed call fails, retry succeeds
call_count[0] += 1
if call_count[0] == 1:
raise requests.ConnectionError("First attempt failed")
return success_response
mock_post.side_effect = post_side_effect
result = embedding.embed("test")
assert result == [0.1, 0.2, 0.3]
embedding._cleanup()
def test_request_fails_after_retry(self):
"""Test that requests fail if retry also fails."""
with (
patch("requests.get") as mock_get,
patch("requests.post") as mock_post,
patch(
"code_rag.embeddings.http_embedding.get_server_info_path"
) as mock_info_path,
patch(
"code_rag.embeddings.http_embedding.get_server_log_path"
) as mock_log_path,
):
mock_get.return_value = Mock(status_code=200)
mock_post.return_value = Mock(status_code=200)
with tempfile.TemporaryDirectory() as temp_dir:
mock_info_path.return_value = Path(temp_dir) / "embedding_server.json"
mock_log_path.return_value = Path(temp_dir) / "embedding_server.log"
from code_rag.embeddings.http_embedding import HttpEmbedding
embedding = HttpEmbedding()
# Use callable side_effect that fails for embed calls but allows cleanup
def post_side_effect(*args, **kwargs):
url = args[0] if args else kwargs.get("url", "")
if "/heartbeat" in url or "/disconnect" in url:
return Mock(status_code=200)
# All embed calls fail
raise requests.ConnectionError("Connection failed")
mock_post.side_effect = post_side_effect
with pytest.raises(RuntimeError, match="Failed to connect"):
embedding.embed("test")
embedding._cleanup()
class TestHttpEmbeddingNoOpMethods:
"""Tests for HTTPEmbedding no-op methods."""
def test_start_background_loading_is_noop(self):
"""Test that start_background_loading does nothing."""
with (
patch("requests.get") as mock_get,
patch("requests.post") as mock_post,
patch(
"code_rag.embeddings.http_embedding.get_server_info_path"
) as mock_info_path,
patch(
"code_rag.embeddings.http_embedding.get_server_log_path"
) as mock_log_path,
):
mock_get.return_value = Mock(status_code=200)
mock_post.return_value = Mock(status_code=200)
with tempfile.TemporaryDirectory() as temp_dir:
mock_info_path.return_value = Path(temp_dir) / "embedding_server.json"
mock_log_path.return_value = Path(temp_dir) / "embedding_server.log"
from code_rag.embeddings.http_embedding import HttpEmbedding
embedding = HttpEmbedding()
# Should not raise
embedding.start_background_loading()
embedding._cleanup()
def test_unload_model_is_noop(self):
"""Test that unload_model does nothing."""
with (
patch("requests.get") as mock_get,
patch("requests.post") as mock_post,
patch(
"code_rag.embeddings.http_embedding.get_server_info_path"
) as mock_info_path,
patch(
"code_rag.embeddings.http_embedding.get_server_log_path"
) as mock_log_path,
):
mock_get.return_value = Mock(status_code=200)
mock_post.return_value = Mock(status_code=200)
with tempfile.TemporaryDirectory() as temp_dir:
mock_info_path.return_value = Path(temp_dir) / "embedding_server.json"
mock_log_path.return_value = Path(temp_dir) / "embedding_server.log"
from code_rag.embeddings.http_embedding import HttpEmbedding
embedding = HttpEmbedding()
# Should not raise
embedding.unload_model()
embedding._cleanup()
# ============================================================================
# LiteLLMEmbedding Tests
# ============================================================================
class TestLiteLLMEmbeddingInit:
"""Tests for LiteLLMEmbedding initialization."""
def test_init_with_model_name(self):
"""Test initialization with model name."""
from code_rag.embeddings.litellm_embedding import LiteLLMEmbedding
embedding = LiteLLMEmbedding(model_name="text-embedding-3-small")
assert embedding.model_name == "text-embedding-3-small"
assert embedding.api_key is None
def test_init_with_api_key(self):
"""Test initialization with API key."""
from code_rag.embeddings.litellm_embedding import LiteLLMEmbedding
embedding = LiteLLMEmbedding(
model_name="text-embedding-3-small", api_key="test-api-key"
)
assert embedding.model_name == "text-embedding-3-small"
assert embedding.api_key == "test-api-key"
def test_init_with_idle_timeout(self):
"""Test initialization stores idle_timeout (even though not used)."""
from code_rag.embeddings.litellm_embedding import LiteLLMEmbedding
embedding = LiteLLMEmbedding(
model_name="text-embedding-3-small", idle_timeout=3600
)
assert embedding._idle_timeout == 3600
class TestLiteLLMEmbeddingEmbed:
"""Tests for LiteLLMEmbedding embedding methods."""
@pytest.fixture
def mock_litellm_embedding(self):
"""Provide a mocked LiteLLM embedding response."""
mock_response = MagicMock()
mock_response.data = [MagicMock(embedding=[0.1, 0.2, 0.3, 0.4, 0.5])]
with patch("code_rag.embeddings.litellm_embedding.embedding") as mock_embed:
mock_embed.return_value = mock_response
yield mock_embed
def test_embed_single_text(self, mock_litellm_embedding):
"""Test embedding a single text."""
from code_rag.embeddings.litellm_embedding import LiteLLMEmbedding
embedding = LiteLLMEmbedding(model_name="text-embedding-3-small")
result = embedding.embed("test text")
assert result == [0.1, 0.2, 0.3, 0.4, 0.5]
mock_litellm_embedding.assert_called_once()
def test_embed_replaces_newlines(self, mock_litellm_embedding):
"""Test that embed replaces newlines in text."""
from code_rag.embeddings.litellm_embedding import LiteLLMEmbedding
embedding = LiteLLMEmbedding(model_name="text-embedding-3-small")
embedding.embed("test\ntext\nwith\nnewlines")
# Verify newlines were replaced
call_args = mock_litellm_embedding.call_args
assert "\n" not in call_args.kwargs["input"][0]
assert "test text with newlines" == call_args.kwargs["input"][0]
def test_embed_batch(self, mock_litellm_embedding):
"""Test embedding multiple texts in batch."""
mock_response = MagicMock()
mock_response.data = [
MagicMock(embedding=[0.1, 0.2, 0.3]),
MagicMock(embedding=[0.4, 0.5, 0.6]),
MagicMock(embedding=[0.7, 0.8, 0.9]),
]
mock_litellm_embedding.return_value = mock_response
from code_rag.embeddings.litellm_embedding import LiteLLMEmbedding
embedding = LiteLLMEmbedding(model_name="text-embedding-3-small")
result = embedding.embed_batch(["text1", "text2", "text3"])
assert result == [[0.1, 0.2, 0.3], [0.4, 0.5, 0.6], [0.7, 0.8, 0.9]]
def test_embed_batch_replaces_newlines(self, mock_litellm_embedding):
"""Test that embed_batch replaces newlines in all texts."""
mock_response = MagicMock()
mock_response.data = [MagicMock(embedding=[0.1, 0.2])]
mock_litellm_embedding.return_value = mock_response
from code_rag.embeddings.litellm_embedding import LiteLLMEmbedding
embedding = LiteLLMEmbedding(model_name="text-embedding-3-small")
embedding.embed_batch(["text\nwith\nnewlines"])
call_args = mock_litellm_embedding.call_args
assert "text with newlines" == call_args.kwargs["input"][0]
class TestLiteLLMEmbeddingDimension:
"""Tests for LiteLLMEmbedding get_embedding_dimension."""
def test_get_dimension_known_model(self):
"""Test getting dimension for known models."""
from code_rag.embeddings.litellm_embedding import LiteLLMEmbedding
test_cases = [
("text-embedding-3-small", 1536),
("text-embedding-3-large", 3072),
("text-embedding-ada-002", 1536),
("vertex_ai/text-embedding-004", 768),
]
for model_name, expected_dim in test_cases:
embedding = LiteLLMEmbedding(model_name=model_name)
assert embedding.get_embedding_dimension() == expected_dim
def test_get_dimension_unknown_model_fallback(self):
"""Test getting dimension for unknown model via API call."""
mock_response = MagicMock()
mock_response.data = [MagicMock(embedding=[0.1] * 512)]
with patch("code_rag.embeddings.litellm_embedding.embedding") as mock_embed:
mock_embed.return_value = mock_response
from code_rag.embeddings.litellm_embedding import LiteLLMEmbedding
embedding = LiteLLMEmbedding(model_name="unknown-model")
assert embedding.get_embedding_dimension() == 512
def test_get_dimension_unknown_model_error_fallback(self):
"""Test getting dimension falls back to 1536 on error."""
with patch("code_rag.embeddings.litellm_embedding.embedding") as mock_embed:
mock_embed.side_effect = Exception("API error")
from code_rag.embeddings.litellm_embedding import LiteLLMEmbedding
embedding = LiteLLMEmbedding(model_name="unknown-model")
assert embedding.get_embedding_dimension() == 1536
# ============================================================================
# OpenAIEmbedding Tests
# ============================================================================
class TestOpenAIEmbeddingInit:
"""Tests for OpenAIEmbedding initialization."""
def test_init_with_api_key(self):
"""Test initialization with API key."""
with patch("code_rag.embeddings.openai_embedding.OpenAI") as mock_openai:
from code_rag.embeddings.openai_embedding import OpenAIEmbedding
embedding = OpenAIEmbedding(api_key="test-api-key")
assert embedding.model_name == "text-embedding-3-small"
mock_openai.assert_called_once_with(api_key="test-api-key")
def test_init_with_custom_model(self):
"""Test initialization with custom model name."""
with patch("code_rag.embeddings.openai_embedding.OpenAI") as mock_openai:
from code_rag.embeddings.openai_embedding import OpenAIEmbedding
embedding = OpenAIEmbedding(
model_name="text-embedding-3-large", api_key="test-api-key"
)
assert embedding.model_name == "text-embedding-3-large"
def test_init_uses_env_var_when_no_key(self):
"""Test initialization uses OPENAI_API_KEY env var when no key provided."""
with (
patch("code_rag.embeddings.openai_embedding.OpenAI") as mock_openai,
patch.dict("os.environ", {"OPENAI_API_KEY": "env-api-key"}),
):
from code_rag.embeddings.openai_embedding import OpenAIEmbedding
embedding = OpenAIEmbedding()
# Should pass the env var to OpenAI
mock_openai.assert_called_once_with(api_key="env-api-key")
class TestOpenAIEmbeddingEmbed:
"""Tests for OpenAIEmbedding embedding methods."""
@pytest.fixture
def mock_openai_client(self):
"""Provide a mocked OpenAI client."""
mock_client = MagicMock()
mock_response = MagicMock()
mock_response.data = [MagicMock(embedding=[0.1, 0.2, 0.3, 0.4, 0.5])]
mock_client.embeddings.create.return_value = mock_response
with patch("code_rag.embeddings.openai_embedding.OpenAI") as mock_openai:
mock_openai.return_value = mock_client
yield mock_client
def test_embed_single_text(self, mock_openai_client):
"""Test embedding a single text."""
from code_rag.embeddings.openai_embedding import OpenAIEmbedding
embedding = OpenAIEmbedding(api_key="test-key")
result = embedding.embed("test text")
assert result == [0.1, 0.2, 0.3, 0.4, 0.5]
mock_openai_client.embeddings.create.assert_called_once()
def test_embed_replaces_newlines(self, mock_openai_client):
"""Test that embed replaces newlines in text."""
from code_rag.embeddings.openai_embedding import OpenAIEmbedding
embedding = OpenAIEmbedding(api_key="test-key")
embedding.embed("test\ntext\nwith\nnewlines")
call_args = mock_openai_client.embeddings.create.call_args
assert call_args.kwargs["input"] == ["test text with newlines"]
def test_embed_batch(self, mock_openai_client):
"""Test embedding multiple texts in batch."""
mock_response = MagicMock()
mock_response.data = [
MagicMock(embedding=[0.1, 0.2, 0.3]),
MagicMock(embedding=[0.4, 0.5, 0.6]),
MagicMock(embedding=[0.7, 0.8, 0.9]),
]
mock_openai_client.embeddings.create.return_value = mock_response
from code_rag.embeddings.openai_embedding import OpenAIEmbedding
embedding = OpenAIEmbedding(api_key="test-key")
result = embedding.embed_batch(["text1", "text2", "text3"])
assert result == [[0.1, 0.2, 0.3], [0.4, 0.5, 0.6], [0.7, 0.8, 0.9]]
def test_embed_batch_replaces_newlines(self, mock_openai_client):
"""Test that embed_batch replaces newlines in all texts."""
from code_rag.embeddings.openai_embedding import OpenAIEmbedding
embedding = OpenAIEmbedding(api_key="test-key")
embedding.embed_batch(["text\none", "text\ntwo"])
call_args = mock_openai_client.embeddings.create.call_args
assert call_args.kwargs["input"] == ["text one", "text two"]
class TestOpenAIEmbeddingDimension:
"""Tests for OpenAIEmbedding get_embedding_dimension."""
def test_get_dimension_known_model(self):
"""Test getting dimension for known models."""
with patch("code_rag.embeddings.openai_embedding.OpenAI"):
from code_rag.embeddings.openai_embedding import OpenAIEmbedding
test_cases = [
("text-embedding-3-small", 1536),
("text-embedding-3-large", 3072),
("text-embedding-ada-002", 1536),
]
for model_name, expected_dim in test_cases:
embedding = OpenAIEmbedding(model_name=model_name, api_key="test-key")
assert embedding.get_embedding_dimension() == expected_dim
def test_get_dimension_unknown_model_fallback(self):
"""Test getting dimension for unknown model via API call."""
mock_client = MagicMock()
mock_response = MagicMock()
mock_response.data = [MagicMock(embedding=[0.1] * 768)]
mock_client.embeddings.create.return_value = mock_response
with patch("code_rag.embeddings.openai_embedding.OpenAI") as mock_openai:
mock_openai.return_value = mock_client
from code_rag.embeddings.openai_embedding import OpenAIEmbedding
embedding = OpenAIEmbedding(model_name="unknown-model", api_key="test-key")
assert embedding.get_embedding_dimension() == 768
def test_get_dimension_unknown_model_error_fallback(self):
"""Test getting dimension falls back to 1536 on error."""
mock_client = MagicMock()
mock_client.embeddings.create.side_effect = Exception("API error")
with patch("code_rag.embeddings.openai_embedding.OpenAI") as mock_openai:
mock_openai.return_value = mock_client
from code_rag.embeddings.openai_embedding import OpenAIEmbedding
embedding = OpenAIEmbedding(model_name="unknown-model", api_key="test-key")
assert embedding.get_embedding_dimension() == 1536
# ============================================================================
# SentenceTransformerEmbedding Tests
# ============================================================================
class TestSentenceTransformerEmbeddingInit:
"""Tests for SentenceTransformerEmbedding initialization."""
def test_init_default_model(self, mock_sentence_transformer_model):
"""Test initialization with default model."""
def create_mock(*args, **kwargs):
return mock_sentence_transformer_model()
with patch(
"code_rag.embeddings.sentence_transformer_embedding.SentenceTransformer",
side_effect=create_mock,
):
from code_rag.embeddings.sentence_transformer_embedding import (
SentenceTransformerEmbedding,
)
embedding = SentenceTransformerEmbedding()
assert embedding.model_name == "all-MiniLM-L6-v2"
assert embedding.model is not None
embedding.stop_cleanup_thread()
def test_init_custom_model(self, mock_sentence_transformer_model):
"""Test initialization with custom model name."""
def create_mock(*args, **kwargs):
return mock_sentence_transformer_model()
with patch(
"code_rag.embeddings.sentence_transformer_embedding.SentenceTransformer",
side_effect=create_mock,
):
from code_rag.embeddings.sentence_transformer_embedding import (
SentenceTransformerEmbedding,
)
embedding = SentenceTransformerEmbedding(model_name="custom-model")
assert embedding.model_name == "custom-model"
embedding.stop_cleanup_thread()
def test_init_lazy_load(self, mock_sentence_transformer_model):
"""Test initialization with lazy loading."""
with patch(
"code_rag.embeddings.sentence_transformer_embedding.SentenceTransformer"
) as mock_st:
from code_rag.embeddings.sentence_transformer_embedding import (
SentenceTransformerEmbedding,
)
embedding = SentenceTransformerEmbedding(lazy_load=True)
# Model should not be loaded yet
assert embedding.model is None
mock_st.assert_not_called()
embedding.stop_cleanup_thread()
def test_init_query_prefix_for_code_rank_embed(
self, mock_sentence_transformer_model
):
"""Test that CodeRankEmbed model gets query prefix."""
def create_mock(*args, **kwargs):
return mock_sentence_transformer_model()
with patch(
"code_rag.embeddings.sentence_transformer_embedding.SentenceTransformer",
side_effect=create_mock,
):
from code_rag.embeddings.sentence_transformer_embedding import (
SentenceTransformerEmbedding,
)
embedding = SentenceTransformerEmbedding(
model_name="nomic-ai/CodeRankEmbed"
)
assert (
embedding.query_prefix
== "Represent this query for searching relevant code: "
)
embedding.stop_cleanup_thread()
class TestSentenceTransformerEmbeddingEmbed:
"""Tests for SentenceTransformerEmbedding embedding methods."""
def test_embed_single_text(self, mock_sentence_transformer_model):
"""Test embedding a single text."""
def create_mock(*args, **kwargs):
return mock_sentence_transformer_model()
with patch(
"code_rag.embeddings.sentence_transformer_embedding.SentenceTransformer",
side_effect=create_mock,
):
from code_rag.embeddings.sentence_transformer_embedding import (
SentenceTransformerEmbedding,
)
embedding = SentenceTransformerEmbedding()
result = embedding.embed("test text")
assert isinstance(result, list)
assert len(result) == 384
assert all(isinstance(x, float) for x in result)
embedding.stop_cleanup_thread()
def test_embed_query_with_prefix(self, mock_sentence_transformer_model):
"""Test embedding a query with model-specific prefix."""
mock_model = mock_sentence_transformer_model()
def create_mock(*args, **kwargs):
return mock_model
with patch(
"code_rag.embeddings.sentence_transformer_embedding.SentenceTransformer",
side_effect=create_mock,
):
from code_rag.embeddings.sentence_transformer_embedding import (
SentenceTransformerEmbedding,
)
embedding = SentenceTransformerEmbedding(
model_name="nomic-ai/CodeRankEmbed"
)
embedding.embed_query("search query")
# The query should have been prefixed
# We can verify by checking the mock was called
assert embedding.query_prefix != ""
embedding.stop_cleanup_thread()
def test_embed_batch(self, mock_sentence_transformer_model):
"""Test embedding multiple texts in batch."""
def create_mock(*args, **kwargs):
return mock_sentence_transformer_model()
with patch(
"code_rag.embeddings.sentence_transformer_embedding.SentenceTransformer",
side_effect=create_mock,
):
from code_rag.embeddings.sentence_transformer_embedding import (
SentenceTransformerEmbedding,
)
embedding = SentenceTransformerEmbedding()
result = embedding.embed_batch(["text1", "text2", "text3"])
assert isinstance(result, list)
assert len(result) == 3
for vec in result:
assert isinstance(vec, list)
assert len(vec) == 384
embedding.stop_cleanup_thread()
def test_get_embedding_dimension(self, mock_sentence_transformer_model):
"""Test getting embedding dimension."""
def create_mock(*args, **kwargs):
return mock_sentence_transformer_model(embedding_dim=512)
with patch(
"code_rag.embeddings.sentence_transformer_embedding.SentenceTransformer",
side_effect=create_mock,
):
from code_rag.embeddings.sentence_transformer_embedding import (
SentenceTransformerEmbedding,
)
embedding = SentenceTransformerEmbedding()
dim = embedding.get_embedding_dimension()
assert dim == 512
embedding.stop_cleanup_thread()
class TestSentenceTransformerEmbeddingLazyLoad:
"""Tests for SentenceTransformerEmbedding lazy loading behavior."""
def test_lazy_load_defers_model_loading(self, mock_sentence_transformer_model):
"""Test that lazy_load=True defers model loading."""
with patch(
"code_rag.embeddings.sentence_transformer_embedding.SentenceTransformer"
) as mock_st: