Skip to content

Commit

Permalink
Added django.utils.translation.override context manager to easily act…
Browse files Browse the repository at this point in the history
…ivate and deactivate a language for a code block.

git-svn-id: http://code.djangoproject.com/svn/django/trunk@16166 bcc190cf-cafb-0310-a4f2-bffc1f526a37
  • Loading branch information
jezdez committed May 6, 2011
1 parent 0dc6420 commit 71ec87f
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 0 deletions.
15 changes: 15 additions & 0 deletions django/utils/translation/__init__.py
Expand Up @@ -102,6 +102,21 @@ def activate(language):
def deactivate():
return _trans.deactivate()

class override(object):
def __init__(self, language, deactivate=False):
self.language = language
self.deactivate = deactivate
self.old_language = get_language()

def __enter__(self):
activate(self.language)

def __exit__(self, exc_type, exc_value, traceback):
if self.deactivate:
deactivate()
else:
activate(self.old_language)

def get_language():
return _trans.get_language()

Expand Down
8 changes: 8 additions & 0 deletions tests/regressiontests/i18n/tests.py
Expand Up @@ -8,6 +8,7 @@

from django.conf import settings
from django.template import Template, Context
from django.test import TestCase
from django.utils.formats import (get_format, date_format, time_format,
localize, localize_input, iter_format_modules, get_format_modules)
from django.utils.importlib import import_module
Expand All @@ -28,6 +29,13 @@

class TranslationTests(TestCase):

def test_override(self):
activate('de')
with translation.override('pl'):
self.assertEqual(get_language(), 'pl')
self.assertEqual(get_language(), 'de')
deactivate()

def test_lazy_objects(self):
"""
Format string interpolation should work with *_lazy objects.
Expand Down

0 comments on commit 71ec87f

Please sign in to comment.