From 253adc2b8a52982139d40c4f55b3fd446e1cb8f3 Mon Sep 17 00:00:00 2001 From: Hasan Date: Mon, 4 Jan 2016 12:20:08 +0330 Subject: [PATCH] Refs #26022 -- Used context manager version of assertRaisesMessage in tests. --- tests/admin_registration/tests.py | 8 +- tests/auth_tests/test_models.py | 7 +- tests/custom_columns/tests.py | 25 +- tests/distinct_on_fields/tests.py | 7 +- tests/expressions/tests.py | 6 +- tests/file_storage/tests.py | 6 +- tests/fixtures_regress/tests.py | 66 +- tests/forms_tests/tests/test_fields.py | 781 ++++++++++-------- tests/forms_tests/tests/test_forms.py | 46 +- .../widget_tests/test_selectdatewidget.py | 4 +- tests/get_earliest_or_latest/tests.py | 17 +- tests/get_object_or_404/tests.py | 27 +- .../test_relative_fields.py | 5 +- tests/mail/tests.py | 8 +- tests/many_to_one/tests.py | 17 +- tests/model_fields/test_uuid.py | 10 +- tests/queries/tests.py | 63 +- tests/requests/tests.py | 28 +- tests/test_utils/tests.py | 3 +- tests/urlpatterns_reverse/tests.py | 8 +- tests/utils_tests/test_datastructures.py | 8 +- 21 files changed, 584 insertions(+), 566 deletions(-) diff --git a/tests/admin_registration/tests.py b/tests/admin_registration/tests.py index ffca76886e..c1efae76c7 100644 --- a/tests/admin_registration/tests.py +++ b/tests/admin_registration/tests.py @@ -127,12 +127,12 @@ class TestRegistrationDecorator(SimpleTestCase): self.default_site.unregister(Place) def test_wrapped_class_not_a_model_admin(self): - self.assertRaisesMessage(ValueError, 'Wrapped class must subclass ModelAdmin.', - register(Person), CustomSite) + with self.assertRaisesMessage(ValueError, 'Wrapped class must subclass ModelAdmin.'): + register(Person)(CustomSite) def test_custom_site_not_an_admin_site(self): - self.assertRaisesMessage(ValueError, 'site must subclass AdminSite', - register(Person, site=Traveler), NameAdmin) + with self.assertRaisesMessage(ValueError, 'site must subclass AdminSite'): + register(Person, site=Traveler)(NameAdmin) def test_empty_models_list_registration_fails(self): with self.assertRaisesMessage(ValueError, 'At least one model must be passed to register.'): diff --git a/tests/auth_tests/test_models.py b/tests/auth_tests/test_models.py index 6256f484da..e5b00f5f29 100644 --- a/tests/auth_tests/test_models.py +++ b/tests/auth_tests/test_models.py @@ -161,11 +161,8 @@ class UserManagerTestCase(TestCase): self.assertEqual(returned, 'email\ with_whitespace@d.com') def test_empty_username(self): - self.assertRaisesMessage( - ValueError, - 'The given username must be set', - User.objects.create_user, username='' - ) + with self.assertRaisesMessage(ValueError, 'The given username must be set'): + User.objects.create_user(username='') def test_create_user_is_staff(self): email = 'normal@normal.com' diff --git a/tests/custom_columns/tests.py b/tests/custom_columns/tests.py index 2b5526453f..7102e4fdbe 100644 --- a/tests/custom_columns/tests.py +++ b/tests/custom_columns/tests.py @@ -91,31 +91,22 @@ class CustomColumnsTests(TestCase): self.assertEqual(self.a1, Author.objects.get(first_name__exact='John')) def test_filter_on_nonexistent_field(self): - self.assertRaisesMessage( - FieldError, + msg = ( "Cannot resolve keyword 'firstname' into field. Choices are: " - "Author_ID, article, first_name, last_name, primary_set", - Author.objects.filter, - firstname__exact='John' + "Author_ID, article, first_name, last_name, primary_set" ) + with self.assertRaisesMessage(FieldError, msg): + Author.objects.filter(firstname__exact='John') def test_author_get_attributes(self): a = Author.objects.get(last_name__exact='Smith') self.assertEqual('John', a.first_name) self.assertEqual('Smith', a.last_name) - self.assertRaisesMessage( - AttributeError, - "'Author' object has no attribute 'firstname'", - getattr, - a, 'firstname' - ) + with self.assertRaisesMessage(AttributeError, "'Author' object has no attribute 'firstname'"): + getattr(a, 'firstname') - self.assertRaisesMessage( - AttributeError, - "'Author' object has no attribute 'last'", - getattr, - a, 'last' - ) + with self.assertRaisesMessage(AttributeError, "'Author' object has no attribute 'last'"): + getattr(a, 'last') def test_m2m_table(self): self.assertQuerysetEqual( diff --git a/tests/distinct_on_fields/tests.py b/tests/distinct_on_fields/tests.py index 9e53ce3ae9..f999f76c4a 100644 --- a/tests/distinct_on_fields/tests.py +++ b/tests/distinct_on_fields/tests.py @@ -90,11 +90,8 @@ class DistinctOnTests(TestCase): # Combining queries with different distinct_fields is not allowed. base_qs = Celebrity.objects.all() - self.assertRaisesMessage( - AssertionError, - "Cannot combine queries with different distinct fields.", - lambda: (base_qs.distinct('id') & base_qs.distinct('name')) - ) + with self.assertRaisesMessage(AssertionError, "Cannot combine queries with different distinct fields."): + base_qs.distinct('id') & base_qs.distinct('name') # Test join unreffing c1 = Celebrity.objects.distinct('greatest_fan__id', 'greatest_fan__fan_of') diff --git a/tests/expressions/tests.py b/tests/expressions/tests.py index c7b7a7a15c..1040bd4b63 100644 --- a/tests/expressions/tests.py +++ b/tests/expressions/tests.py @@ -318,7 +318,8 @@ class BasicExpressionsTests(TestCase): 'expressions.Company.num_employees. F() expressions can only be ' 'used to update, not to insert.' ) - self.assertRaisesMessage(ValueError, msg, acme.save) + with self.assertRaisesMessage(ValueError, msg): + acme.save() acme.num_employees = 12 acme.name = Lower(F('name')) @@ -327,7 +328,8 @@ class BasicExpressionsTests(TestCase): 'expressions.Company.name))" on expressions.Company.name. F() ' 'expressions can only be used to update, not to insert.' ) - self.assertRaisesMessage(ValueError, msg, acme.save) + with self.assertRaisesMessage(ValueError, msg): + acme.save() def test_ticket_11722_iexact_lookup(self): Employee.objects.create(firstname="John", lastname="Doe") diff --git a/tests/file_storage/tests.py b/tests/file_storage/tests.py index 28a09ae557..b5ff073525 100644 --- a/tests/file_storage/tests.py +++ b/tests/file_storage/tests.py @@ -574,10 +574,8 @@ class FileFieldStorageTests(TestCase): # Testing exception is raised when filename is too short to truncate. filename = 'short.longext' objs[0].limited_length.save(filename, ContentFile('Same Content')) - self.assertRaisesMessage( - SuspiciousFileOperation, 'Storage can not find an available filename', - objs[1].limited_length.save, *(filename, ContentFile('Same Content')) - ) + with self.assertRaisesMessage(SuspiciousFileOperation, 'Storage can not find an available filename'): + objs[1].limited_length.save(*(filename, ContentFile('Same Content'))) finally: for o in objs: o.delete() diff --git a/tests/fixtures_regress/tests.py b/tests/fixtures_regress/tests.py index 5edd1c722f..6b4a3f7673 100644 --- a/tests/fixtures_regress/tests.py +++ b/tests/fixtures_regress/tests.py @@ -537,14 +537,8 @@ class TestFixtures(TestCase): settings.FIXTURE_DIRS cannot contain duplicates in order to avoid repeated fixture loading. """ - self.assertRaisesMessage( - ImproperlyConfigured, - "settings.FIXTURE_DIRS contains duplicates.", - management.call_command, - 'loaddata', - 'absolute.json', - verbosity=0, - ) + with self.assertRaisesMessage(ImproperlyConfigured, "settings.FIXTURE_DIRS contains duplicates."): + management.call_command('loaddata', 'absolute.json', verbosity=0) @skipIfNonASCIIPath @override_settings(FIXTURE_DIRS=[os.path.join(_cur_dir, 'fixtures')]) @@ -553,16 +547,13 @@ class TestFixtures(TestCase): settings.FIXTURE_DIRS cannot contain a default fixtures directory for application (app/fixtures) in order to avoid repeated fixture loading. """ - self.assertRaisesMessage( - ImproperlyConfigured, + msg = ( "'%s' is a default fixture directory for the '%s' app " "and cannot be listed in settings.FIXTURE_DIRS." - % (os.path.join(_cur_dir, 'fixtures'), 'fixtures_regress'), - management.call_command, - 'loaddata', - 'absolute.json', - verbosity=0, + % (os.path.join(_cur_dir, 'fixtures'), 'fixtures_regress') ) + with self.assertRaisesMessage(ImproperlyConfigured, msg): + management.call_command('loaddata', 'absolute.json', verbosity=0) @override_settings(FIXTURE_DIRS=[os.path.join(_cur_dir, 'fixtures_1'), os.path.join(_cur_dir, 'fixtures_2')]) @@ -734,41 +725,37 @@ class NaturalKeyFixtureTests(TestCase): ) def test_dependency_sorting_tight_circular(self): - self.assertRaisesMessage( + with self.assertRaisesMessage( RuntimeError, "Can't resolve dependencies for fixtures_regress.Circle1, " - "fixtures_regress.Circle2 in serialized app list.", - serializers.sort_dependencies, - [('fixtures_regress', [Person, Circle2, Circle1, Store, Book])], - ) + "fixtures_regress.Circle2 in serialized app list." + ): + serializers.sort_dependencies([('fixtures_regress', [Person, Circle2, Circle1, Store, Book])]) def test_dependency_sorting_tight_circular_2(self): - self.assertRaisesMessage( + with self.assertRaisesMessage( RuntimeError, "Can't resolve dependencies for fixtures_regress.Circle1, " - "fixtures_regress.Circle2 in serialized app list.", - serializers.sort_dependencies, - [('fixtures_regress', [Circle1, Book, Circle2])], - ) + "fixtures_regress.Circle2 in serialized app list." + ): + serializers.sort_dependencies([('fixtures_regress', [Circle1, Book, Circle2])]) def test_dependency_self_referential(self): - self.assertRaisesMessage( + with self.assertRaisesMessage( RuntimeError, "Can't resolve dependencies for fixtures_regress.Circle3 in " - "serialized app list.", - serializers.sort_dependencies, - [('fixtures_regress', [Book, Circle3])], - ) + "serialized app list." + ): + serializers.sort_dependencies([('fixtures_regress', [Book, Circle3])]) def test_dependency_sorting_long(self): - self.assertRaisesMessage( + with self.assertRaisesMessage( RuntimeError, "Can't resolve dependencies for fixtures_regress.Circle1, " "fixtures_regress.Circle2, fixtures_regress.Circle3 in serialized " - "app list.", - serializers.sort_dependencies, - [('fixtures_regress', [Person, Circle2, Circle1, Circle3, Store, Book])], - ) + "app list." + ): + serializers.sort_dependencies([('fixtures_regress', [Person, Circle2, Circle1, Circle3, Store, Book])]) def test_dependency_sorting_normal(self): sorted_deps = serializers.sort_dependencies( @@ -830,13 +817,12 @@ class M2MNaturalKeyFixtureTests(TestCase): Resolving circular M2M relations without explicit through models should fail loudly """ - self.assertRaisesMessage( + with self.assertRaisesMessage( RuntimeError, "Can't resolve dependencies for fixtures_regress.M2MSimpleCircularA, " - "fixtures_regress.M2MSimpleCircularB in serialized app list.", - serializers.sort_dependencies, - [('fixtures_regress', [M2MSimpleCircularA, M2MSimpleCircularB])] - ) + "fixtures_regress.M2MSimpleCircularB in serialized app list." + ): + serializers.sort_dependencies([('fixtures_regress', [M2MSimpleCircularA, M2MSimpleCircularB])]) def test_dependency_sorting_m2m_complex(self): """ diff --git a/tests/forms_tests/tests/test_fields.py b/tests/forms_tests/tests/test_fields.py index b46f897391..c4798076d3 100644 --- a/tests/forms_tests/tests/test_fields.py +++ b/tests/forms_tests/tests/test_fields.py @@ -96,8 +96,10 @@ class FieldsTests(SimpleTestCase): f = CharField() self.assertEqual('1', f.clean(1)) self.assertEqual('hello', f.clean('hello')) - self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, None) - self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, '') + with self.assertRaisesMessage(ValidationError, "'This field is required.'"): + f.clean(None) + with self.assertRaisesMessage(ValidationError, "'This field is required.'"): + f.clean('') self.assertEqual('[1, 2, 3]', f.clean([1, 2, 3])) self.assertEqual(f.max_length, None) self.assertEqual(f.min_length, None) @@ -135,7 +137,8 @@ class FieldsTests(SimpleTestCase): def test_charfield_5(self): f = CharField(min_length=10, required=True) - self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, '') + with self.assertRaisesMessage(ValidationError, "'This field is required.'"): + f.clean('') msg = "'Ensure this value has at least 10 characters (it has 5).'" with self.assertRaisesMessage(ValidationError, msg): f.clean('12345') @@ -193,18 +196,23 @@ class FieldsTests(SimpleTestCase): def test_integerfield_1(self): f = IntegerField() self.assertWidgetRendersTo(f, '') - self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, '') - self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, None) + with self.assertRaisesMessage(ValidationError, "'This field is required.'"): + f.clean('') + with self.assertRaisesMessage(ValidationError, "'This field is required.'"): + f.clean(None) self.assertEqual(1, f.clean('1')) self.assertIsInstance(f.clean('1'), int) self.assertEqual(23, f.clean('23')) - self.assertRaisesMessage(ValidationError, "'Enter a whole number.'", f.clean, 'a') + with self.assertRaisesMessage(ValidationError, "'Enter a whole number.'"): + f.clean('a') self.assertEqual(42, f.clean(42)) - self.assertRaisesMessage(ValidationError, "'Enter a whole number.'", f.clean, 3.14) + with self.assertRaisesMessage(ValidationError, "'Enter a whole number.'"): + f.clean(3.14) self.assertEqual(1, f.clean('1 ')) self.assertEqual(1, f.clean(' 1')) self.assertEqual(1, f.clean(' 1 ')) - self.assertRaisesMessage(ValidationError, "'Enter a whole number.'", f.clean, '1a') + with self.assertRaisesMessage(ValidationError, "'Enter a whole number.'"): + f.clean('1a') self.assertEqual(f.max_value, None) self.assertEqual(f.min_value, None) @@ -217,31 +225,38 @@ class FieldsTests(SimpleTestCase): self.assertEqual(1, f.clean('1')) self.assertIsInstance(f.clean('1'), int) self.assertEqual(23, f.clean('23')) - self.assertRaisesMessage(ValidationError, "'Enter a whole number.'", f.clean, 'a') + with self.assertRaisesMessage(ValidationError, "'Enter a whole number.'"): + f.clean('a') self.assertEqual(1, f.clean('1 ')) self.assertEqual(1, f.clean(' 1')) self.assertEqual(1, f.clean(' 1 ')) - self.assertRaisesMessage(ValidationError, "'Enter a whole number.'", f.clean, '1a') + with self.assertRaisesMessage(ValidationError, "'Enter a whole number.'"): + f.clean('1a') self.assertEqual(f.max_value, None) self.assertEqual(f.min_value, None) def test_integerfield_3(self): f = IntegerField(max_value=10) self.assertWidgetRendersTo(f, '') - self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, None) + with self.assertRaisesMessage(ValidationError, "'This field is required.'"): + f.clean(None) self.assertEqual(1, f.clean(1)) self.assertEqual(10, f.clean(10)) - self.assertRaisesMessage(ValidationError, "'Ensure this value is less than or equal to 10.'", f.clean, 11) + with self.assertRaisesMessage(ValidationError, "'Ensure this value is less than or equal to 10.'"): + f.clean(11) self.assertEqual(10, f.clean('10')) - self.assertRaisesMessage(ValidationError, "'Ensure this value is less than or equal to 10.'", f.clean, '11') + with self.assertRaisesMessage(ValidationError, "'Ensure this value is less than or equal to 10.'"): + f.clean('11') self.assertEqual(f.max_value, 10) self.assertEqual(f.min_value, None) def test_integerfield_4(self): f = IntegerField(min_value=10) self.assertWidgetRendersTo(f, '') - self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, None) - self.assertRaisesMessage(ValidationError, "'Ensure this value is greater than or equal to 10.'", f.clean, 1) + with self.assertRaisesMessage(ValidationError, "'This field is required.'"): + f.clean(None) + with self.assertRaisesMessage(ValidationError, "'Ensure this value is greater than or equal to 10.'"): + f.clean(1) self.assertEqual(10, f.clean(10)) self.assertEqual(11, f.clean(11)) self.assertEqual(10, f.clean('10')) @@ -252,14 +267,17 @@ class FieldsTests(SimpleTestCase): def test_integerfield_5(self): f = IntegerField(min_value=10, max_value=20) self.assertWidgetRendersTo(f, '') - self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, None) - self.assertRaisesMessage(ValidationError, "'Ensure this value is greater than or equal to 10.'", f.clean, 1) + with self.assertRaisesMessage(ValidationError, "'This field is required.'"): + f.clean(None) + with self.assertRaisesMessage(ValidationError, "'Ensure this value is greater than or equal to 10.'"): + f.clean(1) self.assertEqual(10, f.clean(10)) self.assertEqual(11, f.clean(11)) self.assertEqual(10, f.clean('10')) self.assertEqual(11, f.clean('11')) self.assertEqual(20, f.clean(20)) - self.assertRaisesMessage(ValidationError, "'Ensure this value is less than or equal to 20.'", f.clean, 21) + with self.assertRaisesMessage(ValidationError, "'Ensure this value is less than or equal to 20.'"): + f.clean(21) self.assertEqual(f.max_value, 20) self.assertEqual(f.min_value, 10) @@ -278,8 +296,10 @@ class FieldsTests(SimpleTestCase): self.assertEqual(1, f.clean(' 1.0 ')) self.assertEqual(1, f.clean('1.')) self.assertEqual(1, f.clean(' 1. ')) - self.assertRaisesMessage(ValidationError, "'Enter a whole number.'", f.clean, '1.5') - self.assertRaisesMessage(ValidationError, "'Enter a whole number.'", f.clean, '…') + with self.assertRaisesMessage(ValidationError, "'Enter a whole number.'"): + f.clean('1.5') + with self.assertRaisesMessage(ValidationError, "'Enter a whole number.'"): + f.clean('…') def test_integerfield_big_num(self): f = IntegerField() @@ -304,24 +324,31 @@ class FieldsTests(SimpleTestCase): def test_floatfield_1(self): f = FloatField() self.assertWidgetRendersTo(f, '') - self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, '') - self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, None) + with self.assertRaisesMessage(ValidationError, "'This field is required.'"): + f.clean('') + with self.assertRaisesMessage(ValidationError, "'This field is required.'"): + f.clean(None) self.assertEqual(1.0, f.clean('1')) self.assertIsInstance(f.clean('1'), float) self.assertEqual(23.0, f.clean('23')) self.assertEqual(3.1400000000000001, f.clean('3.14')) self.assertEqual(3.1400000000000001, f.clean(3.14)) self.assertEqual(42.0, f.clean(42)) - self.assertRaisesMessage(ValidationError, "'Enter a number.'", f.clean, 'a') + with self.assertRaisesMessage(ValidationError, "'Enter a number.'"): + f.clean('a') self.assertEqual(1.0, f.clean('1.0 ')) self.assertEqual(1.0, f.clean(' 1.0')) self.assertEqual(1.0, f.clean(' 1.0 ')) - self.assertRaisesMessage(ValidationError, "'Enter a number.'", f.clean, '1.0a') + with self.assertRaisesMessage(ValidationError, "'Enter a number.'"): + f.clean('1.0a') self.assertEqual(f.max_value, None) self.assertEqual(f.min_value, None) - self.assertRaisesMessage(ValidationError, "'Enter a number.'", f.clean, 'Infinity') - self.assertRaisesMessage(ValidationError, "'Enter a number.'", f.clean, 'NaN') - self.assertRaisesMessage(ValidationError, "'Enter a number.'", f.clean, '-Inf') + with self.assertRaisesMessage(ValidationError, "'Enter a number.'"): + f.clean('Infinity') + with self.assertRaisesMessage(ValidationError, "'Enter a number.'"): + f.clean('NaN') + with self.assertRaisesMessage(ValidationError, "'Enter a number.'"): + f.clean('-Inf') def test_floatfield_2(self): f = FloatField(required=False) @@ -334,11 +361,10 @@ class FieldsTests(SimpleTestCase): def test_floatfield_3(self): f = FloatField(max_value=1.5, min_value=0.5) self.assertWidgetRendersTo(f, '') - self.assertRaisesMessage(ValidationError, "'Ensure this value is less than or equal to 1.5.'", f.clean, '1.6') - self.assertRaisesMessage( - ValidationError, "'Ensure this value is greater than or equal to 0.5.'", - f.clean, '0.4' - ) + with self.assertRaisesMessage(ValidationError, "'Ensure this value is less than or equal to 1.5.'"): + f.clean('1.6') + with self.assertRaisesMessage(ValidationError, "'Ensure this value is greater than or equal to 0.5.'"): + f.clean('0.4') self.assertEqual(1.5, f.clean('1.5')) self.assertEqual(0.5, f.clean('0.5')) self.assertEqual(f.max_value, 1.5) @@ -371,52 +397,50 @@ class FieldsTests(SimpleTestCase): def test_decimalfield_1(self): f = DecimalField(max_digits=4, decimal_places=2) self.assertWidgetRendersTo(f, '') - self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, '') - self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, None) + with self.assertRaisesMessage(ValidationError, "'This field is required.'"): + f.clean('') + with self.assertRaisesMessage(ValidationError, "'This field is required.'"): + f.clean(None) self.assertEqual(f.clean('1'), Decimal("1")) self.assertIsInstance(f.clean('1'), Decimal) self.assertEqual(f.clean('23'), Decimal("23")) self.assertEqual(f.clean('3.14'), Decimal("3.14")) self.assertEqual(f.clean(3.14), Decimal("3.14")) self.assertEqual(f.clean(Decimal('3.14')), Decimal("3.14")) - self.assertRaisesMessage(ValidationError, "'Enter a number.'", f.clean, 'NaN') - self.assertRaisesMessage(ValidationError, "'Enter a number.'", f.clean, 'Inf') - self.assertRaisesMessage(ValidationError, "'Enter a number.'", f.clean, '-Inf') - self.assertRaisesMessage(ValidationError, "'Enter a number.'", f.clean, 'a') - self.assertRaisesMessage(ValidationError, "'Enter a number.'", f.clean, 'łąść') + with self.assertRaisesMessage(ValidationError, "'Enter a number.'"): + f.clean('NaN') + with self.assertRaisesMessage(ValidationError, "'Enter a number.'"): + f.clean('Inf') + with self.assertRaisesMessage(ValidationError, "'Enter a number.'"): + f.clean('-Inf') + with self.assertRaisesMessage(ValidationError, "'Enter a number.'"): + f.clean('a') + with self.assertRaisesMessage(ValidationError, "'Enter a number.'"): + f.clean('łąść') self.assertEqual(f.clean('1.0 '), Decimal("1.0")) self.assertEqual(f.clean(' 1.0'), Decimal("1.0")) self.assertEqual(f.clean(' 1.0 '), Decimal("1.0")) - self.assertRaisesMessage(ValidationError, "'Enter a number.'", f.clean, '1.0a') - self.assertRaisesMessage( - ValidationError, "'Ensure that there are no more than 4 digits in total.'", - f.clean, '123.45' - ) - self.assertRaisesMessage( - ValidationError, "'Ensure that there are no more than 2 decimal places.'", - f.clean, '1.234' - ) - self.assertRaisesMessage( - ValidationError, "'Ensure that there are no more than 2 digits before the decimal point.'", - f.clean, '123.4' - ) + with self.assertRaisesMessage(ValidationError, "'Enter a number.'"): + f.clean('1.0a') + with self.assertRaisesMessage(ValidationError, "'Ensure that there are no more than 4 digits in total.'"): + f.clean('123.45') + with self.assertRaisesMessage(ValidationError, "'Ensure that there are no more than 2 decimal places.'"): + f.clean('1.234') + msg = "'Ensure that there are no more than 2 digits before the decimal point.'" + with self.assertRaisesMessage(ValidationError, msg): + f.clean('123.4') self.assertEqual(f.clean('-12.34'), Decimal("-12.34")) - self.assertRaisesMessage( - ValidationError, "'Ensure that there are no more than 4 digits in total.'", - f.clean, '-123.45' - ) + with self.assertRaisesMessage(ValidationError, "'Ensure that there are no more than 4 digits in total.'"): + f.clean('-123.45') self.assertEqual(f.clean('-.12'), Decimal("-0.12")) self.assertEqual(f.clean('-00.12'), Decimal("-0.12")) self.assertEqual(f.clean('-000.12'), Decimal("-0.12")) - self.assertRaisesMessage( - ValidationError, "'Ensure that there are no more than 2 decimal places.'", - f.clean, '-000.123' - ) - self.assertRaisesMessage( - ValidationError, "'Ensure that there are no more than 4 digits in total.'", - f.clean, '-000.12345' - ) - self.assertRaisesMessage(ValidationError, "'Enter a number.'", f.clean, '--0.12') + with self.assertRaisesMessage(ValidationError, "'Ensure that there are no more than 2 decimal places.'"): + f.clean('-000.123') + with self.assertRaisesMessage(ValidationError, "'Ensure that there are no more than 4 digits in total.'"): + f.clean('-000.12345') + with self.assertRaisesMessage(ValidationError, "'Enter a number.'"): + f.clean('--0.12') self.assertEqual(f.max_digits, 4) self.assertEqual(f.decimal_places, 2) self.assertEqual(f.max_value, None) @@ -435,11 +459,10 @@ class FieldsTests(SimpleTestCase): def test_decimalfield_3(self): f = DecimalField(max_digits=4, decimal_places=2, max_value=Decimal('1.5'), min_value=Decimal('0.5')) self.assertWidgetRendersTo(f, '') - self.assertRaisesMessage(ValidationError, "'Ensure this value is less than or equal to 1.5.'", f.clean, '1.6') - self.assertRaisesMessage( - ValidationError, "'Ensure this value is greater than or equal to 0.5.'", - f.clean, '0.4' - ) + with self.assertRaisesMessage(ValidationError, "'Ensure this value is less than or equal to 1.5.'"): + f.clean('1.6') + with self.assertRaisesMessage(ValidationError, "'Ensure this value is greater than or equal to 0.5.'"): + f.clean('0.4') self.assertEqual(f.clean('1.5'), Decimal("1.5")) self.assertEqual(f.clean('0.5'), Decimal("0.5")) self.assertEqual(f.clean('.5'), Decimal("0.5")) @@ -451,10 +474,8 @@ class FieldsTests(SimpleTestCase): def test_decimalfield_4(self): f = DecimalField(decimal_places=2) - self.assertRaisesMessage( - ValidationError, "'Ensure that there are no more than 2 decimal places.'", - f.clean, '0.00000001' - ) + with self.assertRaisesMessage(ValidationError, "'Ensure that there are no more than 2 decimal places.'"): + f.clean('0.00000001') def test_decimalfield_5(self): f = DecimalField(max_digits=3) @@ -464,19 +485,16 @@ class FieldsTests(SimpleTestCase): self.assertEqual(f.clean('0000000.100'), Decimal("0.100")) # Only leading whole zeros "collapse" to one digit. self.assertEqual(f.clean('000000.02'), Decimal('0.02')) - self.assertRaisesMessage( - ValidationError, "'Ensure that there are no more than 3 digits in total.'", - f.clean, '000000.0002' - ) + with self.assertRaisesMessage(ValidationError, "'Ensure that there are no more than 3 digits in total.'"): + f.clean('000000.0002') self.assertEqual(f.clean('.002'), Decimal("0.002")) def test_decimalfield_6(self): f = DecimalField(max_digits=2, decimal_places=2) self.assertEqual(f.clean('.01'), Decimal(".01")) - self.assertRaisesMessage( - ValidationError, "'Ensure that there are no more than 0 digits before the decimal point.'", - f.clean, '1.1' - ) + msg = "'Ensure that there are no more than 0 digits before the decimal point.'" + with self.assertRaisesMessage(ValidationError, msg): + f.clean('1.1') def test_decimalfield_scientific(self): f = DecimalField(max_digits=2, decimal_places=2) @@ -533,10 +551,14 @@ class FieldsTests(SimpleTestCase): self.assertEqual(datetime.date(2006, 10, 25), f.clean('October 25, 2006')) self.assertEqual(datetime.date(2006, 10, 25), f.clean('25 October 2006')) self.assertEqual(datetime.date(2006, 10, 25), f.clean('25 October, 2006')) - self.assertRaisesMessage(ValidationError, "'Enter a valid date.'", f.clean, '2006-4-31') - self.assertRaisesMessage(ValidationError, "'Enter a valid date.'", f.clean, '200a-10-25') - self.assertRaisesMessage(ValidationError, "'Enter a valid date.'", f.clean, '25/10/06') - self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, None) + with self.assertRaisesMessage(ValidationError, "'Enter a valid date.'"): + f.clean('2006-4-31') + with self.assertRaisesMessage(ValidationError, "'Enter a valid date.'"): + f.clean('200a-10-25') + with self.assertRaisesMessage(ValidationError, "'Enter a valid date.'"): + f.clean('25/10/06') + with self.assertRaisesMessage(ValidationError, "'This field is required.'"): + f.clean(None) def test_datefield_2(self): f = DateField(required=False) @@ -550,9 +572,12 @@ class FieldsTests(SimpleTestCase): self.assertEqual(datetime.date(2006, 10, 25), f.clean(datetime.date(2006, 10, 25))) self.assertEqual(datetime.date(2006, 10, 25), f.clean(datetime.datetime(2006, 10, 25, 14, 30))) self.assertEqual(datetime.date(2006, 10, 25), f.clean('2006 10 25')) - self.assertRaisesMessage(ValidationError, "'Enter a valid date.'", f.clean, '2006-10-25') - self.assertRaisesMessage(ValidationError, "'Enter a valid date.'", f.clean, '10/25/2006') - self.assertRaisesMessage(ValidationError, "'Enter a valid date.'", f.clean, '10/25/06') + with self.assertRaisesMessage(ValidationError, "'Enter a valid date.'"): + f.clean('2006-10-25') + with self.assertRaisesMessage(ValidationError, "'Enter a valid date.'"): + f.clean('10/25/2006') + with self.assertRaisesMessage(ValidationError, "'Enter a valid date.'"): + f.clean('10/25/06') def test_datefield_4(self): # Test whitespace stripping behavior (#5714) @@ -563,12 +588,14 @@ class FieldsTests(SimpleTestCase): self.assertEqual(datetime.date(2006, 10, 25), f.clean(' October 25 2006 ')) self.assertEqual(datetime.date(2006, 10, 25), f.clean(' October 25, 2006 ')) self.assertEqual(datetime.date(2006, 10, 25), f.clean(' 25 October 2006 ')) - self.assertRaisesMessage(ValidationError, "'Enter a valid date.'", f.clean, ' ') + with self.assertRaisesMessage(ValidationError, "'Enter a valid date.'"): + f.clean(' ') def test_datefield_5(self): # Test null bytes (#18982) f = DateField() - self.assertRaisesMessage(ValidationError, "'Enter a valid date.'", f.clean, 'a\x00b') + with self.assertRaisesMessage(ValidationError, "'Enter a valid date.'"): + f.clean('a\x00b') def test_datefield_changed(self): format = '%d/%m/%Y' @@ -594,8 +621,10 @@ class FieldsTests(SimpleTestCase): self.assertEqual(datetime.time(14, 25, 59), f.clean(datetime.time(14, 25, 59))) self.assertEqual(datetime.time(14, 25), f.clean('14:25')) self.assertEqual(datetime.time(14, 25, 59), f.clean('14:25:59')) - self.assertRaisesMessage(ValidationError, "'Enter a valid time.'", f.clean, 'hello') - self.assertRaisesMessage(ValidationError, "'Enter a valid time.'", f.clean, '1:24 p.m.') + with self.assertRaisesMessage(ValidationError, "'Enter a valid time.'"): + f.clean('hello') + with self.assertRaisesMessage(ValidationError, "'Enter a valid time.'"): + f.clean('1:24 p.m.') def test_timefield_2(self): f = TimeField(input_formats=['%I:%M %p']) @@ -603,14 +632,16 @@ class FieldsTests(SimpleTestCase): self.assertEqual(datetime.time(14, 25, 59), f.clean(datetime.time(14, 25, 59))) self.assertEqual(datetime.time(4, 25), f.clean('4:25 AM')) self.assertEqual(datetime.time(16, 25), f.clean('4:25 PM')) - self.assertRaisesMessage(ValidationError, "'Enter a valid time.'", f.clean, '14:30:45') + with self.assertRaisesMessage(ValidationError, "'Enter a valid time.'"): + f.clean('14:30:45') def test_timefield_3(self): f = TimeField() # Test whitespace stripping behavior (#5714) self.assertEqual(datetime.time(14, 25), f.clean(' 14:25 ')) self.assertEqual(datetime.time(14, 25, 59), f.clean(' 14:25:59 ')) - self.assertRaisesMessage(ValidationError, "'Enter a valid time.'", f.clean, ' ') + with self.assertRaisesMessage(ValidationError, "'Enter a valid time.'"): + f.clean(' ') def test_timefield_changed(self): t1 = datetime.time(12, 51, 34, 482548) @@ -650,8 +681,10 @@ class FieldsTests(SimpleTestCase): self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30), f.clean('10/25/06 14:30:00')) self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30), f.clean('10/25/06 14:30')) self.assertEqual(datetime.datetime(2006, 10, 25, 0, 0), f.clean('10/25/06')) - self.assertRaisesMessage(ValidationError, "'Enter a valid date/time.'", f.clean, 'hello') - self.assertRaisesMessage(ValidationError, "'Enter a valid date/time.'", f.clean, '2006-10-25 4:30 p.m.') + with self.assertRaisesMessage(ValidationError, "'Enter a valid date/time.'"): + f.clean('hello') + with self.assertRaisesMessage(ValidationError, "'Enter a valid date/time.'"): + f.clean('2006-10-25 4:30 p.m.') def test_datetimefield_2(self): f = DateTimeField(input_formats=['%Y %m %d %I:%M %p']) @@ -666,7 +699,8 @@ class FieldsTests(SimpleTestCase): f.clean(datetime.datetime(2006, 10, 25, 14, 30, 59, 200)) ) self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30), f.clean('2006 10 25 2:30 PM')) - self.assertRaisesMessage(ValidationError, "'Enter a valid date/time.'", f.clean, '2006-10-25 14:30:45') + with self.assertRaisesMessage(ValidationError, "'Enter a valid date/time.'"): + f.clean('2006-10-25 14:30:45') def test_datetimefield_3(self): f = DateTimeField(required=False) @@ -685,7 +719,8 @@ class FieldsTests(SimpleTestCase): self.assertEqual(datetime.datetime(2006, 10, 25, 0, 0), f.clean(' 10/25/2006 ')) self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30, 45), f.clean(' 10/25/06 14:30:45 ')) self.assertEqual(datetime.datetime(2006, 10, 25, 0, 0), f.clean(' 10/25/06 ')) - self.assertRaisesMessage(ValidationError, "'Enter a valid date/time.'", f.clean, ' ') + with self.assertRaisesMessage(ValidationError, "'Enter a valid date/time.'"): + f.clean(' ') def test_datetimefield_5(self): f = DateTimeField(input_formats=['%Y.%m.%d %H:%M:%S.%f']) @@ -742,32 +777,38 @@ class FieldsTests(SimpleTestCase): f = RegexField('^[0-9][A-F][0-9]$') self.assertEqual('2A2', f.clean('2A2')) self.assertEqual('3F3', f.clean('3F3')) - self.assertRaisesMessage(ValidationError, "'Enter a valid value.'", f.clean, '3G3') - self.assertRaisesMessage(ValidationError, "'Enter a valid value.'", f.clean, ' 2A2') - self.assertRaisesMessage(ValidationError, "'Enter a valid value.'", f.clean, '2A2 ') - self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, '') + with self.assertRaisesMessage(ValidationError, "'Enter a valid value.'"): + f.clean('3G3') + with self.assertRaisesMessage(ValidationError, "'Enter a valid value.'"): + f.clean(' 2A2') + with self.assertRaisesMessage(ValidationError, "'Enter a valid value.'"): + f.clean('2A2 ') + with self.assertRaisesMessage(ValidationError, "'This field is required.'"): + f.clean('') def test_regexfield_2(self): f = RegexField('^[0-9][A-F][0-9]$', required=False) self.assertEqual('2A2', f.clean('2A2')) self.assertEqual('3F3', f.clean('3F3')) - self.assertRaisesMessage(ValidationError, "'Enter a valid value.'", f.clean, '3G3') + with self.assertRaisesMessage(ValidationError, "'Enter a valid value.'"): + f.clean('3G3') self.assertEqual('', f.clean('')) def test_regexfield_3(self): f = RegexField(re.compile('^[0-9][A-F][0-9]$')) self.assertEqual('2A2', f.clean('2A2')) self.assertEqual('3F3', f.clean('3F3')) - self.assertRaisesMessage(ValidationError, "'Enter a valid value.'", f.clean, '3G3') - self.assertRaisesMessage(ValidationError, "'Enter a valid value.'", f.clean, ' 2A2') - self.assertRaisesMessage(ValidationError, "'Enter a valid value.'", f.clean, '2A2 ') + with self.assertRaisesMessage(ValidationError, "'Enter a valid value.'"): + f.clean('3G3') + with self.assertRaisesMessage(ValidationError, "'Enter a valid value.'"): + f.clean(' 2A2') + with self.assertRaisesMessage(ValidationError, "'Enter a valid value.'"): + f.clean('2A2 ') def test_regexfield_5(self): f = RegexField('^[0-9]+$', min_length=5, max_length=10) - self.assertRaisesMessage( - ValidationError, "'Ensure this value has at least 5 characters (it has 3).'", - f.clean, '123' - ) + with self.assertRaisesMessage(ValidationError, "'Ensure this value has at least 5 characters (it has 3).'"): + f.clean('123') six.assertRaisesRegex( self, ValidationError, "'Ensure this value has at least 5 characters \(it has 3\)\.'," @@ -776,11 +817,10 @@ class FieldsTests(SimpleTestCase): ) self.assertEqual('12345', f.clean('12345')) self.assertEqual('1234567890', f.clean('1234567890')) - self.assertRaisesMessage( - ValidationError, "'Ensure this value has at most 10 characters (it has 11).'", - f.clean, '12345678901' - ) - self.assertRaisesMessage(ValidationError, "'Enter a valid value.'", f.clean, '12345a') + with self.assertRaisesMessage(ValidationError, "'Ensure this value has at most 10 characters (it has 11).'"): + f.clean('12345678901') + with self.assertRaisesMessage(ValidationError, "'Enter a valid value.'"): + f.clean('12345a') def test_regexfield_6(self): """ @@ -794,7 +834,8 @@ class FieldsTests(SimpleTestCase): f = RegexField('^[a-z]+$') f.regex = '^[0-9]+$' self.assertEqual('1234', f.clean('1234')) - self.assertRaisesMessage(ValidationError, "'Enter a valid value.'", f.clean, 'abcd') + with self.assertRaisesMessage(ValidationError, "'Enter a valid value.'"): + f.clean('abcd') # EmailField ################################################################## # See also validators tests for validate_email specific tests @@ -802,10 +843,13 @@ class FieldsTests(SimpleTestCase): def test_emailfield_1(self): f = EmailField() self.assertWidgetRendersTo(f, '') - self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, '') - self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, None) + with self.assertRaisesMessage(ValidationError, "'This field is required.'"): + f.clean('') + with self.assertRaisesMessage(ValidationError, "'This field is required.'"): + f.clean(None) self.assertEqual('person@example.com', f.clean('person@example.com')) - self.assertRaisesMessage(ValidationError, "'Enter a valid email address.'", f.clean, 'foo') + with self.assertRaisesMessage(ValidationError, "'Enter a valid email address.'"): + f.clean('foo') self.assertEqual('local@domain.with.idn.xyz\xe4\xf6\xfc\xdfabc.part.com', f.clean('local@domain.with.idn.xyzäöüßabc.part.com')) @@ -822,52 +866,44 @@ class FieldsTests(SimpleTestCase): self.assertEqual('', f.clean(None)) self.assertEqual('person@example.com', f.clean('person@example.com')) self.assertEqual('example@example.com', f.clean(' example@example.com \t \t ')) - self.assertRaisesMessage(ValidationError, "'Enter a valid email address.'", f.clean, 'foo') + with self.assertRaisesMessage(ValidationError, "'Enter a valid email address.'"): + f.clean('foo') def test_emailfield_min_max_length(self): f = EmailField(min_length=10, max_length=15) self.assertWidgetRendersTo(f, '') - self.assertRaisesMessage( - ValidationError, "'Ensure this value has at least 10 characters (it has 9).'", - f.clean, 'a@foo.com' - ) + with self.assertRaisesMessage(ValidationError, "'Ensure this value has at least 10 characters (it has 9).'"): + f.clean('a@foo.com') self.assertEqual('alf@foo.com', f.clean('alf@foo.com')) - self.assertRaisesMessage( - ValidationError, "'Ensure this value has at most 15 characters (it has 20).'", - f.clean, 'alf123456788@foo.com' - ) + with self.assertRaisesMessage(ValidationError, "'Ensure this value has at most 15 characters (it has 20).'"): + f.clean('alf123456788@foo.com') # FileField ################################################################## def test_filefield_1(self): f = FileField() - self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, '') - self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, '', '') + with self.assertRaisesMessage(ValidationError, "'This field is required.'"): + f.clean('') + with self.assertRaisesMessage(ValidationError, "'This field is required.'"): + f.clean('', '') self.assertEqual('files/test1.pdf', f.clean('', 'files/test1.pdf')) - self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, None) - self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, None, '') + with self.assertRaisesMessage(ValidationError, "'This field is required.'"): + f.clean(None) + with self.assertRaisesMessage(ValidationError, "'This field is required.'"): + f.clean(None, '') self.assertEqual('files/test2.pdf', f.clean(None, 'files/test2.pdf')) - self.assertRaisesMessage( - ValidationError, "'No file was submitted. Check the encoding type on the form.'", - f.clean, SimpleUploadedFile('', b'') - ) - self.assertRaisesMessage( - ValidationError, "'No file was submitted. Check the encoding type on the form.'", - f.clean, SimpleUploadedFile('', b''), '' - ) + no_file_msg = "'No file was submitted. Check the encoding type on the form.'" + with self.assertRaisesMessage(ValidationError, no_file_msg): + f.clean(SimpleUploadedFile('', b'')) + with self.assertRaisesMessage(ValidationError, no_file_msg): + f.clean(SimpleUploadedFile('', b''), '') self.assertEqual('files/test3.pdf', f.clean(None, 'files/test3.pdf')) - self.assertRaisesMessage( - ValidationError, "'No file was submitted. Check the encoding type on the form.'", - f.clean, 'some content that is not a file' - ) - self.assertRaisesMessage( - ValidationError, "'The submitted file is empty.'", - f.clean, SimpleUploadedFile('name', None) - ) - self.assertRaisesMessage( - ValidationError, "'The submitted file is empty.'", - f.clean, SimpleUploadedFile('name', b'') - ) + with self.assertRaisesMessage(ValidationError, no_file_msg): + f.clean('some content that is not a file') + with self.assertRaisesMessage(ValidationError, "'The submitted file is empty.'"): + f.clean(SimpleUploadedFile('name', None)) + with self.assertRaisesMessage(ValidationError, "'The submitted file is empty.'"): + f.clean(SimpleUploadedFile('name', b'')) self.assertEqual(SimpleUploadedFile, type(f.clean(SimpleUploadedFile('name', b'Some File Content')))) self.assertIsInstance( f.clean(SimpleUploadedFile('我隻氣墊船裝滿晒鱔.txt', 'मेरी मँडराने वाली नाव सर्पमीनों से भरी ह'.encode('utf-8'))), @@ -880,10 +916,8 @@ class FieldsTests(SimpleTestCase): def test_filefield_2(self): f = FileField(max_length=5) - self.assertRaisesMessage( - ValidationError, "'Ensure this filename has at most 5 characters (it has 18).'", - f.clean, SimpleUploadedFile('test_maxlength.txt', b'hello world') - ) + with self.assertRaisesMessage(ValidationError, "'Ensure this filename has at most 5 characters (it has 18).'"): + f.clean(SimpleUploadedFile('test_maxlength.txt', b'hello world')) self.assertEqual('files/test1.pdf', f.clean('', 'files/test1.pdf')) self.assertEqual('files/test2.pdf', f.clean(None, 'files/test2.pdf')) self.assertEqual(SimpleUploadedFile, type(f.clean(SimpleUploadedFile('name', b'Some File Content')))) @@ -962,8 +996,10 @@ class FieldsTests(SimpleTestCase): def test_urlfield_1(self): f = URLField() self.assertWidgetRendersTo(f, '') - self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, '') - self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, None) + with self.assertRaisesMessage(ValidationError, "'This field is required.'"): + f.clean('') + with self.assertRaisesMessage(ValidationError, "'This field is required.'"): + f.clean(None) self.assertEqual('http://localhost', f.clean('http://localhost')) self.assertEqual('http://example.com', f.clean('http://example.com')) self.assertEqual('http://example.com.', f.clean('http://example.com.')) @@ -973,17 +1009,28 @@ class FieldsTests(SimpleTestCase): self.assertEqual('http://subdomain.domain.com', f.clean('subdomain.domain.com')) self.assertEqual('http://200.8.9.10', f.clean('http://200.8.9.10')) self.assertEqual('http://200.8.9.10:8000/test', f.clean('http://200.8.9.10:8000/test')) - self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'", f.clean, 'foo') - self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'", f.clean, 'http://') - self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'", f.clean, 'http://example') - self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'", f.clean, 'http://example.') - self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'", f.clean, 'com.') - self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'", f.clean, '.') - self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'", f.clean, 'http://.com') - self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'", f.clean, 'http://invalid-.com') - self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'", f.clean, 'http://-invalid.com') - self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'", f.clean, 'http://inv-.alid-.com') - self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'", f.clean, 'http://inv-.-alid.com') + with self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'"): + f.clean('foo') + with self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'"): + f.clean('http://') + with self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'"): + f.clean('http://example') + with self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'"): + f.clean('http://example.') + with self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'"): + f.clean('com.') + with self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'"): + f.clean('.') + with self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'"): + f.clean('http://.com') + with self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'"): + f.clean('http://invalid-.com') + with self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'"): + f.clean('http://-invalid.com') + with self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'"): + f.clean('http://inv-.alid-.com') + with self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'"): + f.clean('http://inv-.-alid.com') self.assertEqual('http://valid-----hyphens.com', f.clean('http://valid-----hyphens.com')) self.assertEqual( 'http://some.idn.xyz\xe4\xf6\xfc\xdfabc.domain.com:123/blah', @@ -993,17 +1040,21 @@ class FieldsTests(SimpleTestCase): 'http://www.example.com/s/http://code.djangoproject.com/ticket/13804', f.clean('www.example.com/s/http://code.djangoproject.com/ticket/13804') ) - self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'", f.clean, '[a') - self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'", f.clean, 'http://[a') + with self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'"): + f.clean('[a') + with self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'"): + f.clean('http://[a') def test_url_regex_ticket11198(self): f = URLField() # hangs "forever" if catastrophic backtracking in ticket:#11198 not fixed - self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'", f.clean, 'http://%s' % ("X" * 200,)) + with self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'"): + f.clean('http://%s' % ("X" * 200,)) # a second test, to make sure the problem is really addressed, even on # domains that don't fail the domain label length check in the regex - self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'", f.clean, 'http://%s' % ("X" * 60,)) + with self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'"): + f.clean('http://%s' % ("X" * 60,)) def test_urlfield_2(self): f = URLField(required=False) @@ -1011,24 +1062,25 @@ class FieldsTests(SimpleTestCase): self.assertEqual('', f.clean(None)) self.assertEqual('http://example.com', f.clean('http://example.com')) self.assertEqual('http://www.example.com', f.clean('http://www.example.com')) - self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'", f.clean, 'foo') - self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'", f.clean, 'http://') - self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'", f.clean, 'http://example') - self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'", f.clean, 'http://example.') - self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'", f.clean, 'http://.com') + with self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'"): + f.clean('foo') + with self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'"): + f.clean('http://') + with self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'"): + f.clean('http://example') + with self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'"): + f.clean('http://example.') + with self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'"): + f.clean('http://.com') def test_urlfield_5(self): f = URLField(min_length=15, max_length=20) self.assertWidgetRendersTo(f, '') - self.assertRaisesMessage( - ValidationError, "'Ensure this value has at least 15 characters (it has 12).'", - f.clean, 'http://f.com' - ) + with self.assertRaisesMessage(ValidationError, "'Ensure this value has at least 15 characters (it has 12).'"): + f.clean('http://f.com') self.assertEqual('http://example.com', f.clean('http://example.com')) - self.assertRaisesMessage( - ValidationError, "'Ensure this value has at most 20 characters (it has 37).'", - f.clean, 'http://abcdefghijklmnopqrstuvwxyz.com' - ) + with self.assertRaisesMessage(ValidationError, "'Ensure this value has at most 20 characters (it has 37).'"): + f.clean('http://abcdefghijklmnopqrstuvwxyz.com') def test_urlfield_6(self): f = URLField(required=False) @@ -1075,7 +1127,8 @@ class FieldsTests(SimpleTestCase): def test_urlfield_not_string(self): f = URLField(required=False) - self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'", f.clean, 23) + with self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'"): + f.clean(23) def test_urlfield_normalization(self): f = URLField() @@ -1085,15 +1138,20 @@ class FieldsTests(SimpleTestCase): def test_booleanfield_1(self): f = BooleanField() - self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, '') - self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, None) + with self.assertRaisesMessage(ValidationError, "'This field is required.'"): + f.clean('') + with self.assertRaisesMessage(ValidationError, "'This field is required.'"): + f.clean(None) self.assertEqual(True, f.clean(True)) - self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, False) + with self.assertRaisesMessage(ValidationError, "'This field is required.'"): + f.clean(False) self.assertEqual(True, f.clean(1)) - self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, 0) + with self.assertRaisesMessage(ValidationError, "'This field is required.'"): + f.clean(0) self.assertEqual(True, f.clean('Django rocks')) self.assertEqual(True, f.clean('True')) - self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, 'False') + with self.assertRaisesMessage(ValidationError, "'This field is required.'"): + f.clean('False') def test_booleanfield_2(self): f = BooleanField(required=False) @@ -1129,14 +1187,15 @@ class FieldsTests(SimpleTestCase): def test_choicefield_1(self): f = ChoiceField(choices=[('1', 'One'), ('2', 'Two')]) - self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, '') - self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, None) + with self.assertRaisesMessage(ValidationError, "'This field is required.'"): + f.clean('') + with self.assertRaisesMessage(ValidationError, "'This field is required.'"): + f.clean(None) self.assertEqual('1', f.clean(1)) self.assertEqual('1', f.clean('1')) - self.assertRaisesMessage( - ValidationError, "'Select a valid choice. 3 is not one of the available choices.'", - f.clean, '3' - ) + msg = "'Select a valid choice. 3 is not one of the available choices.'" + with self.assertRaisesMessage(ValidationError, msg): + f.clean('3') def test_choicefield_2(self): f = ChoiceField(choices=[('1', 'One'), ('2', 'Two')], required=False) @@ -1144,18 +1203,16 @@ class FieldsTests(SimpleTestCase): self.assertEqual('', f.clean(None)) self.assertEqual('1', f.clean(1)) self.assertEqual('1', f.clean('1')) - self.assertRaisesMessage( - ValidationError, "'Select a valid choice. 3 is not one of the available choices.'", - f.clean, '3' - ) + msg = "'Select a valid choice. 3 is not one of the available choices.'" + with self.assertRaisesMessage(ValidationError, msg): + f.clean('3') def test_choicefield_3(self): f = ChoiceField(choices=[('J', 'John'), ('P', 'Paul')]) self.assertEqual('J', f.clean('J')) - self.assertRaisesMessage( - ValidationError, "'Select a valid choice. John is not one of the available choices.'", - f.clean, 'John' - ) + msg = "'Select a valid choice. John is not one of the available choices.'" + with self.assertRaisesMessage(ValidationError, msg): + f.clean('John') def test_choicefield_4(self): f = ChoiceField( @@ -1170,10 +1227,9 @@ class FieldsTests(SimpleTestCase): self.assertEqual('3', f.clean('3')) self.assertEqual('5', f.clean(5)) self.assertEqual('5', f.clean('5')) - self.assertRaisesMessage( - ValidationError, "'Select a valid choice. 6 is not one of the available choices.'", - f.clean, '6' - ) + msg = "'Select a valid choice. 6 is not one of the available choices.'" + with self.assertRaisesMessage(ValidationError, msg): + f.clean('6') def test_choicefield_callable(self): def choices(): @@ -1211,10 +1267,9 @@ class FieldsTests(SimpleTestCase): def test_typedchoicefield_1(self): f = TypedChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=int) self.assertEqual(1, f.clean('1')) - self.assertRaisesMessage( - ValidationError, "'Select a valid choice. 2 is not one of the available choices.'", - f.clean, '2' - ) + msg = "'Select a valid choice. 2 is not one of the available choices.'" + with self.assertRaisesMessage(ValidationError, msg): + f.clean('2') def test_typedchoicefield_2(self): # Different coercion, same validation. @@ -1230,12 +1285,12 @@ class FieldsTests(SimpleTestCase): # Even more weirdness: if you have a valid choice but your coercion function # can't coerce, you'll still get a validation error. Don't do this! f = TypedChoiceField(choices=[('A', 'A'), ('B', 'B')], coerce=int) - self.assertRaisesMessage( - ValidationError, "'Select a valid choice. B is not one of the available choices.'", - f.clean, 'B' - ) + msg = "'Select a valid choice. B is not one of the available choices.'" + with self.assertRaisesMessage(ValidationError, msg): + f.clean('B') # Required fields require values - self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, '') + with self.assertRaisesMessage(ValidationError, "'This field is required.'"): + f.clean('') def test_typedchoicefield_5(self): # Non-required fields aren't required @@ -1272,14 +1327,11 @@ class FieldsTests(SimpleTestCase): f = TypedChoiceField(choices=[(1, "1"), (2, "2")], coerce=coerce_func, required=True) self.assertEqual(Decimal('1.2'), f.clean('2')) - self.assertRaisesMessage( - ValidationError, "'This field is required.'", - f.clean, '' - ) - self.assertRaisesMessage( - ValidationError, "'Select a valid choice. 3 is not one of the available choices.'", - f.clean, '3' - ) + with self.assertRaisesMessage(ValidationError, "'This field is required.'"): + f.clean('') + msg = "'Select a valid choice. 3 is not one of the available choices.'" + with self.assertRaisesMessage(ValidationError, msg): + f.clean('3') # NullBooleanField ############################################################ @@ -1347,20 +1399,24 @@ class FieldsTests(SimpleTestCase): def test_multiplechoicefield_1(self): f = MultipleChoiceField(choices=[('1', 'One'), ('2', 'Two')]) - self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, '') - self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, None) + with self.assertRaisesMessage(ValidationError, "'This field is required.'"): + f.clean('') + with self.assertRaisesMessage(ValidationError, "'This field is required.'"): + f.clean(None) self.assertEqual(['1'], f.clean([1])) self.assertEqual(['1'], f.clean(['1'])) self.assertEqual(['1', '2'], f.clean(['1', '2'])) self.assertEqual(['1', '2'], f.clean([1, '2'])) self.assertEqual(['1', '2'], f.clean((1, '2'))) - self.assertRaisesMessage(ValidationError, "'Enter a list of values.'", f.clean, 'hello') - self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, []) - self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, ()) - self.assertRaisesMessage( - ValidationError, "'Select a valid choice. 3 is not one of the available choices.'", - f.clean, ['3'] - ) + with self.assertRaisesMessage(ValidationError, "'Enter a list of values.'"): + f.clean('hello') + with self.assertRaisesMessage(ValidationError, "'This field is required.'"): + f.clean([]) + with self.assertRaisesMessage(ValidationError, "'This field is required.'"): + f.clean(()) + msg = "'Select a valid choice. 3 is not one of the available choices.'" + with self.assertRaisesMessage(ValidationError, msg): + f.clean(['3']) def test_multiplechoicefield_2(self): f = MultipleChoiceField(choices=[('1', 'One'), ('2', 'Two')], required=False) @@ -1371,13 +1427,13 @@ class FieldsTests(SimpleTestCase): self.assertEqual(['1', '2'], f.clean(['1', '2'])) self.assertEqual(['1', '2'], f.clean([1, '2'])) self.assertEqual(['1', '2'], f.clean((1, '2'))) - self.assertRaisesMessage(ValidationError, "'Enter a list of values.'", f.clean, 'hello') + with self.assertRaisesMessage(ValidationError, "'Enter a list of values.'"): + f.clean('hello') self.assertEqual([], f.clean([])) self.assertEqual([], f.clean(())) - self.assertRaisesMessage( - ValidationError, "'Select a valid choice. 3 is not one of the available choices.'", - f.clean, ['3'] - ) + with self.assertRaisesMessage(ValidationError, + "'Select a valid choice. 3 is not one of the available choices.'"): + f.clean(['3']) def test_multiplechoicefield_3(self): f = MultipleChoiceField( @@ -1389,14 +1445,12 @@ class FieldsTests(SimpleTestCase): self.assertEqual(['1', '5'], f.clean([1, '5'])) self.assertEqual(['1', '5'], f.clean(['1', 5])) self.assertEqual(['1', '5'], f.clean(['1', '5'])) - self.assertRaisesMessage( - ValidationError, "'Select a valid choice. 6 is not one of the available choices.'", - f.clean, ['6'] - ) - self.assertRaisesMessage( - ValidationError, "'Select a valid choice. 6 is not one of the available choices.'", - f.clean, ['1', '6'] - ) + msg = "'Select a valid choice. 6 is not one of the available choices.'" + with self.assertRaisesMessage(ValidationError, msg): + f.clean(['6']) + msg = "'Select a valid choice. 6 is not one of the available choices.'" + with self.assertRaisesMessage(ValidationError, msg): + f.clean(['1', '6']) def test_multiplechoicefield_changed(self): f = MultipleChoiceField(choices=[('1', 'One'), ('2', 'Two'), ('3', 'Three')]) @@ -1415,10 +1469,9 @@ class FieldsTests(SimpleTestCase): def test_typedmultiplechoicefield_1(self): f = TypedMultipleChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=int) self.assertEqual([1], f.clean(['1'])) - self.assertRaisesMessage( - ValidationError, "'Select a valid choice. 2 is not one of the available choices.'", - f.clean, ['2'] - ) + msg = "'Select a valid choice. 2 is not one of the available choices.'" + with self.assertRaisesMessage(ValidationError, msg): + f.clean(['2']) def test_typedmultiplechoicefield_2(self): # Different coercion, same validation. @@ -1433,21 +1486,20 @@ class FieldsTests(SimpleTestCase): def test_typedmultiplechoicefield_4(self): f = TypedMultipleChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=int) self.assertEqual([1, -1], f.clean(['1', '-1'])) - self.assertRaisesMessage( - ValidationError, "'Select a valid choice. 2 is not one of the available choices.'", - f.clean, ['1', '2'] - ) + msg = "'Select a valid choice. 2 is not one of the available choices.'" + with self.assertRaisesMessage(ValidationError, msg): + f.clean(['1', '2']) def test_typedmultiplechoicefield_5(self): # Even more weirdness: if you have a valid choice but your coercion function # can't coerce, you'll still get a validation error. Don't do this! f = TypedMultipleChoiceField(choices=[('A', 'A'), ('B', 'B')], coerce=int) - self.assertRaisesMessage( - ValidationError, "'Select a valid choice. B is not one of the available choices.'", - f.clean, ['B'] - ) + msg = "'Select a valid choice. B is not one of the available choices.'" + with self.assertRaisesMessage(ValidationError, msg): + f.clean(['B']) # Required fields require values - self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, []) + with self.assertRaisesMessage(ValidationError, "'This field is required.'"): + f.clean([]) def test_typedmultiplechoicefield_6(self): # Non-required fields aren't required @@ -1475,33 +1527,33 @@ class FieldsTests(SimpleTestCase): f = TypedMultipleChoiceField( choices=[(1, "1"), (2, "2")], coerce=coerce_func, required=True) self.assertEqual([Decimal('1.2')], f.clean(['2'])) - self.assertRaisesMessage(ValidationError, - "'This field is required.'", f.clean, []) - self.assertRaisesMessage(ValidationError, - "'Select a valid choice. 3 is not one of the available choices.'", - f.clean, ['3']) + with self.assertRaisesMessage(ValidationError, "'This field is required.'"): + f.clean([]) + msg = "'Select a valid choice. 3 is not one of the available choices.'" + with self.assertRaisesMessage(ValidationError, msg): + f.clean(['3']) # ComboField ################################################################## def test_combofield_1(self): f = ComboField(fields=[CharField(max_length=20), EmailField()]) self.assertEqual('test@example.com', f.clean('test@example.com')) - self.assertRaisesMessage( - ValidationError, "'Ensure this value has at most 20 characters (it has 28).'", - f.clean, 'longemailaddress@example.com' - ) - self.assertRaisesMessage(ValidationError, "'Enter a valid email address.'", f.clean, 'not an email') - self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, '') - self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, None) + with self.assertRaisesMessage(ValidationError, "'Ensure this value has at most 20 characters (it has 28).'"): + f.clean('longemailaddress@example.com') + with self.assertRaisesMessage(ValidationError, "'Enter a valid email address.'"): + f.clean('not an email') + with self.assertRaisesMessage(ValidationError, "'This field is required.'"): + f.clean('') + with self.assertRaisesMessage(ValidationError, "'This field is required.'"): + f.clean(None) def test_combofield_2(self): f = ComboField(fields=[CharField(max_length=20), EmailField()], required=False) self.assertEqual('test@example.com', f.clean('test@example.com')) - self.assertRaisesMessage( - ValidationError, "'Ensure this value has at most 20 characters (it has 28).'", - f.clean, 'longemailaddress@example.com' - ) - self.assertRaisesMessage(ValidationError, "'Enter a valid email address.'", f.clean, 'not an email') + with self.assertRaisesMessage(ValidationError, "'Ensure this value has at most 20 characters (it has 28).'"): + f.clean('longemailaddress@example.com') + with self.assertRaisesMessage(ValidationError, "'Enter a valid email address.'"): + f.clean('not an email') self.assertEqual('', f.clean('')) self.assertEqual('', f.clean(None)) @@ -1531,10 +1583,9 @@ class FieldsTests(SimpleTestCase): for exp, got in zip(expected, fix_os_paths(f.choices)): self.assertEqual(exp[1], got[1]) self.assertTrue(got[0].endswith(exp[0])) - self.assertRaisesMessage( - ValidationError, "'Select a valid choice. fields.py is not one of the available choices.'", - f.clean, 'fields.py' - ) + msg = "'Select a valid choice. fields.py is not one of the available choices.'" + with self.assertRaisesMessage(ValidationError, msg): + f.clean('fields.py') assert fix_os_paths(f.clean(path + 'fields.py')).endswith('/django/forms/fields.py') def test_filepathfield_3(self): @@ -1615,15 +1666,20 @@ class FieldsTests(SimpleTestCase): datetime.datetime(2006, 1, 10, 7, 30), f.clean([datetime.date(2006, 1, 10), datetime.time(7, 30)]) ) - self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, None) - self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, '') - self.assertRaisesMessage(ValidationError, "'Enter a list of values.'", f.clean, 'hello') + with self.assertRaisesMessage(ValidationError, "'This field is required.'"): + f.clean(None) + with self.assertRaisesMessage(ValidationError, "'This field is required.'"): + f.clean('') + with self.assertRaisesMessage(ValidationError, "'Enter a list of values.'"): + f.clean('hello') six.assertRaisesRegex( self, ValidationError, "'Enter a valid date\.', u?'Enter a valid time\.'", f.clean, ['hello', 'there'] ) - self.assertRaisesMessage(ValidationError, "'Enter a valid time.'", f.clean, ['2006-01-10', 'there']) - self.assertRaisesMessage(ValidationError, "'Enter a valid date.'", f.clean, ['hello', '07:30']) + with self.assertRaisesMessage(ValidationError, "'Enter a valid time.'"): + f.clean(['2006-01-10', 'there']) + with self.assertRaisesMessage(ValidationError, "'Enter a valid date.'"): + f.clean(['hello', '07:30']) def test_splitdatetimefield_2(self): f = SplitDateTimeField(required=False) @@ -1636,16 +1692,22 @@ class FieldsTests(SimpleTestCase): self.assertIsNone(f.clean('')) self.assertIsNone(f.clean([''])) self.assertIsNone(f.clean(['', ''])) - self.assertRaisesMessage(ValidationError, "'Enter a list of values.'", f.clean, 'hello') + with self.assertRaisesMessage(ValidationError, "'Enter a list of values.'"): + f.clean('hello') six.assertRaisesRegex( self, ValidationError, "'Enter a valid date\.', u?'Enter a valid time\.'", f.clean, ['hello', 'there'] ) - self.assertRaisesMessage(ValidationError, "'Enter a valid time.'", f.clean, ['2006-01-10', 'there']) - self.assertRaisesMessage(ValidationError, "'Enter a valid date.'", f.clean, ['hello', '07:30']) - self.assertRaisesMessage(ValidationError, "'Enter a valid time.'", f.clean, ['2006-01-10', '']) - self.assertRaisesMessage(ValidationError, "'Enter a valid time.'", f.clean, ['2006-01-10']) - self.assertRaisesMessage(ValidationError, "'Enter a valid date.'", f.clean, ['', '07:30']) + with self.assertRaisesMessage(ValidationError, "'Enter a valid time.'"): + f.clean(['2006-01-10', 'there']) + with self.assertRaisesMessage(ValidationError, "'Enter a valid date.'"): + f.clean(['hello', '07:30']) + with self.assertRaisesMessage(ValidationError, "'Enter a valid time.'"): + f.clean(['2006-01-10', '']) + with self.assertRaisesMessage(ValidationError, "'Enter a valid time.'"): + f.clean(['2006-01-10']) + with self.assertRaisesMessage(ValidationError, "'Enter a valid date.'"): + f.clean(['', '07:30']) def test_splitdatetimefield_changed(self): f = SplitDateTimeField(input_date_formats=['%d/%m/%Y']) @@ -1666,75 +1728,106 @@ class FieldsTests(SimpleTestCase): # The edge cases of the IPv6 validation code are not deeply tested # here, they are covered in the tests for django.utils.ipv6 f = GenericIPAddressField() - self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, '') - self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, None) + with self.assertRaisesMessage(ValidationError, "'This field is required.'"): + f.clean('') + with self.assertRaisesMessage(ValidationError, "'This field is required.'"): + f.clean(None) self.assertEqual(f.clean(' 127.0.0.1 '), '127.0.0.1') - self.assertRaisesMessage(ValidationError, "'Enter a valid IPv4 or IPv6 address.'", f.clean, 'foo') - self.assertRaisesMessage(ValidationError, "'Enter a valid IPv4 or IPv6 address.'", f.clean, '127.0.0.') - self.assertRaisesMessage(ValidationError, "'Enter a valid IPv4 or IPv6 address.'", f.clean, '1.2.3.4.5') - self.assertRaisesMessage(ValidationError, "'Enter a valid IPv4 or IPv6 address.'", f.clean, '256.125.1.5') + with self.assertRaisesMessage(ValidationError, "'Enter a valid IPv4 or IPv6 address.'"): + f.clean('foo') + with self.assertRaisesMessage(ValidationError, "'Enter a valid IPv4 or IPv6 address.'"): + f.clean('127.0.0.') + with self.assertRaisesMessage(ValidationError, "'Enter a valid IPv4 or IPv6 address.'"): + f.clean('1.2.3.4.5') + with self.assertRaisesMessage(ValidationError, "'Enter a valid IPv4 or IPv6 address.'"): + f.clean('256.125.1.5') self.assertEqual(f.clean(' fe80::223:6cff:fe8a:2e8a '), 'fe80::223:6cff:fe8a:2e8a') self.assertEqual(f.clean(' 2a02::223:6cff:fe8a:2e8a '), '2a02::223:6cff:fe8a:2e8a') - self.assertRaisesMessage(ValidationError, "'This is not a valid IPv6 address.'", f.clean, '12345:2:3:4') - self.assertRaisesMessage(ValidationError, "'This is not a valid IPv6 address.'", f.clean, '1::2:3::4') - self.assertRaisesMessage( - ValidationError, "'This is not a valid IPv6 address.'", - f.clean, 'foo::223:6cff:fe8a:2e8a' - ) - self.assertRaisesMessage(ValidationError, "'This is not a valid IPv6 address.'", f.clean, '1::2:3:4:5:6:7:8') - self.assertRaisesMessage(ValidationError, "'This is not a valid IPv6 address.'", f.clean, '1:2') + with self.assertRaisesMessage(ValidationError, "'This is not a valid IPv6 address.'"): + f.clean('12345:2:3:4') + with self.assertRaisesMessage(ValidationError, "'This is not a valid IPv6 address.'"): + f.clean('1::2:3::4') + with self.assertRaisesMessage(ValidationError, "'This is not a valid IPv6 address.'"): + f.clean('foo::223:6cff:fe8a:2e8a') + with self.assertRaisesMessage(ValidationError, "'This is not a valid IPv6 address.'"): + f.clean('1::2:3:4:5:6:7:8') + with self.assertRaisesMessage(ValidationError, "'This is not a valid IPv6 address.'"): + f.clean('1:2') def test_generic_ipaddress_as_ipv4_only(self): f = GenericIPAddressField(protocol="IPv4") - self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, '') - self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, None) + with self.assertRaisesMessage(ValidationError, "'This field is required.'"): + f.clean('') + with self.assertRaisesMessage(ValidationError, "'This field is required.'"): + f.clean(None) self.assertEqual(f.clean(' 127.0.0.1 '), '127.0.0.1') - self.assertRaisesMessage(ValidationError, "'Enter a valid IPv4 address.'", f.clean, 'foo') - self.assertRaisesMessage(ValidationError, "'Enter a valid IPv4 address.'", f.clean, '127.0.0.') - self.assertRaisesMessage(ValidationError, "'Enter a valid IPv4 address.'", f.clean, '1.2.3.4.5') - self.assertRaisesMessage(ValidationError, "'Enter a valid IPv4 address.'", f.clean, '256.125.1.5') - self.assertRaisesMessage(ValidationError, "'Enter a valid IPv4 address.'", f.clean, 'fe80::223:6cff:fe8a:2e8a') - self.assertRaisesMessage(ValidationError, "'Enter a valid IPv4 address.'", f.clean, '2a02::223:6cff:fe8a:2e8a') + with self.assertRaisesMessage(ValidationError, "'Enter a valid IPv4 address.'"): + f.clean('foo') + with self.assertRaisesMessage(ValidationError, "'Enter a valid IPv4 address.'"): + f.clean('127.0.0.') + with self.assertRaisesMessage(ValidationError, "'Enter a valid IPv4 address.'"): + f.clean('1.2.3.4.5') + with self.assertRaisesMessage(ValidationError, "'Enter a valid IPv4 address.'"): + f.clean('256.125.1.5') + with self.assertRaisesMessage(ValidationError, "'Enter a valid IPv4 address.'"): + f.clean('fe80::223:6cff:fe8a:2e8a') + with self.assertRaisesMessage(ValidationError, "'Enter a valid IPv4 address.'"): + f.clean('2a02::223:6cff:fe8a:2e8a') def test_generic_ipaddress_as_ipv6_only(self): f = GenericIPAddressField(protocol="IPv6") - self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, '') - self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, None) - self.assertRaisesMessage(ValidationError, "'Enter a valid IPv6 address.'", f.clean, '127.0.0.1') - self.assertRaisesMessage(ValidationError, "'Enter a valid IPv6 address.'", f.clean, 'foo') - self.assertRaisesMessage(ValidationError, "'Enter a valid IPv6 address.'", f.clean, '127.0.0.') - self.assertRaisesMessage(ValidationError, "'Enter a valid IPv6 address.'", f.clean, '1.2.3.4.5') - self.assertRaisesMessage(ValidationError, "'Enter a valid IPv6 address.'", f.clean, '256.125.1.5') + with self.assertRaisesMessage(ValidationError, "'This field is required.'"): + f.clean('') + with self.assertRaisesMessage(ValidationError, "'This field is required.'"): + f.clean(None) + with self.assertRaisesMessage(ValidationError, "'Enter a valid IPv6 address.'"): + f.clean('127.0.0.1') + with self.assertRaisesMessage(ValidationError, "'Enter a valid IPv6 address.'"): + f.clean('foo') + with self.assertRaisesMessage(ValidationError, "'Enter a valid IPv6 address.'"): + f.clean('127.0.0.') + with self.assertRaisesMessage(ValidationError, "'Enter a valid IPv6 address.'"): + f.clean('1.2.3.4.5') + with self.assertRaisesMessage(ValidationError, "'Enter a valid IPv6 address.'"): + f.clean('256.125.1.5') self.assertEqual(f.clean(' fe80::223:6cff:fe8a:2e8a '), 'fe80::223:6cff:fe8a:2e8a') self.assertEqual(f.clean(' 2a02::223:6cff:fe8a:2e8a '), '2a02::223:6cff:fe8a:2e8a') - self.assertRaisesMessage(ValidationError, "'This is not a valid IPv6 address.'", f.clean, '12345:2:3:4') - self.assertRaisesMessage(ValidationError, "'This is not a valid IPv6 address.'", f.clean, '1::2:3::4') - self.assertRaisesMessage( - ValidationError, "'This is not a valid IPv6 address.'", - f.clean, 'foo::223:6cff:fe8a:2e8a' - ) - self.assertRaisesMessage(ValidationError, "'This is not a valid IPv6 address.'", f.clean, '1::2:3:4:5:6:7:8') - self.assertRaisesMessage(ValidationError, "'This is not a valid IPv6 address.'", f.clean, '1:2') + with self.assertRaisesMessage(ValidationError, "'This is not a valid IPv6 address.'"): + f.clean('12345:2:3:4') + with self.assertRaisesMessage(ValidationError, "'This is not a valid IPv6 address.'"): + f.clean('1::2:3::4') + with self.assertRaisesMessage(ValidationError, "'This is not a valid IPv6 address.'"): + f.clean('foo::223:6cff:fe8a:2e8a') + with self.assertRaisesMessage(ValidationError, "'This is not a valid IPv6 address.'"): + f.clean('1::2:3:4:5:6:7:8') + with self.assertRaisesMessage(ValidationError, "'This is not a valid IPv6 address.'"): + f.clean('1:2') def test_generic_ipaddress_as_generic_not_required(self): f = GenericIPAddressField(required=False) self.assertEqual(f.clean(''), '') self.assertEqual(f.clean(None), '') self.assertEqual(f.clean('127.0.0.1'), '127.0.0.1') - self.assertRaisesMessage(ValidationError, "'Enter a valid IPv4 or IPv6 address.'", f.clean, 'foo') - self.assertRaisesMessage(ValidationError, "'Enter a valid IPv4 or IPv6 address.'", f.clean, '127.0.0.') - self.assertRaisesMessage(ValidationError, "'Enter a valid IPv4 or IPv6 address.'", f.clean, '1.2.3.4.5') - self.assertRaisesMessage(ValidationError, "'Enter a valid IPv4 or IPv6 address.'", f.clean, '256.125.1.5') + with self.assertRaisesMessage(ValidationError, "'Enter a valid IPv4 or IPv6 address.'"): + f.clean('foo') + with self.assertRaisesMessage(ValidationError, "'Enter a valid IPv4 or IPv6 address.'"): + f.clean('127.0.0.') + with self.assertRaisesMessage(ValidationError, "'Enter a valid IPv4 or IPv6 address.'"): + f.clean('1.2.3.4.5') + with self.assertRaisesMessage(ValidationError, "'Enter a valid IPv4 or IPv6 address.'"): + f.clean('256.125.1.5') self.assertEqual(f.clean(' fe80::223:6cff:fe8a:2e8a '), 'fe80::223:6cff:fe8a:2e8a') self.assertEqual(f.clean(' 2a02::223:6cff:fe8a:2e8a '), '2a02::223:6cff:fe8a:2e8a') - self.assertRaisesMessage(ValidationError, "'This is not a valid IPv6 address.'", f.clean, '12345:2:3:4') - self.assertRaisesMessage(ValidationError, "'This is not a valid IPv6 address.'", f.clean, '1::2:3::4') - self.assertRaisesMessage( - ValidationError, "'This is not a valid IPv6 address.'", - f.clean, 'foo::223:6cff:fe8a:2e8a' - ) - self.assertRaisesMessage(ValidationError, "'This is not a valid IPv6 address.'", f.clean, '1::2:3:4:5:6:7:8') - self.assertRaisesMessage(ValidationError, "'This is not a valid IPv6 address.'", f.clean, '1:2') + with self.assertRaisesMessage(ValidationError, "'This is not a valid IPv6 address.'"): + f.clean('12345:2:3:4') + with self.assertRaisesMessage(ValidationError, "'This is not a valid IPv6 address.'"): + f.clean('1::2:3::4') + with self.assertRaisesMessage(ValidationError, "'This is not a valid IPv6 address.'"): + f.clean('foo::223:6cff:fe8a:2e8a') + with self.assertRaisesMessage(ValidationError, "'This is not a valid IPv6 address.'"): + f.clean('1::2:3:4:5:6:7:8') + with self.assertRaisesMessage(ValidationError, "'This is not a valid IPv6 address.'"): + f.clean('1:2') def test_generic_ipaddress_normalization(self): # Test the normalizing code diff --git a/tests/forms_tests/tests/test_forms.py b/tests/forms_tests/tests/test_forms.py index 66b1737e6f..17703f2d23 100644 --- a/tests/forms_tests/tests/test_forms.py +++ b/tests/forms_tests/tests/test_forms.py @@ -2733,14 +2733,19 @@ Good luck picking a username that doesn't already exist.

# An empty value for any field will raise a `required` error on a # required `MultiValueField`. f = PhoneField() - self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, '') - self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, None) - self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, []) - self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, ['+61']) - self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, ['+61', '287654321', '123']) + with self.assertRaisesMessage(ValidationError, "'This field is required.'"): + f.clean('') + with self.assertRaisesMessage(ValidationError, "'This field is required.'"): + f.clean(None) + with self.assertRaisesMessage(ValidationError, "'This field is required.'"): + f.clean([]) + with self.assertRaisesMessage(ValidationError, "'This field is required.'"): + f.clean(['+61']) + with self.assertRaisesMessage(ValidationError, "'This field is required.'"): + f.clean(['+61', '287654321', '123']) self.assertEqual('+61.287654321 ext. 123 (label: Home)', f.clean(['+61', '287654321', '123', 'Home'])) - self.assertRaisesMessage(ValidationError, - "'Enter a valid country code.'", f.clean, ['61', '287654321', '123', 'Home']) + with self.assertRaisesMessage(ValidationError, "'Enter a valid country code.'"): + f.clean(['61', '287654321', '123', 'Home']) # Empty values for fields will NOT raise a `required` error on an # optional `MultiValueField` @@ -2751,23 +2756,27 @@ Good luck picking a username that doesn't already exist.

self.assertEqual('+61. ext. (label: )', f.clean(['+61'])) self.assertEqual('+61.287654321 ext. 123 (label: )', f.clean(['+61', '287654321', '123'])) self.assertEqual('+61.287654321 ext. 123 (label: Home)', f.clean(['+61', '287654321', '123', 'Home'])) - self.assertRaisesMessage(ValidationError, - "'Enter a valid country code.'", f.clean, ['61', '287654321', '123', 'Home']) + with self.assertRaisesMessage(ValidationError, "'Enter a valid country code.'"): + f.clean(['61', '287654321', '123', 'Home']) # For a required `MultiValueField` with `require_all_fields=False`, a # `required` error will only be raised if all fields are empty. Fields # can individually be required or optional. An empty value for any # required field will raise an `incomplete` error. f = PhoneField(require_all_fields=False) - self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, '') - self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, None) - self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, []) - self.assertRaisesMessage(ValidationError, "'Enter a complete value.'", f.clean, ['+61']) + with self.assertRaisesMessage(ValidationError, "'This field is required.'"): + f.clean('') + with self.assertRaisesMessage(ValidationError, "'This field is required.'"): + f.clean(None) + with self.assertRaisesMessage(ValidationError, "'This field is required.'"): + f.clean([]) + with self.assertRaisesMessage(ValidationError, "'Enter a complete value.'"): + f.clean(['+61']) self.assertEqual('+61.287654321 ext. 123 (label: )', f.clean(['+61', '287654321', '123'])) six.assertRaisesRegex(self, ValidationError, "'Enter a complete value\.', u?'Enter an extension\.'", f.clean, ['', '', '', 'Home']) - self.assertRaisesMessage(ValidationError, - "'Enter a valid country code.'", f.clean, ['61', '287654321', '123', 'Home']) + with self.assertRaisesMessage(ValidationError, "'Enter a valid country code.'"): + f.clean(['61', '287654321', '123', 'Home']) # For an optional `MultiValueField` with `require_all_fields=False`, we # don't get any `required` error but we still get `incomplete` errors. @@ -2775,12 +2784,13 @@ Good luck picking a username that doesn't already exist.

self.assertIsNone(f.clean('')) self.assertIsNone(f.clean(None)) self.assertIsNone(f.clean([])) - self.assertRaisesMessage(ValidationError, "'Enter a complete value.'", f.clean, ['+61']) + with self.assertRaisesMessage(ValidationError, "'Enter a complete value.'"): + f.clean(['+61']) self.assertEqual('+61.287654321 ext. 123 (label: )', f.clean(['+61', '287654321', '123'])) six.assertRaisesRegex(self, ValidationError, "'Enter a complete value\.', u?'Enter an extension\.'", f.clean, ['', '', '', 'Home']) - self.assertRaisesMessage(ValidationError, - "'Enter a valid country code.'", f.clean, ['61', '287654321', '123', 'Home']) + with self.assertRaisesMessage(ValidationError, "'Enter a valid country code.'"): + f.clean(['61', '287654321', '123', 'Home']) def test_custom_empty_values(self): """ diff --git a/tests/forms_tests/widget_tests/test_selectdatewidget.py b/tests/forms_tests/widget_tests/test_selectdatewidget.py index e95c083532..6efa240b66 100644 --- a/tests/forms_tests/widget_tests/test_selectdatewidget.py +++ b/tests/forms_tests/widget_tests/test_selectdatewidget.py @@ -384,8 +384,8 @@ class SelectDateWidgetTest(WidgetTest): """, ) - self.assertRaisesMessage(ValueError, 'empty_label list/tuple must have 3 elements.', - SelectDateWidget, years=('2014',), empty_label=('not enough', 'values')) + with self.assertRaisesMessage(ValueError, 'empty_label list/tuple must have 3 elements.'): + SelectDateWidget(years=('2014',), empty_label=('not enough', 'values')) @override_settings(USE_L10N=True) @translation.override('nl') diff --git a/tests/get_earliest_or_latest/tests.py b/tests/get_earliest_or_latest/tests.py index d74a0724d7..e03f701da6 100644 --- a/tests/get_earliest_or_latest/tests.py +++ b/tests/get_earliest_or_latest/tests.py @@ -58,12 +58,12 @@ class EarliestOrLatestTests(TestCase): # Ensure that error is raised if the user forgot to add a get_latest_by # in the Model.Meta Article.objects.model._meta.get_latest_by = None - self.assertRaisesMessage( + with self.assertRaisesMessage( AssertionError, "earliest() and latest() require either a field_name parameter or " - "'get_latest_by' in the model", - lambda: Article.objects.earliest(), - ) + "'get_latest_by' in the model" + ): + Article.objects.earliest() def test_latest(self): # Because no Articles exist yet, latest() raises ArticleDoesNotExist. @@ -109,12 +109,11 @@ class EarliestOrLatestTests(TestCase): # Ensure that error is raised if the user forgot to add a get_latest_by # in the Model.Meta Article.objects.model._meta.get_latest_by = None - self.assertRaisesMessage( + with self.assertRaisesMessage( AssertionError, - "earliest() and latest() require either a field_name parameter or " - "'get_latest_by' in the model", - lambda: Article.objects.latest(), - ) + "earliest() and latest() require either a field_name parameter or " + "'get_latest_by' in the model"): + Article.objects.latest() def test_latest_manual(self): # You can still use latest() with a model that doesn't have diff --git a/tests/get_object_or_404/tests.py b/tests/get_object_or_404/tests.py index 55d1de7c2c..ac4b2d4738 100644 --- a/tests/get_object_or_404/tests.py +++ b/tests/get_object_or_404/tests.py @@ -81,27 +81,18 @@ class GetObjectOr404Tests(TestCase): def test_bad_class(self): # Given an argument klass that is not a Model, Manager, or Queryset # raises a helpful ValueError message - self.assertRaisesMessage( - ValueError, - "Object is of type 'str', but must be a Django Model, Manager, " - "or QuerySet", - get_object_or_404, str("Article"), title__icontains="Run" - ) + msg = "Object is of type 'str', but must be a Django Model, Manager, or QuerySet" + with self.assertRaisesMessage(ValueError, msg): + get_object_or_404(str("Article"), title__icontains="Run") class CustomClass(object): pass - self.assertRaisesMessage( - ValueError, - "Object is of type 'CustomClass', but must be a Django Model, " - "Manager, or QuerySet", - get_object_or_404, CustomClass, title__icontains="Run" - ) + msg = "Object is of type 'CustomClass', but must be a Django Model, Manager, or QuerySet" + with self.assertRaisesMessage(ValueError, msg): + get_object_or_404(CustomClass, title__icontains="Run") # Works for lists too - self.assertRaisesMessage( - ValueError, - "Object is of type 'list', but must be a Django Model, Manager, " - "or QuerySet", - get_list_or_404, [Article], title__icontains="Run" - ) + msg = "Object is of type 'list', but must be a Django Model, Manager, or QuerySet" + with self.assertRaisesMessage(ValueError, msg): + get_list_or_404([Article], title__icontains="Run") diff --git a/tests/invalid_models_tests/test_relative_fields.py b/tests/invalid_models_tests/test_relative_fields.py index c2895f681f..ba0354d5e1 100644 --- a/tests/invalid_models_tests/test_relative_fields.py +++ b/tests/invalid_models_tests/test_relative_fields.py @@ -1355,9 +1355,8 @@ class M2mThroughFieldsTests(SimpleTestCase): class Fan(models.Model): pass - self.assertRaisesMessage( - ValueError, 'Cannot specify through_fields without a through model', - models.ManyToManyField, Fan, through_fields=('f1', 'f2')) + with self.assertRaisesMessage(ValueError, 'Cannot specify through_fields without a through model'): + models.ManyToManyField(Fan, through_fields=('f1', 'f2')) def test_invalid_order(self): """ diff --git a/tests/mail/tests.py b/tests/mail/tests.py index 58b6151efb..fe564ad765 100644 --- a/tests/mail/tests.py +++ b/tests/mail/tests.py @@ -1109,8 +1109,8 @@ class SMTPBackendTests(BaseEmailBackendTests, SMTPBackendTestsBase): backend = smtp.EmailBackend( username='not empty username', password='not empty password') try: - self.assertRaisesMessage(SMTPException, - 'SMTP AUTH extension not supported by server.', backend.open) + with self.assertRaisesMessage(SMTPException, 'SMTP AUTH extension not supported by server.'): + backend.open() finally: backend.close() @@ -1185,8 +1185,8 @@ class SMTPBackendTests(BaseEmailBackendTests, SMTPBackendTestsBase): backend = smtp.EmailBackend() self.assertTrue(backend.use_tls) try: - self.assertRaisesMessage(SMTPException, - 'STARTTLS extension not supported by server.', backend.open) + with self.assertRaisesMessage(SMTPException, 'STARTTLS extension not supported by server.'): + backend.open() finally: backend.close() diff --git a/tests/many_to_one/tests.py b/tests/many_to_one/tests.py index 692a3e15e4..b3028e00ca 100644 --- a/tests/many_to_one/tests.py +++ b/tests/many_to_one/tests.py @@ -490,17 +490,12 @@ class ManyToOneTests(TestCase): def test_values_list_exception(self): expected_message = "Cannot resolve keyword 'notafield' into field. Choices are: %s" - - self.assertRaisesMessage(FieldError, - expected_message % ', '.join(sorted(f.name for f in Reporter._meta.get_fields())), - Article.objects.values_list, - 'reporter__notafield') - self.assertRaisesMessage( - FieldError, - expected_message % ', '.join(['EXTRA'] + sorted(f.name for f in Article._meta.get_fields())), - Article.objects.extra(select={'EXTRA': 'EXTRA_SELECT'}).values_list, - 'notafield' - ) + reporter_fields = ', '.join(sorted(f.name for f in Reporter._meta.get_fields())) + with self.assertRaisesMessage(FieldError, expected_message % reporter_fields): + Article.objects.values_list('reporter__notafield') + article_fields = ', '.join(['EXTRA'] + sorted(f.name for f in Article._meta.get_fields())) + with self.assertRaisesMessage(FieldError, expected_message % article_fields): + Article.objects.extra(select={'EXTRA': 'EXTRA_SELECT'}).values_list('notafield') def test_fk_assignment_and_related_object_cache(self): # Tests of ForeignKey assignment and the related-object cache (see #6886). diff --git a/tests/model_fields/test_uuid.py b/tests/model_fields/test_uuid.py index 5cded8d6af..050075444e 100644 --- a/tests/model_fields/test_uuid.py +++ b/tests/model_fields/test_uuid.py @@ -47,13 +47,11 @@ class TestSaveLoad(TestCase): PrimaryKeyUUIDModel.objects.get(pk=[]) def test_wrong_value(self): - self.assertRaisesMessage( - ValueError, 'badly formed hexadecimal UUID string', - UUIDModel.objects.get, field='not-a-uuid') + with self.assertRaisesMessage(ValueError, 'badly formed hexadecimal UUID string'): + UUIDModel.objects.get(field='not-a-uuid') - self.assertRaisesMessage( - ValueError, 'badly formed hexadecimal UUID string', - UUIDModel.objects.create, field='not-a-uuid') + with self.assertRaisesMessage(ValueError, 'badly formed hexadecimal UUID string'): + UUIDModel.objects.create(field='not-a-uuid') class TestMigrations(SimpleTestCase): diff --git a/tests/queries/tests.py b/tests/queries/tests.py index b00b64027e..376208c62d 100644 --- a/tests/queries/tests.py +++ b/tests/queries/tests.py @@ -431,16 +431,10 @@ class Queries1Tests(BaseQuerysetTest): def test_heterogeneous_qs_combination(self): # Combining querysets built on different models should behave in a well-defined # fashion. We raise an error. - self.assertRaisesMessage( - AssertionError, - 'Cannot combine queries on two different base models.', - lambda: Author.objects.all() & Tag.objects.all() - ) - self.assertRaisesMessage( - AssertionError, - 'Cannot combine queries on two different base models.', - lambda: Author.objects.all() | Tag.objects.all() - ) + with self.assertRaisesMessage(AssertionError, 'Cannot combine queries on two different base models.'): + Author.objects.all() & Tag.objects.all() + with self.assertRaisesMessage(AssertionError, 'Cannot combine queries on two different base models.'): + Author.objects.all() | Tag.objects.all() def test_ticket3141(self): self.assertEqual(Author.objects.extra(select={'foo': '1'}).count(), 4) @@ -759,11 +753,8 @@ class Queries1Tests(BaseQuerysetTest): [] ) q.query.low_mark = 1 - self.assertRaisesMessage( - AssertionError, - 'Cannot change a query once a slice has been taken', - q.extra, select={'foo': "1"} - ) + with self.assertRaisesMessage(AssertionError, 'Cannot change a query once a slice has been taken'): + q.extra(select={'foo': "1"}) self.assertQuerysetEqual(q.reverse(), []) self.assertQuerysetEqual(q.defer('meal'), []) self.assertQuerysetEqual(q.only('meal'), []) @@ -790,16 +781,10 @@ class Queries1Tests(BaseQuerysetTest): ) # Multi-valued values() and values_list() querysets should raise errors. - self.assertRaisesMessage( - TypeError, - 'Cannot use multi-field values as a filter value.', - lambda: Tag.objects.filter(name__in=Tag.objects.filter(parent=self.t1).values('name', 'id')) - ) - self.assertRaisesMessage( - TypeError, - 'Cannot use multi-field values as a filter value.', - lambda: Tag.objects.filter(name__in=Tag.objects.filter(parent=self.t1).values_list('name', 'id')) - ) + with self.assertRaisesMessage(TypeError, 'Cannot use multi-field values as a filter value.'): + Tag.objects.filter(name__in=Tag.objects.filter(parent=self.t1).values('name', 'id')) + with self.assertRaisesMessage(TypeError, 'Cannot use multi-field values as a filter value.'): + Tag.objects.filter(name__in=Tag.objects.filter(parent=self.t1).values_list('name', 'id')) def test_ticket9985(self): # qs.values_list(...).values(...) combinations should work. @@ -1329,11 +1314,8 @@ class Queries3Tests(BaseQuerysetTest): def test_ticket8683(self): # An error should be raised when QuerySet.datetimes() is passed the # wrong type of field. - self.assertRaisesMessage( - AssertionError, - "'name' isn't a DateTimeField.", - Item.objects.datetimes, 'name', 'month' - ) + with self.assertRaisesMessage(AssertionError, "'name' isn't a DateTimeField."): + Item.objects.datetimes('name', 'month') def test_ticket22023(self): with self.assertRaisesMessage(TypeError, @@ -2413,11 +2395,8 @@ class WeirdQuerysetSlicingTests(BaseQuerysetTest): self.assertQuerysetEqual(Article.objects.all()[0:0], []) self.assertQuerysetEqual(Article.objects.all()[0:0][:10], []) self.assertEqual(Article.objects.all()[:0].count(), 0) - self.assertRaisesMessage( - AssertionError, - 'Cannot change a query once a slice has been taken.', - Article.objects.all()[:0].latest, 'created' - ) + with self.assertRaisesMessage(AssertionError, 'Cannot change a query once a slice has been taken.'): + Article.objects.all()[:0].latest('created') def test_empty_resultset_sql(self): # ticket #12192 @@ -2528,16 +2507,10 @@ class ConditionalTests(BaseQuerysetTest): def test_infinite_loop(self): # If you're not careful, it's possible to introduce infinite loops via # default ordering on foreign keys in a cycle. We detect that. - self.assertRaisesMessage( - FieldError, - 'Infinite loop caused by ordering.', - lambda: list(LoopX.objects.all()) # Force queryset evaluation with list() - ) - self.assertRaisesMessage( - FieldError, - 'Infinite loop caused by ordering.', - lambda: list(LoopZ.objects.all()) # Force queryset evaluation with list() - ) + with self.assertRaisesMessage(FieldError, 'Infinite loop caused by ordering.'): + list(LoopX.objects.all()) # Force queryset evaluation with list() + with self.assertRaisesMessage(FieldError, 'Infinite loop caused by ordering.'): + list(LoopZ.objects.all()) # Force queryset evaluation with list() # Note that this doesn't cause an infinite loop, since the default # ordering on the Tag model is empty (and thus defaults to using "id" diff --git a/tests/requests/tests.py b/tests/requests/tests.py index 280320ae43..8113cb7685 100644 --- a/tests/requests/tests.py +++ b/tests/requests/tests.py @@ -772,11 +772,8 @@ class HostValidationTests(SimpleTestCase): ]: request = HttpRequest() request.META = {'HTTP_HOST': host} - self.assertRaisesMessage( - SuspiciousOperation, - msg_suggestion % (host, host), - request.get_host - ) + with self.assertRaisesMessage(SuspiciousOperation, msg_suggestion % (host, host)): + request.get_host() for domain, port in [ # Valid-looking hosts with a port number ('example.com', 80), @@ -786,28 +783,19 @@ class HostValidationTests(SimpleTestCase): host = '%s:%s' % (domain, port) request = HttpRequest() request.META = {'HTTP_HOST': host} - self.assertRaisesMessage( - SuspiciousOperation, - msg_suggestion % (host, domain), - request.get_host - ) + with self.assertRaisesMessage(SuspiciousOperation, msg_suggestion % (host, domain)): + request.get_host() for host in self.poisoned_hosts: request = HttpRequest() request.META = {'HTTP_HOST': host} - self.assertRaisesMessage( - SuspiciousOperation, - msg_invalid_host % host, - request.get_host - ) + with self.assertRaisesMessage(SuspiciousOperation, msg_invalid_host % host): + request.get_host() request = HttpRequest() request.META = {'HTTP_HOST': "invalid_hostname.com"} - self.assertRaisesMessage( - SuspiciousOperation, - msg_suggestion2 % "invalid_hostname.com", - request.get_host - ) + with self.assertRaisesMessage(SuspiciousOperation, msg_suggestion2 % "invalid_hostname.com"): + request.get_host() class BuildAbsoluteURITestCase(SimpleTestCase): diff --git a/tests/test_utils/tests.py b/tests/test_utils/tests.py index fdc7a7e5dc..c4d51833f4 100644 --- a/tests/test_utils/tests.py +++ b/tests/test_utils/tests.py @@ -801,7 +801,8 @@ class AssertRaisesMsgTest(SimpleTestCase): """assertRaisesMessage shouldn't interpret RE special chars.""" def func1(): raise ValueError("[.*x+]y?") - self.assertRaisesMessage(ValueError, "[.*x+]y?", func1) + with self.assertRaisesMessage(ValueError, "[.*x+]y?"): + func1() @ignore_warnings(category=RemovedInDjango20Warning) def test_callable_obj_param(self): diff --git a/tests/urlpatterns_reverse/tests.py b/tests/urlpatterns_reverse/tests.py index b949cb0173..5c695df9f5 100644 --- a/tests/urlpatterns_reverse/tests.py +++ b/tests/urlpatterns_reverse/tests.py @@ -252,13 +252,13 @@ class NoURLPatternsTests(SimpleTestCase): """ resolver = RegexURLResolver(r'^$', settings.ROOT_URLCONF) - self.assertRaisesMessage( + with self.assertRaisesMessage( ImproperlyConfigured, "The included URLconf 'urlpatterns_reverse.no_urls' does not " "appear to have any patterns in it. If you see valid patterns in " - "the file then the issue is probably caused by a circular import.", - getattr, resolver, 'url_patterns' - ) + "the file then the issue is probably caused by a circular import." + ): + getattr(resolver, 'url_patterns') @override_settings(ROOT_URLCONF='urlpatterns_reverse.urls') diff --git a/tests/utils_tests/test_datastructures.py b/tests/utils_tests/test_datastructures.py index d151f12bb5..c90ef470bb 100644 --- a/tests/utils_tests/test_datastructures.py +++ b/tests/utils_tests/test_datastructures.py @@ -108,8 +108,8 @@ class ImmutableListTests(SimpleTestCase): d = ImmutableList(range(10)) # AttributeError: ImmutableList object is immutable. - self.assertRaisesMessage(AttributeError, - 'ImmutableList object is immutable.', d.sort) + with self.assertRaisesMessage(AttributeError, 'ImmutableList object is immutable.'): + d.sort() self.assertEqual(repr(d), '(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)') @@ -119,8 +119,8 @@ class ImmutableListTests(SimpleTestCase): self.assertEqual(d[1], 1) # AttributeError: Object is immutable! - self.assertRaisesMessage(AttributeError, - 'Object is immutable!', d.__setitem__, 1, 'test') + with self.assertRaisesMessage(AttributeError, 'Object is immutable!'): + d.__setitem__(1, 'test') class DictWrapperTests(SimpleTestCase):