Skip to content

Commit ce262fc

Browse files
hive-botclaude
andcommitted
fix: raise DeepLException when translate_text() gets too few translations
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent a149a50 commit ce262fc

3 files changed

Lines changed: 25 additions & 0 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -138,6 +138,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
138138
- Fixed `translate_text()` raising `TypeError` when a translation in the
139139
response has no `billed_characters`. `TextResult.billed_characters` is now
140140
`None` in that case.
141+
- Fixed `translate_text()` raising `IndexError` when the response holds fewer
142+
translations than texts sent. It now raises `DeepLException`.
141143
- Fixed the `DeprecationWarning` messages of `Usage.Detail.limit_exceeded` and
142144
`Usage.any_limit_exceeded`, which named the replacement instead of the
143145
deprecated property. They now read "limit_exceeded is deprecated, use

‎deepl/translator.py‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -428,6 +428,7 @@ def translate_text(
428428
raise TypeError(
429429
"text parameter must be a string or an iterable of strings"
430430
)
431+
text_count = len(text)
431432

432433
request_data = self._check_language_and_formality(
433434
source_lang,
@@ -517,6 +518,12 @@ def join_tags(tag_argument: Union[str, Iterable[str]]) -> List[str]:
517518
)
518519
)
519520

521+
if len(output) < text_count:
522+
raise DeepLException(
523+
f"Expected {text_count} translations in the response, "
524+
f"received {len(output)}"
525+
)
526+
520527
return output if multi_input else output[0]
521528

522529
def translate_text_with_glossary(

‎tests/offline/test_translate_text.py‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ def reply_with_translation(mocked, body):
2828
"billed_characters": 5,
2929
}
3030
]
31+
* len(body["text"])
3132
},
3233
match=json_request(body),
3334
)
@@ -367,6 +368,21 @@ def test_parses_tag_handling_version(mocked, translation, expected):
367368
assert result.tag_handling_version == expected
368369

369370

371+
@pytest.mark.parametrize(
372+
"text, response",
373+
[
374+
("hello", {"translations": []}),
375+
("hello", {}),
376+
(["x", "y"], {"translations": [{"text": "a"}]}),
377+
],
378+
)
379+
def test_raises_when_response_has_too_few_translations(mocked, text, response):
380+
mocked.post(url("v2/translate"), json=response)
381+
382+
with pytest.raises(deepl.DeepLException, match="translations"):
383+
make_translator().translate_text(text, target_lang="DE")
384+
385+
370386
def test_parses_text_list_into_list_of_results(mocked):
371387
mocked.post(
372388
url("v2/translate"),

0 commit comments

Comments
 (0)