Skip to content

Commit

Permalink
json: improved error messages on invalid data
Browse files Browse the repository at this point in the history
  • Loading branch information
nijel committed Jan 26, 2024
1 parent 1ff9d3e commit 53851f1
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 10 deletions.
10 changes: 10 additions & 0 deletions tests/translate/storage/test_jsonl10n.py
Original file line number Diff line number Diff line change
Expand Up @@ -1178,6 +1178,11 @@ def test_plurals_missing(self):

assert '"other": ""' in bytes(store).decode()

def test_invalid(self):
store = self.StoreClass()
with raises(ValueError):
store.parse(JSON_I18NEXT_PLURAL)


class TestGoI18NV2JsonFile(test_monolingual.TestMonolingualStore):
StoreClass = jsonl10n.GoI18NV2JsonFile
Expand Down Expand Up @@ -1240,6 +1245,11 @@ def test_simplification(self):

assert bytes(store).decode() == JSON_GOI18N_V2_SIMPLE

def test_invalid(self):
store = self.StoreClass()
with raises(ValueError):
store.parse(JSON_I18NEXT_PLURAL)


class TestARBJsonFile(test_monolingual.TestMonolingualStore):
StoreClass = jsonl10n.ARBJsonFile
Expand Down
38 changes: 28 additions & 10 deletions translate/storage/jsonl10n.py
Original file line number Diff line number Diff line change
Expand Up @@ -694,17 +694,26 @@ def _extract_units(
name_last_node=None,
last_node=None,
):
if not isinstance(data, list):
raise ValueError( # noqa: TRY004
"Missing top-level array. Maybe this is not a go-i18n JSON file?"
)
for value in data:
translation = value.get("translation", "")
if isinstance(translation, dict):
# Ordered list of plurals
translation = multistring(
[
translation.get(key)
for key in cldr_plural_categories
if key in translation
]
)
try:
translation = multistring(
[
translation.get(key)
for key in cldr_plural_categories
if key in translation
]
)
except ValueError:
raise ValueError(
f'"{id}" is an object but does not contain plurals. Maybe this is not a go-i18n JSON file?'
)
unit = self.UnitClass(
translation,
value.get("id", ""),
Expand Down Expand Up @@ -767,9 +776,18 @@ def _extract_units(
if isinstance(value, str):
unit = self.UnitClass(value, id)
else:
translation = multistring(
[value.get(key) for key in cldr_plural_categories if key in value]
)
try:
translation = multistring(
[
value.get(key)
for key in cldr_plural_categories
if key in value
]
)
except ValueError:
raise ValueError(
f'"{id}" is an object but does not contain plurals. Maybe this is not a go-i18n v2 JSON file?'
)
unit = self.UnitClass(
translation,
id,
Expand Down

0 comments on commit 53851f1

Please sign in to comment.