11import pytest
2+ import json
23from unittest .mock import Mock , patch
34from lingodotdev import LingoDotDevEngine
45
78async def test_502_html_handling ():
89 """Test that 502 errors with HTML bodies are sanitized"""
910 config = {"api_key" : "test_key" , "api_url" : "https://api.test.com" }
10- engine = LingoDotDevEngine (config )
1111
12- html_body = """<html><body><h1>502 Bad Gateway</h1></body></html>"""
12+ html_body = "<html><body>" + ("<h1>502 Bad Gateway</h1>" * 50 ) + "</body></html>"
13+ assert len (html_body ) > 200 # Ensure it triggers truncation
1314
1415 with patch ("lingodotdev.engine.httpx.AsyncClient.post" ) as mock_post :
1516 mock_response = Mock ()
@@ -22,36 +23,38 @@ async def test_502_html_handling():
2223 ) # simulating non-JSON response
2324 mock_post .return_value = mock_response
2425
25- with pytest .raises (RuntimeError ) as exc_info :
26- await engine .localize_text ("hello" , {"target_locale" : "es" })
26+ async with LingoDotDevEngine (config ) as engine :
27+ with pytest .raises (RuntimeError ) as exc_info :
28+ await engine .localize_text ("hello" , {"target_locale" : "es" })
2729
2830 error_msg = str (exc_info .value )
2931
3032 # Assertions
3133 assert "Server error (502): Bad Gateway." in error_msg
3234 assert "This may be due to temporary service issues." in error_msg
33- assert "<html>" not in error_msg
34- assert "<body>" not in error_msg
35+ assert "Response:" in error_msg # Verify preview is present
36+ assert len (error_msg ) < len (html_body ) # Verify truncation happened
37+ assert "<html>" in error_msg # Accept that the start of HTML is in the preview
3538
3639
3740@pytest .mark .asyncio
3841async def test_500_json_handling ():
3942 """Test that 500 errors with JSON bodies are preserved"""
4043 config = {"api_key" : "test_key" , "api_url" : "https://api.test.com" }
41- engine = LingoDotDevEngine (config )
42-
4344 error_json = {"error" : "Specific internal error message" }
4445
4546 with patch ("lingodotdev.engine.httpx.AsyncClient.post" ) as mock_post :
4647 mock_response = Mock ()
4748 mock_response .is_success = False
4849 mock_response .status_code = 500
4950 mock_response .reason_phrase = "Internal Server Error"
51+ mock_response .text = json .dumps (error_json ) # Needed for response_preview
5052 mock_response .json .return_value = error_json
5153 mock_post .return_value = mock_response
5254
53- with pytest .raises (RuntimeError ) as exc_info :
54- await engine .localize_text ("hello" , {"target_locale" : "es" })
55+ async with LingoDotDevEngine (config ) as engine :
56+ with pytest .raises (RuntimeError ) as exc_info :
57+ await engine .localize_text ("hello" , {"target_locale" : "es" })
5558
5659 error_msg = str (exc_info .value )
5760
0 commit comments