From 51890ce8898f821d28f2f6fb6071c936e9bd88f0 Mon Sep 17 00:00:00 2001
From: Claude Paroz
Date: Sun, 21 Dec 2014 21:19:05 +0100
Subject: [PATCH] Applied ignore_warnings to Django tests
---
django/contrib/auth/tests/test_views.py | 15 +-
.../contrib/gis/tests/geoapp/test_sitemaps.py | 22 +--
django/contrib/sessions/tests.py | 21 +--
.../contrib/sitemaps/tests/test_flatpages.py | 8 +-
django/contrib/sitemaps/tests/test_http.py | 54 +++---
django/contrib/sitemaps/tests/test_https.py | 37 ++--
tests/admin_checks/tests.py | 26 ++-
tests/admin_scripts/tests.py | 11 +-
tests/admin_validation/tests.py | 172 ++++++------------
tests/aggregation/tests.py | 16 +-
tests/backends/tests.py | 15 +-
tests/cache/tests.py | 9 +-
tests/commands_sql/tests.py | 13 +-
tests/deprecation/tests.py | 1 +
tests/field_deconstruction/tests.py | 6 +-
tests/fixtures/tests.py | 15 +-
.../forms_tests/tests/test_error_messages.py | 6 +-
tests/forms_tests/tests/test_extra.py | 9 +-
tests/forms_tests/tests/test_fields.py | 15 +-
tests/forms_tests/tests/test_forms.py | 13 +-
tests/forms_tests/tests/test_regressions.py | 25 ++-
tests/forms_tests/tests/test_widgets.py | 24 +--
tests/generic_views/test_base.py | 6 +-
tests/get_or_create/tests.py | 14 +-
tests/i18n/urls.py | 13 +-
tests/indexes/tests.py | 7 +-
tests/inspectdb/models.py | 6 +-
tests/migrations/test_writer.py | 14 +-
tests/model_fields/models.py | 5 +-
tests/model_fields/tests.py | 20 +-
tests/modeladmin/tests.py | 18 +-
tests/resolve_url/tests.py | 10 +-
tests/serializers_regress/models.py | 5 +-
tests/serializers_regress/tests.py | 13 +-
tests/shortcuts/tests.py | 38 ++--
tests/string_lookup/models.py | 5 +-
.../filter_tests/test_removetags.py | 60 +++---
.../filter_tests/test_unordered_list.py | 64 +++----
.../template_tests/syntax_tests/test_cycle.py | 19 +-
.../syntax_tests/test_filter_syntax.py | 8 +-
.../syntax_tests/test_firstof.py | 24 +--
tests/template_tests/syntax_tests/test_for.py | 42 ++---
tests/template_tests/syntax_tests/test_ssi.py | 17 +-
tests/template_tests/syntax_tests/test_url.py | 103 +++++------
tests/template_tests/test_custom.py | 10 +-
tests/template_tests/test_loaders.py | 10 +-
tests/template_tests/test_response.py | 8 +-
tests/test_client_regress/tests.py | 40 ++--
tests/test_client_regress/views.py | 8 +-
tests/urlpatterns_reverse/tests.py | 25 ++-
tests/user_commands/tests.py | 8 +-
tests/utils_tests/test_checksums.py | 10 +-
tests/utils_tests/test_datastructures.py | 10 +-
tests/utils_tests/test_html.py | 17 +-
tests/utils_tests/test_module_loading.py | 7 +-
tests/utils_tests/test_text.py | 22 +--
tests/utils_tests/test_tzinfo.py | 5 +-
57 files changed, 513 insertions(+), 711 deletions(-)
diff --git a/django/contrib/auth/tests/test_views.py b/django/contrib/auth/tests/test_views.py
index b28615374c..d406b436b3 100644
--- a/django/contrib/auth/tests/test_views.py
+++ b/django/contrib/auth/tests/test_views.py
@@ -1,7 +1,6 @@
from importlib import import_module
import itertools
import re
-import warnings
from django.apps import apps
from django.conf import settings
@@ -15,11 +14,12 @@ from django.contrib.auth.views import login as login_view
from django.core import mail
from django.core.urlresolvers import reverse, NoReverseMatch
from django.http import QueryDict, HttpRequest
+from django.utils.deprecation import RemovedInDjango20Warning
from django.utils.encoding import force_text
from django.utils.http import urlquote
from django.utils.six.moves.urllib.parse import urlparse, ParseResult
from django.utils.translation import LANGUAGE_SESSION_KEY
-from django.test import TestCase, override_settings
+from django.test import TestCase, ignore_warnings, override_settings
from django.test.utils import patch_logger
from django.middleware.csrf import CsrfViewMiddleware
from django.contrib.sessions.middleware import SessionMiddleware
@@ -154,15 +154,14 @@ class PasswordResetTest(AuthViewsTestCase):
self.assertEqual(len(mail.outbox), 1)
self.assertEqual("staffmember@example.com", mail.outbox[0].from_email)
+ @ignore_warnings(category=RemovedInDjango20Warning)
@override_settings(ALLOWED_HOSTS=['adminsite.com'])
def test_admin_reset(self):
"If the reset view is marked as being for admin, the HTTP_HOST header is used for a domain override."
- with warnings.catch_warnings(record=True):
- warnings.simplefilter("always")
- response = self.client.post('/admin_password_reset/',
- {'email': 'staffmember@example.com'},
- HTTP_HOST='adminsite.com'
- )
+ response = self.client.post('/admin_password_reset/',
+ {'email': 'staffmember@example.com'},
+ HTTP_HOST='adminsite.com'
+ )
self.assertEqual(response.status_code, 302)
self.assertEqual(len(mail.outbox), 1)
self.assertIn("http://adminsite.com", mail.outbox[0].body)
diff --git a/django/contrib/gis/tests/geoapp/test_sitemaps.py b/django/contrib/gis/tests/geoapp/test_sitemaps.py
index 5f5dfda3a0..4ef2bb9702 100644
--- a/django/contrib/gis/tests/geoapp/test_sitemaps.py
+++ b/django/contrib/gis/tests/geoapp/test_sitemaps.py
@@ -2,14 +2,13 @@ from __future__ import unicode_literals
from io import BytesIO
from xml.dom import minidom
-import warnings
import zipfile
from django.conf import settings
from django.contrib.gis.geos import HAS_GEOS
from django.contrib.sites.models import Site
from django.test import (
- TestCase, modify_settings, override_settings, skipUnlessDBFeature
+ TestCase, ignore_warnings, modify_settings, override_settings, skipUnlessDBFeature
)
from django.utils.deprecation import RemovedInDjango20Warning
@@ -32,19 +31,18 @@ class GeoSitemapTest(TestCase):
expected = set(expected)
self.assertEqual(actual, expected)
+ @ignore_warnings(category=RemovedInDjango20Warning)
def test_geositemap_kml(self):
"Tests KML/KMZ geographic sitemaps."
for kml_type in ('kml', 'kmz'):
- with warnings.catch_warnings():
- warnings.filterwarnings("ignore", category=RemovedInDjango20Warning)
- # The URL for the sitemaps in urls.py have been updated
- # with a name but since reversing by Python path is tried first
- # before reversing by name and works since we're giving
- # name='django.contrib.gis.sitemaps.views.(kml|kmz)', we need
- # to silence the erroneous warning until reversing by dotted
- # path is removed. The test will work without modification when
- # it's removed.
- doc = minidom.parseString(self.client.get('/sitemaps/%s.xml' % kml_type).content)
+ # The URL for the sitemaps in urls.py have been updated
+ # with a name but since reversing by Python path is tried first
+ # before reversing by name and works since we're giving
+ # name='django.contrib.gis.sitemaps.views.(kml|kmz)', we need
+ # to silence the erroneous warning until reversing by dotted
+ # path is removed. The test will work without modification when
+ # it's removed.
+ doc = minidom.parseString(self.client.get('/sitemaps/%s.xml' % kml_type).content)
# Ensuring the right sitemaps namespace is present.
urlset = doc.firstChild
diff --git a/django/contrib/sessions/tests.py b/django/contrib/sessions/tests.py
index 6679899a34..097cded2f0 100644
--- a/django/contrib/sessions/tests.py
+++ b/django/contrib/sessions/tests.py
@@ -5,7 +5,6 @@ import shutil
import string
import tempfile
import unittest
-import warnings
from django.conf import settings
from django.contrib.sessions.backends.db import SessionStore as DatabaseSession
@@ -20,7 +19,7 @@ from django.core.cache.backends.base import InvalidCacheBackendError
from django.core import management
from django.core.exceptions import ImproperlyConfigured
from django.http import HttpResponse
-from django.test import TestCase, RequestFactory, override_settings
+from django.test import TestCase, RequestFactory, ignore_warnings, override_settings
from django.test.utils import patch_logger
from django.utils import six
from django.utils import timezone
@@ -393,12 +392,11 @@ class CacheDBSessionTests(SessionTestsMixin, TestCase):
with self.assertNumQueries(0):
self.assertTrue(self.session.exists(self.session.session_key))
+ # Some backends might issue a warning
+ @ignore_warnings(module="django.core.cache.backends.base")
def test_load_overlong_key(self):
- # Some backends might issue a warning
- with warnings.catch_warnings():
- warnings.simplefilter("ignore")
- self.session._session_key = (string.ascii_letters + string.digits) * 20
- self.assertEqual(self.session.load(), {})
+ self.session._session_key = (string.ascii_letters + string.digits) * 20
+ self.assertEqual(self.session.load(), {})
@override_settings(SESSION_CACHE_ALIAS='sessions')
def test_non_default_cache(self):
@@ -486,12 +484,11 @@ class CacheSessionTests(SessionTestsMixin, unittest.TestCase):
backend = CacheSession
+ # Some backends might issue a warning
+ @ignore_warnings(module="django.core.cache.backends.base")
def test_load_overlong_key(self):
- # Some backends might issue a warning
- with warnings.catch_warnings():
- warnings.simplefilter("ignore")
- self.session._session_key = (string.ascii_letters + string.digits) * 20
- self.assertEqual(self.session.load(), {})
+ self.session._session_key = (string.ascii_letters + string.digits) * 20
+ self.assertEqual(self.session.load(), {})
def test_default_cache(self):
self.session.save()
diff --git a/django/contrib/sitemaps/tests/test_flatpages.py b/django/contrib/sitemaps/tests/test_flatpages.py
index 1d6f58e77e..ecfe2c094d 100644
--- a/django/contrib/sitemaps/tests/test_flatpages.py
+++ b/django/contrib/sitemaps/tests/test_flatpages.py
@@ -6,13 +6,15 @@ import warnings
from django.apps import apps
from django.conf import settings
from django.contrib.sitemaps import FlatPageSitemap
-from django.test import SimpleTestCase
+from django.test import SimpleTestCase, ignore_warnings
+from django.utils.deprecation import RemovedInDjango19Warning
from .base import SitemapTestsBase
class FlatpagesSitemapTests(SitemapTestsBase):
+ @ignore_warnings(category=RemovedInDjango19Warning)
@skipUnless(apps.is_installed('django.contrib.flatpages'),
"django.contrib.flatpages app not installed.")
def test_flatpage_sitemap(self):
@@ -38,9 +40,7 @@ class FlatpagesSitemapTests(SitemapTestsBase):
registration_required=True
)
private.sites.add(settings.SITE_ID)
- with warnings.catch_warnings():
- warnings.simplefilter('ignore')
- response = self.client.get('/flatpages/sitemap.xml')
+ response = self.client.get('/flatpages/sitemap.xml')
# Public flatpage should be in the sitemap
self.assertContains(response, '%s%s' % (self.base_url, public.url))
# Private flatpage should not be in the sitemap
diff --git a/django/contrib/sitemaps/tests/test_http.py b/django/contrib/sitemaps/tests/test_http.py
index b5700af626..dde9e97c01 100644
--- a/django/contrib/sitemaps/tests/test_http.py
+++ b/django/contrib/sitemaps/tests/test_http.py
@@ -3,14 +3,13 @@ from __future__ import unicode_literals
import os
from datetime import date
from unittest import skipUnless
-import warnings
from django.apps import apps
from django.conf import settings
from django.contrib.sitemaps import Sitemap, GenericSitemap
from django.contrib.sites.models import Site
from django.core.exceptions import ImproperlyConfigured
-from django.test import modify_settings, override_settings
+from django.test import ignore_warnings, modify_settings, override_settings
from django.utils.deprecation import RemovedInDjango20Warning
from django.utils.formats import localize
from django.utils._os import upath
@@ -21,17 +20,16 @@ from .base import TestModel, SitemapTestsBase
class HTTPSitemapTests(SitemapTestsBase):
+ @ignore_warnings(category=RemovedInDjango20Warning)
def test_simple_sitemap_index(self):
"A simple sitemap index can be rendered"
- with warnings.catch_warnings():
- warnings.filterwarnings("ignore", category=RemovedInDjango20Warning)
- # The URL for views.sitemap in tests/urls/http.py has been updated
- # with a name but since reversing by Python path is tried first
- # before reversing by name and works since we're giving
- # name='django.contrib.sitemaps.views.sitemap', we need to silence
- # the erroneous warning until reversing by dotted path is removed.
- # The test will work without modification when it's removed.
- response = self.client.get('/simple/index.xml')
+ # The URL for views.sitemap in tests/urls/http.py has been updated
+ # with a name but since reversing by Python path is tried first
+ # before reversing by name and works since we're giving
+ # name='django.contrib.sitemaps.views.sitemap', we need to silence
+ # the erroneous warning until reversing by dotted path is removed.
+ # The test will work without modification when it's removed.
+ response = self.client.get('/simple/index.xml')
expected_content = """
%s/simple/sitemap-simple.xml
@@ -39,21 +37,20 @@ class HTTPSitemapTests(SitemapTestsBase):
""" % self.base_url
self.assertXMLEqual(response.content.decode('utf-8'), expected_content)
+ @ignore_warnings(category=RemovedInDjango20Warning)
@override_settings(TEMPLATES=[{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(os.path.dirname(upath(__file__)), 'templates')],
}])
def test_simple_sitemap_custom_index(self):
"A simple sitemap index can be rendered with a custom template"
- with warnings.catch_warnings():
- warnings.filterwarnings("ignore", category=RemovedInDjango20Warning)
- # The URL for views.sitemap in tests/urls/http.py has been updated
- # with a name but since reversing by Python path is tried first
- # before reversing by name and works since we're giving
- # name='django.contrib.sitemaps.views.sitemap', we need to silence
- # the erroneous warning until reversing by dotted path is removed.
- # The test will work without modification when it's removed.
- response = self.client.get('/simple/custom-index.xml')
+ # The URL for views.sitemap in tests/urls/http.py has been updated
+ # with a name but since reversing by Python path is tried first
+ # before reversing by name and works since we're giving
+ # name='django.contrib.sitemaps.views.sitemap', we need to silence
+ # the erroneous warning until reversing by dotted path is removed.
+ # The test will work without modification when it's removed.
+ response = self.client.get('/simple/custom-index.xml')
expected_content = """
@@ -196,16 +193,15 @@ class HTTPSitemapTests(SitemapTestsBase):
""" % self.base_url
self.assertXMLEqual(response.content.decode('utf-8'), expected_content)
+ @ignore_warnings(category=RemovedInDjango20Warning)
def test_x_robots_sitemap(self):
- with warnings.catch_warnings():
- warnings.filterwarnings("ignore", category=RemovedInDjango20Warning)
- # The URL for views.sitemap in tests/urls/http.py has been updated
- # with a name but since reversing by Python path is tried first
- # before reversing by name and works since we're giving
- # name='django.contrib.sitemaps.views.sitemap', we need to silence
- # the erroneous warning until reversing by dotted path is removed.
- # The test will work without modification when it's removed.
- response = self.client.get('/simple/index.xml')
+ # The URL for views.sitemap in tests/urls/http.py has been updated
+ # with a name but since reversing by Python path is tried first
+ # before reversing by name and works since we're giving
+ # name='django.contrib.sitemaps.views.sitemap', we need to silence
+ # the erroneous warning until reversing by dotted path is removed.
+ # The test will work without modification when it's removed.
+ response = self.client.get('/simple/index.xml')
self.assertEqual(response['X-Robots-Tag'], 'noindex, noodp, noarchive')
response = self.client.get('/simple/sitemap.xml')
diff --git a/django/contrib/sitemaps/tests/test_https.py b/django/contrib/sitemaps/tests/test_https.py
index 66d44d9554..95537ae412 100644
--- a/django/contrib/sitemaps/tests/test_https.py
+++ b/django/contrib/sitemaps/tests/test_https.py
@@ -1,9 +1,8 @@
from __future__ import unicode_literals
from datetime import date
-import warnings
-from django.test import override_settings
+from django.test import ignore_warnings, override_settings
from django.utils.deprecation import RemovedInDjango20Warning
from .base import SitemapTestsBase
@@ -13,17 +12,16 @@ from .base import SitemapTestsBase
class HTTPSSitemapTests(SitemapTestsBase):
protocol = 'https'
+ @ignore_warnings(category=RemovedInDjango20Warning)
def test_secure_sitemap_index(self):
"A secure sitemap index can be rendered"
- with warnings.catch_warnings():
- warnings.filterwarnings("ignore", category=RemovedInDjango20Warning)
- # The URL for views.sitemap in tests/urls/https.py has been updated
- # with a name but since reversing by Python path is tried first
- # before reversing by name and works since we're giving
- # name='django.contrib.sitemaps.views.sitemap', we need to silence
- # the erroneous warning until reversing by dotted path is removed.
- # The test will work without modification when it's removed.
- response = self.client.get('/secure/index.xml')
+ # The URL for views.sitemap in tests/urls/https.py has been updated
+ # with a name but since reversing by Python path is tried first
+ # before reversing by name and works since we're giving
+ # name='django.contrib.sitemaps.views.sitemap', we need to silence
+ # the erroneous warning until reversing by dotted path is removed.
+ # The test will work without modification when it's removed.
+ response = self.client.get('/secure/index.xml')
expected_content = """
%s/secure/sitemap-simple.xml
@@ -46,17 +44,16 @@ class HTTPSSitemapTests(SitemapTestsBase):
class HTTPSDetectionSitemapTests(SitemapTestsBase):
extra = {'wsgi.url_scheme': 'https'}
+ @ignore_warnings(category=RemovedInDjango20Warning)
def test_sitemap_index_with_https_request(self):
"A sitemap index requested in HTTPS is rendered with HTTPS links"
- with warnings.catch_warnings():
- warnings.filterwarnings("ignore", category=RemovedInDjango20Warning)
- # The URL for views.sitemap in tests/urls/https.py has been updated
- # with a name but since reversing by Python path is tried first
- # before reversing by name and works since we're giving
- # name='django.contrib.sitemaps.views.sitemap', we need to silence
- # the erroneous warning until reversing by dotted path is removed.
- # The test will work without modification when it's removed.
- response = self.client.get('/simple/index.xml', **self.extra)
+ # The URL for views.sitemap in tests/urls/https.py has been updated
+ # with a name but since reversing by Python path is tried first
+ # before reversing by name and works since we're giving
+ # name='django.contrib.sitemaps.views.sitemap', we need to silence
+ # the erroneous warning until reversing by dotted path is removed.
+ # The test will work without modification when it's removed.
+ response = self.client.get('/simple/index.xml', **self.extra)
expected_content = """
%s/simple/sitemap-simple.xml
diff --git a/tests/admin_checks/tests.py b/tests/admin_checks/tests.py
index 500a889c71..d8e6c125dd 100644
--- a/tests/admin_checks/tests.py
+++ b/tests/admin_checks/tests.py
@@ -1,14 +1,11 @@
from __future__ import unicode_literals
-import warnings
-
from django import forms
from django.contrib import admin
from django.contrib.contenttypes.admin import GenericStackedInline
from django.core import checks
from django.core.exceptions import ImproperlyConfigured
-from django.test import TestCase
-from django.test.utils import override_settings
+from django.test import TestCase, ignore_warnings, override_settings
from .models import Song, Book, Album, TwoAlbumFKAndAnE, City, State, Influence
@@ -589,6 +586,7 @@ class SystemChecksTestCase(TestCase):
errors = FieldsOnFormOnlyAdmin.check(model=Song)
self.assertEqual(errors, [])
+ @ignore_warnings(module='django.contrib.admin.options')
def test_validator_compatibility(self):
class MyValidator(object):
def validate(self, cls, model):
@@ -597,18 +595,16 @@ class SystemChecksTestCase(TestCase):
class MyModelAdmin(admin.ModelAdmin):
validator_class = MyValidator
- with warnings.catch_warnings(record=True):
- warnings.filterwarnings('ignore', module='django.contrib.admin.options')
- errors = MyModelAdmin.check(model=Song)
+ errors = MyModelAdmin.check(model=Song)
- expected = [
- checks.Error(
- 'error!',
- hint=None,
- obj=MyModelAdmin,
- )
- ]
- self.assertEqual(errors, expected)
+ expected = [
+ checks.Error(
+ 'error!',
+ hint=None,
+ obj=MyModelAdmin,
+ )
+ ]
+ self.assertEqual(errors, expected)
def test_check_sublists_for_duplicates(self):
class MyModelAdmin(admin.ModelAdmin):
diff --git a/tests/admin_scripts/tests.py b/tests/admin_scripts/tests.py
index 086e5365a1..c0c14d5bc5 100644
--- a/tests/admin_scripts/tests.py
+++ b/tests/admin_scripts/tests.py
@@ -15,17 +15,17 @@ import socket
import subprocess
import sys
import unittest
-import warnings
import django
from django import conf, get_version
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.core.management import BaseCommand, CommandError, call_command, color
+from django.utils.deprecation import RemovedInDjango19Warning
from django.utils.encoding import force_text
from django.utils._os import npath, upath
from django.utils.six import StringIO
-from django.test import LiveServerTestCase, TestCase, mock, override_settings
+from django.test import LiveServerTestCase, TestCase, ignore_warnings, mock, override_settings
from django.test.runner import DiscoverRunner
@@ -1663,11 +1663,10 @@ class CommandTypes(AdminScriptTestCase):
self.assertOutput(out, "EXECUTE:LabelCommand label=testlabel, options=[('no_color', False), ('pythonpath', None), ('settings', None), ('traceback', False), ('verbosity', 1)]")
self.assertOutput(out, "EXECUTE:LabelCommand label=anotherlabel, options=[('no_color', False), ('pythonpath', None), ('settings', None), ('traceback', False), ('verbosity', 1)]")
+ @ignore_warnings(category=RemovedInDjango19Warning)
def test_requires_model_validation_and_requires_system_checks_both_defined(self):
- with warnings.catch_warnings(record=True):
- warnings.filterwarnings('ignore', module='django.core.management.base')
- from .management.commands.validation_command import InvalidCommand
- self.assertRaises(ImproperlyConfigured, InvalidCommand)
+ from .management.commands.validation_command import InvalidCommand
+ self.assertRaises(ImproperlyConfigured, InvalidCommand)
class Discovery(TestCase):
diff --git a/tests/admin_validation/tests.py b/tests/admin_validation/tests.py
index 251493f12b..321e10428c 100644
--- a/tests/admin_validation/tests.py
+++ b/tests/admin_validation/tests.py
@@ -1,12 +1,11 @@
from __future__ import unicode_literals
-import warnings
-
from django import forms
from django.contrib import admin
from django.core.exceptions import ImproperlyConfigured
-from django.test import TestCase
+from django.test import TestCase, ignore_warnings
from django.test.utils import str_prefix
+from django.utils.deprecation import RemovedInDjango19Warning
from .models import Song, Book, Album, TwoAlbumFKAndAnE, City
@@ -33,6 +32,7 @@ class ValidFormFieldsets(admin.ModelAdmin):
)
+@ignore_warnings(category=RemovedInDjango19Warning)
class ValidationTestCase(TestCase):
def test_readonly_and_editable(self):
@@ -44,17 +44,13 @@ class ValidationTestCase(TestCase):
}),
]
- with warnings.catch_warnings(record=True):
- warnings.filterwarnings('ignore', module='django.contrib.admin.options')
- SongAdmin.validate(Song)
+ SongAdmin.validate(Song)
def test_custom_modelforms_with_fields_fieldsets(self):
"""
# Regression test for #8027: custom ModelForms with fields/fieldsets
"""
- with warnings.catch_warnings(record=True):
- warnings.filterwarnings('ignore', module='django.contrib.admin.options')
- ValidFields.validate(Song)
+ ValidFields.validate(Song)
def test_custom_get_form_with_fieldsets(self):
"""
@@ -62,9 +58,7 @@ class ValidationTestCase(TestCase):
is overridden.
Refs #19445.
"""
- with warnings.catch_warnings(record=True):
- warnings.filterwarnings('ignore', module='django.contrib.admin.options')
- ValidFormFieldsets.validate(Song)
+ ValidFormFieldsets.validate(Song)
def test_exclude_values(self):
"""
@@ -73,23 +67,19 @@ class ValidationTestCase(TestCase):
class ExcludedFields1(admin.ModelAdmin):
exclude = ('foo')
- with warnings.catch_warnings(record=True):
- warnings.filterwarnings('ignore', module='django.contrib.admin.options')
- self.assertRaisesMessage(ImproperlyConfigured,
- "'ExcludedFields1.exclude' must be a list or tuple.",
- ExcludedFields1.validate,
- Book)
+ self.assertRaisesMessage(ImproperlyConfigured,
+ "'ExcludedFields1.exclude' must be a list or tuple.",
+ ExcludedFields1.validate,
+ Book)
def test_exclude_duplicate_values(self):
class ExcludedFields2(admin.ModelAdmin):
exclude = ('name', 'name')
- with warnings.catch_warnings(record=True):
- warnings.filterwarnings('ignore', module='django.contrib.admin.options')
- self.assertRaisesMessage(ImproperlyConfigured,
- "There are duplicate field(s) in ExcludedFields2.exclude",
- ExcludedFields2.validate,
- Book)
+ self.assertRaisesMessage(ImproperlyConfigured,
+ "There are duplicate field(s) in ExcludedFields2.exclude",
+ ExcludedFields2.validate,
+ Book)
def test_exclude_in_inline(self):
class ExcludedFieldsInline(admin.TabularInline):
@@ -100,12 +90,10 @@ class ValidationTestCase(TestCase):
model = Album
inlines = [ExcludedFieldsInline]
- with warnings.catch_warnings(record=True):
- warnings.filterwarnings('ignore', module='django.contrib.admin.options')
- self.assertRaisesMessage(ImproperlyConfigured,
- "'ExcludedFieldsInline.exclude' must be a list or tuple.",
- ExcludedFieldsAlbumAdmin.validate,
- Album)
+ self.assertRaisesMessage(ImproperlyConfigured,
+ "'ExcludedFieldsInline.exclude' must be a list or tuple.",
+ ExcludedFieldsAlbumAdmin.validate,
+ Album)
def test_exclude_inline_model_admin(self):
"""
@@ -120,12 +108,10 @@ class ValidationTestCase(TestCase):
model = Album
inlines = [SongInline]
- with warnings.catch_warnings(record=True):
- warnings.filterwarnings('ignore', module='django.contrib.admin.options')
- self.assertRaisesMessage(ImproperlyConfigured,
- "SongInline cannot exclude the field 'album' - this is the foreign key to the parent model admin_validation.Album.",
- AlbumAdmin.validate,
- Album)
+ self.assertRaisesMessage(ImproperlyConfigured,
+ "SongInline cannot exclude the field 'album' - this is the foreign key to the parent model admin_validation.Album.",
+ AlbumAdmin.validate,
+ Album)
def test_app_label_in_admin_validation(self):
"""
@@ -134,12 +120,10 @@ class ValidationTestCase(TestCase):
class RawIdNonexistingAdmin(admin.ModelAdmin):
raw_id_fields = ('nonexisting',)
- with warnings.catch_warnings(record=True):
- warnings.filterwarnings('ignore', module='django.contrib.admin.options')
- self.assertRaisesMessage(ImproperlyConfigured,
- "'RawIdNonexistingAdmin.raw_id_fields' refers to field 'nonexisting' that is missing from model 'admin_validation.Album'.",
- RawIdNonexistingAdmin.validate,
- Album)
+ self.assertRaisesMessage(ImproperlyConfigured,
+ "'RawIdNonexistingAdmin.raw_id_fields' refers to field 'nonexisting' that is missing from model 'admin_validation.Album'.",
+ RawIdNonexistingAdmin.validate,
+ Album)
def test_fk_exclusion(self):
"""
@@ -155,9 +139,7 @@ class ValidationTestCase(TestCase):
class MyAdmin(admin.ModelAdmin):
inlines = [TwoAlbumFKAndAnEInline]
- with warnings.catch_warnings(record=True):
- warnings.filterwarnings('ignore', module='django.contrib.admin.options')
- MyAdmin.validate(Album)
+ MyAdmin.validate(Album)
def test_inline_self_validation(self):
class TwoAlbumFKAndAnEInline(admin.TabularInline):
@@ -166,11 +148,9 @@ class ValidationTestCase(TestCase):
class MyAdmin(admin.ModelAdmin):
inlines = [TwoAlbumFKAndAnEInline]
- with warnings.catch_warnings(record=True):
- warnings.filterwarnings('ignore', module='django.contrib.admin.options')
- self.assertRaisesMessage(ValueError,
- "'admin_validation.TwoAlbumFKAndAnE' has more than one ForeignKey to 'admin_validation.Album'.",
- MyAdmin.validate, Album)
+ self.assertRaisesMessage(ValueError,
+ "'admin_validation.TwoAlbumFKAndAnE' has more than one ForeignKey to 'admin_validation.Album'.",
+ MyAdmin.validate, Album)
def test_inline_with_specified(self):
class TwoAlbumFKAndAnEInline(admin.TabularInline):
@@ -180,17 +160,13 @@ class ValidationTestCase(TestCase):
class MyAdmin(admin.ModelAdmin):
inlines = [TwoAlbumFKAndAnEInline]
- with warnings.catch_warnings(record=True):
- warnings.filterwarnings('ignore', module='django.contrib.admin.options')
- MyAdmin.validate(Album)
+ MyAdmin.validate(Album)
def test_readonly(self):
class SongAdmin(admin.ModelAdmin):
readonly_fields = ("title",)
- with warnings.catch_warnings(record=True):
- warnings.filterwarnings('ignore', module='django.contrib.admin.options')
- SongAdmin.validate(Song)
+ SongAdmin.validate(Song)
def test_readonly_on_method(self):
def my_function(obj):
@@ -199,9 +175,7 @@ class ValidationTestCase(TestCase):
class SongAdmin(admin.ModelAdmin):
readonly_fields = (my_function,)
- with warnings.catch_warnings(record=True):
- warnings.filterwarnings('ignore', module='django.contrib.admin.options')
- SongAdmin.validate(Song)
+ SongAdmin.validate(Song)
def test_readonly_on_modeladmin(self):
class SongAdmin(admin.ModelAdmin):
@@ -210,42 +184,34 @@ class ValidationTestCase(TestCase):
def readonly_method_on_modeladmin(self, obj):
pass
- with warnings.catch_warnings(record=True):
- warnings.filterwarnings('ignore', module='django.contrib.admin.options')
- SongAdmin.validate(Song)
+ SongAdmin.validate(Song)
def test_readonly_method_on_model(self):
class SongAdmin(admin.ModelAdmin):
readonly_fields = ("readonly_method_on_model",)
- with warnings.catch_warnings(record=True):
- warnings.filterwarnings('ignore', module='django.contrib.admin.options')
- SongAdmin.validate(Song)
+ SongAdmin.validate(Song)
def test_nonexistent_field(self):
class SongAdmin(admin.ModelAdmin):
readonly_fields = ("title", "nonexistent")
- with warnings.catch_warnings(record=True):
- warnings.filterwarnings('ignore', module='django.contrib.admin.options')
- self.assertRaisesMessage(ImproperlyConfigured,
- str_prefix("SongAdmin.readonly_fields[1], %(_)s'nonexistent' is not a callable "
- "or an attribute of 'SongAdmin' or found in the model 'Song'."),
- SongAdmin.validate,
- Song)
+ self.assertRaisesMessage(ImproperlyConfigured,
+ str_prefix("SongAdmin.readonly_fields[1], %(_)s'nonexistent' is not a callable "
+ "or an attribute of 'SongAdmin' or found in the model 'Song'."),
+ SongAdmin.validate,
+ Song)
def test_nonexistent_field_on_inline(self):
class CityInline(admin.TabularInline):
model = City
readonly_fields = ['i_dont_exist'] # Missing attribute
- with warnings.catch_warnings(record=True):
- warnings.filterwarnings('ignore', module='django.contrib.admin.options')
- self.assertRaisesMessage(ImproperlyConfigured,
- str_prefix("CityInline.readonly_fields[0], %(_)s'i_dont_exist' is not a callable "
- "or an attribute of 'CityInline' or found in the model 'City'."),
- CityInline.validate,
- City)
+ self.assertRaisesMessage(ImproperlyConfigured,
+ str_prefix("CityInline.readonly_fields[0], %(_)s'i_dont_exist' is not a callable "
+ "or an attribute of 'CityInline' or found in the model 'City'."),
+ CityInline.validate,
+ City)
def test_extra(self):
class SongAdmin(admin.ModelAdmin):
@@ -254,17 +220,13 @@ class ValidationTestCase(TestCase):
return "Best Ever!"
return "Status unknown."
- with warnings.catch_warnings(record=True):
- warnings.filterwarnings('ignore', module='django.contrib.admin.options')
- SongAdmin.validate(Song)
+ SongAdmin.validate(Song)
def test_readonly_lambda(self):
class SongAdmin(admin.ModelAdmin):
readonly_fields = (lambda obj: "test",)
- with warnings.catch_warnings(record=True):
- warnings.filterwarnings('ignore', module='django.contrib.admin.options')
- SongAdmin.validate(Song)
+ SongAdmin.validate(Song)
def test_graceful_m2m_fail(self):
"""
@@ -276,12 +238,10 @@ class ValidationTestCase(TestCase):
class BookAdmin(admin.ModelAdmin):
fields = ['authors']
- with warnings.catch_warnings(record=True):
- warnings.filterwarnings('ignore', module='django.contrib.admin.options')
- self.assertRaisesMessage(ImproperlyConfigured,
- "'BookAdmin.fields' can't include the ManyToManyField field 'authors' because 'authors' manually specifies a 'through' model.",
- BookAdmin.validate,
- Book)
+ self.assertRaisesMessage(ImproperlyConfigured,
+ "'BookAdmin.fields' can't include the ManyToManyField field 'authors' because 'authors' manually specifies a 'through' model.",
+ BookAdmin.validate,
+ Book)
def test_cannot_include_through(self):
class FieldsetBookAdmin(admin.ModelAdmin):
@@ -290,20 +250,16 @@ class ValidationTestCase(TestCase):
('Header 2', {'fields': ('authors',)}),
)
- with warnings.catch_warnings(record=True):
- warnings.filterwarnings('ignore', module='django.contrib.admin.options')
- self.assertRaisesMessage(ImproperlyConfigured,
- "'FieldsetBookAdmin.fieldsets[1][1]['fields']' can't include the ManyToManyField field 'authors' because 'authors' manually specifies a 'through' model.",
- FieldsetBookAdmin.validate,
- Book)
+ self.assertRaisesMessage(ImproperlyConfigured,
+ "'FieldsetBookAdmin.fieldsets[1][1]['fields']' can't include the ManyToManyField field 'authors' because 'authors' manually specifies a 'through' model.",
+ FieldsetBookAdmin.validate,
+ Book)
def test_nested_fields(self):
class NestedFieldsAdmin(admin.ModelAdmin):
fields = ('price', ('name', 'subtitle'))
- with warnings.catch_warnings(record=True):
- warnings.filterwarnings('ignore', module='django.contrib.admin.options')
- NestedFieldsAdmin.validate(Book)
+ NestedFieldsAdmin.validate(Book)
def test_nested_fieldsets(self):
class NestedFieldsetAdmin(admin.ModelAdmin):
@@ -311,9 +267,7 @@ class ValidationTestCase(TestCase):
('Main', {'fields': ('price', ('name', 'subtitle'))}),
)
- with warnings.catch_warnings(record=True):
- warnings.filterwarnings('ignore', module='django.contrib.admin.options')
- NestedFieldsetAdmin.validate(Book)
+ NestedFieldsetAdmin.validate(Book)
def test_explicit_through_override(self):
"""
@@ -330,9 +284,7 @@ class ValidationTestCase(TestCase):
# If the through model is still a string (and hasn't been resolved to a model)
# the validation will fail.
- with warnings.catch_warnings(record=True):
- warnings.filterwarnings('ignore', module='django.contrib.admin.options')
- BookAdmin.validate(Book)
+ BookAdmin.validate(Book)
def test_non_model_fields(self):
"""
@@ -346,9 +298,7 @@ class ValidationTestCase(TestCase):
form = SongForm
fields = ['title', 'extra_data']
- with warnings.catch_warnings(record=True):
- warnings.filterwarnings('ignore', module='django.contrib.admin.options')
- FieldsOnFormOnlyAdmin.validate(Song)
+ FieldsOnFormOnlyAdmin.validate(Song)
def test_non_model_first_field(self):
"""
@@ -366,6 +316,4 @@ class ValidationTestCase(TestCase):
form = SongForm
fields = ['extra_data', 'title']
- with warnings.catch_warnings(record=True):
- warnings.filterwarnings('ignore', module='django.contrib.admin.options')
- FieldsOnFormOnlyAdmin.validate(Song)
+ FieldsOnFormOnlyAdmin.validate(Song)
diff --git a/tests/aggregation/tests.py b/tests/aggregation/tests.py
index 88a5f11053..917137cce1 100644
--- a/tests/aggregation/tests.py
+++ b/tests/aggregation/tests.py
@@ -3,7 +3,6 @@ from __future__ import unicode_literals
import datetime
from decimal import Decimal
import re
-import warnings
from django.core.exceptions import FieldError
from django.db import connection
@@ -11,10 +10,7 @@ from django.db.models import (
Avg, Sum, Count, Max, Min,
Aggregate, F, Value, Func,
IntegerField, FloatField, DecimalField)
-with warnings.catch_warnings(record=True) as w:
- warnings.simplefilter("always")
- from django.db.models.sql import aggregates as sql_aggregates
-from django.test import TestCase
+from django.test import TestCase, ignore_warnings
from django.test.utils import Approximate
from django.test.utils import CaptureQueriesContext
from django.utils import six, timezone
@@ -950,7 +946,9 @@ class ComplexAggregateTestCase(TestCase):
self.assertQuerysetEqual(
qs2, [1, 2], lambda v: v.pk)
+ @ignore_warnings(category=RemovedInDjango20Warning)
def test_backwards_compatibility(self):
+ from django.db.models.sql import aggregates as sql_aggregates
class SqlNewSum(sql_aggregates.Aggregate):
sql_function = 'SUM'
@@ -964,8 +962,6 @@ class ComplexAggregateTestCase(TestCase):
col, source=source, is_summary=is_summary, **self.extra)
query.annotations[alias] = aggregate
- with warnings.catch_warnings():
- warnings.simplefilter("ignore", RemovedInDjango20Warning)
- qs = Author.objects.values('name').annotate(another_age=NewSum('age') + F('age'))
- a = qs.get(pk=1)
- self.assertEqual(a['another_age'], 68)
+ qs = Author.objects.values('name').annotate(another_age=NewSum('age') + F('age'))
+ a = qs.get(pk=1)
+ self.assertEqual(a['another_age'], 68)
diff --git a/tests/backends/tests.py b/tests/backends/tests.py
index f09f9b8168..7fbb57ba0c 100644
--- a/tests/backends/tests.py
+++ b/tests/backends/tests.py
@@ -24,8 +24,9 @@ from django.db.models.sql.constants import CURSOR
from django.db.utils import ConnectionHandler
from django.test import (TestCase, TransactionTestCase, mock, override_settings,
skipUnlessDBFeature, skipIfDBFeature)
-from django.test.utils import str_prefix, IgnoreAllDeprecationWarningsMixin
+from django.test.utils import ignore_warnings, str_prefix
from django.utils import six
+from django.utils.deprecation import RemovedInDjango19Warning
from django.utils.six.moves import range
from . import models
@@ -1080,18 +1081,13 @@ class BackendUtilTests(TestCase):
'1234600000')
-class DBTestSettingsRenamedTests(IgnoreAllDeprecationWarningsMixin, TestCase):
+@ignore_warnings(category=UserWarning,
+ message="Overriding setting DATABASES can lead to unexpected behavior")
+class DBTestSettingsRenamedTests(TestCase):
mismatch_msg = ("Connection 'test-deprecation' has mismatched TEST "
"and TEST_* database settings.")
- @classmethod
- def setUpClass(cls):
- super(DBTestSettingsRenamedTests, cls).setUpClass()
- # Silence "UserWarning: Overriding setting DATABASES can lead to
- # unexpected behavior."
- cls.warning_classes.append(UserWarning)
-
def setUp(self):
super(DBTestSettingsRenamedTests, self).setUp()
self.handler = ConnectionHandler()
@@ -1188,6 +1184,7 @@ class DBTestSettingsRenamedTests(IgnoreAllDeprecationWarningsMixin, TestCase):
with override_settings(DATABASES=self.db_settings):
self.handler.prepare_test_settings('test-deprecation')
+ @ignore_warnings(category=RemovedInDjango19Warning)
def test_old_settings_only(self):
# should be able to define old settings without the new
self.db_settings.update({
diff --git a/tests/cache/tests.py b/tests/cache/tests.py
index be4d52cb05..376f10e533 100644
--- a/tests/cache/tests.py
+++ b/tests/cache/tests.py
@@ -29,14 +29,15 @@ from django.middleware.csrf import CsrfViewMiddleware
from django.template import Template
from django.template.context_processors import csrf
from django.template.response import TemplateResponse
-from django.test import TestCase, TransactionTestCase, RequestFactory, override_settings
+from django.test import (TestCase, TransactionTestCase, RequestFactory,
+ ignore_warnings, override_settings)
from django.test.signals import setting_changed
-from django.test.utils import IgnoreDeprecationWarningsMixin
from django.utils import six
from django.utils import timezone
from django.utils import translation
from django.utils.cache import (patch_vary_headers, get_cache_key,
learn_cache_key, patch_cache_control, patch_response_headers)
+from django.utils.deprecation import RemovedInDjango19Warning
from django.utils.encoding import force_text
from django.views.decorators.cache import cache_page
@@ -1220,8 +1221,9 @@ class CustomCacheKeyValidationTests(TestCase):
}
}
)
-class GetCacheTests(IgnoreDeprecationWarningsMixin, TestCase):
+class GetCacheTests(TestCase):
+ @ignore_warnings(category=RemovedInDjango19Warning)
def test_simple(self):
self.assertIsInstance(
caches[DEFAULT_CACHE_ALIAS],
@@ -1241,6 +1243,7 @@ class GetCacheTests(IgnoreDeprecationWarningsMixin, TestCase):
signals.request_finished.send(self.__class__)
self.assertTrue(cache.closed)
+ @ignore_warnings(category=RemovedInDjango19Warning)
def test_close_deprecated(self):
cache = get_cache('cache.closeable_cache.CacheClass')
self.assertFalse(cache.closed)
diff --git a/tests/commands_sql/tests.py b/tests/commands_sql/tests.py
index 10f0404776..83c47a888f 100644
--- a/tests/commands_sql/tests.py
+++ b/tests/commands_sql/tests.py
@@ -2,14 +2,13 @@ from __future__ import unicode_literals
import re
import unittest
-import warnings
from django.apps import apps
from django.core.management.color import no_style
from django.core.management.sql import (sql_create, sql_delete, sql_indexes,
sql_destroy_indexes, sql_all)
from django.db import connections, DEFAULT_DB_ALIAS
-from django.test import TestCase, override_settings
+from django.test import TestCase, ignore_warnings, override_settings
from django.utils import six
from django.utils.deprecation import RemovedInDjango20Warning
@@ -67,11 +66,10 @@ class SQLCommandsTestCase(TestCase):
sql = drop_tables[-1].lower()
six.assertRegex(self, sql, r'^drop table .commands_sql_comment.*')
+ @ignore_warnings(category=RemovedInDjango20Warning)
def test_sql_indexes(self):
app_config = apps.get_app_config('commands_sql')
- with warnings.catch_warnings():
- warnings.simplefilter("ignore", category=RemovedInDjango20Warning)
- output = sql_indexes(app_config, no_style(), connections[DEFAULT_DB_ALIAS])
+ output = sql_indexes(app_config, no_style(), connections[DEFAULT_DB_ALIAS])
# Number of indexes is backend-dependent
self.assertTrue(1 <= self.count_ddl(output, 'CREATE INDEX') <= 4)
@@ -81,11 +79,10 @@ class SQLCommandsTestCase(TestCase):
# Number of indexes is backend-dependent
self.assertTrue(1 <= self.count_ddl(output, 'DROP INDEX') <= 4)
+ @ignore_warnings(category=RemovedInDjango20Warning)
def test_sql_all(self):
app_config = apps.get_app_config('commands_sql')
- with warnings.catch_warnings():
- warnings.simplefilter("ignore", category=RemovedInDjango20Warning)
- output = sql_all(app_config, no_style(), connections[DEFAULT_DB_ALIAS])
+ output = sql_all(app_config, no_style(), connections[DEFAULT_DB_ALIAS])
self.assertEqual(self.count_ddl(output, 'CREATE TABLE'), 3)
# Number of indexes is backend-dependent
diff --git a/tests/deprecation/tests.py b/tests/deprecation/tests.py
index dcd50a6d11..5cf06f0fdf 100644
--- a/tests/deprecation/tests.py
+++ b/tests/deprecation/tests.py
@@ -182,6 +182,7 @@ class DeprecatingRequestMergeDictTest(SimpleTestCase):
Ensure the correct warning is raised when WSGIRequest.REQUEST is
accessed.
"""
+ reset_warning_registry()
with warnings.catch_warnings(record=True) as recorded:
warnings.simplefilter('always')
request = RequestFactory().get('/')
diff --git a/tests/field_deconstruction/tests.py b/tests/field_deconstruction/tests.py
index 4c1aabb94b..fd827e4b72 100644
--- a/tests/field_deconstruction/tests.py
+++ b/tests/field_deconstruction/tests.py
@@ -1,7 +1,5 @@
from __future__ import unicode_literals
-import warnings
-
from django.db import models
from django.test import TestCase, override_settings
from django.utils import six
@@ -238,9 +236,7 @@ class FieldDeconstructionTests(TestCase):
self.assertEqual(kwargs, {})
def test_ip_address_field(self):
- with warnings.catch_warnings(record=True):
- warnings.simplefilter("always")
- field = models.IPAddressField()
+ field = models.IPAddressField()
name, path, args, kwargs = field.deconstruct()
self.assertEqual(path, "django.db.models.IPAddressField")
self.assertEqual(args, [])
diff --git a/tests/fixtures/tests.py b/tests/fixtures/tests.py
index 294ae82e27..adef8ec5e5 100644
--- a/tests/fixtures/tests.py
+++ b/tests/fixtures/tests.py
@@ -6,7 +6,7 @@ import warnings
from django.contrib.sites.models import Site
from django.core import management
from django.db import connection, IntegrityError
-from django.test import TestCase, TransactionTestCase, skipUnlessDBFeature
+from django.test import TestCase, TransactionTestCase, ignore_warnings, skipUnlessDBFeature
from django.utils.encoding import force_text
from django.utils import six
@@ -335,14 +335,12 @@ class FixtureLoadingTests(DumpDataAssertMixin, TestCase):
management.call_command('loaddata', 'invalid.json', verbosity=0)
self.assertIn("Could not load fixtures.Article(pk=1):", cm.exception.args[0])
+ @ignore_warnings(category=UserWarning, message="No fixture named")
def test_loaddata_app_option(self):
"""
Verifies that the --app option works.
"""
- with warnings.catch_warnings():
- # Ignore: No fixture named ...
- warnings.filterwarnings("ignore", category=UserWarning)
- management.call_command('loaddata', 'db_fixture_1', verbosity=0, app_label="someotherapp")
+ management.call_command('loaddata', 'db_fixture_1', verbosity=0, app_label="someotherapp")
self.assertQuerysetEqual(Article.objects.all(), [])
management.call_command('loaddata', 'db_fixture_1', verbosity=0, app_label="fixtures")
self.assertQuerysetEqual(Article.objects.all(), [
@@ -358,12 +356,11 @@ class FixtureLoadingTests(DumpDataAssertMixin, TestCase):
'',
])
+ @ignore_warnings(category=UserWarning, message="No fixture named")
def test_unmatched_identifier_loading(self):
# Try to load db fixture 3. This won't load because the database identifier doesn't match
- with warnings.catch_warnings():
- warnings.filterwarnings("ignore", category=UserWarning)
- management.call_command('loaddata', 'db_fixture_3', verbosity=0)
- management.call_command('loaddata', 'db_fixture_3', verbosity=0, using='default')
+ management.call_command('loaddata', 'db_fixture_3', verbosity=0)
+ management.call_command('loaddata', 'db_fixture_3', verbosity=0, using='default')
self.assertQuerysetEqual(Article.objects.all(), [])
def test_output_formats(self):
diff --git a/tests/forms_tests/tests/test_error_messages.py b/tests/forms_tests/tests/test_error_messages.py
index 75eddee254..dce1165657 100644
--- a/tests/forms_tests/tests/test_error_messages.py
+++ b/tests/forms_tests/tests/test_error_messages.py
@@ -1,8 +1,6 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
-import warnings
-
from django.core.files.uploadedfile import SimpleUploadedFile
from django.forms import (
BooleanField, CharField, ChoiceField, DateField, DateTimeField,
@@ -203,9 +201,7 @@ class FormsErrorMessagesTestCase(TestCase, AssertFormErrorsMixin):
'required': 'REQUIRED',
'invalid': 'INVALID IP ADDRESS',
}
- with warnings.catch_warnings(record=True):
- warnings.simplefilter("always")
- f = IPAddressField(error_messages=e)
+ f = IPAddressField(error_messages=e)
self.assertFormErrors(['REQUIRED'], f.clean, '')
self.assertFormErrors(['INVALID IP ADDRESS'], f.clean, '127.0.0')
diff --git a/tests/forms_tests/tests/test_extra.py b/tests/forms_tests/tests/test_extra.py
index 1d53a9bd1d..ad84670daa 100644
--- a/tests/forms_tests/tests/test_extra.py
+++ b/tests/forms_tests/tests/test_extra.py
@@ -2,7 +2,6 @@
from __future__ import unicode_literals
import datetime
-import warnings
from django.forms import (
CharField, DateField, EmailField, FileField, Form, GenericIPAddressField,
@@ -484,9 +483,7 @@ class FormsExtraTestCase(TestCase, AssertFormErrorsMixin):
self.assertEqual(f.cleaned_data['field1'], 'some text,JP,2007-04-25 06:24:00')
def test_ipaddress(self):
- with warnings.catch_warnings(record=True):
- warnings.simplefilter("always")
- f = IPAddressField()
+ f = IPAddressField()
self.assertFormErrors(['This field is required.'], f.clean, '')
self.assertFormErrors(['This field is required.'], f.clean, None)
self.assertEqual(f.clean(' 127.0.0.1'), '127.0.0.1')
@@ -495,9 +492,7 @@ class FormsExtraTestCase(TestCase, AssertFormErrorsMixin):
self.assertFormErrors(['Enter a valid IPv4 address.'], f.clean, '1.2.3.4.5')
self.assertFormErrors(['Enter a valid IPv4 address.'], f.clean, '256.125.1.5')
- with warnings.catch_warnings(record=True):
- warnings.simplefilter("always")
- f = IPAddressField(required=False)
+ f = IPAddressField(required=False)
self.assertEqual(f.clean(''), '')
self.assertEqual(f.clean(None), '')
self.assertEqual(f.clean(' 127.0.0.1'), '127.0.0.1')
diff --git a/tests/forms_tests/tests/test_fields.py b/tests/forms_tests/tests/test_fields.py
index b2f0869c47..a588084843 100644
--- a/tests/forms_tests/tests/test_fields.py
+++ b/tests/forms_tests/tests/test_fields.py
@@ -33,7 +33,6 @@ import os
import uuid
from decimal import Decimal
from unittest import skipIf
-import warnings
try:
from PIL import Image
@@ -50,10 +49,11 @@ from django.forms import (
TimeField, TypedChoiceField, TypedMultipleChoiceField, URLField, UUIDField,
ValidationError, Widget,
)
-from django.test import SimpleTestCase
+from django.test import SimpleTestCase, ignore_warnings
from django.utils import formats
from django.utils import six
from django.utils import translation
+from django.utils.deprecation import RemovedInDjango20Warning
from django.utils._os import upath
@@ -491,15 +491,14 @@ class FieldsTests(SimpleTestCase):
f = DateField()
self.assertRaisesMessage(ValidationError, "'Enter a valid date.'", f.clean, 'a\x00b')
+ @ignore_warnings(category=RemovedInDjango20Warning) # for _has_changed
def test_datefield_changed(self):
format = '%d/%m/%Y'
f = DateField(input_formats=[format])
d = datetime.date(2007, 9, 17)
self.assertFalse(f.has_changed(d, '17/09/2007'))
# Test for deprecated behavior _has_changed
- with warnings.catch_warnings(record=True):
- warnings.simplefilter("always")
- self.assertFalse(f._has_changed(d, '17/09/2007'))
+ self.assertFalse(f._has_changed(d, '17/09/2007'))
def test_datefield_strptime(self):
"""Test that field.strptime doesn't raise an UnicodeEncodeError (#16123)"""
@@ -662,11 +661,9 @@ class FieldsTests(SimpleTestCase):
self.assertRaisesMessage(ValidationError, "'Enter a valid value.'", f.clean, ' 2A2')
self.assertRaisesMessage(ValidationError, "'Enter a valid value.'", f.clean, '2A2 ')
+ @ignore_warnings(category=RemovedInDjango20Warning) # error_message deprecation
def test_regexfield_4(self):
- # deprecated error_message argument; remove in Django 2.0
- with warnings.catch_warnings(record=True):
- warnings.simplefilter("always")
- f = RegexField('^[0-9][0-9][0-9][0-9]$', error_message='Enter a four-digit number.')
+ f = RegexField('^[0-9][0-9][0-9][0-9]$', error_message='Enter a four-digit number.')
self.assertEqual('1234', f.clean('1234'))
self.assertRaisesMessage(ValidationError, "'Enter a four-digit number.'", f.clean, '123')
self.assertRaisesMessage(ValidationError, "'Enter a four-digit number.'", f.clean, 'abcd')
diff --git a/tests/forms_tests/tests/test_forms.py b/tests/forms_tests/tests/test_forms.py
index 290e5ba65f..5b1c85ce6a 100644
--- a/tests/forms_tests/tests/test_forms.py
+++ b/tests/forms_tests/tests/test_forms.py
@@ -4,7 +4,6 @@ from __future__ import unicode_literals
import copy
import datetime
import json
-import warnings
from django.core.exceptions import NON_FIELD_ERRORS
from django.core.files.uploadedfile import SimpleUploadedFile
@@ -19,9 +18,10 @@ from django.forms import (
from django.forms.utils import ErrorList
from django.http import QueryDict
from django.template import Template, Context
-from django.test import TestCase
+from django.test import TestCase, ignore_warnings
from django.test.utils import str_prefix
from django.utils.datastructures import MultiValueDict, MergeDict
+from django.utils.deprecation import RemovedInDjango19Warning
from django.utils.encoding import force_text
from django.utils.html import format_html
from django.utils.safestring import mark_safe, SafeData
@@ -552,6 +552,7 @@ class FormsTestCase(TestCase):
""")
+ @ignore_warnings(category=RemovedInDjango19Warning) # MergeDict deprecation
def test_multiple_choice_list_data(self):
# Data for a MultipleChoiceField should be a list. QueryDict, MultiValueDict and
# MergeDict (when created as a merge of MultiValueDicts) conveniently work with
@@ -573,11 +574,9 @@ class FormsTestCase(TestCase):
self.assertEqual(f.errors, {})
# MergeDict is deprecated, but is supported until removed.
- with warnings.catch_warnings(record=True):
- warnings.simplefilter("always")
- data = MergeDict(MultiValueDict(dict(name=['Yesterday'], composers=['J', 'P'])))
- f = SongForm(data)
- self.assertEqual(f.errors, {})
+ data = MergeDict(MultiValueDict(dict(name=['Yesterday'], composers=['J', 'P'])))
+ f = SongForm(data)
+ self.assertEqual(f.errors, {})
def test_multiple_hidden(self):
class SongForm(Form):
diff --git a/tests/forms_tests/tests/test_regressions.py b/tests/forms_tests/tests/test_regressions.py
index 4eea444808..b0b360e679 100644
--- a/tests/forms_tests/tests/test_regressions.py
+++ b/tests/forms_tests/tests/test_regressions.py
@@ -1,14 +1,12 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
-import warnings
-
from django.forms import (
CharField, ChoiceField, Form, HiddenInput, IntegerField, ModelForm,
ModelMultipleChoiceField, MultipleChoiceField, RadioSelect, Select,
TextInput,
)
-from django.test import TestCase
+from django.test import TestCase, ignore_warnings
from django.utils import translation
from django.utils.translation import gettext_lazy, ugettext_lazy
@@ -61,17 +59,6 @@ class FormsRegressionsTestCase(TestCase):
f = SomeForm()
self.assertHTMLEqual(f.as_p(), '
\n\n\n\n
')
- # Testing choice validation with UTF-8 bytestrings as input (these are the
- # Russian abbreviations "мес." and "шт.".
- UNITS = ((b'\xd0\xbc\xd0\xb5\xd1\x81.', b'\xd0\xbc\xd0\xb5\xd1\x81.'),
- (b'\xd1\x88\xd1\x82.', b'\xd1\x88\xd1\x82.'))
- f = ChoiceField(choices=UNITS)
- with warnings.catch_warnings():
- # Ignore UnicodeWarning
- warnings.simplefilter("ignore")
- self.assertEqual(f.clean('\u0448\u0442.'), '\u0448\u0442.')
- self.assertEqual(f.clean(b'\xd1\x88\xd1\x82.'), '\u0448\u0442.')
-
# Translated error messages used to be buggy.
with translation.override('ru'):
f = SomeForm({})
@@ -83,6 +70,16 @@ class FormsRegressionsTestCase(TestCase):
f = CopyForm()
+ @ignore_warnings(category=UnicodeWarning)
+ def test_regression_5216_b(self):
+ # Testing choice validation with UTF-8 bytestrings as input (these are the
+ # Russian abbreviations "мес." and "шт.".
+ UNITS = ((b'\xd0\xbc\xd0\xb5\xd1\x81.', b'\xd0\xbc\xd0\xb5\xd1\x81.'),
+ (b'\xd1\x88\xd1\x82.', b'\xd1\x88\xd1\x82.'))
+ f = ChoiceField(choices=UNITS)
+ self.assertEqual(f.clean('\u0448\u0442.'), '\u0448\u0442.')
+ self.assertEqual(f.clean(b'\xd1\x88\xd1\x82.'), '\u0448\u0442.')
+
def test_misc(self):
# There once was a problem with Form fields called "data". Let's make sure that
# doesn't come back.
diff --git a/tests/forms_tests/tests/test_widgets.py b/tests/forms_tests/tests/test_widgets.py
index 9f7e0d0bec..5742daf32f 100644
--- a/tests/forms_tests/tests/test_widgets.py
+++ b/tests/forms_tests/tests/test_widgets.py
@@ -3,7 +3,6 @@ from __future__ import unicode_literals
import copy
import datetime
-import warnings
from django.contrib.admin.tests import AdminSeleniumWebDriverTestCase
from django.core.files.uploadedfile import SimpleUploadedFile
@@ -20,7 +19,7 @@ from django.utils.deprecation import RemovedInDjango19Warning
from django.utils.safestring import mark_safe, SafeData
from django.utils import six
from django.utils.translation import activate, deactivate, override
-from django.test import TestCase, override_settings
+from django.test import TestCase, ignore_warnings, override_settings
from django.utils.encoding import python_2_unicode_compatible, force_text
from ..models import Article
@@ -1112,27 +1111,24 @@ class WidgetTests(TestCase):
# to make a copy of its sub-widgets when it is copied.
self.assertEqual(w1.choices, [1, 2, 3])
+ @ignore_warnings(category=RemovedInDjango19Warning)
def test_13390(self):
# See ticket #13390
class SplitDateForm(Form):
field = DateTimeField(widget=SplitDateTimeWidget, required=False)
- with warnings.catch_warnings():
- warnings.filterwarnings("ignore", category=RemovedInDjango19Warning)
- form = SplitDateForm({'field': ''})
- self.assertTrue(form.is_valid())
- form = SplitDateForm({'field': ['', '']})
- self.assertTrue(form.is_valid())
+ form = SplitDateForm({'field': ''})
+ self.assertTrue(form.is_valid())
+ form = SplitDateForm({'field': ['', '']})
+ self.assertTrue(form.is_valid())
class SplitDateRequiredForm(Form):
field = DateTimeField(widget=SplitDateTimeWidget, required=True)
- with warnings.catch_warnings():
- warnings.filterwarnings("ignore", category=RemovedInDjango19Warning)
- form = SplitDateRequiredForm({'field': ''})
- self.assertFalse(form.is_valid())
- form = SplitDateRequiredForm({'field': ['', '']})
- self.assertFalse(form.is_valid())
+ form = SplitDateRequiredForm({'field': ''})
+ self.assertFalse(form.is_valid())
+ form = SplitDateRequiredForm({'field': ['', '']})
+ self.assertFalse(form.is_valid())
@override_settings(ROOT_URLCONF='forms_tests.urls')
diff --git a/tests/generic_views/test_base.py b/tests/generic_views/test_base.py
index 1a1236a084..d855a3829b 100644
--- a/tests/generic_views/test_base.py
+++ b/tests/generic_views/test_base.py
@@ -8,8 +8,7 @@ from django.core.exceptions import ImproperlyConfigured
from django.http import HttpResponse
from django.utils import six
from django.utils.deprecation import RemovedInDjango19Warning
-from django.test import TestCase, RequestFactory, override_settings
-from django.test.utils import IgnoreDeprecationWarningsMixin
+from django.test import TestCase, RequestFactory, ignore_warnings, override_settings
from django.views.generic import View, TemplateView, RedirectView
from . import views
@@ -331,8 +330,9 @@ class TemplateViewTest(TestCase):
self.assertEqual(response['Content-Type'], 'text/plain')
+@ignore_warnings(category=RemovedInDjango19Warning)
@override_settings(ROOT_URLCONF='generic_views.urls')
-class RedirectViewTest(IgnoreDeprecationWarningsMixin, TestCase):
+class RedirectViewTest(TestCase):
rf = RequestFactory()
diff --git a/tests/get_or_create/tests.py b/tests/get_or_create/tests.py
index 33ac1317a5..f15d84323d 100644
--- a/tests/get_or_create/tests.py
+++ b/tests/get_or_create/tests.py
@@ -2,11 +2,10 @@ from __future__ import unicode_literals
from datetime import date
import traceback
-import warnings
from django.db import IntegrityError, DatabaseError
from django.utils.encoding import DjangoUnicodeDecodeError
-from django.test import TestCase, TransactionTestCase
+from django.test import TestCase, TransactionTestCase, ignore_warnings
from .models import (DefaultPerson, Person, ManualPrimaryKeyTest, Profile,
Tag, Thing, Publisher, Author, Book)
@@ -155,18 +154,17 @@ class GetOrCreateTestsWithManualPKs(TestCase):
formatted_traceback = traceback.format_exc()
self.assertIn(str('obj.save'), formatted_traceback)
+ # MySQL emits a warning when broken data is saved
+ @ignore_warnings(module='django.db.backends.mysql.base')
def test_savepoint_rollback(self):
"""
Regression test for #20463: the database connection should still be
usable after a DataError or ProgrammingError in .get_or_create().
"""
try:
- # Hide warnings when broken data is saved with a warning (MySQL).
- with warnings.catch_warnings():
- warnings.simplefilter('ignore')
- Person.objects.get_or_create(
- birthday=date(1970, 1, 1),
- defaults={'first_name': b"\xff", 'last_name': b"\xff"})
+ Person.objects.get_or_create(
+ birthday=date(1970, 1, 1),
+ defaults={'first_name': b"\xff", 'last_name': b"\xff"})
except (DatabaseError, DjangoUnicodeDecodeError):
Person.objects.create(
first_name="Bob", last_name="Ross", birthday=date(1950, 1, 1))
diff --git a/tests/i18n/urls.py b/tests/i18n/urls.py
index 196cea92b8..c1124a1b8c 100644
--- a/tests/i18n/urls.py
+++ b/tests/i18n/urls.py
@@ -1,18 +1,17 @@
from __future__ import unicode_literals
-import warnings
from django.conf.urls.i18n import i18n_patterns
from django.http import HttpResponse, StreamingHttpResponse
+from django.test import ignore_warnings
from django.utils.deprecation import RemovedInDjango20Warning
from django.utils.translation import ugettext_lazy as _
# test deprecated version of i18n_patterns() function (with prefix). Remove it
# and convert to list of urls() in Django 2.0
-with warnings.catch_warnings():
- warnings.filterwarnings('ignore', category=RemovedInDjango20Warning)
+i18n_patterns = ignore_warnings(category=RemovedInDjango20Warning)(i18n_patterns)
- urlpatterns = i18n_patterns('',
- (r'^simple/$', lambda r: HttpResponse()),
- (r'^streaming/$', lambda r: StreamingHttpResponse([_("Yes"), "/", _("No")])),
- )
+urlpatterns = i18n_patterns('',
+ (r'^simple/$', lambda r: HttpResponse()),
+ (r'^streaming/$', lambda r: StreamingHttpResponse([_("Yes"), "/", _("No")])),
+)
diff --git a/tests/indexes/tests.py b/tests/indexes/tests.py
index 0710446245..1d60f215fe 100644
--- a/tests/indexes/tests.py
+++ b/tests/indexes/tests.py
@@ -2,13 +2,14 @@ from unittest import skipUnless
from django.core.management.color import no_style
from django.db import connection
-from django.test import TestCase
-from django.test.utils import IgnorePendingDeprecationWarningsMixin
+from django.test import TestCase, ignore_warnings
+from django.utils.deprecation import RemovedInDjango20Warning
from .models import Article, ArticleTranslation, IndexTogetherSingleList
-class CreationIndexesTests(IgnorePendingDeprecationWarningsMixin, TestCase):
+@ignore_warnings(category=RemovedInDjango20Warning)
+class CreationIndexesTests(TestCase):
"""
Test index handling by the to-be-deprecated connection.creation interface.
"""
diff --git a/tests/inspectdb/models.py b/tests/inspectdb/models.py
index 6e4ce02758..925215fdbf 100644
--- a/tests/inspectdb/models.py
+++ b/tests/inspectdb/models.py
@@ -1,8 +1,10 @@
# -*- encoding: utf-8 -*-
from __future__ import unicode_literals
+
import warnings
from django.db import models
+from django.utils.deprecation import RemovedInDjango19Warning
class People(models.Model):
@@ -60,8 +62,8 @@ class ColumnTypes(models.Model):
file_path_field = models.FilePathField()
float_field = models.FloatField()
int_field = models.IntegerField()
- with warnings.catch_warnings(record=True) as w:
- warnings.simplefilter("always")
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore", category=RemovedInDjango19Warning)
ip_address_field = models.IPAddressField()
gen_ip_adress_field = models.GenericIPAddressField(protocol="ipv4")
pos_int_field = models.PositiveIntegerField()
diff --git a/tests/migrations/test_writer.py b/tests/migrations/test_writer.py
index 5e7e8b75cd..edcc5b285d 100644
--- a/tests/migrations/test_writer.py
+++ b/tests/migrations/test_writer.py
@@ -7,12 +7,11 @@ import os
import re
import tokenize
import unittest
-import warnings
from django.core.validators import RegexValidator, EmailValidator
from django.db import models, migrations
from django.db.migrations.writer import MigrationWriter, SettingsReference
-from django.test import TestCase
+from django.test import TestCase, ignore_warnings
from django.conf import settings
from django.utils import datetime_safe, six
from django.utils.deconstruct import deconstructible
@@ -288,6 +287,10 @@ class WriterTests(TestCase):
)
)
+ # Silence warning on Python 2: Not importing directory
+ # 'tests/migrations/migrations_test_apps/without_init_file/migrations':
+ # missing __init__.py
+ @ignore_warnings(category=ImportWarning)
def test_migration_path(self):
test_apps = [
'migrations.migrations_test_apps.normal',
@@ -302,12 +305,7 @@ class WriterTests(TestCase):
migration = migrations.Migration('0001_initial', app.split('.')[-1])
expected_path = os.path.join(base_dir, *(app.split('.') + ['migrations', '0001_initial.py']))
writer = MigrationWriter(migration)
- # Silence warning on Python 2: Not importing directory
- # 'tests/migrations/migrations_test_apps/without_init_file/migrations':
- # missing __init__.py
- with warnings.catch_warnings():
- warnings.filterwarnings("ignore", category=ImportWarning)
- self.assertEqual(writer.path, expected_path)
+ self.assertEqual(writer.path, expected_path)
def test_custom_operation(self):
migration = type(str("Migration"), (migrations.Migration,), {
diff --git a/tests/model_fields/models.py b/tests/model_fields/models.py
index e9e287f04f..ba2affb280 100644
--- a/tests/model_fields/models.py
+++ b/tests/model_fields/models.py
@@ -12,6 +12,7 @@ from django.core.files.storage import FileSystemStorage
from django.db import models
from django.db.models.fields.files import ImageFieldFile, ImageField
from django.utils import six
+from django.utils.deprecation import RemovedInDjango19Warning
class Foo(models.Model):
@@ -160,8 +161,8 @@ class VerboseNameField(models.Model):
# Don't want to depend on Pillow in this test
#field_image = models.ImageField("verbose field")
field12 = models.IntegerField("verbose field12")
- with warnings.catch_warnings(record=True) as w:
- warnings.simplefilter("always")
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore", category=RemovedInDjango19Warning)
field13 = models.IPAddressField("verbose field13")
field14 = models.GenericIPAddressField("verbose field14", protocol="ipv4")
field15 = models.NullBooleanField("verbose field15")
diff --git a/tests/model_fields/tests.py b/tests/model_fields/tests.py
index ddbf69419c..50a381cb8e 100644
--- a/tests/model_fields/tests.py
+++ b/tests/model_fields/tests.py
@@ -3,7 +3,6 @@ from __future__ import unicode_literals
import datetime
from decimal import Decimal
import unittest
-import warnings
from django import test
from django import forms
@@ -800,16 +799,15 @@ class PromiseTest(test.TestCase):
int)
def test_IPAddressField(self):
- with warnings.catch_warnings(record=True):
- warnings.simplefilter("always")
- lazy_func = lazy(lambda: '127.0.0.1', six.text_type)
- self.assertIsInstance(
- IPAddressField().get_prep_value(lazy_func()),
- six.text_type)
- lazy_func = lazy(lambda: 0, int)
- self.assertIsInstance(
- IPAddressField().get_prep_value(lazy_func()),
- six.text_type)
+ # Deprecation silenced in runtests.py
+ lazy_func = lazy(lambda: '127.0.0.1', six.text_type)
+ self.assertIsInstance(
+ IPAddressField().get_prep_value(lazy_func()),
+ six.text_type)
+ lazy_func = lazy(lambda: 0, int)
+ self.assertIsInstance(
+ IPAddressField().get_prep_value(lazy_func()),
+ six.text_type)
def test_GenericIPAddressField(self):
lazy_func = lazy(lambda: '127.0.0.1', six.text_type)
diff --git a/tests/modeladmin/tests.py b/tests/modeladmin/tests.py
index a0dfb2a72d..ca3a8dbfaf 100644
--- a/tests/modeladmin/tests.py
+++ b/tests/modeladmin/tests.py
@@ -1,7 +1,6 @@
from __future__ import unicode_literals
from datetime import date
-import warnings
from django import forms
from django.contrib.admin.options import (ModelAdmin, TabularInline,
@@ -15,7 +14,7 @@ from django.core.checks import Error
from django.core.exceptions import ImproperlyConfigured
from django.forms.models import BaseModelFormSet
from django.forms.widgets import Select
-from django.test import TestCase
+from django.test import TestCase, ignore_warnings
from django.utils import six
from django.utils.deprecation import RemovedInDjango19Warning
@@ -1505,19 +1504,18 @@ class FormsetCheckTests(CheckTestCase):
class CustomModelAdminTests(CheckTestCase):
+ @ignore_warnings(category=RemovedInDjango19Warning)
def test_deprecation(self):
"Deprecated Custom Validator definitions still work with the check framework."
- with warnings.catch_warnings():
- warnings.simplefilter("ignore", category=RemovedInDjango19Warning)
- class CustomValidator(ModelAdminValidator):
- def validate_me(self, model_admin, model):
- raise ImproperlyConfigured('error!')
+ class CustomValidator(ModelAdminValidator):
+ def validate_me(self, model_admin, model):
+ raise ImproperlyConfigured('error!')
- class CustomModelAdmin(ModelAdmin):
- validator_class = CustomValidator
+ class CustomModelAdmin(ModelAdmin):
+ validator_class = CustomValidator
- self.assertIsInvalid(CustomModelAdmin, ValidationTestModel, 'error!')
+ self.assertIsInvalid(CustomModelAdmin, ValidationTestModel, 'error!')
class ListDisplayEditableTests(CheckTestCase):
diff --git a/tests/resolve_url/tests.py b/tests/resolve_url/tests.py
index 4ea68e460b..ce550ea846 100644
--- a/tests/resolve_url/tests.py
+++ b/tests/resolve_url/tests.py
@@ -1,10 +1,9 @@
from __future__ import unicode_literals
-import warnings
from django.core.urlresolvers import NoReverseMatch
from django.contrib.auth.views import logout
from django.shortcuts import resolve_url
-from django.test import TestCase, override_settings
+from django.test import TestCase, ignore_warnings, override_settings
from django.utils.deprecation import RemovedInDjango20Warning
from .models import UnimportantThing
@@ -57,15 +56,14 @@ class ResolveUrlTests(TestCase):
resolved_url = resolve_url(logout)
self.assertEqual('/accounts/logout/', resolved_url)
+ @ignore_warnings(category=RemovedInDjango20Warning)
def test_valid_view_name(self):
"""
Tests that passing a view function to ``resolve_url`` will result in
the URL path mapping to that view.
"""
- with warnings.catch_warnings():
- warnings.filterwarnings("ignore", category=RemovedInDjango20Warning)
- resolved_url = resolve_url('django.contrib.auth.views.logout')
- self.assertEqual('/accounts/logout/', resolved_url)
+ resolved_url = resolve_url('django.contrib.auth.views.logout')
+ self.assertEqual('/accounts/logout/', resolved_url)
def test_domain(self):
"""
diff --git a/tests/serializers_regress/models.py b/tests/serializers_regress/models.py
index 82a3e6dd23..e03101ca89 100644
--- a/tests/serializers_regress/models.py
+++ b/tests/serializers_regress/models.py
@@ -11,6 +11,7 @@ from django.contrib.contenttypes.fields import (
GenericForeignKey, GenericRelation
)
from django.contrib.contenttypes.models import ContentType
+from django.utils.deprecation import RemovedInDjango19Warning
# The following classes are for testing basic data
# marshalling, including NULL values, where allowed.
@@ -68,8 +69,8 @@ class BigIntegerData(models.Model):
class IPAddressData(models.Model):
- with warnings.catch_warnings(record=True) as w:
- warnings.simplefilter("always")
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore", category=RemovedInDjango19Warning)
data = models.IPAddressField(null=True)
diff --git a/tests/serializers_regress/tests.py b/tests/serializers_regress/tests.py
index 86b03c26f4..15ecadaba9 100644
--- a/tests/serializers_regress/tests.py
+++ b/tests/serializers_regress/tests.py
@@ -11,7 +11,6 @@ from __future__ import unicode_literals
import datetime
import decimal
from unittest import skipUnless
-import warnings
try:
import yaml
@@ -24,8 +23,9 @@ from django.core.serializers.base import DeserializationError
from django.core.serializers.xml_serializer import DTDForbidden
from django.db import connection, models
from django.http import HttpResponse
-from django.test import skipUnlessDBFeature, TestCase
+from django.test import ignore_warnings, skipUnlessDBFeature, TestCase
from django.utils import six
+from django.utils.deprecation import RemovedInDjango19Warning
from django.utils.functional import curry
from .models import (BinaryData, BooleanData, CharData, DateData, DateTimeData, EmailData,
@@ -484,6 +484,7 @@ def serializerTest(format, self):
self.assertEqual(count, klass.objects.count())
+@ignore_warnings(category=RemovedInDjango19Warning) # for use_natural_keys
def naturalKeySerializerTest(format, self):
# Create all the objects defined in the test data
objects = []
@@ -497,11 +498,9 @@ def naturalKeySerializerTest(format, self):
instance_count[klass] = klass.objects.count()
# use_natural_keys is deprecated and to be removed in Django 1.9
- with warnings.catch_warnings(record=True):
- warnings.simplefilter("always")
- # Serialize the test database
- serialized_data = serializers.serialize(format, objects, indent=2,
- use_natural_keys=True)
+ # Serialize the test database
+ serialized_data = serializers.serialize(format, objects, indent=2,
+ use_natural_keys=True)
for obj in serializers.deserialize(format, serialized_data):
obj.save()
diff --git a/tests/shortcuts/tests.py b/tests/shortcuts/tests.py
index 1de27c8515..612f4a3dd8 100644
--- a/tests/shortcuts/tests.py
+++ b/tests/shortcuts/tests.py
@@ -1,6 +1,5 @@
-import warnings
from django.utils.deprecation import RemovedInDjango20Warning
-from django.test import TestCase, override_settings
+from django.test import TestCase, ignore_warnings, override_settings
@override_settings(
@@ -15,10 +14,9 @@ class ShortcutTests(TestCase):
self.assertEqual(response.content, b'FOO.BAR..\n')
self.assertEqual(response['Content-Type'], 'text/html; charset=utf-8')
+ @ignore_warnings(category=RemovedInDjango20Warning)
def test_render_to_response_with_request_context(self):
- with warnings.catch_warnings():
- warnings.filterwarnings("ignore", category=RemovedInDjango20Warning)
- response = self.client.get('/render_to_response/request_context/')
+ response = self.client.get('/render_to_response/request_context/')
self.assertEqual(response.status_code, 200)
self.assertEqual(response.content, b'FOO.BAR../path/to/static/media/\n')
self.assertEqual(response['Content-Type'], 'text/html; charset=utf-8')
@@ -29,23 +27,21 @@ class ShortcutTests(TestCase):
self.assertEqual(response.content, b'FOO.BAR..\n')
self.assertEqual(response['Content-Type'], 'application/x-rendertest')
+ @ignore_warnings(category=RemovedInDjango20Warning)
def test_render_to_response_with_dirs(self):
- with warnings.catch_warnings():
- warnings.filterwarnings("ignore", category=RemovedInDjango20Warning)
- response = self.client.get('/render_to_response/dirs/')
+ response = self.client.get('/render_to_response/dirs/')
self.assertEqual(response.status_code, 200)
self.assertEqual(response.content, b'spam eggs\n')
self.assertEqual(response['Content-Type'], 'text/html; charset=utf-8')
+ @ignore_warnings(category=RemovedInDjango20Warning)
def test_render_to_response_with_context_instance_misuse(self):
"""
For backwards-compatibility, ensure that it's possible to pass a
RequestContext instance in the dictionary argument instead of the
context_instance argument.
"""
- with warnings.catch_warnings():
- warnings.filterwarnings("ignore", category=RemovedInDjango20Warning)
- response = self.client.get('/render_to_response/context_instance_misuse/')
+ response = self.client.get('/render_to_response/context_instance_misuse/')
self.assertContains(response, 'context processor output')
def test_render(self):
@@ -55,10 +51,9 @@ class ShortcutTests(TestCase):
self.assertEqual(response['Content-Type'], 'text/html; charset=utf-8')
self.assertFalse(hasattr(response.context.request, 'current_app'))
+ @ignore_warnings(category=RemovedInDjango20Warning)
def test_render_with_base_context(self):
- with warnings.catch_warnings():
- warnings.filterwarnings("ignore", category=RemovedInDjango20Warning)
- response = self.client.get('/render/base_context/')
+ response = self.client.get('/render/base_context/')
self.assertEqual(response.status_code, 200)
self.assertEqual(response.content, b'FOO.BAR..\n')
self.assertEqual(response['Content-Type'], 'text/html; charset=utf-8')
@@ -74,22 +69,19 @@ class ShortcutTests(TestCase):
self.assertEqual(response.status_code, 403)
self.assertEqual(response.content, b'FOO.BAR../path/to/static/media/\n')
+ @ignore_warnings(category=RemovedInDjango20Warning)
def test_render_with_current_app(self):
- with warnings.catch_warnings():
- warnings.filterwarnings("ignore", category=RemovedInDjango20Warning)
- response = self.client.get('/render/current_app/')
+ response = self.client.get('/render/current_app/')
self.assertEqual(response.context.request.current_app, "foobar_app")
+ @ignore_warnings(category=RemovedInDjango20Warning)
def test_render_with_dirs(self):
- with warnings.catch_warnings():
- warnings.filterwarnings("ignore", category=RemovedInDjango20Warning)
- response = self.client.get('/render/dirs/')
+ response = self.client.get('/render/dirs/')
self.assertEqual(response.status_code, 200)
self.assertEqual(response.content, b'spam eggs\n')
self.assertEqual(response['Content-Type'], 'text/html; charset=utf-8')
+ @ignore_warnings(category=RemovedInDjango20Warning)
def test_render_with_current_app_conflict(self):
with self.assertRaises(ValueError):
- with warnings.catch_warnings():
- warnings.filterwarnings("ignore", category=RemovedInDjango20Warning)
- self.client.get('/render/current_app_conflict/')
+ self.client.get('/render/current_app_conflict/')
diff --git a/tests/string_lookup/models.py b/tests/string_lookup/models.py
index 4037c2950e..5761d80d49 100644
--- a/tests/string_lookup/models.py
+++ b/tests/string_lookup/models.py
@@ -1,6 +1,5 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
-import warnings
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
@@ -55,9 +54,7 @@ class Base(models.Model):
class Article(models.Model):
name = models.CharField(max_length=50)
text = models.TextField()
- with warnings.catch_warnings(record=True) as w:
- warnings.simplefilter("always")
- submitted_from = models.IPAddressField(blank=True, null=True)
+ submitted_from = models.GenericIPAddressField(blank=True, null=True)
def __str__(self):
return "Article %s" % self.name
diff --git a/tests/template_tests/filter_tests/test_removetags.py b/tests/template_tests/filter_tests/test_removetags.py
index 35515402d9..4b3dd161e7 100644
--- a/tests/template_tests/filter_tests/test_removetags.py
+++ b/tests/template_tests/filter_tests/test_removetags.py
@@ -1,57 +1,49 @@
-import warnings
-
from django.template.defaultfilters import removetags
-from django.test import SimpleTestCase
+from django.test import SimpleTestCase, ignore_warnings
from django.utils.deprecation import RemovedInDjango20Warning
from django.utils.safestring import mark_safe
from ..utils import setup
+@ignore_warnings(category=RemovedInDjango20Warning)
class RemovetagsTests(SimpleTestCase):
@setup({'removetags01': '{{ a|removetags:"a b" }} {{ b|removetags:"a b" }}'})
def test_removetags01(self):
- with warnings.catch_warnings():
- warnings.simplefilter('ignore', RemovedInDjango20Warning)
- output = self.engine.render_to_string(
- 'removetags01',
- {
- 'a': 'x
\n\t')
@@ -130,28 +118,26 @@ class FunctionTests(SimpleTestCase):
self.assertEqual(unordered_list(item_generator()), '\t
ulitem-a
\n\t
ulitem-b
')
+ @ignore_warnings(category=RemovedInDjango20Warning)
def test_legacy(self):
"""
Old format for unordered lists should still work
"""
- with warnings.catch_warnings():
- warnings.simplefilter('ignore', RemovedInDjango20Warning)
+ self.assertEqual(unordered_list(['item 1', []]), '\t