Skip to content

Commit

Permalink
Use default language if none match accept-language
Browse files Browse the repository at this point in the history
Fix bug 1752823
  • Loading branch information
pmac committed Jan 31, 2022
1 parent 0192b33 commit a57449e
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 2 deletions.
13 changes: 12 additions & 1 deletion lib/l10n_utils/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,10 @@ def get_best_translation(translations, accept_languages):
"""
lang_map = _get_language_map()
# translations contains mixed-case items e.g. "en-US" while the keys
# of `lang_map` are all lowercase. But this works because the values
# of the `lang_map` dict are mixed-case like translations and the
# comparison below is with the values.
valid_lang_map = {k: v for k, v in lang_map.items() if v in translations}
for lang in accept_languages:
lang.lower()
Expand All @@ -179,7 +183,14 @@ def get_best_translation(translations, accept_languages):
if pre in valid_lang_map:
return valid_lang_map[pre]

return lang_map[translations[0].lower()]
# If all the attempts failed, just use en-US, the default locale of
# the site, if it is an available translation.
if settings.LANGUAGE_CODE in translations:
return settings.LANGUAGE_CODE

# In the rare case the default language isn't in the list, return the
# first translation in the valid_lang_map.
return list(valid_lang_map.values())[0]


def get_translations_native_names(locales):
Expand Down
7 changes: 6 additions & 1 deletion lib/l10n_utils/tests/test_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
# file, You can obtain one at https://mozilla.org/MPL/2.0/.

import os
from unittest.mock import ANY, call, patch
from unittest.mock import ANY, Mock, call, patch

from django.test import TestCase
from django.test.client import RequestFactory
Expand Down Expand Up @@ -168,6 +168,7 @@ def test_ftl_activations(self, render_mock):
render_mock.assert_called_with(self.req, ["dude.html"], ANY, ftl_files="dude", activation_files=["dude", "donny"])


@patch.object(l10n_utils, "_get_language_map", Mock(return_value={"an": "an", "de": "de", "en": "en-US", "en-us": "en-US", "fr": "fr"}))
@pytest.mark.parametrize(
"translations, accept_languages, expected",
(
Expand All @@ -184,6 +185,10 @@ def test_ftl_activations(self, render_mock):
(["en-US", "de"], ["de", "en-US"], "de"),
(["en-US", "de", "fr"], ["fr", "de"], "fr"),
(["en-US", "de", "fr"], ["en-CA", "fr", "de"], "en-US"),
# A request for only inactive translations should default to 'en-US'. Bug 1752823
(["am", "an", "en-US"], ["mk", "gu-IN"], "en-US"),
# "am" is not a valid language in the list of PROD_LANGUAGES
(["am", "an"], ["mk", "gu-IN"], "an"),
),
)
def test_get_best_translation(translations, accept_languages, expected):
Expand Down

0 comments on commit a57449e

Please sign in to comment.