Added request.create_translation() function and corresponding unit tests

This commit is contained in:
Jason Gerard DeRose
2008-12-18 16:58:48 -07:00
parent dc54dee622
commit 9a69adeef0
2 changed files with 59 additions and 7 deletions

View File

@@ -28,15 +28,10 @@ import gettext
from constants import OVERRIDE_ERROR
# Thread-local storage of most per-request contextrmation
# Thread-local storage of most per-request information
context = threading.local()
# Thread-local storage of gettext.Translations instances (one per gettext
# domain):
translations = threading.local()
def set_languages(*languages):
if hasattr(context, 'languages'):
raise StandardError(
@@ -46,3 +41,17 @@ def set_languages(*languages):
languages = locale.getdefaultlocale()[:1]
context.languages = languages
assert type(context.languages) is tuple
def create_translation(domain, localedir, *languages):
if hasattr(context, 'gettext') or hasattr(context, 'ngettext'):
raise StandardError(
'create_translation() already called in thread %r' %
threading.currentThread().getName()
)
set_languages(*languages)
translation = gettext.translation(domain,
localedir=localedir, languages=context.languages, fallback=True
)
context.gettext = translation.ugettext
context.ngettext = translation.ungettext

View File

@@ -21,8 +21,9 @@
Test the `ipalib.request` module.
"""
import threading
import locale
from tests.util import raises
from tests.util import raises, TempDir
from ipalib.constants import OVERRIDE_ERROR
from ipalib import request
@@ -54,3 +55,45 @@ def test_set_languages():
assert c.languages == locale.getdefaultlocale()[:1]
del c.languages
assert not hasattr(c, 'languages')
def test_create_translation():
"""
Test the `ipalib.request.create_translation` function.
"""
f = request.create_translation
c = request.context
t = TempDir()
# Test that StandardError is raised if gettext or ngettext:
assert not (hasattr(c, 'gettext') or hasattr(c, 'ngettext'))
for name in 'gettext', 'ngettext':
setattr(c, name, None)
e = raises(StandardError, f, 'ipa', None)
assert str(e) == (
'create_translation() already called in thread %r' %
threading.currentThread().getName()
)
delattr(c, name)
# Test using default language:
assert not hasattr(c, 'gettext')
assert not hasattr(c, 'ngettext')
assert not hasattr(c, 'languages')
f('ipa', t.path)
assert hasattr(c, 'gettext')
assert hasattr(c, 'ngettext')
assert c.languages == locale.getdefaultlocale()[:1]
del c.gettext
del c.ngettext
del c.languages
# Test using explicit languages:
langs = ('de', 'es')
f('ipa', t.path, *langs)
assert hasattr(c, 'gettext')
assert hasattr(c, 'ngettext')
assert c.languages == langs
del c.gettext
del c.ngettext
del c.languages