Make use of new translation and settings context manager in the tests.

git-svn-id: http://code.djangoproject.com/svn/django/trunk@16167 bcc190cf-cafb-0310-a4f2-bffc1f526a37
This commit is contained in:
Jannis Leidel 2011-05-06 13:29:44 +00:00
parent 71ec87fed8
commit 7dd72360a2
7 changed files with 240 additions and 347 deletions

View File

@ -22,12 +22,11 @@ from django.forms.util import ErrorList
import django.template.context
from django.template.response import TemplateResponse
from django.test import TestCase
from django.utils import formats
from django.utils import formats, translation
from django.utils.cache import get_max_age
from django.utils.encoding import iri_to_uri
from django.utils.html import escape
from django.utils.http import urlencode
from django.utils.translation import activate, deactivate
from django.utils import unittest
# local test models
@ -361,42 +360,31 @@ class AdminViewBasicTest(TestCase):
if the default language is non-English but the selected language
is English. See #13388 and #3594 for more details.
"""
try:
settings.LANGUAGE_CODE = 'fr'
activate('en-us')
with self.settings(LANGUAGE_CODE='fr'):
with translation.override('en-us'):
response = self.client.get('/test_admin/admin/jsi18n/')
self.assertNotContains(response, 'Choisir une heure')
finally:
deactivate()
def testI18NLanguageNonEnglishFallback(self):
"""
Makes sure that the fallback language is still working properly
in cases where the selected language cannot be found.
"""
try:
settings.LANGUAGE_CODE = 'fr'
activate('none')
with self.settings(LANGUAGE_CODE='fr'):
with translation.override('none'):
response = self.client.get('/test_admin/admin/jsi18n/')
self.assertContains(response, 'Choisir une heure')
finally:
deactivate()
def testL10NDeactivated(self):
"""
Check if L10N is deactivated, the Javascript i18n view doesn't
return localized date/time formats. Refs #14824.
"""
try:
settings.LANGUAGE_CODE = 'ru'
settings.USE_L10N = False
activate('ru')
with self.settings(LANGUAGE_CODE='ru', USE_L10N=False):
with translation.override('none'):
response = self.client.get('/test_admin/admin/jsi18n/')
self.assertNotContains(response, '%d.%m.%Y %H:%M:%S')
self.assertContains(response, '%Y-%m-%d %H:%M:%S')
finally:
deactivate()
def test_disallowed_filtering(self):
self.assertRaises(SuspiciousOperation,

View File

@ -14,8 +14,8 @@ from django.core.files.storage import default_storage
from django.core.files.uploadedfile import SimpleUploadedFile
from django.db.models import DateField
from django.test import TestCase as DjangoTestCase
from django.utils import translation
from django.utils.html import conditional_escape
from django.utils.translation import activate, deactivate
from django.utils.unittest import TestCase
import models
@ -204,7 +204,7 @@ class FilteredSelectMultipleWidgetTest(TestCase):
)
class AdminSplitDateTimeWidgetTest(TestCase):
class AdminSplitDateTimeWidgetTest(DjangoTestCase):
def test_render(self):
w = AdminSplitDateTime()
self.assertEqual(
@ -215,18 +215,13 @@ class AdminSplitDateTimeWidgetTest(TestCase):
def test_localization(self):
w = AdminSplitDateTime()
activate('de-at')
old_USE_L10N = settings.USE_L10N
try:
settings.USE_L10N = True
with self.settings(USE_L10N=True):
with translation.override('de-at'):
w.is_localized = True
self.assertEqual(
conditional_escape(w.render('test', datetime(2007, 12, 1, 9, 30))),
'<p class="datetime">Datum: <input value="01.12.2007" type="text" class="vDateField" name="test_0" size="10" /><br />Zeit: <input value="09:30:00" type="text" class="vTimeField" name="test_1" size="8" /></p>',
)
finally:
deactivate()
settings.USE_L10N = old_USE_L10N
class AdminFileWidgetTest(DjangoTestCase):

View File

@ -1,10 +1,11 @@
# -*- coding: utf-8 -*-
import datetime
from django.utils import unittest
from django.test import TestCase
from django.utils import unittest, translation
from django.template.defaultfilters import *
class DefaultFiltersTests(unittest.TestCase):
class DefaultFiltersTests(TestCase):
def test_floatformat(self):
self.assertEqual(floatformat(7.7), u'7.7')
@ -458,11 +459,8 @@ class DefaultFiltersTests(unittest.TestCase):
u'0 bytes')
def test_localized_filesizeformat(self):
from django.utils.translation import activate, deactivate
old_localize = settings.USE_L10N
try:
activate('de')
settings.USE_L10N = True
with self.settings(USE_L10N=True):
with translation.override('de', deactivate=True):
self.assertEqual(filesizeformat(1023), u'1023 Bytes')
self.assertEqual(filesizeformat(1024), u'1,0 KB')
self.assertEqual(filesizeformat(10*1024), u'10,0 KB')
@ -480,9 +478,6 @@ class DefaultFiltersTests(unittest.TestCase):
self.assertEqual(filesizeformat(""), u'0 Bytes')
self.assertEqual(filesizeformat(u"\N{GREEK SMALL LETTER ALPHA}"),
u'0 Bytes')
finally:
deactivate()
settings.USE_L10N = old_localize
def test_pluralize(self):
self.assertEqual(pluralize(1), u'')

View File

@ -1,7 +1,7 @@
# -*- coding: utf-8 -*-
from django.forms import *
from django.utils.unittest import TestCase
from django.utils.translation import ugettext_lazy, activate, deactivate
from django.utils.translation import ugettext_lazy, override
from regressiontests.forms.models import Cheese
@ -28,11 +28,10 @@ class FormsRegressionsTestCase(TestCase):
self.assertEqual(f.as_p(), '<p><label for="id_username">Username:</label> <input id="id_username" type="text" name="username" maxlength="10" /></p>')
# Translations are done at rendering time, so multi-lingual apps can define forms)
activate('de')
with override('de'):
self.assertEqual(f.as_p(), '<p><label for="id_username">Benutzername:</label> <input id="id_username" type="text" name="username" maxlength="10" /></p>')
activate('pl')
with override('pl', deactivate=True):
self.assertEqual(f.as_p(), u'<p><label for="id_username">Nazwa u\u017cytkownika:</label> <input id="id_username" type="text" name="username" maxlength="10" /></p>')
deactivate()
def test_regression_5216(self):
# There was some problems with form translations in #5216
@ -61,10 +60,9 @@ class FormsRegressionsTestCase(TestCase):
self.assertEqual(f.clean('\xd1\x88\xd1\x82.'), u'\u0448\u0442.')
# Translated error messages used to be buggy.
activate('ru')
with override('ru'):
f = SomeForm({})
self.assertEqual(f.as_p(), u'<ul class="errorlist"><li>\u041e\u0431\u044f\u0437\u0430\u0442\u0435\u043b\u044c\u043d\u043e\u0435 \u043f\u043e\u043b\u0435.</li></ul>\n<p><label for="id_somechoice_0">\xc5\xf8\xdf:</label> <ul>\n<li><label for="id_somechoice_0"><input type="radio" id="id_somechoice_0" value="\xc5" name="somechoice" /> En tied\xe4</label></li>\n<li><label for="id_somechoice_1"><input type="radio" id="id_somechoice_1" value="\xf8" name="somechoice" /> Mies</label></li>\n<li><label for="id_somechoice_2"><input type="radio" id="id_somechoice_2" value="\xdf" name="somechoice" /> Nainen</label></li>\n</ul></p>')
deactivate()
# Deep copying translated text shouldn't raise an error)
from django.utils.translation import gettext_lazy

View File

@ -14,10 +14,10 @@ from django.utils.formats import (get_format, date_format, time_format,
from django.utils.importlib import import_module
from django.utils.numberformat import format as nformat
from django.utils.safestring import mark_safe, SafeString, SafeUnicode
from django.utils import translation
from django.utils.translation import (ugettext, ugettext_lazy, activate,
deactivate, gettext_lazy, pgettext, npgettext, to_locale,
get_language_info, get_language)
from django.utils.unittest import TestCase
from forms import I18nForm, SelectDateForm, SelectDateWidget, CompanyForm
@ -43,13 +43,10 @@ class TranslationTests(TestCase):
s = ugettext_lazy('Add %(name)s')
d = {'name': 'Ringo'}
self.assertEqual(u'Add Ringo', s % d)
activate('de')
try:
with translation.override('de', deactivate=True):
self.assertEqual(u'Ringo hinzuf\xfcgen', s % d)
activate('pl')
with translation.override('pl'):
self.assertEqual(u'Dodaj Ringo', s % d)
finally:
deactivate()
# It should be possible to compare *_lazy objects.
s1 = ugettext_lazy('Add %(name)s')
@ -69,20 +66,19 @@ class TranslationTests(TestCase):
def test_pgettext(self):
# Reset translation catalog to include other/locale/de
self.old_locale_paths = settings.LOCALE_PATHS
settings.LOCALE_PATHS += (os.path.join(os.path.dirname(os.path.abspath(__file__)), 'other', 'locale'),)
extended_locale_paths = settings.LOCALE_PATHS + (
os.path.join(os.path.dirname(os.path.abspath(__file__)), 'other', 'locale'),
)
with self.settings(LOCALE_PATHS=extended_locale_paths):
from django.utils.translation import trans_real
trans_real._active = local()
trans_real._translations = {}
activate('de')
with translation.override('de'):
self.assertEqual(pgettext("unexisting", "May"), u"May")
self.assertEqual(pgettext("month name", "May"), u"Mai")
self.assertEqual(pgettext("verb", "May"), u"Kann")
self.assertEqual(npgettext("search", "%d result", "%d results", 4) % 4, u"4 Resultate")
settings.LOCALE_PATHS = self.old_locale_paths
def test_string_concat(self):
"""
unicode(string_concat(...)) should not raise a TypeError - #4796
@ -96,11 +92,8 @@ class TranslationTests(TestCase):
"""
s = mark_safe('Password')
self.assertEqual(SafeString, type(s))
activate('de')
try:
with translation.override('de', deactivate=True):
self.assertEqual(SafeUnicode, type(ugettext(s)))
finally:
deactivate()
self.assertEqual('aPassword', SafeString('a') + s)
self.assertEqual('Passworda', s + SafeString('a'))
self.assertEqual('Passworda', s + mark_safe('a'))
@ -112,16 +105,13 @@ class TranslationTests(TestCase):
Translations on files with mac or dos end of lines will be converted
to unix eof in .po catalogs, and they have to match when retrieved
"""
from django.utils.translation.trans_real import translation
ca_translation = translation('ca')
from django.utils.translation.trans_real import translation as Trans
ca_translation = Trans('ca')
ca_translation._catalog[u'Mac\nEOF\n'] = u'Catalan Mac\nEOF\n'
ca_translation._catalog[u'Win\nEOF\n'] = u'Catalan Win\nEOF\n'
activate('ca')
try:
with translation.override('ca', deactivate=True):
self.assertEqual(u'Catalan Mac\nEOF\n', ugettext(u'Mac\rEOF\r'))
self.assertEqual(u'Catalan Win\nEOF\n', ugettext(u'Win\r\nEOF\r\n'))
finally:
deactivate()
def test_to_locale(self):
"""
@ -175,13 +165,12 @@ class FormattingTests(TestCase):
"""
Localization of numbers
"""
settings.USE_L10N = True
settings.USE_THOUSAND_SEPARATOR = False
with self.settings(USE_L10N=True, USE_THOUSAND_SEPARATOR=False):
self.assertEqual(u'66666.66', nformat(self.n, decimal_sep='.', decimal_pos=2, grouping=3, thousand_sep=','))
self.assertEqual(u'66666A6', nformat(self.n, decimal_sep='A', decimal_pos=1, grouping=1, thousand_sep='B'))
self.assertEqual(u'66666', nformat(self.n, decimal_sep='X', decimal_pos=0, grouping=1, thousand_sep='Y'))
settings.USE_THOUSAND_SEPARATOR = True
with self.settings(USE_L10N=True, USE_THOUSAND_SEPARATOR=True):
self.assertEqual(u'66,666.66', nformat(self.n, decimal_sep='.', decimal_pos=2, grouping=3, thousand_sep=','))
self.assertEqual(u'6B6B6B6B6A6', nformat(self.n, decimal_sep='A', decimal_pos=1, grouping=1, thousand_sep='B'))
self.assertEqual(u'-66666.6', nformat(-66666.666, decimal_sep='.', decimal_pos=1))
@ -198,8 +187,7 @@ class FormattingTests(TestCase):
but not formats
"""
settings.USE_L10N = False
activate('ca')
try:
with translation.override('ca', deactivate=True):
self.assertEqual(u'N j, Y', get_format('DATE_FORMAT'))
self.assertEqual(0, get_format('FIRST_DAY_OF_WEEK'))
self.assertEqual(u'.', get_format('DECIMAL_SEPARATOR'))
@ -254,19 +242,15 @@ class FormattingTests(TestCase):
# thousand separator and grouping when USE_L10N is False even
# if the USE_THOUSAND_SEPARATOR, NUMBER_GROUPING and
# THOUSAND_SEPARATOR settings are specified
settings.USE_THOUSAND_SEPARATOR = True
settings.NUMBER_GROUPING = 1
settings.THOUSAND_SEPARATOR = '!'
with self.settings(USE_THOUSAND_SEPARATOR=True,
NUMBER_GROUPING=1, THOUSAND_SEPARATOR='!'):
self.assertEqual(u'66666.67', Template('{{ n|floatformat:2 }}').render(self.ctxt))
self.assertEqual(u'100000.0', Template('{{ f|floatformat }}').render(self.ctxt))
finally:
deactivate()
def test_l10n_enabled(self):
settings.USE_L10N = True
# Catalan locale
activate('ca')
try:
with translation.override('ca', deactivate=True):
self.assertEqual('j \de F \de Y', get_format('DATE_FORMAT'))
self.assertEqual(1, get_format('FIRST_DAY_OF_WEEK'))
self.assertEqual(',', get_format('DECIMAL_SEPARATOR'))
@ -348,22 +332,16 @@ class FormattingTests(TestCase):
u'<select name="mydate_day" id="id_mydate_day">\n<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<option value="24">24</option>\n<option value="25">25</option>\n<option value="26">26</option>\n<option value="27">27</option>\n<option value="28">28</option>\n<option value="29">29</option>\n<option value="30">30</option>\n<option value="31" selected="selected">31</option>\n</select>\n<select name="mydate_month" id="id_mydate_month">\n<option value="1">gener</option>\n<option value="2">febrer</option>\n<option value="3">mar\xe7</option>\n<option value="4">abril</option>\n<option value="5">maig</option>\n<option value="6">juny</option>\n<option value="7">juliol</option>\n<option value="8">agost</option>\n<option value="9">setembre</option>\n<option value="10">octubre</option>\n<option value="11">novembre</option>\n<option value="12" selected="selected">desembre</option>\n</select>\n<select name="mydate_year" id="id_mydate_year">\n<option value="2009" selected="selected">2009</option>\n<option value="2010">2010</option>\n<option value="2011">2011</option>\n<option value="2012">2012</option>\n<option value="2013">2013</option>\n<option value="2014">2014</option>\n<option value="2015">2015</option>\n<option value="2016">2016</option>\n<option value="2017">2017</option>\n<option value="2018">2018</option>\n</select>',
SelectDateWidget(years=range(2009, 2019)).render('mydate', datetime.date(2009, 12, 31))
)
finally:
deactivate()
# Russian locale (with E as month)
activate('ru')
try:
with translation.override('ru', deactivate=True):
self.assertEqual(
u'<select name="mydate_day" id="id_mydate_day">\n<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<option value="24">24</option>\n<option value="25">25</option>\n<option value="26">26</option>\n<option value="27">27</option>\n<option value="28">28</option>\n<option value="29">29</option>\n<option value="30">30</option>\n<option value="31" selected="selected">31</option>\n</select>\n<select name="mydate_month" id="id_mydate_month">\n<option value="1">\u042f\u043d\u0432\u0430\u0440\u044c</option>\n<option value="2">\u0424\u0435\u0432\u0440\u0430\u043b\u044c</option>\n<option value="3">\u041c\u0430\u0440\u0442</option>\n<option value="4">\u0410\u043f\u0440\u0435\u043b\u044c</option>\n<option value="5">\u041c\u0430\u0439</option>\n<option value="6">\u0418\u044e\u043d\u044c</option>\n<option value="7">\u0418\u044e\u043b\u044c</option>\n<option value="8">\u0410\u0432\u0433\u0443\u0441\u0442</option>\n<option value="9">\u0421\u0435\u043d\u0442\u044f\u0431\u0440\u044c</option>\n<option value="10">\u041e\u043a\u0442\u044f\u0431\u0440\u044c</option>\n<option value="11">\u041d\u043e\u044f\u0431\u0440\u044c</option>\n<option value="12" selected="selected">\u0414\u0435\u043a\u0430\u0431\u0440\u044c</option>\n</select>\n<select name="mydate_year" id="id_mydate_year">\n<option value="2009" selected="selected">2009</option>\n<option value="2010">2010</option>\n<option value="2011">2011</option>\n<option value="2012">2012</option>\n<option value="2013">2013</option>\n<option value="2014">2014</option>\n<option value="2015">2015</option>\n<option value="2016">2016</option>\n<option value="2017">2017</option>\n<option value="2018">2018</option>\n</select>',
SelectDateWidget(years=range(2009, 2019)).render('mydate', datetime.date(2009, 12, 31))
)
finally:
deactivate()
# English locale
activate('en')
try:
with translation.override('en', deactivate=True):
self.assertEqual('N j, Y', get_format('DATE_FORMAT'))
self.assertEqual(0, get_format('FIRST_DAY_OF_WEEK'))
self.assertEqual('.', get_format('DECIMAL_SEPARATOR'))
@ -426,34 +404,23 @@ class FormattingTests(TestCase):
u'<select name="mydate_month" id="id_mydate_month">\n<option value="1">January</option>\n<option value="2">February</option>\n<option value="3">March</option>\n<option value="4">April</option>\n<option value="5">May</option>\n<option value="6">June</option>\n<option value="7">July</option>\n<option value="8">August</option>\n<option value="9">September</option>\n<option value="10">October</option>\n<option value="11">November</option>\n<option value="12" selected="selected">December</option>\n</select>\n<select name="mydate_day" id="id_mydate_day">\n<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<option value="24">24</option>\n<option value="25">25</option>\n<option value="26">26</option>\n<option value="27">27</option>\n<option value="28">28</option>\n<option value="29">29</option>\n<option value="30">30</option>\n<option value="31" selected="selected">31</option>\n</select>\n<select name="mydate_year" id="id_mydate_year">\n<option value="2009" selected="selected">2009</option>\n<option value="2010">2010</option>\n<option value="2011">2011</option>\n<option value="2012">2012</option>\n<option value="2013">2013</option>\n<option value="2014">2014</option>\n<option value="2015">2015</option>\n<option value="2016">2016</option>\n<option value="2017">2017</option>\n<option value="2018">2018</option>\n</select>',
SelectDateWidget(years=range(2009, 2019)).render('mydate', datetime.date(2009, 12, 31))
)
finally:
deactivate()
def test_sub_locales(self):
"""
Check if sublocales fall back to the main locale
"""
settings.USE_L10N = True
activate('de-at')
settings.USE_THOUSAND_SEPARATOR = True
try:
with self.settings(USE_L10N=True, USE_THOUSAND_SEPARATOR=True):
with translation.override('de-at', deactivate=True):
self.assertEqual(u'66.666,666', Template('{{ n }}').render(self.ctxt))
finally:
deactivate()
activate('es-us')
try:
with translation.override('es-us', deactivate=True):
self.assertEqual(u'31 de diciembre de 2009', date_format(self.d))
finally:
deactivate()
def test_localized_input(self):
"""
Tests if form input is correctly localized
"""
settings.USE_L10N = True
activate('de-at')
try:
with translation.override('de-at', deactivate=True):
form6 = CompanyForm({
'name': u'acme',
'date_added': datetime.datetime(2009, 12, 31, 6, 0, 0),
@ -467,28 +434,21 @@ class FormattingTests(TestCase):
)
self.assertEqual(localize_input(datetime.datetime(2009, 12, 31, 6, 0, 0)), '31.12.2009 06:00:00')
self.assertEqual(datetime.datetime(2009, 12, 31, 6, 0, 0), form6.cleaned_data['date_added'])
settings.USE_THOUSAND_SEPARATOR = True
with self.settings(USE_THOUSAND_SEPARATOR=True):
# Checking for the localized "products_delivered" field
self.assertTrue(u'<input type="text" name="products_delivered" value="12.000" id="id_products_delivered" />' in form6.as_ul())
finally:
deactivate()
def test_iter_format_modules(self):
"""
Tests the iter_format_modules function.
"""
activate('de-at')
old_format_module_path = settings.FORMAT_MODULE_PATH
try:
settings.USE_L10N = True
with translation.override('de-at', deactivate=True):
de_format_mod = import_module('django.conf.locale.de.formats')
self.assertEqual(list(iter_format_modules('de')), [de_format_mod])
settings.FORMAT_MODULE_PATH = 'regressiontests.i18n.other.locale'
with self.settings(FORMAT_MODULE_PATH='regressiontests.i18n.other.locale'):
test_de_format_mod = import_module('regressiontests.i18n.other.locale.de.formats')
self.assertEqual(list(iter_format_modules('de')), [test_de_format_mod, de_format_mod])
finally:
settings.FORMAT_MODULE_PATH = old_format_module_path
deactivate()
def test_iter_format_modules_stability(self):
"""
@ -501,17 +461,12 @@ class FormattingTests(TestCase):
self.assertEqual(list(iter_format_modules('en-gb')), [en_gb_format_mod, en_format_mod])
def test_get_format_modules_stability(self):
activate('de')
old_format_module_path = settings.FORMAT_MODULE_PATH
settings.FORMAT_MODULE_PATH = 'regressiontests.i18n.other.locale'
try:
settings.USE_L10N = True
with self.settings(USE_L10N=True,
FORMAT_MODULE_PATH='regressiontests.i18n.other.locale'):
with translation.override('de', deactivate=True):
old = "%r" % get_format_modules(reverse=True)
new = "%r" % get_format_modules(reverse=True) # second try
self.assertEqual(new, old, 'Value returned by get_formats_modules() must be preserved between calls.')
finally:
settings.FORMAT_MODULE_PATH = old_format_module_path
deactivate()
def test_localize_templatetag_and_filter(self):
"""
@ -526,19 +481,14 @@ class FormattingTests(TestCase):
output2 = '3,14;3.14;3,14'
output3 = '3,14;3.14'
output4 = '3.14;3,14'
old_localize = settings.USE_L10N
try:
activate('de')
settings.USE_L10N = False
with translation.override('de', deactivate=True):
with self.settings(USE_L10N=False):
self.assertEqual(template1.render(context), output1)
self.assertEqual(template4.render(context), output4)
settings.USE_L10N = True
with self.settings(USE_L10N=True):
self.assertEqual(template1.render(context), output1)
self.assertEqual(template2.render(context), output2)
self.assertEqual(template3.render(context), output3)
finally:
deactivate()
settings.USE_L10N = old_localize
class MiscTests(TestCase):
@ -696,20 +646,13 @@ class LocalePathsResolutionOrderI18NTests(ResolutionOrderI18NTests):
self.assertUgettext('Time', 'LOCALE_PATHS')
def test_locale_paths_override_app_translation(self):
old_installed_apps = settings.INSTALLED_APPS
settings.INSTALLED_APPS = list(settings.INSTALLED_APPS) + ['regressiontests.i18n.resolution']
try:
extended_apps = list(settings.INSTALLED_APPS) + ['regressiontests.i18n.resolution']
with self.settings(INSTALLED_APPS=extended_apps):
self.assertUgettext('Time', 'LOCALE_PATHS')
finally:
settings.INSTALLED_APPS = old_installed_apps
def test_locale_paths_override_project_translation(self):
old_settings_module = settings.SETTINGS_MODULE
settings.SETTINGS_MODULE = 'regressiontests'
try:
with self.settings(SETTINGS_MODULE='regressiontests'):
self.assertUgettext('Date/time', 'LOCALE_PATHS')
finally:
settings.SETTINGS_MODULE = old_settings_module
class ProjectResolutionOrderI18NTests(ResolutionOrderI18NTests):
@ -726,12 +669,9 @@ class ProjectResolutionOrderI18NTests(ResolutionOrderI18NTests):
self.assertUgettext('Date/time', 'PROJECT')
def test_project_override_app_translation(self):
old_installed_apps = settings.INSTALLED_APPS
settings.INSTALLED_APPS = list(settings.INSTALLED_APPS) + ['regressiontests.i18n.resolution']
try:
extended_apps = list(settings.INSTALLED_APPS) + ['regressiontests.i18n.resolution']
with self.settings(INSTALLED_APPS=extended_apps):
self.assertUgettext('Date/time', 'PROJECT')
finally:
settings.INSTALLED_APPS = old_installed_apps
class DjangoFallbackResolutionOrderI18NTests(ResolutionOrderI18NTests):
@ -776,7 +716,7 @@ class MultipleLocaleActivationTests(TestCase):
"""
Simple baseline behavior with one locale for all the supported i18n constructs.
"""
activate('fr')
with translation.override('fr'):
self.assertEqual(Template("{{ _('Yes') }}").render(Context({})), 'Oui')
self.assertEqual(Template("{% load i18n %}{% trans 'Yes' %}").render(Context({})), 'Oui')
self.assertEqual(Template("{% load i18n %}{% blocktrans %}Yes{% endblocktrans %}").render(Context({})), 'Oui')
@ -784,109 +724,105 @@ class MultipleLocaleActivationTests(TestCase):
# Literal marked up with _() in a filter expression
def test_multiple_locale_filter(self):
activate('de')
with translation.override('de'):
t = Template("{% load i18n %}{{ 0|yesno:_('yes,no,maybe') }}")
activate(self._old_language)
activate('nl')
with translation.override(self._old_language):
with translation.override('nl'):
self.assertEqual(t.render(Context({})), 'nee')
def test_multiple_locale_filter_deactivate(self):
activate('de')
with translation.override('de', deactivate=True):
t = Template("{% load i18n %}{{ 0|yesno:_('yes,no,maybe') }}")
deactivate()
activate('nl')
with translation.override('nl'):
self.assertEqual(t.render(Context({})), 'nee')
def test_multiple_locale_filter_direct_switch(self):
activate('de')
with translation.override('de'):
t = Template("{% load i18n %}{{ 0|yesno:_('yes,no,maybe') }}")
activate('nl')
with translation.override('nl'):
self.assertEqual(t.render(Context({})), 'nee')
# Literal marked up with _()
def test_multiple_locale(self):
activate('de')
with translation.override('de'):
t = Template("{{ _('No') }}")
activate(self._old_language)
activate('nl')
with translation.override(self._old_language):
with translation.override('nl'):
self.assertEqual(t.render(Context({})), 'Nee')
def test_multiple_locale_deactivate(self):
activate('de')
with translation.override('de', deactivate=True):
t = Template("{{ _('No') }}")
deactivate()
activate('nl')
with translation.override('nl'):
self.assertEqual(t.render(Context({})), 'Nee')
def test_multiple_locale_direct_switch(self):
activate('de')
with translation.override('de'):
t = Template("{{ _('No') }}")
activate('nl')
with translation.override('nl'):
self.assertEqual(t.render(Context({})), 'Nee')
# Literal marked up with _(), loading the i18n template tag library
def test_multiple_locale_loadi18n(self):
activate('de')
with translation.override('de'):
t = Template("{% load i18n %}{{ _('No') }}")
activate(self._old_language)
activate('nl')
with translation.override(self._old_language):
with translation.override('nl'):
self.assertEqual(t.render(Context({})), 'Nee')
def test_multiple_locale_loadi18n_deactivate(self):
activate('de')
with translation.override('de', deactivate=True):
t = Template("{% load i18n %}{{ _('No') }}")
deactivate()
activate('nl')
with translation.override('nl'):
self.assertEqual(t.render(Context({})), 'Nee')
def test_multiple_locale_loadi18n_direct_switch(self):
activate('de')
with translation.override('de'):
t = Template("{% load i18n %}{{ _('No') }}")
activate('nl')
with translation.override('nl'):
self.assertEqual(t.render(Context({})), 'Nee')
# trans i18n tag
def test_multiple_locale_trans(self):
activate('de')
with translation.override('de'):
t = Template("{% load i18n %}{% trans 'No' %}")
activate(self._old_language)
activate('nl')
with translation.override(self._old_language):
with translation.override('nl'):
self.assertEqual(t.render(Context({})), 'Nee')
def test_multiple_locale_deactivate_trans(self):
activate('de')
with translation.override('de', deactivate=True):
t = Template("{% load i18n %}{% trans 'No' %}")
deactivate()
activate('nl')
with translation.override('nl'):
self.assertEqual(t.render(Context({})), 'Nee')
def test_multiple_locale_direct_switch_trans(self):
activate('de')
with translation.override('de'):
t = Template("{% load i18n %}{% trans 'No' %}")
activate('nl')
with translation.override('nl'):
self.assertEqual(t.render(Context({})), 'Nee')
# blocktrans i18n tag
def test_multiple_locale_btrans(self):
activate('de')
with translation.override('de'):
t = Template("{% load i18n %}{% blocktrans %}No{% endblocktrans %}")
activate(self._old_language)
activate('nl')
with translation.override(self._old_language):
with translation.override('nl'):
self.assertEqual(t.render(Context({})), 'Nee')
def test_multiple_locale_deactivate_btrans(self):
activate('de')
with translation.override('de', deactivate=True):
t = Template("{% load i18n %}{% blocktrans %}No{% endblocktrans %}")
deactivate()
activate('nl')
with translation.override('nl'):
self.assertEqual(t.render(Context({})), 'Nee')
def test_multiple_locale_direct_switch_btrans(self):
activate('de')
with translation.override('de'):
t = Template("{% load i18n %}{% blocktrans %}No{% endblocktrans %}")
activate('nl')
with translation.override('nl'):
self.assertEqual(t.render(Context({})), 'Nee')

View File

@ -4,7 +4,7 @@ from django.test import TestCase
from django.utils.text import *
from django.utils.http import urlquote, urlquote_plus, cookie_date, http_date
from django.utils.encoding import iri_to_uri
from django.utils.translation import activate, deactivate
from django.utils.translation import override
class TextTests(TestCase):
"""
@ -17,9 +17,8 @@ class TextTests(TestCase):
self.assertEqual(get_text_list(['a', 'b'], 'and'), u'a and b')
self.assertEqual(get_text_list(['a']), u'a')
self.assertEqual(get_text_list([]), u'')
activate('ar')
with override('ar'):
self.assertEqual(get_text_list(['a', 'b', 'c']), u"a، b أو c")
deactivate()
def test_smart_split(self):

View File

@ -4,7 +4,7 @@ from os import path
from django.conf import settings
from django.test import TestCase
from django.utils.translation import activate, deactivate
from django.utils.translation import override, activate
from django.utils.text import javascript_quote
from regressiontests.views.urls import locale_dir
@ -42,15 +42,6 @@ class JsI18NTests(TestCase):
settings.LANGUAGE_CODE.
"""
def setUp(self):
self.old_language_code = settings.LANGUAGE_CODE
self.old_installed_apps = settings.INSTALLED_APPS
def tearDown(self):
deactivate()
settings.LANGUAGE_CODE = self.old_language_code
settings.INSTALLED_APPS = self.old_installed_apps
def test_jsi18n_with_missing_en_files(self):
"""
The javascript_catalog shouldn't load the fallback language in the
@ -61,8 +52,8 @@ class JsI18NTests(TestCase):
languages and you've set settings.LANGUAGE_CODE to some other language
than English.
"""
settings.LANGUAGE_CODE = 'es'
activate('en-us')
with self.settings(LANGUAGE_CODE='es'):
with override('en-us'):
response = self.client.get('/views/jsi18n/')
self.assertNotContains(response, 'esto tiene que ser traducido')
@ -71,8 +62,8 @@ class JsI18NTests(TestCase):
Let's make sure that the fallback language is still working properly
in cases where the selected language cannot be found.
"""
settings.LANGUAGE_CODE = 'fr'
activate('fi')
with self.settings(LANGUAGE_CODE='fr'):
with override('fi'):
response = self.client.get('/views/jsi18n/')
self.assertContains(response, 'il faut le traduire')
@ -83,8 +74,8 @@ class JsI18NTests(TestCase):
is English and there is not 'en' translation available. See #13388,
#3594 and #13726 for more details.
"""
settings.LANGUAGE_CODE = 'fr'
activate('en-us')
with self.settings(LANGUAGE_CODE='fr'):
with override('en-us'):
response = self.client.get('/views/jsi18n/')
self.assertNotContains(response, 'Choisir une heure')
@ -94,9 +85,9 @@ class JsI18NTests(TestCase):
available. The Javascript i18n view must return a NON empty language catalog
with the proper English translations. See #13726 for more details.
"""
settings.LANGUAGE_CODE = 'fr'
settings.INSTALLED_APPS = list(settings.INSTALLED_APPS) + ['regressiontests.views.app0']
activate('en-us')
extended_apps = list(settings.INSTALLED_APPS) + ['regressiontests.views.app0']
with self.settings(LANGUAGE_CODE='fr', INSTALLED_APPS=extended_apps):
with override('en-us'):
response = self.client.get('/views/jsi18n_english_translation/')
self.assertContains(response, javascript_quote('this app0 string is to be translated'))
@ -105,8 +96,8 @@ class JsI18NTests(TestCase):
Makes sure that the fallback language is still working properly
in cases where the selected language cannot be found.
"""
settings.LANGUAGE_CODE = 'fr'
activate('none')
with self.settings(LANGUAGE_CODE='fr'):
with override('none'):
response = self.client.get('/views/jsi18n/')
self.assertContains(response, 'Choisir une heure')
@ -116,15 +107,6 @@ class JsI18NTestsMultiPackage(TestCase):
Tests for django views in django/views/i18n.py that need to change
settings.LANGUAGE_CODE and merge JS translation from several packages.
"""
def setUp(self):
self.old_language_code = settings.LANGUAGE_CODE
self.old_installed_apps = settings.INSTALLED_APPS
def tearDown(self):
settings.LANGUAGE_CODE = self.old_language_code
settings.INSTALLED_APPS = self.old_installed_apps
def testI18NLanguageEnglishDefault(self):
"""
Check if the JavaScript i18n view returns a complete language catalog
@ -133,29 +115,29 @@ class JsI18NTestsMultiPackage(TestCase):
translations of multiple Python packages is requested. See #13388,
#3594 and #13514 for more details.
"""
settings.LANGUAGE_CODE = 'en-us'
settings.INSTALLED_APPS = list(settings.INSTALLED_APPS) + ['regressiontests.views.app1', 'regressiontests.views.app2']
activate('fr')
extended_apps = list(settings.INSTALLED_APPS) + ['regressiontests.views.app1', 'regressiontests.views.app2']
with self.settings(LANGUAGE_CODE='en-us', INSTALLED_APPS=extended_apps):
with override('fr'):
response = self.client.get('/views/jsi18n_multi_packages1/')
self.assertContains(response, javascript_quote('il faut traduire cette chaîne de caractères de app1'))
deactivate()
def testI18NDifferentNonEnLangs(self):
"""
Similar to above but with neither default or requested language being
English.
"""
settings.LANGUAGE_CODE = 'fr'
settings.INSTALLED_APPS = list(settings.INSTALLED_APPS) + ['regressiontests.views.app3', 'regressiontests.views.app4']
activate('es-ar')
extended_apps = list(settings.INSTALLED_APPS) + ['regressiontests.views.app3', 'regressiontests.views.app4']
with self.settings(LANGUAGE_CODE='fr', INSTALLED_APPS=extended_apps):
with override('es-ar'):
response = self.client.get('/views/jsi18n_multi_packages2/')
self.assertContains(response, javascript_quote('este texto de app3 debe ser traducido'))
deactivate()
def testI18NWithLocalePaths(self):
settings.LANGUAGE_CODE = 'es-ar'
self.old_locale_paths = settings.LOCALE_PATHS
settings.LOCALE_PATHS += (path.join(path.dirname(path.dirname(path.abspath(__file__))), 'app3', 'locale'),)
extended_locale_paths = settings.LOCALE_PATHS + (
path.join(path.dirname(
path.dirname(path.abspath(__file__))), 'app3', 'locale'),)
with self.settings(LANGUAGE_CODE='es-ar', LOCALE_PATHS=extended_locale_paths):
with override('es-ar'):
response = self.client.get('/views/jsi18n/')
self.assertContains(response, javascript_quote('este texto de app3 debe ser traducido'))
settings.LOCALE_PATHS = self.old_locale_paths
self.assertContains(response,
javascript_quote('este texto de app3 debe ser traducido'))