def temporary_string_store(fake_locales, broken=False): """ with temporary_string_store(fake_locales) as store: string = store.lookup(locale, key, fallback) Make a LazyLocalisedStringStore initialised to work from a temporary directory of locale.json files, which will be emptied out and deleted after the with statement. :param fake_locales: dict of {locale:{key:value}} :param broken: true to generate invalid JSON :return: a ptrans.LazyLocalisedStringStore """ dirpath = tempfile.mkdtemp() files_to_delete = [] for locale in fake_locales: filename = os.path.join(dirpath, locale + ".json") files_to_delete.append(filename) with open(filename, "w", encoding="utf-8") as f: if broken: f.write("#this is not valid JSON#") else: json.dump(fake_locales[locale], f) store = ptrans.LazyLocalisedStringStore(dirpath) yield store for filename in files_to_delete: os.unlink(filename) os.rmdir(dirpath)
def test_locale_hook_works(): string_store = ptrans.LazyLocalisedStringStore(locale_hook=locale_hook) assert_equals(string_store.lookup("en-gb", "hello", "FAIL"), "hello") assert_equals(string_store.lookup("es-MX", "hello", "FAIL"), "hola") assert_equals(string_store.lookup("fr-FR", "hello", "hello"), "bonjour")
def test_locale_hook_called_again_if_no_results(): string_store = ptrans.LazyLocalisedStringStore(locale_hook=locale_hook) assert_equals(string_store.lookup("de-DE", "hello", "hello"), "hello") string_store.install_locale_hook(explode) assert_raises(ValueError, string_store.lookup, "de-DE", "anything", "whatever")
def test_locale_hook_only_called_once(): string_store = ptrans.LazyLocalisedStringStore(locale_hook=locale_hook) assert_equals(string_store.lookup("en-gb", "hello", "FAIL"), "hello") string_store.install_locale_hook(explode) assert_equals(string_store.lookup("en-gb", "goodbye", "goodbye"), "goodbye") # didn't explode
def test_fallback_to_base_language(): string_store = ptrans.LazyLocalisedStringStore(locale_hook=locale_hook) assert_equals(string_store.lookup("fr-CH", "hello", "FAIL"), "FAIL") # no fr-CH locale assert_equals(string_store.lookup("fr-FR", "hello", "FAIL"), "bonjour") # fr-FR is OK assert_equals(string_store.lookup("fr", "hello", "FAIL"), "bonjour") # base fr language works now assert_equals(string_store.lookup("fr-CH", "hello", "FAIL"), "bonjour") # so does fr-CH which falls back to it
def fake_string_store(fake_locales, allow_empty=False): store = ptrans.LazyLocalisedStringStore(allow_empty=allow_empty) store.locales = fake_locales.copy() return store