1
0
Fork 0
forked from github/pelican

Add unit test utilities temporary_locale and TestCaseWithCLocale (#3224)

This commit is contained in:
boxydog 2023-10-28 17:40:40 -05:00 committed by GitHub
commit fad2ff7ae3
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
5 changed files with 111 additions and 119 deletions

View file

@ -116,18 +116,14 @@ class DateFormatter:
self.locale = locale.setlocale(locale.LC_TIME)
def __call__(self, date, date_format):
old_lc_time = locale.setlocale(locale.LC_TIME)
old_lc_ctype = locale.setlocale(locale.LC_CTYPE)
locale.setlocale(locale.LC_TIME, self.locale)
# on OSX, encoding from LC_CTYPE determines the unicode output in PY3
# make sure it's same as LC_TIME
locale.setlocale(locale.LC_CTYPE, self.locale)
with temporary_locale(self.locale, locale.LC_TIME), \
temporary_locale(self.locale, locale.LC_CTYPE):
formatted = strftime(date, date_format)
formatted = strftime(date, date_format)
locale.setlocale(locale.LC_TIME, old_lc_time)
locale.setlocale(locale.LC_CTYPE, old_lc_ctype)
return formatted
@ -872,3 +868,19 @@ def maybe_pluralize(count, singular, plural):
if count == 1:
selection = singular
return '{} {}'.format(count, selection)
@contextmanager
def temporary_locale(temp_locale=None, lc_category=locale.LC_ALL):
'''
Enable code to run in a context with a temporary locale
Resets the locale back when exiting context.
Use tests.support.TestCaseWithCLocale if you want every unit test in a
class to use the C locale.
'''
orig_locale = locale.setlocale(lc_category)
if temp_locale:
locale.setlocale(lc_category, temp_locale)
yield
locale.setlocale(lc_category, orig_locale)