Permalink
Browse files

Combine consecutive with statements

Python 2.7 allows to combine several 'with' instructions.
  • Loading branch information...
1 parent 22c6497 commit 165f44aaaa0b9008f35d8f6a3474db061559ad53 @claudep claudep committed Aug 16, 2013
@@ -121,17 +121,16 @@ def test_inactive_user(self):
[force_text(form.error_messages['inactive'])])
def test_inactive_user_i18n(self):
- with self.settings(USE_I18N=True):
- with translation.override('pt-br', deactivate=True):
- # The user is inactive.
- data = {
- 'username': 'inactive',
- 'password': 'password',
- }
- form = AuthenticationForm(None, data)
- self.assertFalse(form.is_valid())
- self.assertEqual(form.non_field_errors(),
- [force_text(form.error_messages['inactive'])])
+ with self.settings(USE_I18N=True), translation.override('pt-br', deactivate=True):
+ # The user is inactive.
+ data = {
+ 'username': 'inactive',
+ 'password': 'password',
+ }
+ form = AuthenticationForm(None, data)
+ self.assertFalse(form.is_valid())
+ self.assertEqual(form.non_field_errors(),
+ [force_text(form.error_messages['inactive'])])
def test_custom_login_allowed_policy(self):
# The user is inactive, but our custom form policy allows him to log in.
@@ -77,15 +77,14 @@ def test_l10n_intcomma(self):
'100', '1,000', '10,123', '10,311', '1,000,000', '1,234,567.1234567', '1,234,567.1234567',
None)
- with self.settings(USE_L10N=True, USE_THOUSAND_SEPARATOR=False):
- with translation.override('en'):
- self.humanize_tester(test_list, result_list, 'intcomma')
+ with self.settings(USE_L10N=True, USE_THOUSAND_SEPARATOR=False), \
+ translation.override('en'):
+ self.humanize_tester(test_list, result_list, 'intcomma')
def test_intcomma_without_number_grouping(self):
# Regression for #17414
- with translation.override('ja'):
- with self.settings(USE_L10N=True):
- self.humanize_tester([100], ['100'], 'intcomma')
+ with translation.override('ja'), self.settings(USE_L10N=True):
+ self.humanize_tester([100], ['100'], 'intcomma')
def test_intword(self):
test_list = ('100', '1000000', '1200000', '1290000',
@@ -104,18 +103,18 @@ def test_i18n_intcomma(self):
'100', '1000', '10123', '10311', '1000000', None)
result_list = ('100', '1.000', '10.123', '10.311', '1.000.000', '1.234.567,25',
'100', '1.000', '10.123', '10.311', '1.000.000', None)
- with self.settings(USE_L10N=True, USE_THOUSAND_SEPARATOR=True):
- with translation.override('de'):
- self.humanize_tester(test_list, result_list, 'intcomma')
+ with self.settings(USE_L10N=True, USE_THOUSAND_SEPARATOR=True), \
+ translation.override('de'):
+ self.humanize_tester(test_list, result_list, 'intcomma')
def test_i18n_intword(self):
test_list = ('100', '1000000', '1200000', '1290000',
'1000000000', '2000000000', '6000000000000')
result_list = ('100', '1,0 Million', '1,2 Millionen', '1,3 Millionen',
'1,0 Milliarde', '2,0 Milliarden', '6,0 Billionen')
- with self.settings(USE_L10N=True, USE_THOUSAND_SEPARATOR=True):
- with translation.override('de'):
- self.humanize_tester(test_list, result_list, 'intword')
+ with self.settings(USE_L10N=True, USE_THOUSAND_SEPARATOR=True), \
+ translation.override('de'):
+ self.humanize_tester(test_list, result_list, 'intword')
def test_apnumber(self):
test_list = [str(x) for x in range(1, 11)]
@@ -162,9 +161,9 @@ def test_naturalday_uses_localtime(self):
orig_humanize_datetime, humanize.datetime = humanize.datetime, MockDateTime
try:
- with override_settings(TIME_ZONE="America/Chicago", USE_TZ=True):
- with translation.override('en'):
- self.humanize_tester([dt], ['yesterday'], 'naturalday')
+ with override_settings(TIME_ZONE="America/Chicago", USE_TZ=True), \
+ translation.override('en'):
+ self.humanize_tester([dt], ['yesterday'], 'naturalday')
finally:
humanize.datetime = orig_humanize_datetime
View
@@ -524,31 +524,28 @@ def testI18NLanguageNonEnglishDefault(self):
if the default language is non-English but the selected language
is English. See #13388 and #3594 for more details.
"""
- 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')
+ with self.settings(LANGUAGE_CODE='fr'), translation.override('en-us'):
+ response = self.client.get('/test_admin/admin/jsi18n/')
+ self.assertNotContains(response, 'Choisir une heure')
def testI18NLanguageNonEnglishFallback(self):
"""
Makes sure that the fallback language is still working properly
in cases where the selected language cannot be found.
"""
- with self.settings(LANGUAGE_CODE='fr'):
- with translation.override('none'):
- response = self.client.get('/test_admin/admin/jsi18n/')
- self.assertContains(response, 'Choisir une heure')
+ with self.settings(LANGUAGE_CODE='fr'), translation.override('none'):
+ response = self.client.get('/test_admin/admin/jsi18n/')
+ self.assertContains(response, 'Choisir une heure')
def testL10NDeactivated(self):
"""
Check if L10N is deactivated, the JavaScript i18n view doesn't
return localized date/time formats. Refs #14824.
"""
- 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')
+ with self.settings(LANGUAGE_CODE='ru', USE_L10N=False), 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')
def test_disallowed_filtering(self):
with patch_logger('django.security.DisallowedModelAdminLookup', 'error') as calls:
@@ -295,13 +295,12 @@ def test_render(self):
def test_localization(self):
w = widgets.AdminSplitDateTime()
- with self.settings(USE_L10N=True):
- with translation.override('de-at'):
- w.is_localized = True
- self.assertHTMLEqual(
- 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>',
- )
+ with self.settings(USE_L10N=True), translation.override('de-at'):
+ w.is_localized = True
+ self.assertHTMLEqual(
+ 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>',
+ )
class AdminURLWidgetTest(DjangoTestCase):
@@ -647,22 +647,21 @@ class DefaultFiltersI18NTests(TransRealMixin, TestCase):
def test_localized_filesizeformat(self):
# NOTE: \xa0 avoids wrapping between value and unit
- with self.settings(USE_L10N=True):
- with translation.override('de', deactivate=True):
- self.assertEqual(filesizeformat(1023), '1023\xa0Bytes')
- self.assertEqual(filesizeformat(1024), '1,0\xa0KB')
- self.assertEqual(filesizeformat(10*1024), '10,0\xa0KB')
- self.assertEqual(filesizeformat(1024*1024-1), '1024,0\xa0KB')
- self.assertEqual(filesizeformat(1024*1024), '1,0\xa0MB')
- self.assertEqual(filesizeformat(1024*1024*50), '50,0\xa0MB')
- self.assertEqual(filesizeformat(1024*1024*1024-1), '1024,0\xa0MB')
- self.assertEqual(filesizeformat(1024*1024*1024), '1,0\xa0GB')
- self.assertEqual(filesizeformat(1024*1024*1024*1024), '1,0\xa0TB')
- self.assertEqual(filesizeformat(1024*1024*1024*1024*1024),
- '1,0\xa0PB')
- self.assertEqual(filesizeformat(1024*1024*1024*1024*1024*2000),
- '2000,0\xa0PB')
- self.assertEqual(filesizeformat(complex(1,-1)), '0\xa0Bytes')
- self.assertEqual(filesizeformat(""), '0\xa0Bytes')
- self.assertEqual(filesizeformat("\N{GREEK SMALL LETTER ALPHA}"),
- '0\xa0Bytes')
+ with self.settings(USE_L10N=True), translation.override('de', deactivate=True):
+ self.assertEqual(filesizeformat(1023), '1023\xa0Bytes')
+ self.assertEqual(filesizeformat(1024), '1,0\xa0KB')
+ self.assertEqual(filesizeformat(10*1024), '10,0\xa0KB')
+ self.assertEqual(filesizeformat(1024*1024-1), '1024,0\xa0KB')
+ self.assertEqual(filesizeformat(1024*1024), '1,0\xa0MB')
+ self.assertEqual(filesizeformat(1024*1024*50), '50,0\xa0MB')
+ self.assertEqual(filesizeformat(1024*1024*1024-1), '1024,0\xa0MB')
+ self.assertEqual(filesizeformat(1024*1024*1024), '1,0\xa0GB')
+ self.assertEqual(filesizeformat(1024*1024*1024*1024), '1,0\xa0TB')
+ self.assertEqual(filesizeformat(1024*1024*1024*1024*1024),
+ '1,0\xa0PB')
+ self.assertEqual(filesizeformat(1024*1024*1024*1024*1024*2000),
+ '2000,0\xa0PB')
+ self.assertEqual(filesizeformat(complex(1,-1)), '0\xa0Bytes')
+ self.assertEqual(filesizeformat(""), '0\xa0Bytes')
+ self.assertEqual(filesizeformat("\N{GREEK SMALL LETTER ALPHA}"),
+ '0\xa0Bytes')
@@ -286,11 +286,10 @@ def test_floatfield_changed(self):
n = 4.35
self.assertFalse(f._has_changed(n, '4.3500'))
- with translation.override('fr'):
- with self.settings(USE_L10N=True):
- f = FloatField(localize=True)
- localized_n = formats.localize_input(n) # -> '4,35' in French
- self.assertFalse(f._has_changed(n, localized_n))
+ with translation.override('fr'), self.settings(USE_L10N=True):
+ f = FloatField(localize=True)
+ localized_n = formats.localize_input(n) # -> '4,35' in French
+ self.assertFalse(f._has_changed(n, localized_n))
# DecimalField ################################################################
@@ -399,11 +398,10 @@ def test_decimalfield_changed(self):
self.assertFalse(f._has_changed(d, '0.10'))
self.assertTrue(f._has_changed(d, '0.101'))
- with translation.override('fr'):
- with self.settings(USE_L10N=True):
- f = DecimalField(max_digits=2, decimal_places=2, localize=True)
- localized_d = formats.localize_input(d) # -> '0,1' in French
- self.assertFalse(f._has_changed(d, localized_d))
+ with translation.override('fr'), self.settings(USE_L10N=True):
+ f = DecimalField(max_digits=2, decimal_places=2, localize=True)
+ localized_d = formats.localize_input(d) # -> '0,1' in French
+ self.assertFalse(f._has_changed(d, localized_d))
# DateField ###################################################################
View
@@ -746,11 +746,11 @@ def test_get_format_modules_lang(self):
self.assertEqual('.', get_format('DECIMAL_SEPARATOR', lang='en'))
def test_get_format_modules_stability(self):
- with self.settings(FORMAT_MODULE_PATH='i18n.other.locale'):
- with translation.override('de', deactivate=True):
- old = str("%r") % get_format_modules(reverse=True)
- new = str("%r") % get_format_modules(reverse=True) # second try
- self.assertEqual(new, old, 'Value returned by get_formats_modules() must be preserved between calls.')
+ with self.settings(FORMAT_MODULE_PATH='i18n.other.locale'), \
+ translation.override('de', deactivate=True):
+ old = str("%r") % get_format_modules(reverse=True)
+ new = str("%r") % get_format_modules(reverse=True) # second try
+ self.assertEqual(new, old, 'Value returned by get_formats_modules() must be preserved between calls.')
def test_localize_templatetag_and_filter(self):
"""
@@ -1062,9 +1062,8 @@ def test_single_locale_activation(self):
def test_multiple_locale_filter(self):
with translation.override('de'):
t = Template("{% load i18n %}{{ 0|yesno:_('yes,no,maybe') }}")
- with translation.override(self._old_language):
- with translation.override('nl'):
- self.assertEqual(t.render(Context({})), 'nee')
+ with translation.override(self._old_language), translation.override('nl'):
+ self.assertEqual(t.render(Context({})), 'nee')
def test_multiple_locale_filter_deactivate(self):
with translation.override('de', deactivate=True):
@@ -1083,9 +1082,8 @@ def test_multiple_locale_filter_direct_switch(self):
def test_multiple_locale(self):
with translation.override('de'):
t = Template("{{ _('No') }}")
- with translation.override(self._old_language):
- with translation.override('nl'):
- self.assertEqual(t.render(Context({})), 'Nee')
+ with translation.override(self._old_language), translation.override('nl'):
+ self.assertEqual(t.render(Context({})), 'Nee')
def test_multiple_locale_deactivate(self):
with translation.override('de', deactivate=True):
@@ -1104,9 +1102,8 @@ def test_multiple_locale_direct_switch(self):
def test_multiple_locale_loadi18n(self):
with translation.override('de'):
t = Template("{% load i18n %}{{ _('No') }}")
- with translation.override(self._old_language):
- with translation.override('nl'):
- self.assertEqual(t.render(Context({})), 'Nee')
+ with translation.override(self._old_language), translation.override('nl'):
+ self.assertEqual(t.render(Context({})), 'Nee')
def test_multiple_locale_loadi18n_deactivate(self):
with translation.override('de', deactivate=True):
@@ -1125,9 +1122,8 @@ def test_multiple_locale_loadi18n_direct_switch(self):
def test_multiple_locale_trans(self):
with translation.override('de'):
t = Template("{% load i18n %}{% trans 'No' %}")
- with translation.override(self._old_language):
- with translation.override('nl'):
- self.assertEqual(t.render(Context({})), 'Nee')
+ with translation.override(self._old_language), translation.override('nl'):
+ self.assertEqual(t.render(Context({})), 'Nee')
def test_multiple_locale_deactivate_trans(self):
with translation.override('de', deactivate=True):
@@ -1146,9 +1142,8 @@ def test_multiple_locale_direct_switch_trans(self):
def test_multiple_locale_btrans(self):
with translation.override('de'):
t = Template("{% load i18n %}{% blocktrans %}No{% endblocktrans %}")
- with translation.override(self._old_language):
- with translation.override('nl'):
- self.assertEqual(t.render(Context({})), 'Nee')
+ with translation.override(self._old_language), translation.override('nl'):
+ self.assertEqual(t.render(Context({})), 'Nee')
def test_multiple_locale_deactivate_btrans(self):
with translation.override('de', deactivate=True):
@@ -355,20 +355,19 @@ def test_configure_initializes_logging(self):
self.assertTrue(dictConfig.called)
+@override_settings(DEBUG=True)
class SecurityLoggerTest(TestCase):
urls = 'logging_tests.urls'
def test_suspicious_operation_creates_log_message(self):
- with self.settings(DEBUG=True):
- with patch_logger('django.security.SuspiciousOperation', 'error') as calls:
- response = self.client.get('/suspicious/')
- self.assertEqual(len(calls), 1)
- self.assertEqual(calls[0], 'dubious')
+ with patch_logger('django.security.SuspiciousOperation', 'error') as calls:
+ response = self.client.get('/suspicious/')
+ self.assertEqual(len(calls), 1)
+ self.assertEqual(calls[0], 'dubious')
def test_suspicious_operation_uses_sublogger(self):
- with self.settings(DEBUG=True):
- with patch_logger('django.security.DisallowedHost', 'error') as calls:
- response = self.client.get('/suspicious_spec/')
- self.assertEqual(len(calls), 1)
- self.assertEqual(calls[0], 'dubious')
+ with patch_logger('django.security.DisallowedHost', 'error') as calls:
+ response = self.client.get('/suspicious_spec/')
+ self.assertEqual(len(calls), 1)
+ self.assertEqual(calls[0], 'dubious')
Oops, something went wrong.

4 comments on commit 165f44a

Owner

jezdez replied Aug 16, 2013

Oh noes, the backslashes, they are everywhere! Can we please, please, use the implied line continuation in braces like PEP 8 says?

Member

claudep replied Aug 16, 2013

I would, I would, if only this was possible! Try by yourself and tell me what I missed...

Owner

aaugustin replied Aug 17, 2013

I had the same reaction as jezdez.

I'm in favor of reverting to:

with long_long_long_foo:
    with long_long_long_bar:
        ...

if the alternative is:

with long_long_long_foo, \
        long_long_long_bar:
    ...

The extra indent doesn't hurt in most of the places you've changed.

Member

claudep replied Aug 18, 2013

Personally, I'd either revert all or nothing. If someone is motivated to cherry-pick and change the syntax whenever lines are too long, he can do it.

Please sign in to comment.