|
| 1 | +import pytest |
| 2 | +import json |
| 3 | +from unittest.mock import Mock, patch |
| 4 | +from lingodotdev import LingoDotDevEngine |
| 5 | + |
| 6 | + |
| 7 | +@pytest.mark.asyncio |
| 8 | +async def test_502_html_handling(): |
| 9 | + """Test that 502 errors with HTML bodies are sanitized""" |
| 10 | + config = {"api_key": "test_key", "api_url": "https://api.test.com"} |
| 11 | + |
| 12 | + html_body = "<html><body>" + ("<h1>502 Bad Gateway</h1>" * 50) + "</body></html>" |
| 13 | + assert len(html_body) > 200 # Ensure it triggers truncation |
| 14 | + |
| 15 | + with patch("lingodotdev.engine.httpx.AsyncClient.post") as mock_post: |
| 16 | + mock_response = Mock() |
| 17 | + mock_response.is_success = False |
| 18 | + mock_response.status_code = 502 |
| 19 | + mock_response.reason_phrase = "Bad Gateway" |
| 20 | + mock_response.text = html_body |
| 21 | + mock_response.json.side_effect = ValueError( |
| 22 | + "Not JSON" |
| 23 | + ) # simulating non-JSON response |
| 24 | + mock_post.return_value = mock_response |
| 25 | + |
| 26 | + async with LingoDotDevEngine(config) as engine: |
| 27 | + with pytest.raises(RuntimeError) as exc_info: |
| 28 | + await engine.localize_text("hello", {"target_locale": "es"}) |
| 29 | + |
| 30 | + error_msg = str(exc_info.value) |
| 31 | + |
| 32 | + # Assertions |
| 33 | + assert "Server error (502): Bad Gateway." in error_msg |
| 34 | + assert "This may be due to temporary service issues." in error_msg |
| 35 | + assert "Response:" not in error_msg |
| 36 | + assert "<html>" not in error_msg |
| 37 | + assert "<body>" not in error_msg |
| 38 | + |
| 39 | + |
| 40 | +@pytest.mark.asyncio |
| 41 | +async def test_500_json_handling(): |
| 42 | + """Test that 500 errors with JSON bodies are preserved""" |
| 43 | + config = {"api_key": "test_key", "api_url": "https://api.test.com"} |
| 44 | + error_json = {"error": "Specific internal error message"} |
| 45 | + |
| 46 | + with patch("lingodotdev.engine.httpx.AsyncClient.post") as mock_post: |
| 47 | + mock_response = Mock() |
| 48 | + mock_response.is_success = False |
| 49 | + mock_response.status_code = 500 |
| 50 | + mock_response.reason_phrase = "Internal Server Error" |
| 51 | + mock_response.text = json.dumps(error_json) # Needed for response_preview |
| 52 | + mock_response.json.return_value = error_json |
| 53 | + mock_post.return_value = mock_response |
| 54 | + |
| 55 | + async with LingoDotDevEngine(config) as engine: |
| 56 | + with pytest.raises(RuntimeError) as exc_info: |
| 57 | + await engine.localize_text("hello", {"target_locale": "es"}) |
| 58 | + |
| 59 | + error_msg = str(exc_info.value) |
| 60 | + |
| 61 | + # Assertions |
| 62 | + assert "Server error (500): Internal Server Error." in error_msg |
| 63 | + assert "Specific internal error message" in error_msg |
0 commit comments