Skip to content

Commit

Permalink
Don't quietly use English strings when we fail to load translation file.
Browse files Browse the repository at this point in the history
Fixes #177.
  • Loading branch information
eggpi committed Mar 7, 2022
1 parent 89a3647 commit 79c2bea
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 4 deletions.
11 changes: 8 additions & 3 deletions chstrings/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -159,11 +159,16 @@ def _load_strings_for_lang_tag(lang_tag):
return json.load(json_fp)

def get_localized_strings(config, lang_tag):
strings = _load_strings_for_lang_tag(config.fallback_lang_tag)
localized_strings = {}
try:
strings.update(_load_strings_for_lang_tag(lang_tag))
localized_strings = _load_strings_for_lang_tag(lang_tag)
except:
pass
return localized_strings

# Complete the strings with the fallback in case of incomplete
# translations, but only if there is a translation at all.
strings = _load_strings_for_lang_tag(config.fallback_lang_tag)
strings.update(localized_strings)
strings = _preprocess_variables(config, strings)
_partition_js_strings(strings)
return strings
9 changes: 9 additions & 0 deletions chstrings/chstrings_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,15 @@ def _load_strings_side_effect(lang_tag):
self.assertEqual(fallback_strings['instructions_goal'],
strings['instructions_goal'])

def test_missing_lang_tag_has_no_fallback(self):
# We must only apply the fallback strings if there is an incomplete
# strings file (test_fallback_lang_tag exercises that behavior).
# If the file does not exist at all, we must return {} rather than just
# the fallback strings.
self.assertEqual(
chstrings.get_localized_strings(cfg, 'fake'), {})


if __name__ == '__main__':
for lc in config.LANG_CODES_TO_LANG_NAMES:
cfg = config.get_localized_config(lc, api = False)
Expand Down
2 changes: 1 addition & 1 deletion handlers/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ def load_strings_for_request(lang_code, cfg, accept_language_hdr):
header_locales = accept_language_hdr.split(',')
for l in header_locales:
lang_tag = l.split(';', 1)[0] # drop weight, if any
lang = l.split('-', 1)[0] # en-GB -> en
lang = l.split('-', 1)[0] # en-GB -> en

lang_tag_matches_config = (
lang == lang_code or
Expand Down

0 comments on commit 79c2bea

Please sign in to comment.