| 1 |
#!/usr/bin/env python |
| 2 |
|
| 3 |
|
| 4 |
import unittest |
| 5 |
from unittest import mock |
| 6 |
|
| 7 |
from mkdocs.config.base import ValidationError |
| 8 |
from mkdocs.localization import install_translations, parse_locale |
| 9 |
from mkdocs.tests.base import tempdir |
| 10 |
|
| 11 |
|
| 12 |
class LocalizationTests(unittest.TestCase): |
| 13 |
def setUp(self): |
| 14 |
self.env = mock.Mock() |
| 15 |
|
| 16 |
def test_jinja_extension_installed(self): |
| 17 |
install_translations(self.env, parse_locale('en'), []) |
| 18 |
self.env.add_extension.assert_called_once_with('jinja2.ext.i18n') |
| 19 |
|
| 20 |
def test_valid_language(self): |
| 21 |
locale = parse_locale('en') |
| 22 |
self.assertEqual(locale.language, 'en') |
| 23 |
|
| 24 |
def test_valid_language_territory(self): |
| 25 |
locale = parse_locale('en_US') |
| 26 |
self.assertEqual(locale.language, 'en') |
| 27 |
self.assertEqual(locale.territory, 'US') |
| 28 |
self.assertEqual(str(locale), 'en_US') |
| 29 |
|
| 30 |
def test_unknown_locale(self): |
| 31 |
self.assertRaises(ValidationError, parse_locale, 'foo') |
| 32 |
|
| 33 |
def test_invalid_locale(self): |
| 34 |
self.assertRaises(ValidationError, parse_locale, '42') |
| 35 |
|
| 36 |
@tempdir() |
| 37 |
def test_no_translations_found(self, dir_without_translations): |
| 38 |
with self.assertLogs('mkdocs') as cm: |
| 39 |
install_translations(self.env, parse_locale('fr_CA'), [dir_without_translations]) |
| 40 |
self.assertEqual( |
| 41 |
'\n'.join(cm.output), |
| 42 |
"WARNING:mkdocs.localization:No translations could be found for the locale 'fr_CA'. " |
| 43 |
"Defaulting to English.", |
| 44 |
) |
| 45 |
self.env.install_null_translations.assert_called_once() |
| 46 |
|
| 47 |
@tempdir() |
| 48 |
def test_translations_found(self, tdir): |
| 49 |
translations = mock.Mock() |
| 50 |
|
| 51 |
with mock.patch('mkdocs.localization.Translations.load', return_value=translations): |
| 52 |
install_translations(self.env, parse_locale('en'), [tdir]) |
| 53 |
|
| 54 |
self.env.install_gettext_translations.assert_called_once_with(translations) |
| 55 |
|
| 56 |
@tempdir() |
| 57 |
@tempdir() |
| 58 |
def test_merge_translations(self, custom_dir, theme_dir): |
| 59 |
custom_dir_translations = mock.Mock() |
| 60 |
theme_dir_translations = mock.Mock() |
| 61 |
|
| 62 |
def side_effet(*args, **kwargs): |
| 63 |
dirname = args[0] |
| 64 |
if dirname.startswith(custom_dir): |
| 65 |
return custom_dir_translations |
| 66 |
elif dirname.startswith(theme_dir): |
| 67 |
return theme_dir_translations |
| 68 |
else: |
| 69 |
self.fail() |
| 70 |
|
| 71 |
with mock.patch('mkdocs.localization.Translations.load', side_effect=side_effet): |
| 72 |
install_translations(self.env, parse_locale('en'), [custom_dir, theme_dir]) |
| 73 |
|
| 74 |
theme_dir_translations.merge.assert_called_once_with(custom_dir_translations) |