From 3dc5d34c2336e906b6b3ac1e0bdfce389970da04 Mon Sep 17 00:00:00 2001 From: Wil Clouser Date: Wed, 3 Mar 2010 14:03:20 -0800 Subject: [PATCH] Add lazy gettext functions --- lib/l10n/__init__.py | 4 ++++ lib/l10n/tests/tests.py | 28 ++++++++++++++++++++++++++++ 2 files changed, 32 insertions(+) diff --git a/lib/l10n/__init__.py b/lib/l10n/__init__.py index caa15c65af..43fb09d3b6 100644 --- a/lib/l10n/__init__.py +++ b/lib/l10n/__init__.py @@ -2,6 +2,7 @@ import gettext import re from django.conf import settings +from django.utils.functional import lazy from django.utils.importlib import import_module from django.utils.thread_support import currentThread from django.utils.translation import (trans_real as django_trans, @@ -42,6 +43,9 @@ def ungettext(singular, plural, number, context=None): return plural_stripped return ret +ugettext_lazy = lazy(ugettext, unicode) +ungettext_lazy = lazy(ungettext, unicode) + def _add_context(context, message): # \x04 is a magic gettext number. diff --git a/lib/l10n/tests/tests.py b/lib/l10n/tests/tests.py index 47d7ff8eba..73b604051c 100644 --- a/lib/l10n/tests/tests.py +++ b/lib/l10n/tests/tests.py @@ -9,10 +9,24 @@ from nose.tools import eq_ import l10n from l10n import ugettext as _, ungettext as n_ +from l10n import ugettext_lazy as _lazy, ungettext_lazy as n_lazy LOCALEDIR = os.path.join('locale', 'xx') MOFILE = os.path.join(LOCALEDIR, 'LC_MESSAGES', 'messages.mo') +# Used for the _lazy() tests +_lazy_strings = {} +_lazy_strings['nocontext'] = _lazy('this is a test') +_lazy_strings['context'] = _lazy('What time is it?', 'context_one') + +n_lazy_strings = {} +n_lazy_strings['s_nocontext'] = n_lazy('one light !', 'many lights !', 1) +n_lazy_strings['p_nocontext'] = n_lazy('one light !', 'many lights !', 3) +n_lazy_strings['s_context'] = n_lazy('%d poodle please', '%d poodles please', + 1, 'context_one') +n_lazy_strings['p_context'] = n_lazy('%d poodle please', '%d poodles please', + 3, 'context_one') + def setup(): if not os.path.isdir(os.path.join(LOCALEDIR, 'LC_MESSAGES')): @@ -84,6 +98,20 @@ def test_ungettext_not_found(): eq_('yo yos', n_('yo', ' yo yos ', 3, 'context')) +@with_setup(setup, teardown) +def test_ugettext_lazy(): + eq_(unicode(_lazy_strings['nocontext']), 'you ran a test!') + eq_(unicode(_lazy_strings['context']), 'What time is it? (context=1)') + + +@with_setup(setup, teardown) +def test_ungettext_lazy(): + eq_(unicode(n_lazy_strings['s_nocontext']), 'you found a light!') + eq_(unicode(n_lazy_strings['p_nocontext']), 'you found a pile of lights!') + eq_(unicode(n_lazy_strings['s_context']), '%d poodle (context=1)') + eq_(unicode(n_lazy_strings['p_context']), '%d poodles (context=1)') + + def test_activate(): l10n.deactivate_all() l10n.activate('fr')