summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorClaude Paroz <claude@2xlibre.net>2014-12-21 21:19:05 +0100
committerClaude Paroz <claude@2xlibre.net>2014-12-30 18:16:25 +0100
commit51890ce8898f821d28f2f6fb6071c936e9bd88f0 (patch)
tree6522c597d411086b0a5c2ec3dd7a1d9bc2feeafd
parent66f9a74b4514bd259976ce8ee3a4e78288358a5f (diff)
downloaddjango-51890ce8898f821d28f2f6fb6071c936e9bd88f0.tar.gz
Applied ignore_warnings to Django tests
-rw-r--r--django/contrib/auth/tests/test_views.py15
-rw-r--r--django/contrib/gis/tests/geoapp/test_sitemaps.py22
-rw-r--r--django/contrib/sessions/tests.py21
-rw-r--r--django/contrib/sitemaps/tests/test_flatpages.py8
-rw-r--r--django/contrib/sitemaps/tests/test_http.py54
-rw-r--r--django/contrib/sitemaps/tests/test_https.py37
-rw-r--r--tests/admin_checks/tests.py26
-rw-r--r--tests/admin_scripts/tests.py11
-rw-r--r--tests/admin_validation/tests.py172
-rw-r--r--tests/aggregation/tests.py16
-rw-r--r--tests/backends/tests.py15
-rw-r--r--tests/cache/tests.py9
-rw-r--r--tests/commands_sql/tests.py13
-rw-r--r--tests/deprecation/tests.py1
-rw-r--r--tests/field_deconstruction/tests.py6
-rw-r--r--tests/fixtures/tests.py15
-rw-r--r--tests/forms_tests/tests/test_error_messages.py6
-rw-r--r--tests/forms_tests/tests/test_extra.py9
-rw-r--r--tests/forms_tests/tests/test_fields.py15
-rw-r--r--tests/forms_tests/tests/test_forms.py13
-rw-r--r--tests/forms_tests/tests/test_regressions.py25
-rw-r--r--tests/forms_tests/tests/test_widgets.py24
-rw-r--r--tests/generic_views/test_base.py6
-rw-r--r--tests/get_or_create/tests.py14
-rw-r--r--tests/i18n/urls.py13
-rw-r--r--tests/indexes/tests.py7
-rw-r--r--tests/inspectdb/models.py6
-rw-r--r--tests/migrations/test_writer.py14
-rw-r--r--tests/model_fields/models.py5
-rw-r--r--tests/model_fields/tests.py20
-rw-r--r--tests/modeladmin/tests.py18
-rw-r--r--tests/resolve_url/tests.py10
-rw-r--r--tests/serializers_regress/models.py5
-rw-r--r--tests/serializers_regress/tests.py13
-rw-r--r--tests/shortcuts/tests.py38
-rw-r--r--tests/string_lookup/models.py5
-rw-r--r--tests/template_tests/filter_tests/test_removetags.py60
-rw-r--r--tests/template_tests/filter_tests/test_unordered_list.py70
-rw-r--r--tests/template_tests/syntax_tests/test_cycle.py19
-rw-r--r--tests/template_tests/syntax_tests/test_filter_syntax.py8
-rw-r--r--tests/template_tests/syntax_tests/test_firstof.py24
-rw-r--r--tests/template_tests/syntax_tests/test_for.py42
-rw-r--r--tests/template_tests/syntax_tests/test_ssi.py17
-rw-r--r--tests/template_tests/syntax_tests/test_url.py103
-rw-r--r--tests/template_tests/test_custom.py10
-rw-r--r--tests/template_tests/test_loaders.py10
-rw-r--r--tests/template_tests/test_response.py8
-rw-r--r--tests/test_client_regress/tests.py40
-rw-r--r--tests/test_client_regress/views.py8
-rw-r--r--tests/urlpatterns_reverse/tests.py25
-rw-r--r--tests/user_commands/tests.py8
-rw-r--r--tests/utils_tests/test_checksums.py10
-rw-r--r--tests/utils_tests/test_datastructures.py10
-rw-r--r--tests/utils_tests/test_html.py17
-rw-r--r--tests/utils_tests/test_module_loading.py7
-rw-r--r--tests/utils_tests/test_text.py22
-rw-r--r--tests/utils_tests/test_tzinfo.py5
57 files changed, 516 insertions, 714 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, '<loc>%s%s</loc>' % (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 = """<?xml version="1.0" encoding="UTF-8"?>
<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<sitemap><loc>%s/simple/sitemap-simple.xml</loc></sitemap>
@@ -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 = """<?xml version="1.0" encoding="UTF-8"?>
<!-- This is a customised template -->
<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
@@ -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 = """<?xml version="1.0" encoding="UTF-8"?>
<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<sitemap><loc>%s/secure/sitemap-simple.xml</loc></sitemap>
@@ -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 = """<?xml version="1.0" encoding="UTF-8"?>
<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<sitemap><loc>%s/simple/sitemap-simple.xml</loc></sitemap>
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):
'<Article: Who needs to use compressed data?>',
])
+ @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):
<li><label for="composers_id_1"><input type="checkbox" name="composers" value="P" id="composers_id_1" /> Paul McCartney</label></li>
</ul>""")
+ @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(), '<p><label for="id_somechoice_0">\xc5\xf8\xdf:</label> <ul id="id_somechoice">\n<li><label for="id_somechoice_0"><input type="radio" id="id_somechoice_0" value="\xc5" name="somechoice" /> En tied\xe4</label></li>\n<li><label for="id_somechoice_1"><input type="radio" id="id_somechoice_1" value="\xf8" name="somechoice" /> Mies</label></li>\n<li><label for="id_somechoice_2"><input type="radio" id="id_somechoice_2" value="\xdf" name="somechoice" /> Nainen</label></li>\n</ul></p>')
- # 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': '<a>x</a> <p><b>y</b></p>',
- 'b': mark_safe('<a>x</a> <p><b>y</b></p>'),
- },
- )
- self.assertEqual(output, 'x &lt;p&gt;y&lt;/p&gt; x <p>y</p>')
+ output = self.engine.render_to_string(
+ 'removetags01',
+ {
+ 'a': '<a>x</a> <p><b>y</b></p>',
+ 'b': mark_safe('<a>x</a> <p><b>y</b></p>'),
+ },
+ )
+ self.assertEqual(output, 'x &lt;p&gt;y&lt;/p&gt; x <p>y</p>')
@setup({'removetags02':
'{% autoescape off %}{{ a|removetags:"a b" }} {{ b|removetags:"a b" }}{% endautoescape %}'})
def test_removetags02(self):
- with warnings.catch_warnings():
- warnings.simplefilter('ignore', RemovedInDjango20Warning)
- output = self.engine.render_to_string(
- 'removetags02',
- {
- 'a': '<a>x</a> <p><b>y</b></p>',
- 'b': mark_safe('<a>x</a> <p><b>y</b></p>'),
- },
- )
+ output = self.engine.render_to_string(
+ 'removetags02',
+ {
+ 'a': '<a>x</a> <p><b>y</b></p>',
+ 'b': mark_safe('<a>x</a> <p><b>y</b></p>'),
+ },
+ )
self.assertEqual(output, 'x <p>y</p> x <p>y</p>')
+@ignore_warnings(category=RemovedInDjango20Warning)
class FunctionTests(SimpleTestCase):
def test_removetags(self):
- with warnings.catch_warnings():
- warnings.simplefilter('ignore', RemovedInDjango20Warning)
- self.assertEqual(
- removetags(
- 'some <b>html</b> with <script>alert("You smell")</script> disallowed <img /> tags',
- 'script img',
- ),
- 'some <b>html</b> with alert("You smell") disallowed tags',
- )
+ self.assertEqual(
+ removetags(
+ 'some <b>html</b> with <script>alert("You smell")</script> disallowed <img /> tags',
+ 'script img',
+ ),
+ 'some <b>html</b> with alert("You smell") disallowed tags',
+ )
def test_non_string_input(self):
- with warnings.catch_warnings():
- warnings.simplefilter('ignore', RemovedInDjango20Warning)
- self.assertEqual(removetags(123, 'a'), '123')
+ self.assertEqual(removetags(123, 'a'), '123')
diff --git a/tests/template_tests/filter_tests/test_unordered_list.py b/tests/template_tests/filter_tests/test_unordered_list.py
index 97726a5a44..59d677b59a 100644
--- a/tests/template_tests/filter_tests/test_unordered_list.py
+++ b/tests/template_tests/filter_tests/test_unordered_list.py
@@ -1,7 +1,5 @@
-import warnings
-
from django.template.defaultfilters import unordered_list
-from django.test import SimpleTestCase
+from django.test import SimpleTestCase, ignore_warnings
from django.utils.deprecation import RemovedInDjango20Warning
from django.utils.encoding import python_2_unicode_compatible
from django.utils.safestring import mark_safe
@@ -16,11 +14,10 @@ class UnorderedListTests(SimpleTestCase):
output = self.engine.render_to_string('unordered_list01', {'a': ['x>', ['<y']]})
self.assertEqual(output, '\t<li>x&gt;\n\t<ul>\n\t\t<li>&lt;y</li>\n\t</ul>\n\t</li>')
+ @ignore_warnings(category=RemovedInDjango20Warning)
@setup({'unordered_list02': '{% autoescape off %}{{ a|unordered_list }}{% endautoescape %}'})
def test_unordered_list02(self):
- with warnings.catch_warnings():
- warnings.simplefilter('ignore', RemovedInDjango20Warning)
- output = self.engine.render_to_string('unordered_list02', {'a': ['x>', ['<y']]})
+ output = self.engine.render_to_string('unordered_list02', {'a': ['x>', ['<y']]})
self.assertEqual(output, '\t<li>x>\n\t<ul>\n\t\t<li><y</li>\n\t</ul>\n\t</li>')
@setup({'unordered_list03': '{{ a|unordered_list }}'})
@@ -39,41 +36,32 @@ class UnorderedListTests(SimpleTestCase):
self.assertEqual(output, '\t<li>x>\n\t<ul>\n\t\t<li><y</li>\n\t</ul>\n\t</li>')
+@ignore_warnings(category=RemovedInDjango20Warning)
class DeprecatedUnorderedListSyntaxTests(SimpleTestCase):
@setup({'unordered_list01': '{{ a|unordered_list }}'})
def test_unordered_list01(self):
- with warnings.catch_warnings():
- warnings.simplefilter('ignore', RemovedInDjango20Warning)
- output = self.engine.render_to_string('unordered_list01', {'a': ['x>', [['<y', []]]]})
+ output = self.engine.render_to_string('unordered_list01', {'a': ['x>', [['<y', []]]]})
self.assertEqual(output, '\t<li>x&gt;\n\t<ul>\n\t\t<li>&lt;y</li>\n\t</ul>\n\t</li>')
@setup({'unordered_list02': '{% autoescape off %}{{ a|unordered_list }}{% endautoescape %}'})
def test_unordered_list02(self):
- with warnings.catch_warnings():
- warnings.simplefilter('ignore', RemovedInDjango20Warning)
- output = self.engine.render_to_string('unordered_list02', {'a': ['x>', [['<y', []]]]})
+ output = self.engine.render_to_string('unordered_list02', {'a': ['x>', [['<y', []]]]})
self.assertEqual(output, '\t<li>x>\n\t<ul>\n\t\t<li><y</li>\n\t</ul>\n\t</li>')
@setup({'unordered_list03': '{{ a|unordered_list }}'})
def test_unordered_list03(self):
- with warnings.catch_warnings():
- warnings.simplefilter('ignore', RemovedInDjango20Warning)
- output = self.engine.render_to_string('unordered_list03', {'a': ['x>', [[mark_safe('<y'), []]]]})
+ output = self.engine.render_to_string('unordered_list03', {'a': ['x>', [[mark_safe('<y'), []]]]})
self.assertEqual(output, '\t<li>x&gt;\n\t<ul>\n\t\t<li><y</li>\n\t</ul>\n\t</li>')
@setup({'unordered_list04': '{% autoescape off %}{{ a|unordered_list }}{% endautoescape %}'})
def test_unordered_list04(self):
- with warnings.catch_warnings():
- warnings.simplefilter('ignore', RemovedInDjango20Warning)
- output = self.engine.render_to_string('unordered_list04', {'a': ['x>', [[mark_safe('<y'), []]]]})
+ output = self.engine.render_to_string('unordered_list04', {'a': ['x>', [[mark_safe('<y'), []]]]})
self.assertEqual(output, '\t<li>x>\n\t<ul>\n\t\t<li><y</li>\n\t</ul>\n\t</li>')
@setup({'unordered_list05': '{% autoescape off %}{{ a|unordered_list }}{% endautoescape %}'})
def test_unordered_list05(self):
- with warnings.catch_warnings():
- warnings.simplefilter('ignore', RemovedInDjango20Warning)
- output = self.engine.render_to_string('unordered_list05', {'a': ['x>', [['<y', []]]]})
+ output = self.engine.render_to_string('unordered_list05', {'a': ['x>', [['<y', []]]]})
self.assertEqual(output, '\t<li>x>\n\t<ul>\n\t\t<li><y</li>\n\t</ul>\n\t</li>')
@@ -130,28 +118,26 @@ class FunctionTests(SimpleTestCase):
self.assertEqual(unordered_list(item_generator()), '\t<li>ulitem-a</li>\n\t<li>ulitem-b</li>')
+ @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<li>item 1</li>')
-
- self.assertEqual(
- unordered_list(['item 1', [['item 1.1', []]]]),
- '\t<li>item 1\n\t<ul>\n\t\t<li>item 1.1</li>\n\t</ul>\n\t</li>',
- )
-
- self.assertEqual(
- unordered_list(['item 1', [['item 1.1', []],
- ['item 1.2', []]]]), '\t<li>item 1\n\t<ul>\n\t\t<li>item 1.1'
- '</li>\n\t\t<li>item 1.2</li>\n\t</ul>\n\t</li>',
- )
-
- self.assertEqual(
- unordered_list(['States', [['Kansas', [['Lawrence', []], ['Topeka', []]]], ['Illinois', []]]]),
- '\t<li>States\n\t<ul>\n\t\t<li>Kansas\n\t\t<ul>\n\t\t\t<li>Lawrence</li>'
- '\n\t\t\t<li>Topeka</li>\n\t\t</ul>\n\t\t</li>\n\t\t<li>Illinois</li>\n\t</ul>\n\t</li>',
- )
+ self.assertEqual(unordered_list(['item 1', []]), '\t<li>item 1</li>')
+
+ self.assertEqual(
+ unordered_list(['item 1', [['item 1.1', []]]]),
+ '\t<li>item 1\n\t<ul>\n\t\t<li>item 1.1</li>\n\t</ul>\n\t</li>',
+ )
+
+ self.assertEqual(
+ unordered_list(['item 1', [['item 1.1', []],
+ ['item 1.2', []]]]), '\t<li>item 1\n\t<ul>\n\t\t<li>item 1.1'
+ '</li>\n\t\t<li>item 1.2</li>\n\t</ul>\n\t</li>',
+ )
+
+ self.assertEqual(
+ unordered_list(['States', [['Kansas', [['Lawrence', []], ['Topeka', []]]], ['Illinois', []]]]),
+ '\t<li>States\n\t<ul>\n\t\t<li>Kansas\n\t\t<ul>\n\t\t\t<li>Lawrence</li>'
+ '\n\t\t\t<li>Topeka</li>\n\t\t</ul>\n\t\t</li>\n\t\t<li>Illinois</li>\n\t</ul>\n\t</li>',
+ )
diff --git a/tests/template_tests/syntax_tests/test_cycle.py b/tests/template_tests/syntax_tests/test_cycle.py
index 8a47ff8879..88a7187b1a 100644
--- a/tests/template_tests/syntax_tests/test_cycle.py
+++ b/tests/template_tests/syntax_tests/test_cycle.py
@@ -1,7 +1,5 @@
-import warnings
-
from django.template import TemplateSyntaxError
-from django.test import SimpleTestCase
+from django.test import SimpleTestCase, ignore_warnings
from django.utils.deprecation import RemovedInDjango20Warning
from ..utils import setup
@@ -141,24 +139,21 @@ class CycleTagTests(SimpleTestCase):
output = self.engine.render_to_string('cycle25', {'a': '<'})
self.assertEqual(output, '&lt;')
+ @ignore_warnings(category=RemovedInDjango20Warning)
@setup({'cycle26': '{% load cycle from future %}{% cycle a b as ab %}{% cycle ab %}'})
def test_cycle26(self):
- with warnings.catch_warnings():
- warnings.simplefilter("ignore", RemovedInDjango20Warning)
- output = self.engine.render_to_string('cycle26', {'a': '<', 'b': '>'})
+ output = self.engine.render_to_string('cycle26', {'a': '<', 'b': '>'})
self.assertEqual(output, '&lt;&gt;')
+ @ignore_warnings(category=RemovedInDjango20Warning)
@setup({'cycle27': '{% load cycle from future %}'
'{% autoescape off %}{% cycle a b as ab %}{% cycle ab %}{% endautoescape %}'})
def test_cycle27(self):
- with warnings.catch_warnings():
- warnings.simplefilter("ignore", RemovedInDjango20Warning)
- output = self.engine.render_to_string('cycle27', {'a': '<', 'b': '>'})
+ output = self.engine.render_to_string('cycle27', {'a': '<', 'b': '>'})
self.assertEqual(output, '<>')
+ @ignore_warnings(category=RemovedInDjango20Warning)
@setup({'cycle28': '{% load cycle from future %}{% cycle a|safe b as ab %}{% cycle ab %}'})
def test_cycle28(self):
- with warnings.catch_warnings():
- warnings.simplefilter("ignore", RemovedInDjango20Warning)
- output = self.engine.render_to_string('cycle28', {'a': '<', 'b': '>'})
+ output = self.engine.render_to_string('cycle28', {'a': '<', 'b': '>'})
self.assertEqual(output, '<&gt;')
diff --git a/tests/template_tests/syntax_tests/test_filter_syntax.py b/tests/template_tests/syntax_tests/test_filter_syntax.py
index 4fd62be7c8..58ee527758 100644
--- a/tests/template_tests/syntax_tests/test_filter_syntax.py
+++ b/tests/template_tests/syntax_tests/test_filter_syntax.py
@@ -1,9 +1,8 @@
# coding: utf-8
from __future__ import unicode_literals
-import warnings
from django.template import TemplateSyntaxError
-from django.test import SimpleTestCase
+from django.test import SimpleTestCase, ignore_warnings
from django.utils.deprecation import RemovedInDjango20Warning
from ..utils import setup, SomeClass, SomeOtherException, UTF8Class
@@ -76,14 +75,13 @@ class FilterSyntaxTests(SimpleTestCase):
with self.assertRaises(TemplateSyntaxError):
self.engine.get_template('filter-syntax08')
+ @ignore_warnings(category=RemovedInDjango20Warning)
@setup({'filter-syntax09': '{{ var|removetags:"b i"|upper|lower }}'})
def test_filter_syntax09(self):
"""
Chained filters, with an argument to the first one
"""
- with warnings.catch_warnings():
- warnings.simplefilter("ignore", RemovedInDjango20Warning)
- output = self.engine.render_to_string('filter-syntax09', {'var': '<b><i>Yes</i></b>'})
+ output = self.engine.render_to_string('filter-syntax09', {'var': '<b><i>Yes</i></b>'})
self.assertEqual(output, 'yes')
@setup({'filter-syntax10': r'{{ var|default_if_none:" endquote\" hah" }}'})
diff --git a/tests/template_tests/syntax_tests/test_firstof.py b/tests/template_tests/syntax_tests/test_firstof.py
index c7c4434446..2c227f2304 100644
--- a/tests/template_tests/syntax_tests/test_firstof.py
+++ b/tests/template_tests/syntax_tests/test_firstof.py
@@ -1,7 +1,5 @@
-import warnings
-
from django.template import TemplateSyntaxError
-from django.test import SimpleTestCase
+from django.test import SimpleTestCase, ignore_warnings
from django.utils.deprecation import RemovedInDjango20Warning
from ..utils import setup
@@ -59,31 +57,27 @@ class FirstOfTagTests(SimpleTestCase):
output = self.engine.render_to_string('firstof10', {'a': '<'})
self.assertEqual(output, '&lt;')
+ @ignore_warnings(category=RemovedInDjango20Warning)
@setup({'firstof11': '{% load firstof from future %}{% firstof a b %}'})
def test_firstof11(self):
- with warnings.catch_warnings():
- warnings.simplefilter("ignore", RemovedInDjango20Warning)
- output = self.engine.render_to_string('firstof11', {'a': '<', 'b': '>'})
+ output = self.engine.render_to_string('firstof11', {'a': '<', 'b': '>'})
self.assertEqual(output, '&lt;')
+ @ignore_warnings(category=RemovedInDjango20Warning)
@setup({'firstof12': '{% load firstof from future %}{% firstof a b %}'})
def test_firstof12(self):
- with warnings.catch_warnings():
- warnings.simplefilter("ignore", RemovedInDjango20Warning)
- output = self.engine.render_to_string('firstof12', {'a': '', 'b': '>'})
+ output = self.engine.render_to_string('firstof12', {'a': '', 'b': '>'})
self.assertEqual(output, '&gt;')
+ @ignore_warnings(category=RemovedInDjango20Warning)
@setup({'firstof13': '{% load firstof from future %}'
'{% autoescape off %}{% firstof a %}{% endautoescape %}'})
def test_firstof13(self):
- with warnings.catch_warnings():
- warnings.simplefilter("ignore", RemovedInDjango20Warning)
- output = self.engine.render_to_string('firstof13', {'a': '<'})
+ output = self.engine.render_to_string('firstof13', {'a': '<'})
self.assertEqual(output, '<')
+ @ignore_warnings(category=RemovedInDjango20Warning)
@setup({'firstof14': '{% load firstof from future %}{% firstof a|safe b %}'})
def test_firstof14(self):
- with warnings.catch_warnings():
- warnings.simplefilter("ignore", RemovedInDjango20Warning)
- output = self.engine.render_to_string('firstof14', {'a': '<'})
+ output = self.engine.render_to_string('firstof14', {'a': '<'})
self.assertEqual(output, '<')
diff --git a/tests/template_tests/syntax_tests/test_for.py b/tests/template_tests/syntax_tests/test_for.py
index 156d17d0b1..566b86f3d8 100644
--- a/tests/template_tests/syntax_tests/test_for.py
+++ b/tests/template_tests/syntax_tests/test_for.py
@@ -1,7 +1,5 @@
-import warnings
-
from django.template import TemplateSyntaxError
-from django.test import SimpleTestCase
+from django.test import SimpleTestCase, ignore_warnings
from django.utils.deprecation import RemovedInDjango20Warning
from ..utils import setup
@@ -129,48 +127,44 @@ class ForTagTests(SimpleTestCase):
# These tests raise deprecation warnings and will raise an exception
# in Django 2.0. The existing behavior is silent truncation if the
# length of loopvars differs to the length of each set of items.
+ @ignore_warnings(category=RemovedInDjango20Warning)
@setup({'for-tag-unpack10': '{% for x,y in items %}{{ x }}:{{ y }}/{% endfor %}'})
def test_for_tag_unpack10(self):
- with warnings.catch_warnings():
- warnings.simplefilter("ignore", RemovedInDjango20Warning)
- output = self.engine.render_to_string(
- 'for-tag-unpack10',
- {'items': (('one', 1, 'carrot'), ('two', 2, 'orange'))},
- )
+ output = self.engine.render_to_string(
+ 'for-tag-unpack10',
+ {'items': (('one', 1, 'carrot'), ('two', 2, 'orange'))},
+ )
self.assertEqual(output, 'one:1/two:2/')
+ @ignore_warnings(category=RemovedInDjango20Warning)
@setup({'for-tag-unpack11': '{% for x,y,z in items %}{{ x }}:{{ y }},{{ z }}/{% endfor %}'})
def test_for_tag_unpack11(self):
- with warnings.catch_warnings():
- warnings.simplefilter("ignore", RemovedInDjango20Warning)
- output = self.engine.render_to_string(
- 'for-tag-unpack11',
- {'items': (('one', 1), ('two', 2))},
- )
+ output = self.engine.render_to_string(
+ 'for-tag-unpack11',
+ {'items': (('one', 1), ('two', 2))},
+ )
if self.engine.string_if_invalid:
self.assertEqual(output, 'one:1,INVALID/two:2,INVALID/')
else:
self.assertEqual(output, 'one:1,/two:2,/')
+ @ignore_warnings(category=RemovedInDjango20Warning)
@setup({'for-tag-unpack12': '{% for x,y,z in items %}{{ x }}:{{ y }},{{ z }}/{% endfor %}'})
def test_for_tag_unpack12(self):
- with warnings.catch_warnings():
- warnings.simplefilter("ignore", RemovedInDjango20Warning)
- output = self.engine.render_to_string(
- 'for-tag-unpack12',
- {'items': (('one', 1, 'carrot'), ('two', 2))}
- )
+ output = self.engine.render_to_string(
+ 'for-tag-unpack12',
+ {'items': (('one', 1, 'carrot'), ('two', 2))}
+ )
if self.engine.string_if_invalid:
self.assertEqual(output, 'one:1,carrot/two:2,INVALID/')
else:
self.assertEqual(output, 'one:1,carrot/two:2,/')
+ @ignore_warnings(category=RemovedInDjango20Warning)
@setup({'for-tag-unpack14': '{% for x,y in items %}{{ x }}:{{ y }}/{% endfor %}'})
def test_for_tag_unpack14(self):
- with warnings.catch_warnings():
- warnings.simplefilter("ignore", RemovedInDjango20Warning)
- output = self.engine.render_to_string('for-tag-unpack14', {'items': (1, 2)})
+ output = self.engine.render_to_string('for-tag-unpack14', {'items': (1, 2)})
if self.engine.string_if_invalid:
self.assertEqual(output, 'INVALID:INVALID/INVALID:INVALID/')
diff --git a/tests/template_tests/syntax_tests/test_ssi.py b/tests/template_tests/syntax_tests/test_ssi.py
index c5e89b0d2f..bc70aca9c6 100644
--- a/tests/template_tests/syntax_tests/test_ssi.py
+++ b/tests/template_tests/syntax_tests/test_ssi.py
@@ -1,7 +1,6 @@
import os
-import warnings
-from django.test import SimpleTestCase
+from django.test import ignore_warnings, SimpleTestCase
from django.utils.deprecation import RemovedInDjango19Warning
from ..utils import ROOT, setup
@@ -32,20 +31,18 @@ class SsiTagTests(SimpleTestCase):
self.assertEqual(output, ''),
# Test passing as a variable
+ @ignore_warnings(category=RemovedInDjango19Warning)
@setup({'ssi04': '{% load ssi from future %}{% ssi ssi_file %}'})
def test_ssi04(self):
- with warnings.catch_warnings():
- warnings.simplefilter("ignore", RemovedInDjango19Warning)
- output = self.engine.render_to_string('ssi04', {
- 'ssi_file': os.path.join(ROOT, 'templates', 'ssi_include.html')
- })
+ output = self.engine.render_to_string('ssi04', {
+ 'ssi_file': os.path.join(ROOT, 'templates', 'ssi_include.html')
+ })
self.assertEqual(output, 'This is for testing an ssi include. {{ test }}\n')
+ @ignore_warnings(category=RemovedInDjango19Warning)
@setup({'ssi05': '{% load ssi from future %}{% ssi ssi_file %}'})
def test_ssi05(self):
- with warnings.catch_warnings():
- warnings.simplefilter("ignore", RemovedInDjango19Warning)
- output = self.engine.render_to_string('ssi05', {'ssi_file': 'no_file'})
+ output = self.engine.render_to_string('ssi05', {'ssi_file': 'no_file'})
self.assertEqual(output, '')
# Test parsed output
diff --git a/tests/template_tests/syntax_tests/test_url.py b/tests/template_tests/syntax_tests/test_url.py
index 389aefa00a..60f777f6d0 100644
--- a/tests/template_tests/syntax_tests/test_url.py
+++ b/tests/template_tests/syntax_tests/test_url.py
@@ -1,9 +1,7 @@
# coding: utf-8
-import warnings
-
from django.core.urlresolvers import NoReverseMatch
from django.template import TemplateSyntaxError
-from django.test import override_settings, SimpleTestCase
+from django.test import ignore_warnings, override_settings, SimpleTestCase
from django.utils.deprecation import RemovedInDjango20Warning
from ..utils import setup
@@ -13,46 +11,40 @@ from ..utils import setup
class UrlTagTests(SimpleTestCase):
# Successes
+ @ignore_warnings(category=RemovedInDjango20Warning)
@setup({'url01': '{% url "template_tests.views.client" client.id %}'})
def test_url01(self):
- with warnings.catch_warnings():
- warnings.simplefilter("ignore", RemovedInDjango20Warning)
- output = self.engine.render_to_string('url01', {'client': {'id': 1}})
+ output = self.engine.render_to_string('url01', {'client': {'id': 1}})
self.assertEqual(output, '/client/1/')
+ @ignore_warnings(category=RemovedInDjango20Warning)
@setup({'url02': '{% url "template_tests.views.client_action" id=client.id action="update" %}'})
def test_url02(self):
- with warnings.catch_warnings():
- warnings.simplefilter("ignore", RemovedInDjango20Warning)
- output = self.engine.render_to_string('url02', {'client': {'id': 1}})
+ output = self.engine.render_to_string('url02', {'client': {'id': 1}})
self.assertEqual(output, '/client/1/update/')
+ @ignore_warnings(category=RemovedInDjango20Warning)
@setup({'url02a': '{% url "template_tests.views.client_action" client.id "update" %}'})
def test_url02a(self):
- with warnings.catch_warnings():
- warnings.simplefilter("ignore", RemovedInDjango20Warning)
- output = self.engine.render_to_string('url02a', {'client': {'id': 1}})
+ output = self.engine.render_to_string('url02a', {'client': {'id': 1}})
self.assertEqual(output, '/client/1/update/')
+ @ignore_warnings(category=RemovedInDjango20Warning)
@setup({'url02b': "{% url 'template_tests.views.client_action' id=client.id action='update' %}"})
def test_url02b(self):
- with warnings.catch_warnings():
- warnings.simplefilter("ignore", RemovedInDjango20Warning)
- output = self.engine.render_to_string('url02b', {'client': {'id': 1}})
+ output = self.engine.render_to_string('url02b', {'client': {'id': 1}})
self.assertEqual(output, '/client/1/update/')
+ @ignore_warnings(category=RemovedInDjango20Warning)
@setup({'url02c': "{% url 'template_tests.views.client_action' client.id 'update' %}"})
def test_url02c(self):
- with warnings.catch_warnings():
- warnings.simplefilter("ignore", RemovedInDjango20Warning)
- output = self.engine.render_to_string('url02c', {'client': {'id': 1}})
+ output = self.engine.render_to_string('url02c', {'client': {'id': 1}})
self.assertEqual(output, '/client/1/update/')
+ @ignore_warnings(category=RemovedInDjango20Warning)
@setup({'url03': '{% url "template_tests.views.index" %}'})
def test_url03(self):
- with warnings.catch_warnings():
- warnings.simplefilter("ignore", RemovedInDjango20Warning)
- output = self.engine.render_to_string('url03')
+ output = self.engine.render_to_string('url03')
self.assertEqual(output, '/')
@setup({'url04': '{% url "named.client" client.id %}'})
@@ -70,11 +62,10 @@ class UrlTagTests(SimpleTestCase):
output = self.engine.render_to_string('url06', {'v': 'Ω'})
self.assertEqual(output, '/%D0%AE%D0%BD%D0%B8%D0%BA%D0%BE%D0%B4/%CE%A9/')
+ @ignore_warnings(category=RemovedInDjango20Warning)
@setup({'url07': '{% url "template_tests.views.client2" tag=v %}'})
def test_url07(self):
- with warnings.catch_warnings():
- warnings.simplefilter("ignore", RemovedInDjango20Warning)
- output = self.engine.render_to_string('url07', {'v': 'Ω'})
+ output = self.engine.render_to_string('url07', {'v': 'Ω'})
self.assertEqual(output, '/%D0%AE%D0%BD%D0%B8%D0%BA%D0%BE%D0%B4/%CE%A9/')
@setup({'url08': '{% url "метка_оператора" v %}'})
@@ -87,62 +78,54 @@ class UrlTagTests(SimpleTestCase):
output = self.engine.render_to_string('url09', {'v': 'Ω'})
self.assertEqual(output, '/%D0%AE%D0%BD%D0%B8%D0%BA%D0%BE%D0%B4/%CE%A9/')
+ @ignore_warnings(category=RemovedInDjango20Warning)
@setup({'url10': '{% url "template_tests.views.client_action" id=client.id action="two words" %}'})
def test_url10(self):
- with warnings.catch_warnings():
- warnings.simplefilter("ignore", RemovedInDjango20Warning)
- output = self.engine.render_to_string('url10', {'client': {'id': 1}})
+ output = self.engine.render_to_string('url10', {'client': {'id': 1}})
self.assertEqual(output, '/client/1/two%20words/')
+ @ignore_warnings(category=RemovedInDjango20Warning)
@setup({'url11': '{% url "template_tests.views.client_action" id=client.id action="==" %}'})
def test_url11(self):
- with warnings.catch_warnings():
- warnings.simplefilter("ignore", RemovedInDjango20Warning)
- output = self.engine.render_to_string('url11', {'client': {'id': 1}})
+ output = self.engine.render_to_string('url11', {'client': {'id': 1}})
self.assertEqual(output, '/client/1/==/')
@setup({'url12': '{% url "template_tests.views.client_action" '
'id=client.id action="!$&\'()*+,;=~:@," %}'})
+ @ignore_warnings(category=RemovedInDjango20Warning)
def test_url12(self):
- with warnings.catch_warnings():
- warnings.simplefilter("ignore", RemovedInDjango20Warning)
- output = self.engine.render_to_string('url12', {'client': {'id': 1}})
+ output = self.engine.render_to_string('url12', {'client': {'id': 1}})
self.assertEqual(output, '/client/1/!$&\'()*+,;=~:@,/')
+ @ignore_warnings(category=RemovedInDjango20Warning)
@setup({'url13': '{% url "template_tests.views.client_action" '
'id=client.id action=arg|join:"-" %}'})
def test_url13(self):
- with warnings.catch_warnings():
- warnings.simplefilter("ignore", RemovedInDjango20Warning)
- output = self.engine.render_to_string('url13', {'client': {'id': 1}, 'arg': ['a', 'b']})
+ output = self.engine.render_to_string('url13', {'client': {'id': 1}, 'arg': ['a', 'b']})
self.assertEqual(output, '/client/1/a-b/')
+ @ignore_warnings(category=RemovedInDjango20Warning)
@setup({'url14': '{% url "template_tests.views.client_action" client.id arg|join:"-" %}'})
def test_url14(self):
- with warnings.catch_warnings():
- warnings.simplefilter("ignore", RemovedInDjango20Warning)
- output = self.engine.render_to_string('url14', {'client': {'id': 1}, 'arg': ['a', 'b']})
+ output = self.engine.render_to_string('url14', {'client': {'id': 1}, 'arg': ['a', 'b']})
self.assertEqual(output, '/client/1/a-b/')
+ @ignore_warnings(category=RemovedInDjango20Warning)
@setup({'url15': '{% url "template_tests.views.client_action" 12 "test" %}'})
def test_url15(self):
- with warnings.catch_warnings():
- warnings.simplefilter("ignore", RemovedInDjango20Warning)
- output = self.engine.render_to_string('url15')
+ output = self.engine.render_to_string('url15')
self.assertEqual(output, '/client/12/test/')
+ @ignore_warnings(category=RemovedInDjango20Warning)
@setup({'url18': '{% url "template_tests.views.client" "1,2" %}'})
def test_url18(self):
- with warnings.catch_warnings():
- warnings.simplefilter("ignore", RemovedInDjango20Warning)
- output = self.engine.render_to_string('url18')
+ output = self.engine.render_to_string('url18')
self.assertEqual(output, '/client/1,2/')
+ @ignore_warnings(category=RemovedInDjango20Warning)
@setup({'url19': '{% url named_url client.id %}'})
def test_url19(self):
- with warnings.catch_warnings():
- warnings.simplefilter("ignore", RemovedInDjango20Warning)
- output = self.engine.render_to_string('url19', {'client': {'id': 1}, 'named_url': 'template_tests.views.client'})
+ output = self.engine.render_to_string('url19', {'client': {'id': 1}, 'named_url': 'template_tests.views.client'})
self.assertEqual(output, '/client/1/')
@setup({'url20': '{% url url_name_in_var client.id %}'})
@@ -161,12 +144,11 @@ class UrlTagTests(SimpleTestCase):
with self.assertRaises(NoReverseMatch):
self.engine.render_to_string('url-fail02')
+ @ignore_warnings(category=RemovedInDjango20Warning)
@setup({'url-fail03': '{% url "template_tests.views.client" %}'})
def test_url_fail03(self):
- with warnings.catch_warnings():
- warnings.simplefilter("ignore", RemovedInDjango20Warning)
- with self.assertRaises(NoReverseMatch):
- self.engine.render_to_string('url-fail03')
+ with self.assertRaises(NoReverseMatch):
+ self.engine.render_to_string('url-fail03')
@setup({'url-fail04': '{% url "view" id, %}'})
def test_url_fail04(self):
@@ -208,12 +190,11 @@ class UrlTagTests(SimpleTestCase):
with self.assertRaises(NoReverseMatch):
self.engine.render_to_string('url-fail12', {'named_url': 'no_such_view'})
+ @ignore_warnings(category=RemovedInDjango20Warning)
@setup({'url-fail13': '{% url named_url %}'})
def test_url_fail13(self):
- with warnings.catch_warnings():
- warnings.simplefilter("ignore", RemovedInDjango20Warning)
- with self.assertRaises(NoReverseMatch):
- self.engine.render_to_string('url-fail13', {'named_url': 'template_tests.views.client'})
+ with self.assertRaises(NoReverseMatch):
+ self.engine.render_to_string('url-fail13', {'named_url': 'template_tests.views.client'})
@setup({'url-fail14': '{% url named_url id, %}'})
def test_url_fail14(self):
@@ -246,18 +227,16 @@ class UrlTagTests(SimpleTestCase):
self.engine.render_to_string('url-fail19', {'named_url': 'view'})
# {% url ... as var %}
+ @ignore_warnings(category=RemovedInDjango20Warning)
@setup({'url-asvar01': '{% url "template_tests.views.index" as url %}'})
def test_url_asvar01(self):
- with warnings.catch_warnings():
- warnings.simplefilter("ignore", RemovedInDjango20Warning)
- output = self.engine.render_to_string('url-asvar01')
+ output = self.engine.render_to_string('url-asvar01')
self.assertEqual(output, '')
+ @ignore_warnings(category=RemovedInDjango20Warning)
@setup({'url-asvar02': '{% url "template_tests.views.index" as url %}{{ url }}'})
def test_url_asvar02(self):
- with warnings.catch_warnings():
- warnings.simplefilter("ignore", RemovedInDjango20Warning)
- output = self.engine.render_to_string('url-asvar02')
+ output = self.engine.render_to_string('url-asvar02')
self.assertEqual(output, '/')
@setup({'url-asvar03': '{% url "no_such_view" as url %}{{ url }}'})
diff --git a/tests/template_tests/test_custom.py b/tests/template_tests/test_custom.py
index f0768ba2a5..780776fa20 100644
--- a/tests/template_tests/test_custom.py
+++ b/tests/template_tests/test_custom.py
@@ -1,9 +1,9 @@
from __future__ import unicode_literals
from unittest import TestCase
-import warnings
from django import template
+from django.test import ignore_warnings
from django.utils import six
from django.utils.deprecation import RemovedInDjango20Warning
@@ -246,6 +246,7 @@ class CustomTagTests(TestCase):
self.verify_tag(custom.inclusion_tag_current_app, 'inclusion_tag_current_app')
self.verify_tag(custom.inclusion_unlimited_args_kwargs, 'inclusion_unlimited_args_kwargs')
+ @ignore_warnings(category=RemovedInDjango20Warning)
def test_15070_current_app(self):
"""
Test that inclusion tag passes down `current_app` of context to the
@@ -255,10 +256,9 @@ class CustomTagTests(TestCase):
t = template.Template('{% load custom %}{% inclusion_tag_current_app %}')
self.assertEqual(t.render(c).strip(), 'None')
- with warnings.catch_warnings():
- warnings.filterwarnings("ignore", category=RemovedInDjango20Warning)
- c = template.Context({}, current_app='advanced')
- self.assertEqual(t.render(c).strip(), 'advanced')
+ # That part produces the deprecation warning
+ c = template.Context({}, current_app='advanced')
+ self.assertEqual(t.render(c).strip(), 'advanced')
def test_15070_use_l10n(self):
"""
diff --git a/tests/template_tests/test_loaders.py b/tests/template_tests/test_loaders.py
index 47e69ad3c5..073e57bf67 100644
--- a/tests/template_tests/test_loaders.py
+++ b/tests/template_tests/test_loaders.py
@@ -19,9 +19,9 @@ from django.template import TemplateDoesNotExist, Context
from django.template.loaders import cached, eggs
from django.template.engine import Engine
from django.template import loader
-from django.test import SimpleTestCase, override_settings
-from django.test.utils import IgnorePendingDeprecationWarningsMixin
+from django.test import SimpleTestCase, ignore_warnings, override_settings
from django.utils import six
+from django.utils.deprecation import RemovedInDjango20Warning
from django.utils._os import upath
from django.utils.six import StringIO
@@ -166,11 +166,12 @@ class RenderToStringTest(SimpleTestCase):
loader.select_template, [])
+@ignore_warnings(category=RemovedInDjango20Warning)
@override_settings(TEMPLATES=[{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [TEMPLATES_DIR],
}])
-class DeprecatedRenderToStringTest(IgnorePendingDeprecationWarningsMixin, SimpleTestCase):
+class DeprecatedRenderToStringTest(SimpleTestCase):
def test_existing_context_kept_clean(self):
context = Context({'obj': 'before'})
@@ -192,10 +193,11 @@ class DeprecatedRenderToStringTest(IgnorePendingDeprecationWarningsMixin, Simple
loader.render_to_string('test_context_stack.html', context_instance=Context()).strip())
+@ignore_warnings(category=RemovedInDjango20Warning)
@override_settings(TEMPLATES=[{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
}])
-class TemplateDirsOverrideTest(IgnorePendingDeprecationWarningsMixin, SimpleTestCase):
+class TemplateDirsOverrideTest(SimpleTestCase):
dirs_tuple = (os.path.join(os.path.dirname(upath(__file__)), 'other_templates'),)
dirs_list = list(dirs_tuple)
diff --git a/tests/template_tests/test_response.py b/tests/template_tests/test_response.py
index 6ae5457c98..c96eb8ff37 100644
--- a/tests/template_tests/test_response.py
+++ b/tests/template_tests/test_response.py
@@ -4,14 +4,13 @@ from datetime import datetime
import os
import pickle
import time
-import warnings
from django.test import RequestFactory, SimpleTestCase
from django.conf import settings
from django.template import Template, Context
from django.template.response import (TemplateResponse, SimpleTemplateResponse,
ContentNotRenderedError)
-from django.test import override_settings
+from django.test import ignore_warnings, override_settings
from django.utils._os import upath
from django.utils.deprecation import RemovedInDjango20Warning
@@ -256,10 +255,9 @@ class TemplateResponseTest(SimpleTestCase):
self.assertEqual(response['content-type'], 'application/json')
self.assertEqual(response.status_code, 504)
+ @ignore_warnings(category=RemovedInDjango20Warning)
def test_custom_app(self):
- with warnings.catch_warnings():
- warnings.filterwarnings("ignore", category=RemovedInDjango20Warning)
- response = self._response('{{ foo }}', current_app="foobar")
+ response = self._response('{{ foo }}', current_app="foobar")
rc = response.resolve_context(response.context_data)
diff --git a/tests/test_client_regress/tests.py b/tests/test_client_regress/tests.py
index fc68c5b5f7..6f8d97c886 100644
--- a/tests/test_client_regress/tests.py
+++ b/tests/test_client_regress/tests.py
@@ -6,16 +6,15 @@ from __future__ import unicode_literals
import os
import itertools
-import warnings
from django.core.urlresolvers import reverse, NoReverseMatch
from django.template import TemplateSyntaxError, Context, Template
-from django.test import Client, TestCase, override_settings
+from django.test import Client, TestCase, ignore_warnings, override_settings
from django.test.client import RedirectCycleError, RequestFactory, encode_file
from django.test.utils import ContextList, str_prefix
from django.template.response import SimpleTemplateResponse
+from django.utils.deprecation import RemovedInDjango19Warning, RemovedInDjango20Warning
from django.utils._os import upath
-from django.utils.deprecation import RemovedInDjango20Warning
from django.utils.translation import ugettext_lazy
from django.http import HttpResponse
from django.contrib.auth.signals import user_logged_out, user_logged_in
@@ -952,6 +951,7 @@ class zzUrlconfSubstitutionTests(TestCase):
class ContextTests(TestCase):
fixtures = ['testdata']
+ @ignore_warnings(category=RemovedInDjango19Warning) # `request.REQUEST` is deprecated
def test_single_context(self):
"Context variables can be retrieved from a single context"
response = self.client.get("/request_data/", data={'foo': 'whiz'})
@@ -967,6 +967,7 @@ class ContextTests(TestCase):
except KeyError as e:
self.assertEqual(e.args[0], 'does-not-exist')
+ @ignore_warnings(category=RemovedInDjango19Warning) # `request.REQUEST` is deprecated
def test_inherited_context(self):
"Context variables can be retrieved from a list of contexts"
response = self.client.get("/request_data_extended/", data={'foo': 'whiz'})
@@ -998,23 +999,22 @@ class ContextTests(TestCase):
'python', 'dolly'},
l.keys())
+ @ignore_warnings(category=RemovedInDjango20Warning)
def test_15368(self):
- with warnings.catch_warnings():
- warnings.filterwarnings("ignore", category=RemovedInDjango20Warning)
- # Need to insert a context processor that assumes certain things about
- # the request instance. This triggers a bug caused by some ways of
- # copying RequestContext.
- with self.settings(TEMPLATES=[{
- 'BACKEND': 'django.template.backends.django.DjangoTemplates',
- 'APP_DIRS': True,
- 'OPTIONS': {
- 'context_processors': [
- 'test_client_regress.context_processors.special',
- ],
- },
- }]):
- response = self.client.get("/request_context_view/")
- self.assertContains(response, 'Path: /request_context_view/')
+ # Need to insert a context processor that assumes certain things about
+ # the request instance. This triggers a bug caused by some ways of
+ # copying RequestContext.
+ with self.settings(TEMPLATES=[{
+ 'BACKEND': 'django.template.backends.django.DjangoTemplates',
+ 'APP_DIRS': True,
+ 'OPTIONS': {
+ 'context_processors': [
+ 'test_client_regress.context_processors.special',
+ ],
+ },
+ }]):
+ response = self.client.get("/request_context_view/")
+ self.assertContains(response, 'Path: /request_context_view/')
def test_nested_requests(self):
"""
@@ -1250,6 +1250,7 @@ class RequestMethodStringDataTests(TestCase):
@override_settings(ROOT_URLCONF='test_client_regress.urls',)
class QueryStringTests(TestCase):
+ @ignore_warnings(category=RemovedInDjango19Warning) # `request.REQUEST` is deprecated
def test_get_like_requests(self):
# See: https://code.djangoproject.com/ticket/10571.
for method_name in ('get', 'head'):
@@ -1275,6 +1276,7 @@ class QueryStringTests(TestCase):
self.assertEqual(response.context['request-foo'], None)
self.assertEqual(response.context['request-bar'], 'bang')
+ @ignore_warnings(category=RemovedInDjango19Warning) # `request.REQUEST` is deprecated
def test_post_like_requests(self):
# A POST-like request can pass a query string as data
response = self.client.post("/request_data/", data={'foo': 'whiz'})
diff --git a/tests/test_client_regress/views.py b/tests/test_client_regress/views.py
index b752d1b9f7..28635940ae 100644
--- a/tests/test_client_regress/views.py
+++ b/tests/test_client_regress/views.py
@@ -1,5 +1,4 @@
import json
-import warnings
from django.conf import settings
from django.contrib.auth.decorators import login_required
@@ -40,11 +39,8 @@ get_view = login_required(get_view)
def request_data(request, template='base.html', data='sausage'):
"A simple view that returns the request data in the context"
- # request.REQUEST is deprecated, but needs testing until removed.
- with warnings.catch_warnings(record=True):
- warnings.simplefilter("always")
- request_foo = request.REQUEST.get('foo')
- request_bar = request.REQUEST.get('bar')
+ request_foo = request.REQUEST.get('foo')
+ request_bar = request.REQUEST.get('bar')
return render_to_response(template, {
'get-foo': request.GET.get('foo'),
diff --git a/tests/urlpatterns_reverse/tests.py b/tests/urlpatterns_reverse/tests.py
index 18299fe733..bb732d2fec 100644
--- a/tests/urlpatterns_reverse/tests.py
+++ b/tests/urlpatterns_reverse/tests.py
@@ -6,7 +6,6 @@ from __future__ import unicode_literals
import sys
import unittest
-import warnings
from django.contrib.auth.models import User
from django.conf import settings
@@ -16,7 +15,7 @@ from django.core.urlresolvers import (reverse, reverse_lazy, resolve, get_callab
RegexURLPattern)
from django.http import HttpRequest, HttpResponseRedirect, HttpResponsePermanentRedirect
from django.shortcuts import redirect
-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
@@ -177,16 +176,15 @@ class NoURLPatternsTests(TestCase):
@override_settings(ROOT_URLCONF='urlpatterns_reverse.urls')
class URLPatternReverse(TestCase):
+ @ignore_warnings(category=RemovedInDjango20Warning)
def test_urlpattern_reverse(self):
- with warnings.catch_warnings():
- warnings.filterwarnings("ignore", category=RemovedInDjango20Warning)
- for name, expected, args, kwargs in test_data:
- try:
- got = reverse(name, args=args, kwargs=kwargs)
- except NoReverseMatch:
- self.assertEqual(expected, NoReverseMatch)
- else:
- self.assertEqual(got, expected)
+ for name, expected, args, kwargs in test_data:
+ try:
+ got = reverse(name, args=args, kwargs=kwargs)
+ except NoReverseMatch:
+ self.assertEqual(expected, NoReverseMatch)
+ else:
+ self.assertEqual(got, expected)
def test_reverse_none(self):
# Reversing None should raise an error, not return the last un-named view.
@@ -385,12 +383,11 @@ class ReverseShortcutTests(TestCase):
redirect("urlpatterns_reverse.nonimported_module.view")
self.assertNotIn("urlpatterns_reverse.nonimported_module", sys.modules)
+ @ignore_warnings(category=RemovedInDjango20Warning)
def test_reverse_by_path_nested(self):
# Views that are added to urlpatterns using include() should be
# reversible by doted path.
- with warnings.catch_warnings():
- warnings.filterwarnings("ignore", category=RemovedInDjango20Warning)
- self.assertEqual(reverse('urlpatterns_reverse.views.nested_view'), '/includes/nested_path/')
+ self.assertEqual(reverse('urlpatterns_reverse.views.nested_view'), '/includes/nested_path/')
def test_redirect_view_object(self):
from .views import absolute_kwargs_view
diff --git a/tests/user_commands/tests.py b/tests/user_commands/tests.py
index 3839f23e78..6a5677f2c9 100644
--- a/tests/user_commands/tests.py
+++ b/tests/user_commands/tests.py
@@ -1,11 +1,10 @@
import os
-import warnings
from django.db import connection
from django.core import management
from django.core.management import BaseCommand, CommandError
from django.core.management.utils import find_command, popen_wrapper
-from django.test import SimpleTestCase
+from django.test import SimpleTestCase, ignore_warnings
from django.test.utils import captured_stderr, captured_stdout
from django.utils import translation
from django.utils.deprecation import RemovedInDjango20Warning
@@ -84,14 +83,13 @@ class CommandTests(SimpleTestCase):
self.assertNotIn("opt_3", out.getvalue())
self.assertNotIn("opt-3", out.getvalue())
+ @ignore_warnings(category=RemovedInDjango20Warning)
def test_optparse_compatibility(self):
"""
optparse should be supported during Django 1.8/1.9 releases.
"""
out = StringIO()
- with warnings.catch_warnings():
- warnings.filterwarnings("ignore", category=RemovedInDjango20Warning)
- management.call_command('optparse_cmd', stdout=out)
+ management.call_command('optparse_cmd', stdout=out)
self.assertEqual(out.getvalue(), "All right, let's dance Rock'n'Roll.\n")
# Simulate command line execution
diff --git a/tests/utils_tests/test_checksums.py b/tests/utils_tests/test_checksums.py
index 0302956014..0f6c8d6454 100644
--- a/tests/utils_tests/test_checksums.py
+++ b/tests/utils_tests/test_checksums.py
@@ -1,14 +1,8 @@
import unittest
-import warnings
+from django.test import ignore_warnings
from django.utils.deprecation import RemovedInDjango20Warning
-with warnings.catch_warnings():
- warnings.filterwarnings(
- 'ignore', 'django.utils.checksums will be removed in Django 2.0.',
- RemovedInDjango20Warning)
- from django.utils import checksums
-
class TestUtilsChecksums(unittest.TestCase):
@@ -21,7 +15,9 @@ class TestUtilsChecksums(unittest.TestCase):
output = value
self.assertEqual(function(value), output)
+ @ignore_warnings(category=RemovedInDjango20Warning)
def test_luhn(self):
+ from django.utils import checksums
f = checksums.luhn
items = (
(4111111111111111, True), ('4111111111111111', True),
diff --git a/tests/utils_tests/test_datastructures.py b/tests/utils_tests/test_datastructures.py
index d9a0a678f8..04ae61902c 100644
--- a/tests/utils_tests/test_datastructures.py
+++ b/tests/utils_tests/test_datastructures.py
@@ -5,14 +5,15 @@ Tests for stuff in django.utils.datastructures.
import copy
import pickle
-from django.test import SimpleTestCase
-from django.test.utils import IgnoreDeprecationWarningsMixin
+from django.test import SimpleTestCase, ignore_warnings
from django.utils.datastructures import (DictWrapper, ImmutableList,
MultiValueDict, MultiValueDictKeyError, MergeDict, OrderedSet, SortedDict)
+from django.utils.deprecation import RemovedInDjango19Warning
from django.utils import six
-class SortedDictTests(IgnoreDeprecationWarningsMixin, SimpleTestCase):
+@ignore_warnings(category=RemovedInDjango19Warning)
+class SortedDictTests(SimpleTestCase):
def setUp(self):
super(SortedDictTests, self).setUp()
self.d1 = SortedDict()
@@ -136,7 +137,8 @@ class SortedDictTests(IgnoreDeprecationWarningsMixin, SimpleTestCase):
self.assertEqual(list(reversed(self.d2)), [7, 0, 9, 1])
-class MergeDictTests(IgnoreDeprecationWarningsMixin, SimpleTestCase):
+@ignore_warnings(category=RemovedInDjango19Warning)
+class MergeDictTests(SimpleTestCase):
def test_simple_mergedict(self):
d1 = {'chris': 'cool', 'camri': 'cute', 'cotton': 'adorable',
diff --git a/tests/utils_tests/test_html.py b/tests/utils_tests/test_html.py
index 4023434101..6375f2280b 100644
--- a/tests/utils_tests/test_html.py
+++ b/tests/utils_tests/test_html.py
@@ -4,10 +4,11 @@ from __future__ import unicode_literals
from datetime import datetime
import os
from unittest import TestCase
-import warnings
+from django.test import ignore_warnings
from django.utils import html, safestring
from django.utils._os import upath
+from django.utils.deprecation import RemovedInDjango20Warning
from django.utils.encoding import force_text
@@ -120,14 +121,13 @@ class TestUtilsHtml(TestCase):
for value, output in items:
self.check_output(f, value, output)
+ @ignore_warnings(category=RemovedInDjango20Warning)
def test_strip_entities(self):
f = html.strip_entities
# Strings that should come out untouched.
values = ("&", "&a", "&a", "a&#a")
for value in values:
- with warnings.catch_warnings(record=True):
- warnings.simplefilter("always")
- self.check_output(f, value)
+ self.check_output(f, value)
# Valid entities that should be stripped from the patterns.
entities = ("&#1;", "&#12;", "&a;", "&fdasdfasdfasdf;")
patterns = (
@@ -138,9 +138,7 @@ class TestUtilsHtml(TestCase):
)
for entity in entities:
for in_pattern, output in patterns:
- with warnings.catch_warnings(record=True):
- warnings.simplefilter("always")
- self.check_output(f, in_pattern % {'entity': entity}, output)
+ self.check_output(f, in_pattern % {'entity': entity}, output)
def test_escapejs(self):
f = html.escapejs
@@ -154,6 +152,7 @@ class TestUtilsHtml(TestCase):
for value, output in items:
self.check_output(f, value, output)
+ @ignore_warnings(category=RemovedInDjango20Warning)
def test_remove_tags(self):
f = html.remove_tags
items = (
@@ -161,9 +160,7 @@ class TestUtilsHtml(TestCase):
("<a>x</a> <p><b>y</b></p>", "a b", "x <p>y</p>"),
)
for value, tags, output in items:
- with warnings.catch_warnings(record=True):
- warnings.simplefilter("always")
- self.assertEqual(f(value, tags), output)
+ self.assertEqual(f(value, tags), output)
def test_smart_urlquote(self):
quote = html.smart_urlquote
diff --git a/tests/utils_tests/test_module_loading.py b/tests/utils_tests/test_module_loading.py
index 31608bfcc1..89c9d03b9e 100644
--- a/tests/utils_tests/test_module_loading.py
+++ b/tests/utils_tests/test_module_loading.py
@@ -7,8 +7,8 @@ import warnings
from zipimport import zipimporter
from django.core.exceptions import ImproperlyConfigured
-from django.test import SimpleTestCase, modify_settings
-from django.test.utils import IgnoreDeprecationWarningsMixin, extend_sys_path
+from django.test import SimpleTestCase, ignore_warnings, modify_settings
+from django.test.utils import extend_sys_path
from django.utils import six
from django.utils.deprecation import RemovedInDjango19Warning
from django.utils.module_loading import (autodiscover_modules, import_by_path, import_string,
@@ -110,7 +110,8 @@ class EggLoader(unittest.TestCase):
self.assertRaises(ImportError, import_module, 'egg_module.sub1.sub2.no_such_module')
-class ModuleImportTestCase(IgnoreDeprecationWarningsMixin, unittest.TestCase):
+@ignore_warnings(category=RemovedInDjango19Warning)
+class ModuleImportTestCase(unittest.TestCase):
def test_import_by_path(self):
cls = import_by_path('django.utils.module_loading.import_by_path')
self.assertEqual(cls, import_by_path)
diff --git a/tests/utils_tests/test_text.py b/tests/utils_tests/test_text.py
index f315cf41ce..142963893e 100644
--- a/tests/utils_tests/test_text.py
+++ b/tests/utils_tests/test_text.py
@@ -4,7 +4,7 @@ from __future__ import unicode_literals
from unittest import skipUnless
import warnings
-from django.test import SimpleTestCase
+from django.test import SimpleTestCase, ignore_warnings
from django.test.utils import reset_warning_registry
from django.utils import six, text
from django.utils.deprecation import RemovedInDjango19Warning
@@ -198,26 +198,24 @@ class TestUtilsText(SimpleTestCase):
filename = "^&'@{}[],$=!-#()%+~_123.txt"
self.assertEqual(text.get_valid_filename(filename), "-_123.txt")
+ @ignore_warnings(category=RemovedInDjango19Warning)
def test_javascript_quote(self):
input = "<script>alert('Hello \\xff.\n Welcome\there\r');</script>"
output = r"<script>alert(\'Hello \\xff.\n Welcome\there\r\');<\/script>"
- with warnings.catch_warnings():
- warnings.simplefilter("ignore", RemovedInDjango19Warning)
- self.assertEqual(text.javascript_quote(input), output)
+ self.assertEqual(text.javascript_quote(input), output)
- # Exercising quote_double_quotes keyword argument
- input = '"Text"'
- self.assertEqual(text.javascript_quote(input), '"Text"')
- self.assertEqual(text.javascript_quote(input, quote_double_quotes=True),
- '&quot;Text&quot;')
+ # Exercising quote_double_quotes keyword argument
+ input = '"Text"'
+ self.assertEqual(text.javascript_quote(input), '"Text"')
+ self.assertEqual(text.javascript_quote(input, quote_double_quotes=True),
+ '&quot;Text&quot;')
+ @ignore_warnings(category=RemovedInDjango19Warning)
@skipUnless(IS_WIDE_BUILD, 'Not running in a wide build of Python')
def test_javascript_quote_unicode(self):
input = "<script>alert('Hello \\xff.\n Wel𝕃come\there\r');</script>"
output = r"<script>alert(\'Hello \\xff.\n Wel𝕃come\there\r\');<\/script>"
- with warnings.catch_warnings():
- warnings.simplefilter("ignore", RemovedInDjango19Warning)
- self.assertEqual(text.javascript_quote(input), output)
+ self.assertEqual(text.javascript_quote(input), output)
def test_deprecation(self):
reset_warning_registry()
diff --git a/tests/utils_tests/test_tzinfo.py b/tests/utils_tests/test_tzinfo.py
index 4d1af62f0a..b1a08fb600 100644
--- a/tests/utils_tests/test_tzinfo.py
+++ b/tests/utils_tests/test_tzinfo.py
@@ -6,7 +6,7 @@ import time
import unittest
import warnings
-from django.test.utils import IgnoreDeprecationWarningsMixin
+from django.test import ignore_warnings
from django.utils.deprecation import RemovedInDjango19Warning
@@ -16,7 +16,8 @@ with warnings.catch_warnings():
from django.utils.tzinfo import FixedOffset, LocalTimezone
-class TzinfoTests(IgnoreDeprecationWarningsMixin, unittest.TestCase):
+@ignore_warnings(category=RemovedInDjango19Warning)
+class TzinfoTests(unittest.TestCase):
@classmethod
def setUpClass(cls):