-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathtest_engine.py
More file actions
820 lines (668 loc) · 31.8 KB
/
test_engine.py
File metadata and controls
820 lines (668 loc) · 31.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
"""
Tests for the LingoDotDevEngine class
"""
import pytest
import asyncio
from unittest.mock import Mock, patch, AsyncMock
import httpx
from lingodotdev import LingoDotDevEngine
from lingodotdev.engine import EngineConfig
class TestEngineConfig:
"""Test the EngineConfig model"""
def test_valid_config(self):
"""Test valid configuration"""
config = EngineConfig(
api_key="test_key",
api_url="https://api.test.com",
batch_size=50,
ideal_batch_item_size=500,
)
assert config.api_key == "test_key"
assert config.api_url == "https://api.test.com"
assert config.batch_size == 50
assert config.ideal_batch_item_size == 500
def test_default_values(self):
"""Test default configuration values"""
config = EngineConfig(api_key="test_key")
assert config.api_url == "https://engine.lingo.dev"
assert config.batch_size == 25
assert config.ideal_batch_item_size == 250
def test_invalid_api_url(self):
"""Test invalid API URL validation"""
with pytest.raises(ValueError, match="API URL must be a valid HTTP/HTTPS URL"):
EngineConfig(api_key="test_key", api_url="invalid_url")
def test_invalid_batch_size(self):
"""Test invalid batch size validation"""
with pytest.raises(ValueError):
EngineConfig(api_key="test_key", batch_size=0)
with pytest.raises(ValueError):
EngineConfig(api_key="test_key", batch_size=300)
def test_invalid_ideal_batch_item_size(self):
"""Test invalid ideal batch item size validation"""
with pytest.raises(ValueError):
EngineConfig(api_key="test_key", ideal_batch_item_size=0)
with pytest.raises(ValueError):
EngineConfig(api_key="test_key", ideal_batch_item_size=3000)
class TestErrorHandling:
"""Test error handling utilities for non-JSON responses (e.g., 502 HTML errors)"""
def test_truncate_response_short_text(self):
"""Test that short responses are not truncated"""
short_text = "Short error message"
result = LingoDotDevEngine._truncate_response(short_text)
assert result == short_text
def test_truncate_response_long_text(self):
"""Test that long responses are truncated with ellipsis"""
long_text = "x" * 300
result = LingoDotDevEngine._truncate_response(long_text)
assert len(result) == 203 # 200 chars + "..."
assert result.endswith("...")
def test_truncate_response_custom_max_length(self):
"""Test truncation with custom max length"""
text = "x" * 100
result = LingoDotDevEngine._truncate_response(text, max_length=50)
assert len(result) == 53 # 50 chars + "..."
assert result.endswith("...")
def test_truncate_response_exact_length(self):
"""Test text exactly at max length is not truncated"""
text = "x" * 200
result = LingoDotDevEngine._truncate_response(text, max_length=200)
assert result == text
assert not result.endswith("...")
def test_safe_parse_json_valid_json(self):
"""Test parsing valid JSON response"""
mock_response = Mock(spec=httpx.Response)
mock_response.json.return_value = {"data": "test"}
result = LingoDotDevEngine._safe_parse_json(mock_response)
assert result == {"data": "test"}
def test_safe_parse_json_html_response(self):
"""Test handling HTML response (like 502 error page)"""
import json as json_module
# Use a large HTML body (>200 chars) to test truncation
html_body = """<!DOCTYPE html>
<html>
<head><title>502 Bad Gateway</title></head>
<body>
<center><h1>502 Bad Gateway</h1></center>
<p>The server encountered a temporary error and could not complete your request.</p>
<p>Please try again in a few moments. If the problem persists, contact support.</p>
<hr><center>nginx/1.18.0 (Ubuntu)</center>
</body>
</html>"""
mock_response = Mock(spec=httpx.Response)
mock_response.json.side_effect = json_module.JSONDecodeError(
"Expecting value", html_body, 0
)
mock_response.text = html_body
mock_response.status_code = 502
with pytest.raises(RuntimeError) as exc_info:
LingoDotDevEngine._safe_parse_json(mock_response)
error_msg = str(exc_info.value)
assert "Failed to parse API response as JSON" in error_msg
assert "status 502" in error_msg
assert "gateway or proxy error" in error_msg
# Verify HTML is truncated (original is ~400 chars, should be truncated to 200 + ...)
assert "..." in error_msg
assert len(error_msg) < len(html_body) + 150
def test_safe_parse_json_empty_response(self):
"""Test handling empty response body"""
import json as json_module
mock_response = Mock(spec=httpx.Response)
mock_response.json.side_effect = json_module.JSONDecodeError(
"Expecting value", "", 0
)
mock_response.text = ""
mock_response.status_code = 500
with pytest.raises(RuntimeError) as exc_info:
LingoDotDevEngine._safe_parse_json(mock_response)
assert "status 500" in str(exc_info.value)
def test_safe_parse_json_malformed_json(self):
"""Test handling malformed JSON response"""
import json as json_module
mock_response = Mock(spec=httpx.Response)
mock_response.json.side_effect = json_module.JSONDecodeError(
"Expecting value", '{"data": incomplete', 8
)
mock_response.text = '{"data": incomplete'
mock_response.status_code = 200
with pytest.raises(RuntimeError) as exc_info:
LingoDotDevEngine._safe_parse_json(mock_response)
assert "Failed to parse API response as JSON" in str(exc_info.value)
@pytest.mark.asyncio
class TestErrorHandlingIntegration:
"""Integration tests for error handling with mocked HTTP responses"""
def setup_method(self):
"""Set up test fixtures"""
self.config = {"api_key": "test_api_key", "api_url": "https://api.test.com"}
self.engine = LingoDotDevEngine(self.config)
@patch("lingodotdev.engine.httpx.AsyncClient.post")
async def test_localize_chunk_502_html_response(self, mock_post):
"""Test that 502 with HTML body raises clean RuntimeError"""
html_body = "<html><body><h1>502 Bad Gateway</h1></body></html>"
mock_response = Mock()
mock_response.is_success = False
mock_response.status_code = 502
mock_response.reason_phrase = "Bad Gateway"
mock_response.text = html_body
mock_post.return_value = mock_response
with pytest.raises(RuntimeError) as exc_info:
await self.engine._localize_chunk(
"en", "es", {"data": {"key": "value"}}, "workflow_id", False
)
error_msg = str(exc_info.value)
assert "Server error (502)" in error_msg
assert "Bad Gateway" in error_msg
assert "temporary service issues" in error_msg
@patch("lingodotdev.engine.httpx.AsyncClient.post")
async def test_localize_chunk_success_but_html_response(self, mock_post):
"""Test handling when server returns 200 but with HTML body (edge case)"""
import json as json_module
mock_response = Mock()
mock_response.is_success = True
mock_response.status_code = 200
mock_response.json.side_effect = json_module.JSONDecodeError(
"Expecting value", "<html>Unexpected HTML</html>", 0
)
mock_response.text = "<html>Unexpected HTML</html>"
mock_post.return_value = mock_response
with pytest.raises(RuntimeError) as exc_info:
await self.engine._localize_chunk(
"en", "es", {"data": {"key": "value"}}, "workflow_id", False
)
assert "Failed to parse API response as JSON" in str(exc_info.value)
@patch("lingodotdev.engine.httpx.AsyncClient.post")
async def test_recognize_locale_502_html_response(self, mock_post):
"""Test recognize_locale handles 502 HTML gracefully"""
mock_response = Mock()
mock_response.is_success = False
mock_response.status_code = 502
mock_response.reason_phrase = "Bad Gateway"
mock_response.text = "<html><body>502 Bad Gateway</body></html>"
mock_post.return_value = mock_response
with pytest.raises(RuntimeError) as exc_info:
await self.engine.recognize_locale("Hello world")
error_msg = str(exc_info.value)
assert "Server error (502)" in error_msg
@patch("lingodotdev.engine.httpx.AsyncClient.post")
async def test_whoami_502_html_response(self, mock_post):
"""Test whoami handles 502 HTML gracefully"""
mock_response = Mock()
mock_response.is_success = False
mock_response.status_code = 502
mock_response.reason_phrase = "Bad Gateway"
mock_response.text = "<html><body>502 Bad Gateway</body></html>"
mock_post.return_value = mock_response
with pytest.raises(RuntimeError) as exc_info:
await self.engine.whoami()
error_msg = str(exc_info.value)
assert "Server error (502)" in error_msg
@patch("lingodotdev.engine.httpx.AsyncClient.post")
async def test_error_message_truncation_in_api_call(self, mock_post):
"""Test that large HTML error pages are truncated in error messages"""
large_html = "<html>" + "x" * 1000 + "</html>"
mock_response = Mock()
mock_response.is_success = False
mock_response.status_code = 503
mock_response.reason_phrase = "Service Unavailable"
mock_response.text = large_html
mock_post.return_value = mock_response
with pytest.raises(RuntimeError) as exc_info:
await self.engine._localize_chunk(
"en", "es", {"data": {"key": "value"}}, "workflow_id", False
)
error_msg = str(exc_info.value)
# Error message should be much shorter than the full HTML
assert len(error_msg) < 500
assert "..." in error_msg # Truncation indicator
@pytest.mark.asyncio
class TestLingoDotDevEngine:
"""Test the LingoDotDevEngine class"""
def setup_method(self):
"""Set up test fixtures"""
self.config = {
"api_key": "test_api_key",
"api_url": "https://api.test.com",
"batch_size": 10,
"ideal_batch_item_size": 100,
}
self.engine = LingoDotDevEngine(self.config)
def test_initialization(self):
"""Test engine initialization"""
assert self.engine.config.api_key == "test_api_key"
assert self.engine.config.api_url == "https://api.test.com"
assert self.engine.config.batch_size == 10
assert self.engine.config.ideal_batch_item_size == 100
assert self.engine._client is None # Client not initialized yet
async def test_async_context_manager(self):
"""Test async context manager functionality"""
async with LingoDotDevEngine(self.config) as engine:
assert engine._client is not None
assert not engine._client.is_closed
def test_count_words_in_record_string(self):
"""Test word counting in strings"""
assert self.engine._count_words_in_record("hello world") == 2
assert self.engine._count_words_in_record(" hello world ") == 2
assert self.engine._count_words_in_record("") == 0
assert self.engine._count_words_in_record("single") == 1
def test_count_words_in_record_list(self):
"""Test word counting in lists"""
assert self.engine._count_words_in_record(["hello world", "test"]) == 3
assert self.engine._count_words_in_record([]) == 0
assert self.engine._count_words_in_record(["hello", ["world", "test"]]) == 3
def test_count_words_in_record_dict(self):
"""Test word counting in dictionaries"""
assert (
self.engine._count_words_in_record({"key1": "hello world", "key2": "test"})
== 3
)
assert self.engine._count_words_in_record({}) == 0
assert (
self.engine._count_words_in_record({"key1": {"nested": "hello world"}}) == 2
)
def test_count_words_in_record_other_types(self):
"""Test word counting with non-string types"""
assert self.engine._count_words_in_record(123) == 0
assert self.engine._count_words_in_record(None) == 0
assert self.engine._count_words_in_record(True) == 0
def test_extract_payload_chunks_small_payload(self):
"""Test payload chunking with small payload"""
payload = {"key1": "hello", "key2": "world"}
chunks = self.engine._extract_payload_chunks(payload)
assert len(chunks) == 1
assert chunks[0] == payload
def test_extract_payload_chunks_large_payload(self):
"""Test payload chunking with large payload"""
# Create a payload that exceeds batch size
payload = {f"key{i}": "hello world" for i in range(15)}
chunks = self.engine._extract_payload_chunks(payload)
assert len(chunks) == 2 # Should split into 2 chunks based on batch_size=10
@patch("lingodotdev.engine.httpx.AsyncClient.post")
async def test_localize_chunk_success(self, mock_post):
"""Test successful chunk localization"""
mock_response = Mock()
mock_response.is_success = True
mock_response.json.return_value = {"data": {"key": "translated_value"}}
mock_post.return_value = mock_response
result = await self.engine._localize_chunk(
"en", "es", {"data": {"key": "value"}}, "workflow_id", False
)
assert result == {"key": "translated_value"}
mock_post.assert_called_once()
@patch("lingodotdev.engine.httpx.AsyncClient.post")
async def test_localize_chunk_server_error(self, mock_post):
"""Test server error handling in chunk localization"""
mock_response = Mock()
mock_response.is_success = False
mock_response.status_code = 500
mock_response.reason_phrase = "Internal Server Error"
mock_response.text = "Server error details"
mock_post.return_value = mock_response
with pytest.raises(RuntimeError, match="Server error"):
await self.engine._localize_chunk(
"en", "es", {"data": {"key": "value"}}, "workflow_id", False
)
@patch("lingodotdev.engine.httpx.AsyncClient.post")
async def test_localize_chunk_bad_request(self, mock_post):
"""Test bad request handling in chunk localization"""
mock_response = Mock()
mock_response.is_success = False
mock_response.status_code = 400
mock_response.reason_phrase = "Bad Request"
mock_response.text = "Invalid parameters"
mock_post.return_value = mock_response
with pytest.raises(ValueError, match="Invalid request \\(400\\)"):
await self.engine._localize_chunk(
"en", "es", {"data": {"key": "value"}}, "workflow_id", False
)
@patch("lingodotdev.engine.httpx.AsyncClient.post")
async def test_localize_chunk_streaming_error(self, mock_post):
"""Test streaming error handling in chunk localization"""
mock_response = Mock()
mock_response.is_success = True
mock_response.json.return_value = {"error": "Streaming error occurred"}
mock_post.return_value = mock_response
with pytest.raises(RuntimeError, match="Streaming error occurred"):
await self.engine._localize_chunk(
"en", "es", {"data": {"key": "value"}}, "workflow_id", False
)
@patch("lingodotdev.engine.LingoDotDevEngine._localize_raw")
async def test_localize_text(self, mock_localize_raw):
"""Test text localization"""
mock_localize_raw.return_value = {"text": "translated_text"}
result = await self.engine.localize_text(
"hello world", {"source_locale": "en", "target_locale": "es"}
)
assert result == "translated_text"
mock_localize_raw.assert_called_once()
@patch("lingodotdev.engine.LingoDotDevEngine._localize_raw")
async def test_localize_object(self, mock_localize_raw):
"""Test object localization"""
mock_localize_raw.return_value = {"greeting": "hola", "farewell": "adiós"}
result = await self.engine.localize_object(
{"greeting": "hello", "farewell": "goodbye"},
{"source_locale": "en", "target_locale": "es"},
)
assert result == {"greeting": "hola", "farewell": "adiós"}
mock_localize_raw.assert_called_once()
@patch("lingodotdev.engine.LingoDotDevEngine.localize_text")
async def test_batch_localize_text(self, mock_localize_text):
"""Test batch text localization"""
mock_localize_text.side_effect = AsyncMock(side_effect=["hola", "bonjour"])
result = await self.engine.batch_localize_text(
"hello",
{"source_locale": "en", "target_locales": ["es", "fr"], "fast": True},
)
assert result == ["hola", "bonjour"]
assert mock_localize_text.call_count == 2
async def test_batch_localize_text_missing_target_locales(self):
"""Test batch text localization with missing target_locales"""
with pytest.raises(ValueError, match="target_locales is required"):
await self.engine.batch_localize_text("hello", {"source_locale": "en"})
@patch("lingodotdev.engine.LingoDotDevEngine._localize_raw")
async def test_localize_chat(self, mock_localize_raw):
"""Test chat localization"""
mock_localize_raw.return_value = {
"chat": [
{"name": "Alice", "text": "hola"},
{"name": "Bob", "text": "adiós"},
]
}
chat = [{"name": "Alice", "text": "hello"}, {"name": "Bob", "text": "goodbye"}]
result = await self.engine.localize_chat(
chat, {"source_locale": "en", "target_locale": "es"}
)
expected = [{"name": "Alice", "text": "hola"}, {"name": "Bob", "text": "adiós"}]
assert result == expected
mock_localize_raw.assert_called_once()
async def test_localize_chat_invalid_format(self):
"""Test chat localization with invalid message format"""
invalid_chat = [{"name": "Alice"}] # Missing 'text' key
with pytest.raises(
ValueError, match="Each chat message must have 'name' and 'text' properties"
):
await self.engine.localize_chat(
invalid_chat, {"source_locale": "en", "target_locale": "es"}
)
@patch("lingodotdev.engine.httpx.AsyncClient.post")
async def test_recognize_locale_success(self, mock_post):
"""Test successful locale recognition"""
mock_response = Mock()
mock_response.is_success = True
mock_response.json.return_value = {"locale": "es"}
mock_post.return_value = mock_response
result = await self.engine.recognize_locale("Hola mundo")
assert result == "es"
mock_post.assert_called_once()
async def test_recognize_locale_empty_text(self):
"""Test locale recognition with empty text"""
with pytest.raises(ValueError, match="Text cannot be empty"):
await self.engine.recognize_locale(" ")
@patch("lingodotdev.engine.httpx.AsyncClient.post")
async def test_recognize_locale_server_error(self, mock_post):
"""Test locale recognition with server error"""
mock_response = Mock()
mock_response.is_success = False
mock_response.status_code = 500
mock_response.reason_phrase = "Internal Server Error"
mock_response.text = "Server error details"
mock_post.return_value = mock_response
with pytest.raises(RuntimeError, match="Server error"):
await self.engine.recognize_locale("Hello world")
@patch("lingodotdev.engine.httpx.AsyncClient.post")
async def test_whoami_success(self, mock_post):
"""Test successful whoami request"""
mock_response = Mock()
mock_response.is_success = True
mock_response.json.return_value = {
"email": "test@example.com",
"id": "user_123",
}
mock_post.return_value = mock_response
result = await self.engine.whoami()
assert result == {"email": "test@example.com", "id": "user_123"}
mock_post.assert_called_once()
@patch("lingodotdev.engine.httpx.AsyncClient.post")
async def test_whoami_unauthenticated(self, mock_post):
"""Test whoami request when unauthenticated"""
mock_response = Mock()
mock_response.is_success = False
mock_response.status_code = 401
mock_post.return_value = mock_response
result = await self.engine.whoami()
assert result is None
@patch("lingodotdev.engine.httpx.AsyncClient.post")
async def test_whoami_server_error(self, mock_post):
"""Test whoami request with server error"""
mock_response = Mock()
mock_response.is_success = False
mock_response.status_code = 500
mock_response.reason_phrase = "Internal Server Error"
mock_response.text = "Server error details"
mock_post.return_value = mock_response
with pytest.raises(RuntimeError, match="Server error"):
await self.engine.whoami()
@patch("lingodotdev.engine.httpx.AsyncClient.post")
async def test_whoami_no_email(self, mock_post):
"""Test whoami request with no email in response"""
mock_response = Mock()
mock_response.is_success = True
mock_response.status_code = 200
mock_response.json.return_value = {}
mock_post.return_value = mock_response
result = await self.engine.whoami()
assert result is None
@patch("lingodotdev.engine.LingoDotDevEngine.localize_object")
async def test_batch_localize_objects(self, mock_localize_object):
"""Test batch object localization"""
mock_localize_object.side_effect = AsyncMock(
side_effect=[{"greeting": "hola"}, {"farewell": "adiós"}]
)
objects = [{"greeting": "hello"}, {"farewell": "goodbye"}]
params = {"source_locale": "en", "target_locale": "es"}
result = await self.engine.batch_localize_objects(objects, params)
assert result == [{"greeting": "hola"}, {"farewell": "adiós"}]
assert mock_localize_object.call_count == 2
async def test_concurrent_processing(self):
"""Test concurrent processing functionality"""
with patch(
"lingodotdev.engine.LingoDotDevEngine._localize_chunk"
) as mock_chunk:
mock_chunk.return_value = {"key": "value"}
large_payload = {f"key{i}": f"value{i}" for i in range(5)}
# Create mock params object (Python 3.8 compatible)
mock_params = type(
"MockParams",
(),
{
"source_locale": "en",
"target_locale": "es",
"fast": False,
"reference": None,
},
)()
# Test concurrent mode
await self.engine._localize_raw(
large_payload,
mock_params,
concurrent=True,
)
# Should have called _localize_chunk multiple times concurrently
assert mock_chunk.call_count > 0
@pytest.mark.asyncio
class TestIntegration:
"""Integration tests with mocked HTTP responses"""
def setup_method(self):
"""Set up test fixtures"""
self.config = {"api_key": "test_api_key", "api_url": "https://api.test.com"}
self.engine = LingoDotDevEngine(self.config)
@patch("lingodotdev.engine.httpx.AsyncClient.post")
async def test_full_localization_workflow(self, mock_post):
"""Test full localization workflow"""
# Mock the API response
mock_response = Mock()
mock_response.is_success = True
mock_response.json.return_value = {
"data": {"greeting": "hola", "farewell": "adiós"}
}
mock_post.return_value = mock_response
# Test object localization
result = await self.engine.localize_object(
{"greeting": "hello", "farewell": "goodbye"},
{"source_locale": "en", "target_locale": "es", "fast": True},
)
assert result == {"greeting": "hola", "farewell": "adiós"}
# Verify the API was called with correct parameters
mock_post.assert_called_once()
call_args = mock_post.call_args
assert call_args[0][0].endswith("/i18n")
request_data = call_args[1]["json"]
assert request_data["locale"]["source"] == "en"
assert request_data["locale"]["target"] == "es"
assert request_data["params"]["fast"] is True
assert request_data["data"] == {"greeting": "hello", "farewell": "goodbye"}
@pytest.mark.asyncio
class TestVNextEngine:
"""Test vNext / Engine ID specific behavior"""
def setup_method(self):
"""Set up test fixtures"""
self.config = {"api_key": "test_api_key", "engine_id": "my-engine-id"}
self.engine = LingoDotDevEngine(self.config)
def teardown_method(self):
"""Clean up engine client"""
if self.engine._client and not self.engine._client.is_closed:
asyncio.get_event_loop().run_until_complete(self.engine.close())
def test_engine_id_empty_string_treated_as_none(self):
"""Test that empty engine_id is treated as None"""
engine = LingoDotDevEngine({"api_key": "key", "engine_id": ""})
assert engine.config.engine_id is None
assert engine._is_vnext is False
assert engine.config.api_url == "https://engine.lingo.dev"
def test_engine_id_whitespace_treated_as_none(self):
"""Test that whitespace-only engine_id is treated as None"""
engine = LingoDotDevEngine({"api_key": "key", "engine_id": " "})
assert engine.config.engine_id is None
assert engine._is_vnext is False
assert engine.config.api_url == "https://engine.lingo.dev"
def test_engine_id_stripped(self):
"""Test that engine_id is stripped of whitespace"""
engine = LingoDotDevEngine({"api_key": "key", "engine_id": " eng_123 "})
assert engine.config.engine_id == "eng_123"
assert engine._is_vnext is True
def test_api_url_trailing_slash_stripped(self):
"""Test that trailing slash is stripped from api_url"""
engine = LingoDotDevEngine(
{
"api_key": "key",
"engine_id": "eng",
"api_url": "https://custom.api.com/",
}
)
assert engine.config.api_url == "https://custom.api.com"
def test_engine_id_default_api_url(self):
"""Test that engine_id switches default api_url to api.lingo.dev"""
assert self.engine.config.api_url == "https://api.lingo.dev"
assert self.engine.config.engine_id == "my-engine-id"
def test_engine_id_with_explicit_api_url(self):
"""Test that explicit api_url is preserved with engine_id"""
engine = LingoDotDevEngine(
{
"api_key": "key",
"engine_id": "eng",
"api_url": "https://custom.api.com",
}
)
assert engine.config.api_url == "https://custom.api.com"
def test_is_vnext_true(self):
"""Test _is_vnext is True with engine_id"""
assert self.engine._is_vnext is True
def test_is_vnext_false_without_engine_id(self):
"""Test _is_vnext is False without engine_id"""
engine = LingoDotDevEngine(
{"api_key": "key", "api_url": "https://api.test.com"}
)
assert engine._is_vnext is False
def test_session_id_generated(self):
"""Test that session_id is generated on init"""
assert self.engine._session_id
assert isinstance(self.engine._session_id, str)
async def test_vnext_ensure_client_uses_x_api_key(self):
"""Test that vNext engine uses X-API-Key header"""
await self.engine._ensure_client()
assert self.engine._client is not None
assert self.engine._client.headers.get("x-api-key") == "test_api_key"
assert "authorization" not in self.engine._client.headers
await self.engine.close()
async def test_classic_ensure_client_uses_bearer(self):
"""Test that classic engine uses Bearer auth header"""
engine = LingoDotDevEngine(
{"api_key": "test_key", "api_url": "https://api.test.com"}
)
await engine._ensure_client()
assert engine._client is not None
assert engine._client.headers.get("authorization") == "Bearer test_key"
assert "x-api-key" not in engine._client.headers
await engine.close()
@patch("lingodotdev.engine.httpx.AsyncClient.post")
async def test_vnext_localize_chunk_url_and_body(self, mock_post):
"""Test vNext localize chunk uses correct URL and body format"""
mock_response = Mock()
mock_response.is_success = True
mock_response.json.return_value = {"data": {"key": "translated"}}
mock_post.return_value = mock_response
await self.engine._localize_chunk(
"en",
"es",
{"data": {"key": "value"}, "reference": {"es": {"key": "ref"}}},
"wf",
True,
)
call_args = mock_post.call_args
url = call_args[0][0]
assert url == "https://api.lingo.dev/process/my-engine-id/localize"
body = call_args[1]["json"]
assert body["sourceLocale"] == "en"
assert body["targetLocale"] == "es"
assert body["params"] == {"fast": True}
assert body["data"] == {"key": "value"}
assert body["sessionId"] == self.engine._session_id
assert body["reference"] == {"es": {"key": "ref"}}
@patch("lingodotdev.engine.httpx.AsyncClient.post")
async def test_vnext_recognize_locale_url(self, mock_post):
"""Test vNext recognize_locale uses correct URL"""
mock_response = Mock()
mock_response.is_success = True
mock_response.json.return_value = {"locale": "es"}
mock_post.return_value = mock_response
await self.engine.recognize_locale("Hola mundo")
url = mock_post.call_args[0][0]
assert url == "https://api.lingo.dev/process/recognize"
@patch("lingodotdev.engine.httpx.AsyncClient.get")
async def test_vnext_whoami(self, mock_get):
"""Test vNext whoami calls GET /users/me"""
mock_response = Mock()
mock_response.is_success = True
mock_response.json.return_value = {"id": "usr_abc", "email": "user@example.com"}
mock_get.return_value = mock_response
result = await self.engine.whoami()
assert result == {"email": "user@example.com", "id": "usr_abc"}
url = mock_get.call_args[0][0]
assert url == "https://api.lingo.dev/users/me"
@patch("lingodotdev.engine.httpx.AsyncClient.post")
async def test_vnext_full_localization_workflow(self, mock_post):
"""Test full vNext localization workflow via localize_object"""
mock_response = Mock()
mock_response.is_success = True
mock_response.json.return_value = {"data": {"greeting": "hola"}}
mock_post.return_value = mock_response
result = await self.engine.localize_object(
{"greeting": "hello"},
{"source_locale": "en", "target_locale": "es", "fast": True},
)
assert result == {"greeting": "hola"}
call_args = mock_post.call_args
url = call_args[0][0]
assert url == "https://api.lingo.dev/process/my-engine-id/localize"
body = call_args[1]["json"]
assert body["sourceLocale"] == "en"
assert body["targetLocale"] == "es"
assert "sessionId" in body
assert "locale" not in body # classic format should NOT be present