Applied ignore_warnings to Django tests

This commit is contained in:
Claude Paroz 2014-12-21 21:19:05 +01:00
parent 66f9a74b45
commit 51890ce889
57 changed files with 513 additions and 711 deletions

View File

@ -1,7 +1,6 @@
from importlib import import_module from importlib import import_module
import itertools import itertools
import re import re
import warnings
from django.apps import apps from django.apps import apps
from django.conf import settings 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 import mail
from django.core.urlresolvers import reverse, NoReverseMatch from django.core.urlresolvers import reverse, NoReverseMatch
from django.http import QueryDict, HttpRequest from django.http import QueryDict, HttpRequest
from django.utils.deprecation import RemovedInDjango20Warning
from django.utils.encoding import force_text from django.utils.encoding import force_text
from django.utils.http import urlquote from django.utils.http import urlquote
from django.utils.six.moves.urllib.parse import urlparse, ParseResult from django.utils.six.moves.urllib.parse import urlparse, ParseResult
from django.utils.translation import LANGUAGE_SESSION_KEY 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.test.utils import patch_logger
from django.middleware.csrf import CsrfViewMiddleware from django.middleware.csrf import CsrfViewMiddleware
from django.contrib.sessions.middleware import SessionMiddleware from django.contrib.sessions.middleware import SessionMiddleware
@ -154,15 +154,14 @@ class PasswordResetTest(AuthViewsTestCase):
self.assertEqual(len(mail.outbox), 1) self.assertEqual(len(mail.outbox), 1)
self.assertEqual("staffmember@example.com", mail.outbox[0].from_email) self.assertEqual("staffmember@example.com", mail.outbox[0].from_email)
@ignore_warnings(category=RemovedInDjango20Warning)
@override_settings(ALLOWED_HOSTS=['adminsite.com']) @override_settings(ALLOWED_HOSTS=['adminsite.com'])
def test_admin_reset(self): 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." "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): response = self.client.post('/admin_password_reset/',
warnings.simplefilter("always") {'email': 'staffmember@example.com'},
response = self.client.post('/admin_password_reset/', HTTP_HOST='adminsite.com'
{'email': 'staffmember@example.com'}, )
HTTP_HOST='adminsite.com'
)
self.assertEqual(response.status_code, 302) self.assertEqual(response.status_code, 302)
self.assertEqual(len(mail.outbox), 1) self.assertEqual(len(mail.outbox), 1)
self.assertIn("http://adminsite.com", mail.outbox[0].body) self.assertIn("http://adminsite.com", mail.outbox[0].body)

View File

@ -2,14 +2,13 @@ from __future__ import unicode_literals
from io import BytesIO from io import BytesIO
from xml.dom import minidom from xml.dom import minidom
import warnings
import zipfile import zipfile
from django.conf import settings from django.conf import settings
from django.contrib.gis.geos import HAS_GEOS from django.contrib.gis.geos import HAS_GEOS
from django.contrib.sites.models import Site from django.contrib.sites.models import Site
from django.test import ( from django.test import (
TestCase, modify_settings, override_settings, skipUnlessDBFeature TestCase, ignore_warnings, modify_settings, override_settings, skipUnlessDBFeature
) )
from django.utils.deprecation import RemovedInDjango20Warning from django.utils.deprecation import RemovedInDjango20Warning
@ -32,19 +31,18 @@ class GeoSitemapTest(TestCase):
expected = set(expected) expected = set(expected)
self.assertEqual(actual, expected) self.assertEqual(actual, expected)
@ignore_warnings(category=RemovedInDjango20Warning)
def test_geositemap_kml(self): def test_geositemap_kml(self):
"Tests KML/KMZ geographic sitemaps." "Tests KML/KMZ geographic sitemaps."
for kml_type in ('kml', 'kmz'): for kml_type in ('kml', 'kmz'):
with warnings.catch_warnings(): # The URL for the sitemaps in urls.py have been updated
warnings.filterwarnings("ignore", category=RemovedInDjango20Warning) # with a name but since reversing by Python path is tried first
# The URL for the sitemaps in urls.py have been updated # before reversing by name and works since we're giving
# with a name but since reversing by Python path is tried first # name='django.contrib.gis.sitemaps.views.(kml|kmz)', we need
# before reversing by name and works since we're giving # to silence the erroneous warning until reversing by dotted
# name='django.contrib.gis.sitemaps.views.(kml|kmz)', we need # path is removed. The test will work without modification when
# to silence the erroneous warning until reversing by dotted # it's removed.
# path is removed. The test will work without modification when doc = minidom.parseString(self.client.get('/sitemaps/%s.xml' % kml_type).content)
# it's removed.
doc = minidom.parseString(self.client.get('/sitemaps/%s.xml' % kml_type).content)
# Ensuring the right sitemaps namespace is present. # Ensuring the right sitemaps namespace is present.
urlset = doc.firstChild urlset = doc.firstChild

View File

@ -5,7 +5,6 @@ import shutil
import string import string
import tempfile import tempfile
import unittest import unittest
import warnings
from django.conf import settings from django.conf import settings
from django.contrib.sessions.backends.db import SessionStore as DatabaseSession 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 import management
from django.core.exceptions import ImproperlyConfigured from django.core.exceptions import ImproperlyConfigured
from django.http import HttpResponse 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.test.utils import patch_logger
from django.utils import six from django.utils import six
from django.utils import timezone from django.utils import timezone
@ -393,12 +392,11 @@ class CacheDBSessionTests(SessionTestsMixin, TestCase):
with self.assertNumQueries(0): with self.assertNumQueries(0):
self.assertTrue(self.session.exists(self.session.session_key)) 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): def test_load_overlong_key(self):
# Some backends might issue a warning self.session._session_key = (string.ascii_letters + string.digits) * 20
with warnings.catch_warnings(): self.assertEqual(self.session.load(), {})
warnings.simplefilter("ignore")
self.session._session_key = (string.ascii_letters + string.digits) * 20
self.assertEqual(self.session.load(), {})
@override_settings(SESSION_CACHE_ALIAS='sessions') @override_settings(SESSION_CACHE_ALIAS='sessions')
def test_non_default_cache(self): def test_non_default_cache(self):
@ -486,12 +484,11 @@ class CacheSessionTests(SessionTestsMixin, unittest.TestCase):
backend = CacheSession backend = CacheSession
# Some backends might issue a warning
@ignore_warnings(module="django.core.cache.backends.base")
def test_load_overlong_key(self): def test_load_overlong_key(self):
# Some backends might issue a warning self.session._session_key = (string.ascii_letters + string.digits) * 20
with warnings.catch_warnings(): self.assertEqual(self.session.load(), {})
warnings.simplefilter("ignore")
self.session._session_key = (string.ascii_letters + string.digits) * 20
self.assertEqual(self.session.load(), {})
def test_default_cache(self): def test_default_cache(self):
self.session.save() self.session.save()

View File

@ -6,13 +6,15 @@ import warnings
from django.apps import apps from django.apps import apps
from django.conf import settings from django.conf import settings
from django.contrib.sitemaps import FlatPageSitemap 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 from .base import SitemapTestsBase
class FlatpagesSitemapTests(SitemapTestsBase): class FlatpagesSitemapTests(SitemapTestsBase):
@ignore_warnings(category=RemovedInDjango19Warning)
@skipUnless(apps.is_installed('django.contrib.flatpages'), @skipUnless(apps.is_installed('django.contrib.flatpages'),
"django.contrib.flatpages app not installed.") "django.contrib.flatpages app not installed.")
def test_flatpage_sitemap(self): def test_flatpage_sitemap(self):
@ -38,9 +40,7 @@ class FlatpagesSitemapTests(SitemapTestsBase):
registration_required=True registration_required=True
) )
private.sites.add(settings.SITE_ID) private.sites.add(settings.SITE_ID)
with warnings.catch_warnings(): response = self.client.get('/flatpages/sitemap.xml')
warnings.simplefilter('ignore')
response = self.client.get('/flatpages/sitemap.xml')
# Public flatpage should be in the sitemap # Public flatpage should be in the sitemap
self.assertContains(response, '<loc>%s%s</loc>' % (self.base_url, public.url)) self.assertContains(response, '<loc>%s%s</loc>' % (self.base_url, public.url))
# Private flatpage should not be in the sitemap # Private flatpage should not be in the sitemap

View File

@ -3,14 +3,13 @@ from __future__ import unicode_literals
import os import os
from datetime import date from datetime import date
from unittest import skipUnless from unittest import skipUnless
import warnings
from django.apps import apps from django.apps import apps
from django.conf import settings from django.conf import settings
from django.contrib.sitemaps import Sitemap, GenericSitemap from django.contrib.sitemaps import Sitemap, GenericSitemap
from django.contrib.sites.models import Site from django.contrib.sites.models import Site
from django.core.exceptions import ImproperlyConfigured 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.deprecation import RemovedInDjango20Warning
from django.utils.formats import localize from django.utils.formats import localize
from django.utils._os import upath from django.utils._os import upath
@ -21,17 +20,16 @@ from .base import TestModel, SitemapTestsBase
class HTTPSitemapTests(SitemapTestsBase): class HTTPSitemapTests(SitemapTestsBase):
@ignore_warnings(category=RemovedInDjango20Warning)
def test_simple_sitemap_index(self): def test_simple_sitemap_index(self):
"A simple sitemap index can be rendered" "A simple sitemap index can be rendered"
with warnings.catch_warnings(): # The URL for views.sitemap in tests/urls/http.py has been updated
warnings.filterwarnings("ignore", category=RemovedInDjango20Warning) # with a name but since reversing by Python path is tried first
# The URL for views.sitemap in tests/urls/http.py has been updated # before reversing by name and works since we're giving
# with a name but since reversing by Python path is tried first # name='django.contrib.sitemaps.views.sitemap', we need to silence
# before reversing by name and works since we're giving # the erroneous warning until reversing by dotted path is removed.
# name='django.contrib.sitemaps.views.sitemap', we need to silence # The test will work without modification when it's removed.
# the erroneous warning until reversing by dotted path is removed. response = self.client.get('/simple/index.xml')
# 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"?> expected_content = """<?xml version="1.0" encoding="UTF-8"?>
<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> <sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<sitemap><loc>%s/simple/sitemap-simple.xml</loc></sitemap> <sitemap><loc>%s/simple/sitemap-simple.xml</loc></sitemap>
@ -39,21 +37,20 @@ class HTTPSitemapTests(SitemapTestsBase):
""" % self.base_url """ % self.base_url
self.assertXMLEqual(response.content.decode('utf-8'), expected_content) self.assertXMLEqual(response.content.decode('utf-8'), expected_content)
@ignore_warnings(category=RemovedInDjango20Warning)
@override_settings(TEMPLATES=[{ @override_settings(TEMPLATES=[{
'BACKEND': 'django.template.backends.django.DjangoTemplates', 'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(os.path.dirname(upath(__file__)), 'templates')], 'DIRS': [os.path.join(os.path.dirname(upath(__file__)), 'templates')],
}]) }])
def test_simple_sitemap_custom_index(self): def test_simple_sitemap_custom_index(self):
"A simple sitemap index can be rendered with a custom template" "A simple sitemap index can be rendered with a custom template"
with warnings.catch_warnings(): # The URL for views.sitemap in tests/urls/http.py has been updated
warnings.filterwarnings("ignore", category=RemovedInDjango20Warning) # with a name but since reversing by Python path is tried first
# The URL for views.sitemap in tests/urls/http.py has been updated # before reversing by name and works since we're giving
# with a name but since reversing by Python path is tried first # name='django.contrib.sitemaps.views.sitemap', we need to silence
# before reversing by name and works since we're giving # the erroneous warning until reversing by dotted path is removed.
# name='django.contrib.sitemaps.views.sitemap', we need to silence # The test will work without modification when it's removed.
# the erroneous warning until reversing by dotted path is removed. response = self.client.get('/simple/custom-index.xml')
# 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"?> expected_content = """<?xml version="1.0" encoding="UTF-8"?>
<!-- This is a customised template --> <!-- This is a customised template -->
<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> <sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
@ -196,16 +193,15 @@ class HTTPSitemapTests(SitemapTestsBase):
""" % self.base_url """ % self.base_url
self.assertXMLEqual(response.content.decode('utf-8'), expected_content) self.assertXMLEqual(response.content.decode('utf-8'), expected_content)
@ignore_warnings(category=RemovedInDjango20Warning)
def test_x_robots_sitemap(self): def test_x_robots_sitemap(self):
with warnings.catch_warnings(): # The URL for views.sitemap in tests/urls/http.py has been updated
warnings.filterwarnings("ignore", category=RemovedInDjango20Warning) # with a name but since reversing by Python path is tried first
# The URL for views.sitemap in tests/urls/http.py has been updated # before reversing by name and works since we're giving
# with a name but since reversing by Python path is tried first # name='django.contrib.sitemaps.views.sitemap', we need to silence
# before reversing by name and works since we're giving # the erroneous warning until reversing by dotted path is removed.
# name='django.contrib.sitemaps.views.sitemap', we need to silence # The test will work without modification when it's removed.
# the erroneous warning until reversing by dotted path is removed. response = self.client.get('/simple/index.xml')
# 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') self.assertEqual(response['X-Robots-Tag'], 'noindex, noodp, noarchive')
response = self.client.get('/simple/sitemap.xml') response = self.client.get('/simple/sitemap.xml')

View File

@ -1,9 +1,8 @@
from __future__ import unicode_literals from __future__ import unicode_literals
from datetime import date 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 django.utils.deprecation import RemovedInDjango20Warning
from .base import SitemapTestsBase from .base import SitemapTestsBase
@ -13,17 +12,16 @@ from .base import SitemapTestsBase
class HTTPSSitemapTests(SitemapTestsBase): class HTTPSSitemapTests(SitemapTestsBase):
protocol = 'https' protocol = 'https'
@ignore_warnings(category=RemovedInDjango20Warning)
def test_secure_sitemap_index(self): def test_secure_sitemap_index(self):
"A secure sitemap index can be rendered" "A secure sitemap index can be rendered"
with warnings.catch_warnings(): # The URL for views.sitemap in tests/urls/https.py has been updated
warnings.filterwarnings("ignore", category=RemovedInDjango20Warning) # with a name but since reversing by Python path is tried first
# The URL for views.sitemap in tests/urls/https.py has been updated # before reversing by name and works since we're giving
# with a name but since reversing by Python path is tried first # name='django.contrib.sitemaps.views.sitemap', we need to silence
# before reversing by name and works since we're giving # the erroneous warning until reversing by dotted path is removed.
# name='django.contrib.sitemaps.views.sitemap', we need to silence # The test will work without modification when it's removed.
# the erroneous warning until reversing by dotted path is removed. response = self.client.get('/secure/index.xml')
# 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"?> expected_content = """<?xml version="1.0" encoding="UTF-8"?>
<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> <sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<sitemap><loc>%s/secure/sitemap-simple.xml</loc></sitemap> <sitemap><loc>%s/secure/sitemap-simple.xml</loc></sitemap>
@ -46,17 +44,16 @@ class HTTPSSitemapTests(SitemapTestsBase):
class HTTPSDetectionSitemapTests(SitemapTestsBase): class HTTPSDetectionSitemapTests(SitemapTestsBase):
extra = {'wsgi.url_scheme': 'https'} extra = {'wsgi.url_scheme': 'https'}
@ignore_warnings(category=RemovedInDjango20Warning)
def test_sitemap_index_with_https_request(self): def test_sitemap_index_with_https_request(self):
"A sitemap index requested in HTTPS is rendered with HTTPS links" "A sitemap index requested in HTTPS is rendered with HTTPS links"
with warnings.catch_warnings(): # The URL for views.sitemap in tests/urls/https.py has been updated
warnings.filterwarnings("ignore", category=RemovedInDjango20Warning) # with a name but since reversing by Python path is tried first
# The URL for views.sitemap in tests/urls/https.py has been updated # before reversing by name and works since we're giving
# with a name but since reversing by Python path is tried first # name='django.contrib.sitemaps.views.sitemap', we need to silence
# before reversing by name and works since we're giving # the erroneous warning until reversing by dotted path is removed.
# name='django.contrib.sitemaps.views.sitemap', we need to silence # The test will work without modification when it's removed.
# the erroneous warning until reversing by dotted path is removed. response = self.client.get('/simple/index.xml', **self.extra)
# 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"?> expected_content = """<?xml version="1.0" encoding="UTF-8"?>
<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> <sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<sitemap><loc>%s/simple/sitemap-simple.xml</loc></sitemap> <sitemap><loc>%s/simple/sitemap-simple.xml</loc></sitemap>

View File

@ -1,14 +1,11 @@
from __future__ import unicode_literals from __future__ import unicode_literals
import warnings
from django import forms from django import forms
from django.contrib import admin from django.contrib import admin
from django.contrib.contenttypes.admin import GenericStackedInline from django.contrib.contenttypes.admin import GenericStackedInline
from django.core import checks from django.core import checks
from django.core.exceptions import ImproperlyConfigured from django.core.exceptions import ImproperlyConfigured
from django.test import TestCase from django.test import TestCase, ignore_warnings, override_settings
from django.test.utils import override_settings
from .models import Song, Book, Album, TwoAlbumFKAndAnE, City, State, Influence from .models import Song, Book, Album, TwoAlbumFKAndAnE, City, State, Influence
@ -589,6 +586,7 @@ class SystemChecksTestCase(TestCase):
errors = FieldsOnFormOnlyAdmin.check(model=Song) errors = FieldsOnFormOnlyAdmin.check(model=Song)
self.assertEqual(errors, []) self.assertEqual(errors, [])
@ignore_warnings(module='django.contrib.admin.options')
def test_validator_compatibility(self): def test_validator_compatibility(self):
class MyValidator(object): class MyValidator(object):
def validate(self, cls, model): def validate(self, cls, model):
@ -597,18 +595,16 @@ class SystemChecksTestCase(TestCase):
class MyModelAdmin(admin.ModelAdmin): class MyModelAdmin(admin.ModelAdmin):
validator_class = MyValidator validator_class = MyValidator
with warnings.catch_warnings(record=True): errors = MyModelAdmin.check(model=Song)
warnings.filterwarnings('ignore', module='django.contrib.admin.options')
errors = MyModelAdmin.check(model=Song)
expected = [ expected = [
checks.Error( checks.Error(
'error!', 'error!',
hint=None, hint=None,
obj=MyModelAdmin, obj=MyModelAdmin,
) )
] ]
self.assertEqual(errors, expected) self.assertEqual(errors, expected)
def test_check_sublists_for_duplicates(self): def test_check_sublists_for_duplicates(self):
class MyModelAdmin(admin.ModelAdmin): class MyModelAdmin(admin.ModelAdmin):

View File

@ -15,17 +15,17 @@ import socket
import subprocess import subprocess
import sys import sys
import unittest import unittest
import warnings
import django import django
from django import conf, get_version from django import conf, get_version
from django.conf import settings from django.conf import settings
from django.core.exceptions import ImproperlyConfigured from django.core.exceptions import ImproperlyConfigured
from django.core.management import BaseCommand, CommandError, call_command, color 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.encoding import force_text
from django.utils._os import npath, upath from django.utils._os import npath, upath
from django.utils.six import StringIO 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 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=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)]") 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): def test_requires_model_validation_and_requires_system_checks_both_defined(self):
with warnings.catch_warnings(record=True): from .management.commands.validation_command import InvalidCommand
warnings.filterwarnings('ignore', module='django.core.management.base') self.assertRaises(ImproperlyConfigured, InvalidCommand)
from .management.commands.validation_command import InvalidCommand
self.assertRaises(ImproperlyConfigured, InvalidCommand)
class Discovery(TestCase): class Discovery(TestCase):

View File

@ -1,12 +1,11 @@
from __future__ import unicode_literals from __future__ import unicode_literals
import warnings
from django import forms from django import forms
from django.contrib import admin from django.contrib import admin
from django.core.exceptions import ImproperlyConfigured 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.test.utils import str_prefix
from django.utils.deprecation import RemovedInDjango19Warning
from .models import Song, Book, Album, TwoAlbumFKAndAnE, City from .models import Song, Book, Album, TwoAlbumFKAndAnE, City
@ -33,6 +32,7 @@ class ValidFormFieldsets(admin.ModelAdmin):
) )
@ignore_warnings(category=RemovedInDjango19Warning)
class ValidationTestCase(TestCase): class ValidationTestCase(TestCase):
def test_readonly_and_editable(self): def test_readonly_and_editable(self):
@ -44,17 +44,13 @@ class ValidationTestCase(TestCase):
}), }),
] ]
with warnings.catch_warnings(record=True): SongAdmin.validate(Song)
warnings.filterwarnings('ignore', module='django.contrib.admin.options')
SongAdmin.validate(Song)
def test_custom_modelforms_with_fields_fieldsets(self): def test_custom_modelforms_with_fields_fieldsets(self):
""" """
# Regression test for #8027: custom ModelForms with fields/fieldsets # Regression test for #8027: custom ModelForms with fields/fieldsets
""" """
with warnings.catch_warnings(record=True): ValidFields.validate(Song)
warnings.filterwarnings('ignore', module='django.contrib.admin.options')
ValidFields.validate(Song)
def test_custom_get_form_with_fieldsets(self): def test_custom_get_form_with_fieldsets(self):
""" """
@ -62,9 +58,7 @@ class ValidationTestCase(TestCase):
is overridden. is overridden.
Refs #19445. Refs #19445.
""" """
with warnings.catch_warnings(record=True): ValidFormFieldsets.validate(Song)
warnings.filterwarnings('ignore', module='django.contrib.admin.options')
ValidFormFieldsets.validate(Song)
def test_exclude_values(self): def test_exclude_values(self):
""" """
@ -73,23 +67,19 @@ class ValidationTestCase(TestCase):
class ExcludedFields1(admin.ModelAdmin): class ExcludedFields1(admin.ModelAdmin):
exclude = ('foo') exclude = ('foo')
with warnings.catch_warnings(record=True): self.assertRaisesMessage(ImproperlyConfigured,
warnings.filterwarnings('ignore', module='django.contrib.admin.options') "'ExcludedFields1.exclude' must be a list or tuple.",
self.assertRaisesMessage(ImproperlyConfigured, ExcludedFields1.validate,
"'ExcludedFields1.exclude' must be a list or tuple.", Book)
ExcludedFields1.validate,
Book)
def test_exclude_duplicate_values(self): def test_exclude_duplicate_values(self):
class ExcludedFields2(admin.ModelAdmin): class ExcludedFields2(admin.ModelAdmin):
exclude = ('name', 'name') exclude = ('name', 'name')
with warnings.catch_warnings(record=True): self.assertRaisesMessage(ImproperlyConfigured,
warnings.filterwarnings('ignore', module='django.contrib.admin.options') "There are duplicate field(s) in ExcludedFields2.exclude",
self.assertRaisesMessage(ImproperlyConfigured, ExcludedFields2.validate,
"There are duplicate field(s) in ExcludedFields2.exclude", Book)
ExcludedFields2.validate,
Book)
def test_exclude_in_inline(self): def test_exclude_in_inline(self):
class ExcludedFieldsInline(admin.TabularInline): class ExcludedFieldsInline(admin.TabularInline):
@ -100,12 +90,10 @@ class ValidationTestCase(TestCase):
model = Album model = Album
inlines = [ExcludedFieldsInline] inlines = [ExcludedFieldsInline]
with warnings.catch_warnings(record=True): self.assertRaisesMessage(ImproperlyConfigured,
warnings.filterwarnings('ignore', module='django.contrib.admin.options') "'ExcludedFieldsInline.exclude' must be a list or tuple.",
self.assertRaisesMessage(ImproperlyConfigured, ExcludedFieldsAlbumAdmin.validate,
"'ExcludedFieldsInline.exclude' must be a list or tuple.", Album)
ExcludedFieldsAlbumAdmin.validate,
Album)
def test_exclude_inline_model_admin(self): def test_exclude_inline_model_admin(self):
""" """
@ -120,12 +108,10 @@ class ValidationTestCase(TestCase):
model = Album model = Album
inlines = [SongInline] inlines = [SongInline]
with warnings.catch_warnings(record=True): self.assertRaisesMessage(ImproperlyConfigured,
warnings.filterwarnings('ignore', module='django.contrib.admin.options') "SongInline cannot exclude the field 'album' - this is the foreign key to the parent model admin_validation.Album.",
self.assertRaisesMessage(ImproperlyConfigured, AlbumAdmin.validate,
"SongInline cannot exclude the field 'album' - this is the foreign key to the parent model admin_validation.Album.", Album)
AlbumAdmin.validate,
Album)
def test_app_label_in_admin_validation(self): def test_app_label_in_admin_validation(self):
""" """
@ -134,12 +120,10 @@ class ValidationTestCase(TestCase):
class RawIdNonexistingAdmin(admin.ModelAdmin): class RawIdNonexistingAdmin(admin.ModelAdmin):
raw_id_fields = ('nonexisting',) raw_id_fields = ('nonexisting',)
with warnings.catch_warnings(record=True): self.assertRaisesMessage(ImproperlyConfigured,
warnings.filterwarnings('ignore', module='django.contrib.admin.options') "'RawIdNonexistingAdmin.raw_id_fields' refers to field 'nonexisting' that is missing from model 'admin_validation.Album'.",
self.assertRaisesMessage(ImproperlyConfigured, RawIdNonexistingAdmin.validate,
"'RawIdNonexistingAdmin.raw_id_fields' refers to field 'nonexisting' that is missing from model 'admin_validation.Album'.", Album)
RawIdNonexistingAdmin.validate,
Album)
def test_fk_exclusion(self): def test_fk_exclusion(self):
""" """
@ -155,9 +139,7 @@ class ValidationTestCase(TestCase):
class MyAdmin(admin.ModelAdmin): class MyAdmin(admin.ModelAdmin):
inlines = [TwoAlbumFKAndAnEInline] inlines = [TwoAlbumFKAndAnEInline]
with warnings.catch_warnings(record=True): MyAdmin.validate(Album)
warnings.filterwarnings('ignore', module='django.contrib.admin.options')
MyAdmin.validate(Album)
def test_inline_self_validation(self): def test_inline_self_validation(self):
class TwoAlbumFKAndAnEInline(admin.TabularInline): class TwoAlbumFKAndAnEInline(admin.TabularInline):
@ -166,11 +148,9 @@ class ValidationTestCase(TestCase):
class MyAdmin(admin.ModelAdmin): class MyAdmin(admin.ModelAdmin):
inlines = [TwoAlbumFKAndAnEInline] inlines = [TwoAlbumFKAndAnEInline]
with warnings.catch_warnings(record=True): self.assertRaisesMessage(ValueError,
warnings.filterwarnings('ignore', module='django.contrib.admin.options') "'admin_validation.TwoAlbumFKAndAnE' has more than one ForeignKey to 'admin_validation.Album'.",
self.assertRaisesMessage(ValueError, MyAdmin.validate, Album)
"'admin_validation.TwoAlbumFKAndAnE' has more than one ForeignKey to 'admin_validation.Album'.",
MyAdmin.validate, Album)
def test_inline_with_specified(self): def test_inline_with_specified(self):
class TwoAlbumFKAndAnEInline(admin.TabularInline): class TwoAlbumFKAndAnEInline(admin.TabularInline):
@ -180,17 +160,13 @@ class ValidationTestCase(TestCase):
class MyAdmin(admin.ModelAdmin): class MyAdmin(admin.ModelAdmin):
inlines = [TwoAlbumFKAndAnEInline] inlines = [TwoAlbumFKAndAnEInline]
with warnings.catch_warnings(record=True): MyAdmin.validate(Album)
warnings.filterwarnings('ignore', module='django.contrib.admin.options')
MyAdmin.validate(Album)
def test_readonly(self): def test_readonly(self):
class SongAdmin(admin.ModelAdmin): class SongAdmin(admin.ModelAdmin):
readonly_fields = ("title",) readonly_fields = ("title",)
with warnings.catch_warnings(record=True): SongAdmin.validate(Song)
warnings.filterwarnings('ignore', module='django.contrib.admin.options')
SongAdmin.validate(Song)
def test_readonly_on_method(self): def test_readonly_on_method(self):
def my_function(obj): def my_function(obj):
@ -199,9 +175,7 @@ class ValidationTestCase(TestCase):
class SongAdmin(admin.ModelAdmin): class SongAdmin(admin.ModelAdmin):
readonly_fields = (my_function,) readonly_fields = (my_function,)
with warnings.catch_warnings(record=True): SongAdmin.validate(Song)
warnings.filterwarnings('ignore', module='django.contrib.admin.options')
SongAdmin.validate(Song)
def test_readonly_on_modeladmin(self): def test_readonly_on_modeladmin(self):
class SongAdmin(admin.ModelAdmin): class SongAdmin(admin.ModelAdmin):
@ -210,42 +184,34 @@ class ValidationTestCase(TestCase):
def readonly_method_on_modeladmin(self, obj): def readonly_method_on_modeladmin(self, obj):
pass pass
with warnings.catch_warnings(record=True): SongAdmin.validate(Song)
warnings.filterwarnings('ignore', module='django.contrib.admin.options')
SongAdmin.validate(Song)
def test_readonly_method_on_model(self): def test_readonly_method_on_model(self):
class SongAdmin(admin.ModelAdmin): class SongAdmin(admin.ModelAdmin):
readonly_fields = ("readonly_method_on_model",) readonly_fields = ("readonly_method_on_model",)
with warnings.catch_warnings(record=True): SongAdmin.validate(Song)
warnings.filterwarnings('ignore', module='django.contrib.admin.options')
SongAdmin.validate(Song)
def test_nonexistent_field(self): def test_nonexistent_field(self):
class SongAdmin(admin.ModelAdmin): class SongAdmin(admin.ModelAdmin):
readonly_fields = ("title", "nonexistent") readonly_fields = ("title", "nonexistent")
with warnings.catch_warnings(record=True): self.assertRaisesMessage(ImproperlyConfigured,
warnings.filterwarnings('ignore', module='django.contrib.admin.options') str_prefix("SongAdmin.readonly_fields[1], %(_)s'nonexistent' is not a callable "
self.assertRaisesMessage(ImproperlyConfigured, "or an attribute of 'SongAdmin' or found in the model 'Song'."),
str_prefix("SongAdmin.readonly_fields[1], %(_)s'nonexistent' is not a callable " SongAdmin.validate,
"or an attribute of 'SongAdmin' or found in the model 'Song'."), Song)
SongAdmin.validate,
Song)
def test_nonexistent_field_on_inline(self): def test_nonexistent_field_on_inline(self):
class CityInline(admin.TabularInline): class CityInline(admin.TabularInline):
model = City model = City
readonly_fields = ['i_dont_exist'] # Missing attribute readonly_fields = ['i_dont_exist'] # Missing attribute
with warnings.catch_warnings(record=True): self.assertRaisesMessage(ImproperlyConfigured,
warnings.filterwarnings('ignore', module='django.contrib.admin.options') str_prefix("CityInline.readonly_fields[0], %(_)s'i_dont_exist' is not a callable "
self.assertRaisesMessage(ImproperlyConfigured, "or an attribute of 'CityInline' or found in the model 'City'."),
str_prefix("CityInline.readonly_fields[0], %(_)s'i_dont_exist' is not a callable " CityInline.validate,
"or an attribute of 'CityInline' or found in the model 'City'."), City)
CityInline.validate,
City)
def test_extra(self): def test_extra(self):
class SongAdmin(admin.ModelAdmin): class SongAdmin(admin.ModelAdmin):
@ -254,17 +220,13 @@ class ValidationTestCase(TestCase):
return "Best Ever!" return "Best Ever!"
return "Status unknown." return "Status unknown."
with warnings.catch_warnings(record=True): SongAdmin.validate(Song)
warnings.filterwarnings('ignore', module='django.contrib.admin.options')
SongAdmin.validate(Song)
def test_readonly_lambda(self): def test_readonly_lambda(self):
class SongAdmin(admin.ModelAdmin): class SongAdmin(admin.ModelAdmin):
readonly_fields = (lambda obj: "test",) readonly_fields = (lambda obj: "test",)
with warnings.catch_warnings(record=True): SongAdmin.validate(Song)
warnings.filterwarnings('ignore', module='django.contrib.admin.options')
SongAdmin.validate(Song)
def test_graceful_m2m_fail(self): def test_graceful_m2m_fail(self):
""" """
@ -276,12 +238,10 @@ class ValidationTestCase(TestCase):
class BookAdmin(admin.ModelAdmin): class BookAdmin(admin.ModelAdmin):
fields = ['authors'] fields = ['authors']
with warnings.catch_warnings(record=True): self.assertRaisesMessage(ImproperlyConfigured,
warnings.filterwarnings('ignore', module='django.contrib.admin.options') "'BookAdmin.fields' can't include the ManyToManyField field 'authors' because 'authors' manually specifies a 'through' model.",
self.assertRaisesMessage(ImproperlyConfigured, BookAdmin.validate,
"'BookAdmin.fields' can't include the ManyToManyField field 'authors' because 'authors' manually specifies a 'through' model.", Book)
BookAdmin.validate,
Book)
def test_cannot_include_through(self): def test_cannot_include_through(self):
class FieldsetBookAdmin(admin.ModelAdmin): class FieldsetBookAdmin(admin.ModelAdmin):
@ -290,20 +250,16 @@ class ValidationTestCase(TestCase):
('Header 2', {'fields': ('authors',)}), ('Header 2', {'fields': ('authors',)}),
) )
with warnings.catch_warnings(record=True): self.assertRaisesMessage(ImproperlyConfigured,
warnings.filterwarnings('ignore', module='django.contrib.admin.options') "'FieldsetBookAdmin.fieldsets[1][1]['fields']' can't include the ManyToManyField field 'authors' because 'authors' manually specifies a 'through' model.",
self.assertRaisesMessage(ImproperlyConfigured, FieldsetBookAdmin.validate,
"'FieldsetBookAdmin.fieldsets[1][1]['fields']' can't include the ManyToManyField field 'authors' because 'authors' manually specifies a 'through' model.", Book)
FieldsetBookAdmin.validate,
Book)
def test_nested_fields(self): def test_nested_fields(self):
class NestedFieldsAdmin(admin.ModelAdmin): class NestedFieldsAdmin(admin.ModelAdmin):
fields = ('price', ('name', 'subtitle')) fields = ('price', ('name', 'subtitle'))
with warnings.catch_warnings(record=True): NestedFieldsAdmin.validate(Book)
warnings.filterwarnings('ignore', module='django.contrib.admin.options')
NestedFieldsAdmin.validate(Book)
def test_nested_fieldsets(self): def test_nested_fieldsets(self):
class NestedFieldsetAdmin(admin.ModelAdmin): class NestedFieldsetAdmin(admin.ModelAdmin):
@ -311,9 +267,7 @@ class ValidationTestCase(TestCase):
('Main', {'fields': ('price', ('name', 'subtitle'))}), ('Main', {'fields': ('price', ('name', 'subtitle'))}),
) )
with warnings.catch_warnings(record=True): NestedFieldsetAdmin.validate(Book)
warnings.filterwarnings('ignore', module='django.contrib.admin.options')
NestedFieldsetAdmin.validate(Book)
def test_explicit_through_override(self): 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) # If the through model is still a string (and hasn't been resolved to a model)
# the validation will fail. # the validation will fail.
with warnings.catch_warnings(record=True): BookAdmin.validate(Book)
warnings.filterwarnings('ignore', module='django.contrib.admin.options')
BookAdmin.validate(Book)
def test_non_model_fields(self): def test_non_model_fields(self):
""" """
@ -346,9 +298,7 @@ class ValidationTestCase(TestCase):
form = SongForm form = SongForm
fields = ['title', 'extra_data'] fields = ['title', 'extra_data']
with warnings.catch_warnings(record=True): FieldsOnFormOnlyAdmin.validate(Song)
warnings.filterwarnings('ignore', module='django.contrib.admin.options')
FieldsOnFormOnlyAdmin.validate(Song)
def test_non_model_first_field(self): def test_non_model_first_field(self):
""" """
@ -366,6 +316,4 @@ class ValidationTestCase(TestCase):
form = SongForm form = SongForm
fields = ['extra_data', 'title'] fields = ['extra_data', 'title']
with warnings.catch_warnings(record=True): FieldsOnFormOnlyAdmin.validate(Song)
warnings.filterwarnings('ignore', module='django.contrib.admin.options')
FieldsOnFormOnlyAdmin.validate(Song)

View File

@ -3,7 +3,6 @@ from __future__ import unicode_literals
import datetime import datetime
from decimal import Decimal from decimal import Decimal
import re import re
import warnings
from django.core.exceptions import FieldError from django.core.exceptions import FieldError
from django.db import connection from django.db import connection
@ -11,10 +10,7 @@ from django.db.models import (
Avg, Sum, Count, Max, Min, Avg, Sum, Count, Max, Min,
Aggregate, F, Value, Func, Aggregate, F, Value, Func,
IntegerField, FloatField, DecimalField) IntegerField, FloatField, DecimalField)
with warnings.catch_warnings(record=True) as w: from django.test import TestCase, ignore_warnings
warnings.simplefilter("always")
from django.db.models.sql import aggregates as sql_aggregates
from django.test import TestCase
from django.test.utils import Approximate from django.test.utils import Approximate
from django.test.utils import CaptureQueriesContext from django.test.utils import CaptureQueriesContext
from django.utils import six, timezone from django.utils import six, timezone
@ -950,7 +946,9 @@ class ComplexAggregateTestCase(TestCase):
self.assertQuerysetEqual( self.assertQuerysetEqual(
qs2, [1, 2], lambda v: v.pk) qs2, [1, 2], lambda v: v.pk)
@ignore_warnings(category=RemovedInDjango20Warning)
def test_backwards_compatibility(self): def test_backwards_compatibility(self):
from django.db.models.sql import aggregates as sql_aggregates
class SqlNewSum(sql_aggregates.Aggregate): class SqlNewSum(sql_aggregates.Aggregate):
sql_function = 'SUM' sql_function = 'SUM'
@ -964,8 +962,6 @@ class ComplexAggregateTestCase(TestCase):
col, source=source, is_summary=is_summary, **self.extra) col, source=source, is_summary=is_summary, **self.extra)
query.annotations[alias] = aggregate query.annotations[alias] = aggregate
with warnings.catch_warnings(): qs = Author.objects.values('name').annotate(another_age=NewSum('age') + F('age'))
warnings.simplefilter("ignore", RemovedInDjango20Warning) a = qs.get(pk=1)
qs = Author.objects.values('name').annotate(another_age=NewSum('age') + F('age')) self.assertEqual(a['another_age'], 68)
a = qs.get(pk=1)
self.assertEqual(a['another_age'], 68)

View File

@ -24,8 +24,9 @@ from django.db.models.sql.constants import CURSOR
from django.db.utils import ConnectionHandler from django.db.utils import ConnectionHandler
from django.test import (TestCase, TransactionTestCase, mock, override_settings, from django.test import (TestCase, TransactionTestCase, mock, override_settings,
skipUnlessDBFeature, skipIfDBFeature) 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 import six
from django.utils.deprecation import RemovedInDjango19Warning
from django.utils.six.moves import range from django.utils.six.moves import range
from . import models from . import models
@ -1080,18 +1081,13 @@ class BackendUtilTests(TestCase):
'1234600000') '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 " mismatch_msg = ("Connection 'test-deprecation' has mismatched TEST "
"and TEST_* database settings.") "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): def setUp(self):
super(DBTestSettingsRenamedTests, self).setUp() super(DBTestSettingsRenamedTests, self).setUp()
self.handler = ConnectionHandler() self.handler = ConnectionHandler()
@ -1188,6 +1184,7 @@ class DBTestSettingsRenamedTests(IgnoreAllDeprecationWarningsMixin, TestCase):
with override_settings(DATABASES=self.db_settings): with override_settings(DATABASES=self.db_settings):
self.handler.prepare_test_settings('test-deprecation') self.handler.prepare_test_settings('test-deprecation')
@ignore_warnings(category=RemovedInDjango19Warning)
def test_old_settings_only(self): def test_old_settings_only(self):
# should be able to define old settings without the new # should be able to define old settings without the new
self.db_settings.update({ self.db_settings.update({

View File

@ -29,14 +29,15 @@ from django.middleware.csrf import CsrfViewMiddleware
from django.template import Template from django.template import Template
from django.template.context_processors import csrf from django.template.context_processors import csrf
from django.template.response import TemplateResponse 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.signals import setting_changed
from django.test.utils import IgnoreDeprecationWarningsMixin
from django.utils import six from django.utils import six
from django.utils import timezone from django.utils import timezone
from django.utils import translation from django.utils import translation
from django.utils.cache import (patch_vary_headers, get_cache_key, from django.utils.cache import (patch_vary_headers, get_cache_key,
learn_cache_key, patch_cache_control, patch_response_headers) learn_cache_key, patch_cache_control, patch_response_headers)
from django.utils.deprecation import RemovedInDjango19Warning
from django.utils.encoding import force_text from django.utils.encoding import force_text
from django.views.decorators.cache import cache_page 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): def test_simple(self):
self.assertIsInstance( self.assertIsInstance(
caches[DEFAULT_CACHE_ALIAS], caches[DEFAULT_CACHE_ALIAS],
@ -1241,6 +1243,7 @@ class GetCacheTests(IgnoreDeprecationWarningsMixin, TestCase):
signals.request_finished.send(self.__class__) signals.request_finished.send(self.__class__)
self.assertTrue(cache.closed) self.assertTrue(cache.closed)
@ignore_warnings(category=RemovedInDjango19Warning)
def test_close_deprecated(self): def test_close_deprecated(self):
cache = get_cache('cache.closeable_cache.CacheClass') cache = get_cache('cache.closeable_cache.CacheClass')
self.assertFalse(cache.closed) self.assertFalse(cache.closed)

View File

@ -2,14 +2,13 @@ from __future__ import unicode_literals
import re import re
import unittest import unittest
import warnings
from django.apps import apps from django.apps import apps
from django.core.management.color import no_style from django.core.management.color import no_style
from django.core.management.sql import (sql_create, sql_delete, sql_indexes, from django.core.management.sql import (sql_create, sql_delete, sql_indexes,
sql_destroy_indexes, sql_all) sql_destroy_indexes, sql_all)
from django.db import connections, DEFAULT_DB_ALIAS 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 import six
from django.utils.deprecation import RemovedInDjango20Warning from django.utils.deprecation import RemovedInDjango20Warning
@ -67,11 +66,10 @@ class SQLCommandsTestCase(TestCase):
sql = drop_tables[-1].lower() sql = drop_tables[-1].lower()
six.assertRegex(self, sql, r'^drop table .commands_sql_comment.*') six.assertRegex(self, sql, r'^drop table .commands_sql_comment.*')
@ignore_warnings(category=RemovedInDjango20Warning)
def test_sql_indexes(self): def test_sql_indexes(self):
app_config = apps.get_app_config('commands_sql') app_config = apps.get_app_config('commands_sql')
with warnings.catch_warnings(): output = sql_indexes(app_config, no_style(), connections[DEFAULT_DB_ALIAS])
warnings.simplefilter("ignore", category=RemovedInDjango20Warning)
output = sql_indexes(app_config, no_style(), connections[DEFAULT_DB_ALIAS])
# Number of indexes is backend-dependent # Number of indexes is backend-dependent
self.assertTrue(1 <= self.count_ddl(output, 'CREATE INDEX') <= 4) self.assertTrue(1 <= self.count_ddl(output, 'CREATE INDEX') <= 4)
@ -81,11 +79,10 @@ class SQLCommandsTestCase(TestCase):
# Number of indexes is backend-dependent # Number of indexes is backend-dependent
self.assertTrue(1 <= self.count_ddl(output, 'DROP INDEX') <= 4) self.assertTrue(1 <= self.count_ddl(output, 'DROP INDEX') <= 4)
@ignore_warnings(category=RemovedInDjango20Warning)
def test_sql_all(self): def test_sql_all(self):
app_config = apps.get_app_config('commands_sql') app_config = apps.get_app_config('commands_sql')
with warnings.catch_warnings(): output = sql_all(app_config, no_style(), connections[DEFAULT_DB_ALIAS])
warnings.simplefilter("ignore", category=RemovedInDjango20Warning)
output = sql_all(app_config, no_style(), connections[DEFAULT_DB_ALIAS])
self.assertEqual(self.count_ddl(output, 'CREATE TABLE'), 3) self.assertEqual(self.count_ddl(output, 'CREATE TABLE'), 3)
# Number of indexes is backend-dependent # Number of indexes is backend-dependent

View File

@ -182,6 +182,7 @@ class DeprecatingRequestMergeDictTest(SimpleTestCase):
Ensure the correct warning is raised when WSGIRequest.REQUEST is Ensure the correct warning is raised when WSGIRequest.REQUEST is
accessed. accessed.
""" """
reset_warning_registry()
with warnings.catch_warnings(record=True) as recorded: with warnings.catch_warnings(record=True) as recorded:
warnings.simplefilter('always') warnings.simplefilter('always')
request = RequestFactory().get('/') request = RequestFactory().get('/')

View File

@ -1,7 +1,5 @@
from __future__ import unicode_literals from __future__ import unicode_literals
import warnings
from django.db import models from django.db import models
from django.test import TestCase, override_settings from django.test import TestCase, override_settings
from django.utils import six from django.utils import six
@ -238,9 +236,7 @@ class FieldDeconstructionTests(TestCase):
self.assertEqual(kwargs, {}) self.assertEqual(kwargs, {})
def test_ip_address_field(self): def test_ip_address_field(self):
with warnings.catch_warnings(record=True): field = models.IPAddressField()
warnings.simplefilter("always")
field = models.IPAddressField()
name, path, args, kwargs = field.deconstruct() name, path, args, kwargs = field.deconstruct()
self.assertEqual(path, "django.db.models.IPAddressField") self.assertEqual(path, "django.db.models.IPAddressField")
self.assertEqual(args, []) self.assertEqual(args, [])

View File

@ -6,7 +6,7 @@ import warnings
from django.contrib.sites.models import Site from django.contrib.sites.models import Site
from django.core import management from django.core import management
from django.db import connection, IntegrityError 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.encoding import force_text
from django.utils import six from django.utils import six
@ -335,14 +335,12 @@ class FixtureLoadingTests(DumpDataAssertMixin, TestCase):
management.call_command('loaddata', 'invalid.json', verbosity=0) management.call_command('loaddata', 'invalid.json', verbosity=0)
self.assertIn("Could not load fixtures.Article(pk=1):", cm.exception.args[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): def test_loaddata_app_option(self):
""" """
Verifies that the --app option works. Verifies that the --app option works.
""" """
with warnings.catch_warnings(): management.call_command('loaddata', 'db_fixture_1', verbosity=0, app_label="someotherapp")
# Ignore: No fixture named ...
warnings.filterwarnings("ignore", category=UserWarning)
management.call_command('loaddata', 'db_fixture_1', verbosity=0, app_label="someotherapp")
self.assertQuerysetEqual(Article.objects.all(), []) self.assertQuerysetEqual(Article.objects.all(), [])
management.call_command('loaddata', 'db_fixture_1', verbosity=0, app_label="fixtures") management.call_command('loaddata', 'db_fixture_1', verbosity=0, app_label="fixtures")
self.assertQuerysetEqual(Article.objects.all(), [ self.assertQuerysetEqual(Article.objects.all(), [
@ -358,12 +356,11 @@ class FixtureLoadingTests(DumpDataAssertMixin, TestCase):
'<Article: Who needs to use compressed data?>', '<Article: Who needs to use compressed data?>',
]) ])
@ignore_warnings(category=UserWarning, message="No fixture named")
def test_unmatched_identifier_loading(self): def test_unmatched_identifier_loading(self):
# Try to load db fixture 3. This won't load because the database identifier doesn't match # Try to load db fixture 3. This won't load because the database identifier doesn't match
with warnings.catch_warnings(): management.call_command('loaddata', 'db_fixture_3', verbosity=0)
warnings.filterwarnings("ignore", category=UserWarning) 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(), []) self.assertQuerysetEqual(Article.objects.all(), [])
def test_output_formats(self): def test_output_formats(self):

View File

@ -1,8 +1,6 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from __future__ import unicode_literals from __future__ import unicode_literals
import warnings
from django.core.files.uploadedfile import SimpleUploadedFile from django.core.files.uploadedfile import SimpleUploadedFile
from django.forms import ( from django.forms import (
BooleanField, CharField, ChoiceField, DateField, DateTimeField, BooleanField, CharField, ChoiceField, DateField, DateTimeField,
@ -203,9 +201,7 @@ class FormsErrorMessagesTestCase(TestCase, AssertFormErrorsMixin):
'required': 'REQUIRED', 'required': 'REQUIRED',
'invalid': 'INVALID IP ADDRESS', 'invalid': 'INVALID IP ADDRESS',
} }
with warnings.catch_warnings(record=True): f = IPAddressField(error_messages=e)
warnings.simplefilter("always")
f = IPAddressField(error_messages=e)
self.assertFormErrors(['REQUIRED'], f.clean, '') self.assertFormErrors(['REQUIRED'], f.clean, '')
self.assertFormErrors(['INVALID IP ADDRESS'], f.clean, '127.0.0') self.assertFormErrors(['INVALID IP ADDRESS'], f.clean, '127.0.0')

View File

@ -2,7 +2,6 @@
from __future__ import unicode_literals from __future__ import unicode_literals
import datetime import datetime
import warnings
from django.forms import ( from django.forms import (
CharField, DateField, EmailField, FileField, Form, GenericIPAddressField, 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') self.assertEqual(f.cleaned_data['field1'], 'some text,JP,2007-04-25 06:24:00')
def test_ipaddress(self): def test_ipaddress(self):
with warnings.catch_warnings(record=True): f = IPAddressField()
warnings.simplefilter("always")
f = IPAddressField()
self.assertFormErrors(['This field is required.'], f.clean, '') self.assertFormErrors(['This field is required.'], f.clean, '')
self.assertFormErrors(['This field is required.'], f.clean, None) self.assertFormErrors(['This field is required.'], f.clean, None)
self.assertEqual(f.clean(' 127.0.0.1'), '127.0.0.1') 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, '1.2.3.4.5')
self.assertFormErrors(['Enter a valid IPv4 address.'], f.clean, '256.125.1.5') self.assertFormErrors(['Enter a valid IPv4 address.'], f.clean, '256.125.1.5')
with warnings.catch_warnings(record=True): f = IPAddressField(required=False)
warnings.simplefilter("always")
f = IPAddressField(required=False)
self.assertEqual(f.clean(''), '') self.assertEqual(f.clean(''), '')
self.assertEqual(f.clean(None), '') self.assertEqual(f.clean(None), '')
self.assertEqual(f.clean(' 127.0.0.1'), '127.0.0.1') self.assertEqual(f.clean(' 127.0.0.1'), '127.0.0.1')

View File

@ -33,7 +33,6 @@ import os
import uuid import uuid
from decimal import Decimal from decimal import Decimal
from unittest import skipIf from unittest import skipIf
import warnings
try: try:
from PIL import Image from PIL import Image
@ -50,10 +49,11 @@ from django.forms import (
TimeField, TypedChoiceField, TypedMultipleChoiceField, URLField, UUIDField, TimeField, TypedChoiceField, TypedMultipleChoiceField, URLField, UUIDField,
ValidationError, Widget, ValidationError, Widget,
) )
from django.test import SimpleTestCase from django.test import SimpleTestCase, ignore_warnings
from django.utils import formats from django.utils import formats
from django.utils import six from django.utils import six
from django.utils import translation from django.utils import translation
from django.utils.deprecation import RemovedInDjango20Warning
from django.utils._os import upath from django.utils._os import upath
@ -491,15 +491,14 @@ class FieldsTests(SimpleTestCase):
f = DateField() f = DateField()
self.assertRaisesMessage(ValidationError, "'Enter a valid date.'", f.clean, 'a\x00b') self.assertRaisesMessage(ValidationError, "'Enter a valid date.'", f.clean, 'a\x00b')
@ignore_warnings(category=RemovedInDjango20Warning) # for _has_changed
def test_datefield_changed(self): def test_datefield_changed(self):
format = '%d/%m/%Y' format = '%d/%m/%Y'
f = DateField(input_formats=[format]) f = DateField(input_formats=[format])
d = datetime.date(2007, 9, 17) d = datetime.date(2007, 9, 17)
self.assertFalse(f.has_changed(d, '17/09/2007')) self.assertFalse(f.has_changed(d, '17/09/2007'))
# Test for deprecated behavior _has_changed # Test for deprecated behavior _has_changed
with warnings.catch_warnings(record=True): self.assertFalse(f._has_changed(d, '17/09/2007'))
warnings.simplefilter("always")
self.assertFalse(f._has_changed(d, '17/09/2007'))
def test_datefield_strptime(self): def test_datefield_strptime(self):
"""Test that field.strptime doesn't raise an UnicodeEncodeError (#16123)""" """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')
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): def test_regexfield_4(self):
# deprecated error_message argument; remove in Django 2.0 f = RegexField('^[0-9][0-9][0-9][0-9]$', error_message='Enter a four-digit number.')
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.')
self.assertEqual('1234', f.clean('1234')) 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, '123')
self.assertRaisesMessage(ValidationError, "'Enter a four-digit number.'", f.clean, 'abcd') self.assertRaisesMessage(ValidationError, "'Enter a four-digit number.'", f.clean, 'abcd')

View File

@ -4,7 +4,6 @@ from __future__ import unicode_literals
import copy import copy
import datetime import datetime
import json import json
import warnings
from django.core.exceptions import NON_FIELD_ERRORS from django.core.exceptions import NON_FIELD_ERRORS
from django.core.files.uploadedfile import SimpleUploadedFile from django.core.files.uploadedfile import SimpleUploadedFile
@ -19,9 +18,10 @@ from django.forms import (
from django.forms.utils import ErrorList from django.forms.utils import ErrorList
from django.http import QueryDict from django.http import QueryDict
from django.template import Template, Context 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.test.utils import str_prefix
from django.utils.datastructures import MultiValueDict, MergeDict from django.utils.datastructures import MultiValueDict, MergeDict
from django.utils.deprecation import RemovedInDjango19Warning
from django.utils.encoding import force_text from django.utils.encoding import force_text
from django.utils.html import format_html from django.utils.html import format_html
from django.utils.safestring import mark_safe, SafeData 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> <li><label for="composers_id_1"><input type="checkbox" name="composers" value="P" id="composers_id_1" /> Paul McCartney</label></li>
</ul>""") </ul>""")
@ignore_warnings(category=RemovedInDjango19Warning) # MergeDict deprecation
def test_multiple_choice_list_data(self): def test_multiple_choice_list_data(self):
# Data for a MultipleChoiceField should be a list. QueryDict, MultiValueDict and # Data for a MultipleChoiceField should be a list. QueryDict, MultiValueDict and
# MergeDict (when created as a merge of MultiValueDicts) conveniently work with # MergeDict (when created as a merge of MultiValueDicts) conveniently work with
@ -573,11 +574,9 @@ class FormsTestCase(TestCase):
self.assertEqual(f.errors, {}) self.assertEqual(f.errors, {})
# MergeDict is deprecated, but is supported until removed. # MergeDict is deprecated, but is supported until removed.
with warnings.catch_warnings(record=True): data = MergeDict(MultiValueDict(dict(name=['Yesterday'], composers=['J', 'P'])))
warnings.simplefilter("always") f = SongForm(data)
data = MergeDict(MultiValueDict(dict(name=['Yesterday'], composers=['J', 'P']))) self.assertEqual(f.errors, {})
f = SongForm(data)
self.assertEqual(f.errors, {})
def test_multiple_hidden(self): def test_multiple_hidden(self):
class SongForm(Form): class SongForm(Form):

View File

@ -1,14 +1,12 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from __future__ import unicode_literals from __future__ import unicode_literals
import warnings
from django.forms import ( from django.forms import (
CharField, ChoiceField, Form, HiddenInput, IntegerField, ModelForm, CharField, ChoiceField, Form, HiddenInput, IntegerField, ModelForm,
ModelMultipleChoiceField, MultipleChoiceField, RadioSelect, Select, ModelMultipleChoiceField, MultipleChoiceField, RadioSelect, Select,
TextInput, TextInput,
) )
from django.test import TestCase from django.test import TestCase, ignore_warnings
from django.utils import translation from django.utils import translation
from django.utils.translation import gettext_lazy, ugettext_lazy from django.utils.translation import gettext_lazy, ugettext_lazy
@ -61,17 +59,6 @@ class FormsRegressionsTestCase(TestCase):
f = SomeForm() 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>') 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. # Translated error messages used to be buggy.
with translation.override('ru'): with translation.override('ru'):
f = SomeForm({}) f = SomeForm({})
@ -83,6 +70,16 @@ class FormsRegressionsTestCase(TestCase):
f = CopyForm() 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): def test_misc(self):
# There once was a problem with Form fields called "data". Let's make sure that # There once was a problem with Form fields called "data". Let's make sure that
# doesn't come back. # doesn't come back.

View File

@ -3,7 +3,6 @@ from __future__ import unicode_literals
import copy import copy
import datetime import datetime
import warnings
from django.contrib.admin.tests import AdminSeleniumWebDriverTestCase from django.contrib.admin.tests import AdminSeleniumWebDriverTestCase
from django.core.files.uploadedfile import SimpleUploadedFile 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.safestring import mark_safe, SafeData
from django.utils import six from django.utils import six
from django.utils.translation import activate, deactivate, override 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 django.utils.encoding import python_2_unicode_compatible, force_text
from ..models import Article from ..models import Article
@ -1112,27 +1111,24 @@ class WidgetTests(TestCase):
# to make a copy of its sub-widgets when it is copied. # to make a copy of its sub-widgets when it is copied.
self.assertEqual(w1.choices, [1, 2, 3]) self.assertEqual(w1.choices, [1, 2, 3])
@ignore_warnings(category=RemovedInDjango19Warning)
def test_13390(self): def test_13390(self):
# See ticket #13390 # See ticket #13390
class SplitDateForm(Form): class SplitDateForm(Form):
field = DateTimeField(widget=SplitDateTimeWidget, required=False) field = DateTimeField(widget=SplitDateTimeWidget, required=False)
with warnings.catch_warnings(): form = SplitDateForm({'field': ''})
warnings.filterwarnings("ignore", category=RemovedInDjango19Warning) self.assertTrue(form.is_valid())
form = SplitDateForm({'field': ''}) form = SplitDateForm({'field': ['', '']})
self.assertTrue(form.is_valid()) self.assertTrue(form.is_valid())
form = SplitDateForm({'field': ['', '']})
self.assertTrue(form.is_valid())
class SplitDateRequiredForm(Form): class SplitDateRequiredForm(Form):
field = DateTimeField(widget=SplitDateTimeWidget, required=True) field = DateTimeField(widget=SplitDateTimeWidget, required=True)
with warnings.catch_warnings(): form = SplitDateRequiredForm({'field': ''})
warnings.filterwarnings("ignore", category=RemovedInDjango19Warning) self.assertFalse(form.is_valid())
form = SplitDateRequiredForm({'field': ''}) form = SplitDateRequiredForm({'field': ['', '']})
self.assertFalse(form.is_valid()) self.assertFalse(form.is_valid())
form = SplitDateRequiredForm({'field': ['', '']})
self.assertFalse(form.is_valid())
@override_settings(ROOT_URLCONF='forms_tests.urls') @override_settings(ROOT_URLCONF='forms_tests.urls')

View File

@ -8,8 +8,7 @@ from django.core.exceptions import ImproperlyConfigured
from django.http import HttpResponse from django.http import HttpResponse
from django.utils import six from django.utils import six
from django.utils.deprecation import RemovedInDjango19Warning from django.utils.deprecation import RemovedInDjango19Warning
from django.test import TestCase, RequestFactory, override_settings from django.test import TestCase, RequestFactory, ignore_warnings, override_settings
from django.test.utils import IgnoreDeprecationWarningsMixin
from django.views.generic import View, TemplateView, RedirectView from django.views.generic import View, TemplateView, RedirectView
from . import views from . import views
@ -331,8 +330,9 @@ class TemplateViewTest(TestCase):
self.assertEqual(response['Content-Type'], 'text/plain') self.assertEqual(response['Content-Type'], 'text/plain')
@ignore_warnings(category=RemovedInDjango19Warning)
@override_settings(ROOT_URLCONF='generic_views.urls') @override_settings(ROOT_URLCONF='generic_views.urls')
class RedirectViewTest(IgnoreDeprecationWarningsMixin, TestCase): class RedirectViewTest(TestCase):
rf = RequestFactory() rf = RequestFactory()

View File

@ -2,11 +2,10 @@ from __future__ import unicode_literals
from datetime import date from datetime import date
import traceback import traceback
import warnings
from django.db import IntegrityError, DatabaseError from django.db import IntegrityError, DatabaseError
from django.utils.encoding import DjangoUnicodeDecodeError 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, from .models import (DefaultPerson, Person, ManualPrimaryKeyTest, Profile,
Tag, Thing, Publisher, Author, Book) Tag, Thing, Publisher, Author, Book)
@ -155,18 +154,17 @@ class GetOrCreateTestsWithManualPKs(TestCase):
formatted_traceback = traceback.format_exc() formatted_traceback = traceback.format_exc()
self.assertIn(str('obj.save'), formatted_traceback) 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): def test_savepoint_rollback(self):
""" """
Regression test for #20463: the database connection should still be Regression test for #20463: the database connection should still be
usable after a DataError or ProgrammingError in .get_or_create(). usable after a DataError or ProgrammingError in .get_or_create().
""" """
try: try:
# Hide warnings when broken data is saved with a warning (MySQL). Person.objects.get_or_create(
with warnings.catch_warnings(): birthday=date(1970, 1, 1),
warnings.simplefilter('ignore') 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): except (DatabaseError, DjangoUnicodeDecodeError):
Person.objects.create( Person.objects.create(
first_name="Bob", last_name="Ross", birthday=date(1950, 1, 1)) first_name="Bob", last_name="Ross", birthday=date(1950, 1, 1))

View File

@ -1,18 +1,17 @@
from __future__ import unicode_literals from __future__ import unicode_literals
import warnings
from django.conf.urls.i18n import i18n_patterns from django.conf.urls.i18n import i18n_patterns
from django.http import HttpResponse, StreamingHttpResponse from django.http import HttpResponse, StreamingHttpResponse
from django.test import ignore_warnings
from django.utils.deprecation import RemovedInDjango20Warning from django.utils.deprecation import RemovedInDjango20Warning
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import ugettext_lazy as _
# test deprecated version of i18n_patterns() function (with prefix). Remove it # test deprecated version of i18n_patterns() function (with prefix). Remove it
# and convert to list of urls() in Django 2.0 # and convert to list of urls() in Django 2.0
with warnings.catch_warnings(): i18n_patterns = ignore_warnings(category=RemovedInDjango20Warning)(i18n_patterns)
warnings.filterwarnings('ignore', category=RemovedInDjango20Warning)
urlpatterns = i18n_patterns('', urlpatterns = i18n_patterns('',
(r'^simple/$', lambda r: HttpResponse()), (r'^simple/$', lambda r: HttpResponse()),
(r'^streaming/$', lambda r: StreamingHttpResponse([_("Yes"), "/", _("No")])), (r'^streaming/$', lambda r: StreamingHttpResponse([_("Yes"), "/", _("No")])),
) )

View File

@ -2,13 +2,14 @@ from unittest import skipUnless
from django.core.management.color import no_style from django.core.management.color import no_style
from django.db import connection from django.db import connection
from django.test import TestCase from django.test import TestCase, ignore_warnings
from django.test.utils import IgnorePendingDeprecationWarningsMixin from django.utils.deprecation import RemovedInDjango20Warning
from .models import Article, ArticleTranslation, IndexTogetherSingleList 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. Test index handling by the to-be-deprecated connection.creation interface.
""" """

View File

@ -1,8 +1,10 @@
# -*- encoding: utf-8 -*- # -*- encoding: utf-8 -*-
from __future__ import unicode_literals from __future__ import unicode_literals
import warnings import warnings
from django.db import models from django.db import models
from django.utils.deprecation import RemovedInDjango19Warning
class People(models.Model): class People(models.Model):
@ -60,8 +62,8 @@ class ColumnTypes(models.Model):
file_path_field = models.FilePathField() file_path_field = models.FilePathField()
float_field = models.FloatField() float_field = models.FloatField()
int_field = models.IntegerField() int_field = models.IntegerField()
with warnings.catch_warnings(record=True) as w: with warnings.catch_warnings():
warnings.simplefilter("always") warnings.simplefilter("ignore", category=RemovedInDjango19Warning)
ip_address_field = models.IPAddressField() ip_address_field = models.IPAddressField()
gen_ip_adress_field = models.GenericIPAddressField(protocol="ipv4") gen_ip_adress_field = models.GenericIPAddressField(protocol="ipv4")
pos_int_field = models.PositiveIntegerField() pos_int_field = models.PositiveIntegerField()

View File

@ -7,12 +7,11 @@ import os
import re import re
import tokenize import tokenize
import unittest import unittest
import warnings
from django.core.validators import RegexValidator, EmailValidator from django.core.validators import RegexValidator, EmailValidator
from django.db import models, migrations from django.db import models, migrations
from django.db.migrations.writer import MigrationWriter, SettingsReference 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.conf import settings
from django.utils import datetime_safe, six from django.utils import datetime_safe, six
from django.utils.deconstruct import deconstructible 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): def test_migration_path(self):
test_apps = [ test_apps = [
'migrations.migrations_test_apps.normal', 'migrations.migrations_test_apps.normal',
@ -302,12 +305,7 @@ class WriterTests(TestCase):
migration = migrations.Migration('0001_initial', app.split('.')[-1]) migration = migrations.Migration('0001_initial', app.split('.')[-1])
expected_path = os.path.join(base_dir, *(app.split('.') + ['migrations', '0001_initial.py'])) expected_path = os.path.join(base_dir, *(app.split('.') + ['migrations', '0001_initial.py']))
writer = MigrationWriter(migration) writer = MigrationWriter(migration)
# Silence warning on Python 2: Not importing directory self.assertEqual(writer.path, expected_path)
# '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)
def test_custom_operation(self): def test_custom_operation(self):
migration = type(str("Migration"), (migrations.Migration,), { migration = type(str("Migration"), (migrations.Migration,), {

View File

@ -12,6 +12,7 @@ from django.core.files.storage import FileSystemStorage
from django.db import models from django.db import models
from django.db.models.fields.files import ImageFieldFile, ImageField from django.db.models.fields.files import ImageFieldFile, ImageField
from django.utils import six from django.utils import six
from django.utils.deprecation import RemovedInDjango19Warning
class Foo(models.Model): class Foo(models.Model):
@ -160,8 +161,8 @@ class VerboseNameField(models.Model):
# Don't want to depend on Pillow in this test # Don't want to depend on Pillow in this test
#field_image = models.ImageField("verbose field") #field_image = models.ImageField("verbose field")
field12 = models.IntegerField("verbose field12") field12 = models.IntegerField("verbose field12")
with warnings.catch_warnings(record=True) as w: with warnings.catch_warnings():
warnings.simplefilter("always") warnings.simplefilter("ignore", category=RemovedInDjango19Warning)
field13 = models.IPAddressField("verbose field13") field13 = models.IPAddressField("verbose field13")
field14 = models.GenericIPAddressField("verbose field14", protocol="ipv4") field14 = models.GenericIPAddressField("verbose field14", protocol="ipv4")
field15 = models.NullBooleanField("verbose field15") field15 = models.NullBooleanField("verbose field15")

View File

@ -3,7 +3,6 @@ from __future__ import unicode_literals
import datetime import datetime
from decimal import Decimal from decimal import Decimal
import unittest import unittest
import warnings
from django import test from django import test
from django import forms from django import forms
@ -800,16 +799,15 @@ class PromiseTest(test.TestCase):
int) int)
def test_IPAddressField(self): def test_IPAddressField(self):
with warnings.catch_warnings(record=True): # Deprecation silenced in runtests.py
warnings.simplefilter("always") lazy_func = lazy(lambda: '127.0.0.1', six.text_type)
lazy_func = lazy(lambda: '127.0.0.1', six.text_type) self.assertIsInstance(
self.assertIsInstance( IPAddressField().get_prep_value(lazy_func()),
IPAddressField().get_prep_value(lazy_func()), six.text_type)
six.text_type) lazy_func = lazy(lambda: 0, int)
lazy_func = lazy(lambda: 0, int) self.assertIsInstance(
self.assertIsInstance( IPAddressField().get_prep_value(lazy_func()),
IPAddressField().get_prep_value(lazy_func()), six.text_type)
six.text_type)
def test_GenericIPAddressField(self): def test_GenericIPAddressField(self):
lazy_func = lazy(lambda: '127.0.0.1', six.text_type) lazy_func = lazy(lambda: '127.0.0.1', six.text_type)

View File

@ -1,7 +1,6 @@
from __future__ import unicode_literals from __future__ import unicode_literals
from datetime import date from datetime import date
import warnings
from django import forms from django import forms
from django.contrib.admin.options import (ModelAdmin, TabularInline, 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.core.exceptions import ImproperlyConfigured
from django.forms.models import BaseModelFormSet from django.forms.models import BaseModelFormSet
from django.forms.widgets import Select 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 import six
from django.utils.deprecation import RemovedInDjango19Warning from django.utils.deprecation import RemovedInDjango19Warning
@ -1505,19 +1504,18 @@ class FormsetCheckTests(CheckTestCase):
class CustomModelAdminTests(CheckTestCase): class CustomModelAdminTests(CheckTestCase):
@ignore_warnings(category=RemovedInDjango19Warning)
def test_deprecation(self): def test_deprecation(self):
"Deprecated Custom Validator definitions still work with the check framework." "Deprecated Custom Validator definitions still work with the check framework."
with warnings.catch_warnings():
warnings.simplefilter("ignore", category=RemovedInDjango19Warning)
class CustomValidator(ModelAdminValidator): class CustomValidator(ModelAdminValidator):
def validate_me(self, model_admin, model): def validate_me(self, model_admin, model):
raise ImproperlyConfigured('error!') raise ImproperlyConfigured('error!')
class CustomModelAdmin(ModelAdmin): class CustomModelAdmin(ModelAdmin):
validator_class = CustomValidator validator_class = CustomValidator
self.assertIsInvalid(CustomModelAdmin, ValidationTestModel, 'error!') self.assertIsInvalid(CustomModelAdmin, ValidationTestModel, 'error!')
class ListDisplayEditableTests(CheckTestCase): class ListDisplayEditableTests(CheckTestCase):

View File

@ -1,10 +1,9 @@
from __future__ import unicode_literals from __future__ import unicode_literals
import warnings
from django.core.urlresolvers import NoReverseMatch from django.core.urlresolvers import NoReverseMatch
from django.contrib.auth.views import logout from django.contrib.auth.views import logout
from django.shortcuts import resolve_url 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 django.utils.deprecation import RemovedInDjango20Warning
from .models import UnimportantThing from .models import UnimportantThing
@ -57,15 +56,14 @@ class ResolveUrlTests(TestCase):
resolved_url = resolve_url(logout) resolved_url = resolve_url(logout)
self.assertEqual('/accounts/logout/', resolved_url) self.assertEqual('/accounts/logout/', resolved_url)
@ignore_warnings(category=RemovedInDjango20Warning)
def test_valid_view_name(self): def test_valid_view_name(self):
""" """
Tests that passing a view function to ``resolve_url`` will result in Tests that passing a view function to ``resolve_url`` will result in
the URL path mapping to that view. the URL path mapping to that view.
""" """
with warnings.catch_warnings(): resolved_url = resolve_url('django.contrib.auth.views.logout')
warnings.filterwarnings("ignore", category=RemovedInDjango20Warning) 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): def test_domain(self):
""" """

View File

@ -11,6 +11,7 @@ from django.contrib.contenttypes.fields import (
GenericForeignKey, GenericRelation GenericForeignKey, GenericRelation
) )
from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes.models import ContentType
from django.utils.deprecation import RemovedInDjango19Warning
# The following classes are for testing basic data # The following classes are for testing basic data
# marshalling, including NULL values, where allowed. # marshalling, including NULL values, where allowed.
@ -68,8 +69,8 @@ class BigIntegerData(models.Model):
class IPAddressData(models.Model): class IPAddressData(models.Model):
with warnings.catch_warnings(record=True) as w: with warnings.catch_warnings():
warnings.simplefilter("always") warnings.simplefilter("ignore", category=RemovedInDjango19Warning)
data = models.IPAddressField(null=True) data = models.IPAddressField(null=True)

View File

@ -11,7 +11,6 @@ from __future__ import unicode_literals
import datetime import datetime
import decimal import decimal
from unittest import skipUnless from unittest import skipUnless
import warnings
try: try:
import yaml import yaml
@ -24,8 +23,9 @@ from django.core.serializers.base import DeserializationError
from django.core.serializers.xml_serializer import DTDForbidden from django.core.serializers.xml_serializer import DTDForbidden
from django.db import connection, models from django.db import connection, models
from django.http import HttpResponse 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 import six
from django.utils.deprecation import RemovedInDjango19Warning
from django.utils.functional import curry from django.utils.functional import curry
from .models import (BinaryData, BooleanData, CharData, DateData, DateTimeData, EmailData, from .models import (BinaryData, BooleanData, CharData, DateData, DateTimeData, EmailData,
@ -484,6 +484,7 @@ def serializerTest(format, self):
self.assertEqual(count, klass.objects.count()) self.assertEqual(count, klass.objects.count())
@ignore_warnings(category=RemovedInDjango19Warning) # for use_natural_keys
def naturalKeySerializerTest(format, self): def naturalKeySerializerTest(format, self):
# Create all the objects defined in the test data # Create all the objects defined in the test data
objects = [] objects = []
@ -497,11 +498,9 @@ def naturalKeySerializerTest(format, self):
instance_count[klass] = klass.objects.count() instance_count[klass] = klass.objects.count()
# use_natural_keys is deprecated and to be removed in Django 1.9 # use_natural_keys is deprecated and to be removed in Django 1.9
with warnings.catch_warnings(record=True): # Serialize the test database
warnings.simplefilter("always") serialized_data = serializers.serialize(format, objects, indent=2,
# Serialize the test database use_natural_keys=True)
serialized_data = serializers.serialize(format, objects, indent=2,
use_natural_keys=True)
for obj in serializers.deserialize(format, serialized_data): for obj in serializers.deserialize(format, serialized_data):
obj.save() obj.save()

View File

@ -1,6 +1,5 @@
import warnings
from django.utils.deprecation import RemovedInDjango20Warning from django.utils.deprecation import RemovedInDjango20Warning
from django.test import TestCase, override_settings from django.test import TestCase, ignore_warnings, override_settings
@override_settings( @override_settings(
@ -15,10 +14,9 @@ class ShortcutTests(TestCase):
self.assertEqual(response.content, b'FOO.BAR..\n') self.assertEqual(response.content, b'FOO.BAR..\n')
self.assertEqual(response['Content-Type'], 'text/html; charset=utf-8') self.assertEqual(response['Content-Type'], 'text/html; charset=utf-8')
@ignore_warnings(category=RemovedInDjango20Warning)
def test_render_to_response_with_request_context(self): def test_render_to_response_with_request_context(self):
with warnings.catch_warnings(): response = self.client.get('/render_to_response/request_context/')
warnings.filterwarnings("ignore", category=RemovedInDjango20Warning)
response = self.client.get('/render_to_response/request_context/')
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
self.assertEqual(response.content, b'FOO.BAR../path/to/static/media/\n') self.assertEqual(response.content, b'FOO.BAR../path/to/static/media/\n')
self.assertEqual(response['Content-Type'], 'text/html; charset=utf-8') 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, b'FOO.BAR..\n')
self.assertEqual(response['Content-Type'], 'application/x-rendertest') self.assertEqual(response['Content-Type'], 'application/x-rendertest')
@ignore_warnings(category=RemovedInDjango20Warning)
def test_render_to_response_with_dirs(self): def test_render_to_response_with_dirs(self):
with warnings.catch_warnings(): response = self.client.get('/render_to_response/dirs/')
warnings.filterwarnings("ignore", category=RemovedInDjango20Warning)
response = self.client.get('/render_to_response/dirs/')
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
self.assertEqual(response.content, b'spam eggs\n') self.assertEqual(response.content, b'spam eggs\n')
self.assertEqual(response['Content-Type'], 'text/html; charset=utf-8') self.assertEqual(response['Content-Type'], 'text/html; charset=utf-8')
@ignore_warnings(category=RemovedInDjango20Warning)
def test_render_to_response_with_context_instance_misuse(self): def test_render_to_response_with_context_instance_misuse(self):
""" """
For backwards-compatibility, ensure that it's possible to pass a For backwards-compatibility, ensure that it's possible to pass a
RequestContext instance in the dictionary argument instead of the RequestContext instance in the dictionary argument instead of the
context_instance argument. context_instance argument.
""" """
with warnings.catch_warnings(): response = self.client.get('/render_to_response/context_instance_misuse/')
warnings.filterwarnings("ignore", category=RemovedInDjango20Warning)
response = self.client.get('/render_to_response/context_instance_misuse/')
self.assertContains(response, 'context processor output') self.assertContains(response, 'context processor output')
def test_render(self): def test_render(self):
@ -55,10 +51,9 @@ class ShortcutTests(TestCase):
self.assertEqual(response['Content-Type'], 'text/html; charset=utf-8') self.assertEqual(response['Content-Type'], 'text/html; charset=utf-8')
self.assertFalse(hasattr(response.context.request, 'current_app')) self.assertFalse(hasattr(response.context.request, 'current_app'))
@ignore_warnings(category=RemovedInDjango20Warning)
def test_render_with_base_context(self): def test_render_with_base_context(self):
with warnings.catch_warnings(): response = self.client.get('/render/base_context/')
warnings.filterwarnings("ignore", category=RemovedInDjango20Warning)
response = self.client.get('/render/base_context/')
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
self.assertEqual(response.content, b'FOO.BAR..\n') self.assertEqual(response.content, b'FOO.BAR..\n')
self.assertEqual(response['Content-Type'], 'text/html; charset=utf-8') 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.status_code, 403)
self.assertEqual(response.content, b'FOO.BAR../path/to/static/media/\n') self.assertEqual(response.content, b'FOO.BAR../path/to/static/media/\n')
@ignore_warnings(category=RemovedInDjango20Warning)
def test_render_with_current_app(self): def test_render_with_current_app(self):
with warnings.catch_warnings(): response = self.client.get('/render/current_app/')
warnings.filterwarnings("ignore", category=RemovedInDjango20Warning)
response = self.client.get('/render/current_app/')
self.assertEqual(response.context.request.current_app, "foobar_app") self.assertEqual(response.context.request.current_app, "foobar_app")
@ignore_warnings(category=RemovedInDjango20Warning)
def test_render_with_dirs(self): def test_render_with_dirs(self):
with warnings.catch_warnings(): response = self.client.get('/render/dirs/')
warnings.filterwarnings("ignore", category=RemovedInDjango20Warning)
response = self.client.get('/render/dirs/')
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
self.assertEqual(response.content, b'spam eggs\n') self.assertEqual(response.content, b'spam eggs\n')
self.assertEqual(response['Content-Type'], 'text/html; charset=utf-8') self.assertEqual(response['Content-Type'], 'text/html; charset=utf-8')
@ignore_warnings(category=RemovedInDjango20Warning)
def test_render_with_current_app_conflict(self): def test_render_with_current_app_conflict(self):
with self.assertRaises(ValueError): with self.assertRaises(ValueError):
with warnings.catch_warnings(): self.client.get('/render/current_app_conflict/')
warnings.filterwarnings("ignore", category=RemovedInDjango20Warning)
self.client.get('/render/current_app_conflict/')

View File

@ -1,6 +1,5 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from __future__ import unicode_literals from __future__ import unicode_literals
import warnings
from django.db import models from django.db import models
from django.utils.encoding import python_2_unicode_compatible from django.utils.encoding import python_2_unicode_compatible
@ -55,9 +54,7 @@ class Base(models.Model):
class Article(models.Model): class Article(models.Model):
name = models.CharField(max_length=50) name = models.CharField(max_length=50)
text = models.TextField() text = models.TextField()
with warnings.catch_warnings(record=True) as w: submitted_from = models.GenericIPAddressField(blank=True, null=True)
warnings.simplefilter("always")
submitted_from = models.IPAddressField(blank=True, null=True)
def __str__(self): def __str__(self):
return "Article %s" % self.name return "Article %s" % self.name

View File

@ -1,57 +1,49 @@
import warnings
from django.template.defaultfilters import removetags 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.deprecation import RemovedInDjango20Warning
from django.utils.safestring import mark_safe from django.utils.safestring import mark_safe
from ..utils import setup from ..utils import setup
@ignore_warnings(category=RemovedInDjango20Warning)
class RemovetagsTests(SimpleTestCase): class RemovetagsTests(SimpleTestCase):
@setup({'removetags01': '{{ a|removetags:"a b" }} {{ b|removetags:"a b" }}'}) @setup({'removetags01': '{{ a|removetags:"a b" }} {{ b|removetags:"a b" }}'})
def test_removetags01(self): def test_removetags01(self):
with warnings.catch_warnings(): output = self.engine.render_to_string(
warnings.simplefilter('ignore', RemovedInDjango20Warning) 'removetags01',
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>'),
'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>')
)
self.assertEqual(output, 'x &lt;p&gt;y&lt;/p&gt; x <p>y</p>')
@setup({'removetags02': @setup({'removetags02':
'{% autoescape off %}{{ a|removetags:"a b" }} {{ b|removetags:"a b" }}{% endautoescape %}'}) '{% autoescape off %}{{ a|removetags:"a b" }} {{ b|removetags:"a b" }}{% endautoescape %}'})
def test_removetags02(self): def test_removetags02(self):
with warnings.catch_warnings(): output = self.engine.render_to_string(
warnings.simplefilter('ignore', RemovedInDjango20Warning) 'removetags02',
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>'),
'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>') self.assertEqual(output, 'x <p>y</p> x <p>y</p>')
@ignore_warnings(category=RemovedInDjango20Warning)
class FunctionTests(SimpleTestCase): class FunctionTests(SimpleTestCase):
def test_removetags(self): def test_removetags(self):
with warnings.catch_warnings(): self.assertEqual(
warnings.simplefilter('ignore', RemovedInDjango20Warning) removetags(
self.assertEqual( 'some <b>html</b> with <script>alert("You smell")</script> disallowed <img /> tags',
removetags( 'script img',
'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',
), )
'some <b>html</b> with alert("You smell") disallowed tags',
)
def test_non_string_input(self): def test_non_string_input(self):
with warnings.catch_warnings(): self.assertEqual(removetags(123, 'a'), '123')
warnings.simplefilter('ignore', RemovedInDjango20Warning)
self.assertEqual(removetags(123, 'a'), '123')

View File

@ -1,7 +1,5 @@
import warnings
from django.template.defaultfilters import unordered_list 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.deprecation import RemovedInDjango20Warning
from django.utils.encoding import python_2_unicode_compatible from django.utils.encoding import python_2_unicode_compatible
from django.utils.safestring import mark_safe 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']]}) 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>') 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 %}'}) @setup({'unordered_list02': '{% autoescape off %}{{ a|unordered_list }}{% endautoescape %}'})
def test_unordered_list02(self): def test_unordered_list02(self):
with warnings.catch_warnings(): output = self.engine.render_to_string('unordered_list02', {'a': ['x>', ['<y']]})
warnings.simplefilter('ignore', RemovedInDjango20Warning)
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>') 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 }}'}) @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>') 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): class DeprecatedUnorderedListSyntaxTests(SimpleTestCase):
@setup({'unordered_list01': '{{ a|unordered_list }}'}) @setup({'unordered_list01': '{{ a|unordered_list }}'})
def test_unordered_list01(self): def test_unordered_list01(self):
with warnings.catch_warnings(): output = self.engine.render_to_string('unordered_list01', {'a': ['x>', [['<y', []]]]})
warnings.simplefilter('ignore', RemovedInDjango20Warning)
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>') 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 %}'}) @setup({'unordered_list02': '{% autoescape off %}{{ a|unordered_list }}{% endautoescape %}'})
def test_unordered_list02(self): def test_unordered_list02(self):
with warnings.catch_warnings(): output = self.engine.render_to_string('unordered_list02', {'a': ['x>', [['<y', []]]]})
warnings.simplefilter('ignore', RemovedInDjango20Warning)
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>') 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 }}'}) @setup({'unordered_list03': '{{ a|unordered_list }}'})
def test_unordered_list03(self): def test_unordered_list03(self):
with warnings.catch_warnings(): output = self.engine.render_to_string('unordered_list03', {'a': ['x>', [[mark_safe('<y'), []]]]})
warnings.simplefilter('ignore', RemovedInDjango20Warning)
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>') 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 %}'}) @setup({'unordered_list04': '{% autoescape off %}{{ a|unordered_list }}{% endautoescape %}'})
def test_unordered_list04(self): def test_unordered_list04(self):
with warnings.catch_warnings(): output = self.engine.render_to_string('unordered_list04', {'a': ['x>', [[mark_safe('<y'), []]]]})
warnings.simplefilter('ignore', RemovedInDjango20Warning)
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>') 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 %}'}) @setup({'unordered_list05': '{% autoescape off %}{{ a|unordered_list }}{% endautoescape %}'})
def test_unordered_list05(self): def test_unordered_list05(self):
with warnings.catch_warnings(): output = self.engine.render_to_string('unordered_list05', {'a': ['x>', [['<y', []]]]})
warnings.simplefilter('ignore', RemovedInDjango20Warning)
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>') 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>') 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): def test_legacy(self):
""" """
Old format for unordered lists should still work Old format for unordered lists should still work
""" """
with warnings.catch_warnings(): self.assertEqual(unordered_list(['item 1', []]), '\t<li>item 1</li>')
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( self.assertEqual(
unordered_list(['item 1', [['item 1.1', []]]]), 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>', ['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( self.assertEqual(
unordered_list(['item 1', [['item 1.1', []], unordered_list(['States', [['Kansas', [['Lawrence', []], ['Topeka', []]]], ['Illinois', []]]]),
['item 1.2', []]]]), '\t<li>item 1\n\t<ul>\n\t\t<li>item 1.1' '\t<li>States\n\t<ul>\n\t\t<li>Kansas\n\t\t<ul>\n\t\t\t<li>Lawrence</li>'
'</li>\n\t\t<li>item 1.2</li>\n\t</ul>\n\t</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(['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>',
)

View File

@ -1,7 +1,5 @@
import warnings
from django.template import TemplateSyntaxError from django.template import TemplateSyntaxError
from django.test import SimpleTestCase from django.test import SimpleTestCase, ignore_warnings
from django.utils.deprecation import RemovedInDjango20Warning from django.utils.deprecation import RemovedInDjango20Warning
from ..utils import setup from ..utils import setup
@ -141,24 +139,21 @@ class CycleTagTests(SimpleTestCase):
output = self.engine.render_to_string('cycle25', {'a': '<'}) output = self.engine.render_to_string('cycle25', {'a': '<'})
self.assertEqual(output, '&lt;') self.assertEqual(output, '&lt;')
@ignore_warnings(category=RemovedInDjango20Warning)
@setup({'cycle26': '{% load cycle from future %}{% cycle a b as ab %}{% cycle ab %}'}) @setup({'cycle26': '{% load cycle from future %}{% cycle a b as ab %}{% cycle ab %}'})
def test_cycle26(self): def test_cycle26(self):
with warnings.catch_warnings(): output = self.engine.render_to_string('cycle26', {'a': '<', 'b': '>'})
warnings.simplefilter("ignore", RemovedInDjango20Warning)
output = self.engine.render_to_string('cycle26', {'a': '<', 'b': '>'})
self.assertEqual(output, '&lt;&gt;') self.assertEqual(output, '&lt;&gt;')
@ignore_warnings(category=RemovedInDjango20Warning)
@setup({'cycle27': '{% load cycle from future %}' @setup({'cycle27': '{% load cycle from future %}'
'{% autoescape off %}{% cycle a b as ab %}{% cycle ab %}{% endautoescape %}'}) '{% autoescape off %}{% cycle a b as ab %}{% cycle ab %}{% endautoescape %}'})
def test_cycle27(self): def test_cycle27(self):
with warnings.catch_warnings(): output = self.engine.render_to_string('cycle27', {'a': '<', 'b': '>'})
warnings.simplefilter("ignore", RemovedInDjango20Warning)
output = self.engine.render_to_string('cycle27', {'a': '<', 'b': '>'})
self.assertEqual(output, '<>') self.assertEqual(output, '<>')
@ignore_warnings(category=RemovedInDjango20Warning)
@setup({'cycle28': '{% load cycle from future %}{% cycle a|safe b as ab %}{% cycle ab %}'}) @setup({'cycle28': '{% load cycle from future %}{% cycle a|safe b as ab %}{% cycle ab %}'})
def test_cycle28(self): def test_cycle28(self):
with warnings.catch_warnings(): output = self.engine.render_to_string('cycle28', {'a': '<', 'b': '>'})
warnings.simplefilter("ignore", RemovedInDjango20Warning)
output = self.engine.render_to_string('cycle28', {'a': '<', 'b': '>'})
self.assertEqual(output, '<&gt;') self.assertEqual(output, '<&gt;')

View File

@ -1,9 +1,8 @@
# coding: utf-8 # coding: utf-8
from __future__ import unicode_literals from __future__ import unicode_literals
import warnings
from django.template import TemplateSyntaxError from django.template import TemplateSyntaxError
from django.test import SimpleTestCase from django.test import SimpleTestCase, ignore_warnings
from django.utils.deprecation import RemovedInDjango20Warning from django.utils.deprecation import RemovedInDjango20Warning
from ..utils import setup, SomeClass, SomeOtherException, UTF8Class from ..utils import setup, SomeClass, SomeOtherException, UTF8Class
@ -76,14 +75,13 @@ class FilterSyntaxTests(SimpleTestCase):
with self.assertRaises(TemplateSyntaxError): with self.assertRaises(TemplateSyntaxError):
self.engine.get_template('filter-syntax08') self.engine.get_template('filter-syntax08')
@ignore_warnings(category=RemovedInDjango20Warning)
@setup({'filter-syntax09': '{{ var|removetags:"b i"|upper|lower }}'}) @setup({'filter-syntax09': '{{ var|removetags:"b i"|upper|lower }}'})
def test_filter_syntax09(self): def test_filter_syntax09(self):
""" """
Chained filters, with an argument to the first one Chained filters, with an argument to the first one
""" """
with warnings.catch_warnings(): output = self.engine.render_to_string('filter-syntax09', {'var': '<b><i>Yes</i></b>'})
warnings.simplefilter("ignore", RemovedInDjango20Warning)
output = self.engine.render_to_string('filter-syntax09', {'var': '<b><i>Yes</i></b>'})
self.assertEqual(output, 'yes') self.assertEqual(output, 'yes')
@setup({'filter-syntax10': r'{{ var|default_if_none:" endquote\" hah" }}'}) @setup({'filter-syntax10': r'{{ var|default_if_none:" endquote\" hah" }}'})

View File

@ -1,7 +1,5 @@
import warnings
from django.template import TemplateSyntaxError from django.template import TemplateSyntaxError
from django.test import SimpleTestCase from django.test import SimpleTestCase, ignore_warnings
from django.utils.deprecation import RemovedInDjango20Warning from django.utils.deprecation import RemovedInDjango20Warning
from ..utils import setup from ..utils import setup
@ -59,31 +57,27 @@ class FirstOfTagTests(SimpleTestCase):
output = self.engine.render_to_string('firstof10', {'a': '<'}) output = self.engine.render_to_string('firstof10', {'a': '<'})
self.assertEqual(output, '&lt;') self.assertEqual(output, '&lt;')
@ignore_warnings(category=RemovedInDjango20Warning)
@setup({'firstof11': '{% load firstof from future %}{% firstof a b %}'}) @setup({'firstof11': '{% load firstof from future %}{% firstof a b %}'})
def test_firstof11(self): def test_firstof11(self):
with warnings.catch_warnings(): output = self.engine.render_to_string('firstof11', {'a': '<', 'b': '>'})
warnings.simplefilter("ignore", RemovedInDjango20Warning)
output = self.engine.render_to_string('firstof11', {'a': '<', 'b': '>'})
self.assertEqual(output, '&lt;') self.assertEqual(output, '&lt;')
@ignore_warnings(category=RemovedInDjango20Warning)
@setup({'firstof12': '{% load firstof from future %}{% firstof a b %}'}) @setup({'firstof12': '{% load firstof from future %}{% firstof a b %}'})
def test_firstof12(self): def test_firstof12(self):
with warnings.catch_warnings(): output = self.engine.render_to_string('firstof12', {'a': '', 'b': '>'})
warnings.simplefilter("ignore", RemovedInDjango20Warning)
output = self.engine.render_to_string('firstof12', {'a': '', 'b': '>'})
self.assertEqual(output, '&gt;') self.assertEqual(output, '&gt;')
@ignore_warnings(category=RemovedInDjango20Warning)
@setup({'firstof13': '{% load firstof from future %}' @setup({'firstof13': '{% load firstof from future %}'
'{% autoescape off %}{% firstof a %}{% endautoescape %}'}) '{% autoescape off %}{% firstof a %}{% endautoescape %}'})
def test_firstof13(self): def test_firstof13(self):
with warnings.catch_warnings(): output = self.engine.render_to_string('firstof13', {'a': '<'})
warnings.simplefilter("ignore", RemovedInDjango20Warning)
output = self.engine.render_to_string('firstof13', {'a': '<'})
self.assertEqual(output, '<') self.assertEqual(output, '<')
@ignore_warnings(category=RemovedInDjango20Warning)
@setup({'firstof14': '{% load firstof from future %}{% firstof a|safe b %}'}) @setup({'firstof14': '{% load firstof from future %}{% firstof a|safe b %}'})
def test_firstof14(self): def test_firstof14(self):
with warnings.catch_warnings(): output = self.engine.render_to_string('firstof14', {'a': '<'})
warnings.simplefilter("ignore", RemovedInDjango20Warning)
output = self.engine.render_to_string('firstof14', {'a': '<'})
self.assertEqual(output, '<') self.assertEqual(output, '<')

View File

@ -1,7 +1,5 @@
import warnings
from django.template import TemplateSyntaxError from django.template import TemplateSyntaxError
from django.test import SimpleTestCase from django.test import SimpleTestCase, ignore_warnings
from django.utils.deprecation import RemovedInDjango20Warning from django.utils.deprecation import RemovedInDjango20Warning
from ..utils import setup from ..utils import setup
@ -129,48 +127,44 @@ class ForTagTests(SimpleTestCase):
# These tests raise deprecation warnings and will raise an exception # These tests raise deprecation warnings and will raise an exception
# in Django 2.0. The existing behavior is silent truncation if the # in Django 2.0. The existing behavior is silent truncation if the
# length of loopvars differs to the length of each set of items. # 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 %}'}) @setup({'for-tag-unpack10': '{% for x,y in items %}{{ x }}:{{ y }}/{% endfor %}'})
def test_for_tag_unpack10(self): def test_for_tag_unpack10(self):
with warnings.catch_warnings(): output = self.engine.render_to_string(
warnings.simplefilter("ignore", RemovedInDjango20Warning) 'for-tag-unpack10',
output = self.engine.render_to_string( {'items': (('one', 1, 'carrot'), ('two', 2, 'orange'))},
'for-tag-unpack10', )
{'items': (('one', 1, 'carrot'), ('two', 2, 'orange'))},
)
self.assertEqual(output, 'one:1/two:2/') 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 %}'}) @setup({'for-tag-unpack11': '{% for x,y,z in items %}{{ x }}:{{ y }},{{ z }}/{% endfor %}'})
def test_for_tag_unpack11(self): def test_for_tag_unpack11(self):
with warnings.catch_warnings(): output = self.engine.render_to_string(
warnings.simplefilter("ignore", RemovedInDjango20Warning) 'for-tag-unpack11',
output = self.engine.render_to_string( {'items': (('one', 1), ('two', 2))},
'for-tag-unpack11', )
{'items': (('one', 1), ('two', 2))},
)
if self.engine.string_if_invalid: if self.engine.string_if_invalid:
self.assertEqual(output, 'one:1,INVALID/two:2,INVALID/') self.assertEqual(output, 'one:1,INVALID/two:2,INVALID/')
else: else:
self.assertEqual(output, 'one:1,/two:2,/') 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 %}'}) @setup({'for-tag-unpack12': '{% for x,y,z in items %}{{ x }}:{{ y }},{{ z }}/{% endfor %}'})
def test_for_tag_unpack12(self): def test_for_tag_unpack12(self):
with warnings.catch_warnings(): output = self.engine.render_to_string(
warnings.simplefilter("ignore", RemovedInDjango20Warning) 'for-tag-unpack12',
output = self.engine.render_to_string( {'items': (('one', 1, 'carrot'), ('two', 2))}
'for-tag-unpack12', )
{'items': (('one', 1, 'carrot'), ('two', 2))}
)
if self.engine.string_if_invalid: if self.engine.string_if_invalid:
self.assertEqual(output, 'one:1,carrot/two:2,INVALID/') self.assertEqual(output, 'one:1,carrot/two:2,INVALID/')
else: else:
self.assertEqual(output, 'one:1,carrot/two:2,/') self.assertEqual(output, 'one:1,carrot/two:2,/')
@ignore_warnings(category=RemovedInDjango20Warning)
@setup({'for-tag-unpack14': '{% for x,y in items %}{{ x }}:{{ y }}/{% endfor %}'}) @setup({'for-tag-unpack14': '{% for x,y in items %}{{ x }}:{{ y }}/{% endfor %}'})
def test_for_tag_unpack14(self): def test_for_tag_unpack14(self):
with warnings.catch_warnings(): output = self.engine.render_to_string('for-tag-unpack14', {'items': (1, 2)})
warnings.simplefilter("ignore", RemovedInDjango20Warning)
output = self.engine.render_to_string('for-tag-unpack14', {'items': (1, 2)})
if self.engine.string_if_invalid: if self.engine.string_if_invalid:
self.assertEqual(output, 'INVALID:INVALID/INVALID:INVALID/') self.assertEqual(output, 'INVALID:INVALID/INVALID:INVALID/')

View File

@ -1,7 +1,6 @@
import os import os
import warnings
from django.test import SimpleTestCase from django.test import ignore_warnings, SimpleTestCase
from django.utils.deprecation import RemovedInDjango19Warning from django.utils.deprecation import RemovedInDjango19Warning
from ..utils import ROOT, setup from ..utils import ROOT, setup
@ -32,20 +31,18 @@ class SsiTagTests(SimpleTestCase):
self.assertEqual(output, ''), self.assertEqual(output, ''),
# Test passing as a variable # Test passing as a variable
@ignore_warnings(category=RemovedInDjango19Warning)
@setup({'ssi04': '{% load ssi from future %}{% ssi ssi_file %}'}) @setup({'ssi04': '{% load ssi from future %}{% ssi ssi_file %}'})
def test_ssi04(self): def test_ssi04(self):
with warnings.catch_warnings(): output = self.engine.render_to_string('ssi04', {
warnings.simplefilter("ignore", RemovedInDjango19Warning) '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') 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 %}'}) @setup({'ssi05': '{% load ssi from future %}{% ssi ssi_file %}'})
def test_ssi05(self): def test_ssi05(self):
with warnings.catch_warnings(): output = self.engine.render_to_string('ssi05', {'ssi_file': 'no_file'})
warnings.simplefilter("ignore", RemovedInDjango19Warning)
output = self.engine.render_to_string('ssi05', {'ssi_file': 'no_file'})
self.assertEqual(output, '') self.assertEqual(output, '')
# Test parsed output # Test parsed output

View File

@ -1,9 +1,7 @@
# coding: utf-8 # coding: utf-8
import warnings
from django.core.urlresolvers import NoReverseMatch from django.core.urlresolvers import NoReverseMatch
from django.template import TemplateSyntaxError 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 django.utils.deprecation import RemovedInDjango20Warning
from ..utils import setup from ..utils import setup
@ -13,46 +11,40 @@ from ..utils import setup
class UrlTagTests(SimpleTestCase): class UrlTagTests(SimpleTestCase):
# Successes # Successes
@ignore_warnings(category=RemovedInDjango20Warning)
@setup({'url01': '{% url "template_tests.views.client" client.id %}'}) @setup({'url01': '{% url "template_tests.views.client" client.id %}'})
def test_url01(self): def test_url01(self):
with warnings.catch_warnings(): output = self.engine.render_to_string('url01', {'client': {'id': 1}})
warnings.simplefilter("ignore", RemovedInDjango20Warning)
output = self.engine.render_to_string('url01', {'client': {'id': 1}})
self.assertEqual(output, '/client/1/') self.assertEqual(output, '/client/1/')
@ignore_warnings(category=RemovedInDjango20Warning)
@setup({'url02': '{% url "template_tests.views.client_action" id=client.id action="update" %}'}) @setup({'url02': '{% url "template_tests.views.client_action" id=client.id action="update" %}'})
def test_url02(self): def test_url02(self):
with warnings.catch_warnings(): output = self.engine.render_to_string('url02', {'client': {'id': 1}})
warnings.simplefilter("ignore", RemovedInDjango20Warning)
output = self.engine.render_to_string('url02', {'client': {'id': 1}})
self.assertEqual(output, '/client/1/update/') self.assertEqual(output, '/client/1/update/')
@ignore_warnings(category=RemovedInDjango20Warning)
@setup({'url02a': '{% url "template_tests.views.client_action" client.id "update" %}'}) @setup({'url02a': '{% url "template_tests.views.client_action" client.id "update" %}'})
def test_url02a(self): def test_url02a(self):
with warnings.catch_warnings(): output = self.engine.render_to_string('url02a', {'client': {'id': 1}})
warnings.simplefilter("ignore", RemovedInDjango20Warning)
output = self.engine.render_to_string('url02a', {'client': {'id': 1}})
self.assertEqual(output, '/client/1/update/') self.assertEqual(output, '/client/1/update/')
@ignore_warnings(category=RemovedInDjango20Warning)
@setup({'url02b': "{% url 'template_tests.views.client_action' id=client.id action='update' %}"}) @setup({'url02b': "{% url 'template_tests.views.client_action' id=client.id action='update' %}"})
def test_url02b(self): def test_url02b(self):
with warnings.catch_warnings(): output = self.engine.render_to_string('url02b', {'client': {'id': 1}})
warnings.simplefilter("ignore", RemovedInDjango20Warning)
output = self.engine.render_to_string('url02b', {'client': {'id': 1}})
self.assertEqual(output, '/client/1/update/') self.assertEqual(output, '/client/1/update/')
@ignore_warnings(category=RemovedInDjango20Warning)
@setup({'url02c': "{% url 'template_tests.views.client_action' client.id 'update' %}"}) @setup({'url02c': "{% url 'template_tests.views.client_action' client.id 'update' %}"})
def test_url02c(self): def test_url02c(self):
with warnings.catch_warnings(): output = self.engine.render_to_string('url02c', {'client': {'id': 1}})
warnings.simplefilter("ignore", RemovedInDjango20Warning)
output = self.engine.render_to_string('url02c', {'client': {'id': 1}})
self.assertEqual(output, '/client/1/update/') self.assertEqual(output, '/client/1/update/')
@ignore_warnings(category=RemovedInDjango20Warning)
@setup({'url03': '{% url "template_tests.views.index" %}'}) @setup({'url03': '{% url "template_tests.views.index" %}'})
def test_url03(self): def test_url03(self):
with warnings.catch_warnings(): output = self.engine.render_to_string('url03')
warnings.simplefilter("ignore", RemovedInDjango20Warning)
output = self.engine.render_to_string('url03')
self.assertEqual(output, '/') self.assertEqual(output, '/')
@setup({'url04': '{% url "named.client" client.id %}'}) @setup({'url04': '{% url "named.client" client.id %}'})
@ -70,11 +62,10 @@ class UrlTagTests(SimpleTestCase):
output = self.engine.render_to_string('url06', {'v': 'Ω'}) 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/') 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 %}'}) @setup({'url07': '{% url "template_tests.views.client2" tag=v %}'})
def test_url07(self): def test_url07(self):
with warnings.catch_warnings(): output = self.engine.render_to_string('url07', {'v': 'Ω'})
warnings.simplefilter("ignore", RemovedInDjango20Warning)
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/') self.assertEqual(output, '/%D0%AE%D0%BD%D0%B8%D0%BA%D0%BE%D0%B4/%CE%A9/')
@setup({'url08': '{% url "метка_оператора" v %}'}) @setup({'url08': '{% url "метка_оператора" v %}'})
@ -87,62 +78,54 @@ class UrlTagTests(SimpleTestCase):
output = self.engine.render_to_string('url09', {'v': 'Ω'}) 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/') 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" %}'}) @setup({'url10': '{% url "template_tests.views.client_action" id=client.id action="two words" %}'})
def test_url10(self): def test_url10(self):
with warnings.catch_warnings(): output = self.engine.render_to_string('url10', {'client': {'id': 1}})
warnings.simplefilter("ignore", RemovedInDjango20Warning)
output = self.engine.render_to_string('url10', {'client': {'id': 1}})
self.assertEqual(output, '/client/1/two%20words/') self.assertEqual(output, '/client/1/two%20words/')
@ignore_warnings(category=RemovedInDjango20Warning)
@setup({'url11': '{% url "template_tests.views.client_action" id=client.id action="==" %}'}) @setup({'url11': '{% url "template_tests.views.client_action" id=client.id action="==" %}'})
def test_url11(self): def test_url11(self):
with warnings.catch_warnings(): output = self.engine.render_to_string('url11', {'client': {'id': 1}})
warnings.simplefilter("ignore", RemovedInDjango20Warning)
output = self.engine.render_to_string('url11', {'client': {'id': 1}})
self.assertEqual(output, '/client/1/==/') self.assertEqual(output, '/client/1/==/')
@setup({'url12': '{% url "template_tests.views.client_action" ' @setup({'url12': '{% url "template_tests.views.client_action" '
'id=client.id action="!$&\'()*+,;=~:@," %}'}) 'id=client.id action="!$&\'()*+,;=~:@," %}'})
@ignore_warnings(category=RemovedInDjango20Warning)
def test_url12(self): def test_url12(self):
with warnings.catch_warnings(): output = self.engine.render_to_string('url12', {'client': {'id': 1}})
warnings.simplefilter("ignore", RemovedInDjango20Warning)
output = self.engine.render_to_string('url12', {'client': {'id': 1}})
self.assertEqual(output, '/client/1/!$&\'()*+,;=~:@,/') self.assertEqual(output, '/client/1/!$&\'()*+,;=~:@,/')
@ignore_warnings(category=RemovedInDjango20Warning)
@setup({'url13': '{% url "template_tests.views.client_action" ' @setup({'url13': '{% url "template_tests.views.client_action" '
'id=client.id action=arg|join:"-" %}'}) 'id=client.id action=arg|join:"-" %}'})
def test_url13(self): def test_url13(self):
with warnings.catch_warnings(): output = self.engine.render_to_string('url13', {'client': {'id': 1}, 'arg': ['a', 'b']})
warnings.simplefilter("ignore", RemovedInDjango20Warning)
output = self.engine.render_to_string('url13', {'client': {'id': 1}, 'arg': ['a', 'b']})
self.assertEqual(output, '/client/1/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:"-" %}'}) @setup({'url14': '{% url "template_tests.views.client_action" client.id arg|join:"-" %}'})
def test_url14(self): def test_url14(self):
with warnings.catch_warnings(): output = self.engine.render_to_string('url14', {'client': {'id': 1}, 'arg': ['a', 'b']})
warnings.simplefilter("ignore", RemovedInDjango20Warning)
output = self.engine.render_to_string('url14', {'client': {'id': 1}, 'arg': ['a', 'b']})
self.assertEqual(output, '/client/1/a-b/') self.assertEqual(output, '/client/1/a-b/')
@ignore_warnings(category=RemovedInDjango20Warning)
@setup({'url15': '{% url "template_tests.views.client_action" 12 "test" %}'}) @setup({'url15': '{% url "template_tests.views.client_action" 12 "test" %}'})
def test_url15(self): def test_url15(self):
with warnings.catch_warnings(): output = self.engine.render_to_string('url15')
warnings.simplefilter("ignore", RemovedInDjango20Warning)
output = self.engine.render_to_string('url15')
self.assertEqual(output, '/client/12/test/') self.assertEqual(output, '/client/12/test/')
@ignore_warnings(category=RemovedInDjango20Warning)
@setup({'url18': '{% url "template_tests.views.client" "1,2" %}'}) @setup({'url18': '{% url "template_tests.views.client" "1,2" %}'})
def test_url18(self): def test_url18(self):
with warnings.catch_warnings(): output = self.engine.render_to_string('url18')
warnings.simplefilter("ignore", RemovedInDjango20Warning)
output = self.engine.render_to_string('url18')
self.assertEqual(output, '/client/1,2/') self.assertEqual(output, '/client/1,2/')
@ignore_warnings(category=RemovedInDjango20Warning)
@setup({'url19': '{% url named_url client.id %}'}) @setup({'url19': '{% url named_url client.id %}'})
def test_url19(self): def test_url19(self):
with warnings.catch_warnings(): output = self.engine.render_to_string('url19', {'client': {'id': 1}, 'named_url': 'template_tests.views.client'})
warnings.simplefilter("ignore", RemovedInDjango20Warning)
output = self.engine.render_to_string('url19', {'client': {'id': 1}, 'named_url': 'template_tests.views.client'})
self.assertEqual(output, '/client/1/') self.assertEqual(output, '/client/1/')
@setup({'url20': '{% url url_name_in_var client.id %}'}) @setup({'url20': '{% url url_name_in_var client.id %}'})
@ -161,12 +144,11 @@ class UrlTagTests(SimpleTestCase):
with self.assertRaises(NoReverseMatch): with self.assertRaises(NoReverseMatch):
self.engine.render_to_string('url-fail02') self.engine.render_to_string('url-fail02')
@ignore_warnings(category=RemovedInDjango20Warning)
@setup({'url-fail03': '{% url "template_tests.views.client" %}'}) @setup({'url-fail03': '{% url "template_tests.views.client" %}'})
def test_url_fail03(self): def test_url_fail03(self):
with warnings.catch_warnings(): with self.assertRaises(NoReverseMatch):
warnings.simplefilter("ignore", RemovedInDjango20Warning) self.engine.render_to_string('url-fail03')
with self.assertRaises(NoReverseMatch):
self.engine.render_to_string('url-fail03')
@setup({'url-fail04': '{% url "view" id, %}'}) @setup({'url-fail04': '{% url "view" id, %}'})
def test_url_fail04(self): def test_url_fail04(self):
@ -208,12 +190,11 @@ class UrlTagTests(SimpleTestCase):
with self.assertRaises(NoReverseMatch): with self.assertRaises(NoReverseMatch):
self.engine.render_to_string('url-fail12', {'named_url': 'no_such_view'}) self.engine.render_to_string('url-fail12', {'named_url': 'no_such_view'})
@ignore_warnings(category=RemovedInDjango20Warning)
@setup({'url-fail13': '{% url named_url %}'}) @setup({'url-fail13': '{% url named_url %}'})
def test_url_fail13(self): def test_url_fail13(self):
with warnings.catch_warnings(): with self.assertRaises(NoReverseMatch):
warnings.simplefilter("ignore", RemovedInDjango20Warning) 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, %}'}) @setup({'url-fail14': '{% url named_url id, %}'})
def test_url_fail14(self): def test_url_fail14(self):
@ -246,18 +227,16 @@ class UrlTagTests(SimpleTestCase):
self.engine.render_to_string('url-fail19', {'named_url': 'view'}) self.engine.render_to_string('url-fail19', {'named_url': 'view'})
# {% url ... as var %} # {% url ... as var %}
@ignore_warnings(category=RemovedInDjango20Warning)
@setup({'url-asvar01': '{% url "template_tests.views.index" as url %}'}) @setup({'url-asvar01': '{% url "template_tests.views.index" as url %}'})
def test_url_asvar01(self): def test_url_asvar01(self):
with warnings.catch_warnings(): output = self.engine.render_to_string('url-asvar01')
warnings.simplefilter("ignore", RemovedInDjango20Warning)
output = self.engine.render_to_string('url-asvar01')
self.assertEqual(output, '') self.assertEqual(output, '')
@ignore_warnings(category=RemovedInDjango20Warning)
@setup({'url-asvar02': '{% url "template_tests.views.index" as url %}{{ url }}'}) @setup({'url-asvar02': '{% url "template_tests.views.index" as url %}{{ url }}'})
def test_url_asvar02(self): def test_url_asvar02(self):
with warnings.catch_warnings(): output = self.engine.render_to_string('url-asvar02')
warnings.simplefilter("ignore", RemovedInDjango20Warning)
output = self.engine.render_to_string('url-asvar02')
self.assertEqual(output, '/') self.assertEqual(output, '/')
@setup({'url-asvar03': '{% url "no_such_view" as url %}{{ url }}'}) @setup({'url-asvar03': '{% url "no_such_view" as url %}{{ url }}'})

View File

@ -1,9 +1,9 @@
from __future__ import unicode_literals from __future__ import unicode_literals
from unittest import TestCase from unittest import TestCase
import warnings
from django import template from django import template
from django.test import ignore_warnings
from django.utils import six from django.utils import six
from django.utils.deprecation import RemovedInDjango20Warning 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_tag_current_app, 'inclusion_tag_current_app')
self.verify_tag(custom.inclusion_unlimited_args_kwargs, 'inclusion_unlimited_args_kwargs') self.verify_tag(custom.inclusion_unlimited_args_kwargs, 'inclusion_unlimited_args_kwargs')
@ignore_warnings(category=RemovedInDjango20Warning)
def test_15070_current_app(self): def test_15070_current_app(self):
""" """
Test that inclusion tag passes down `current_app` of context to the 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 %}') t = template.Template('{% load custom %}{% inclusion_tag_current_app %}')
self.assertEqual(t.render(c).strip(), 'None') self.assertEqual(t.render(c).strip(), 'None')
with warnings.catch_warnings(): # That part produces the deprecation warning
warnings.filterwarnings("ignore", category=RemovedInDjango20Warning) c = template.Context({}, current_app='advanced')
c = template.Context({}, current_app='advanced') self.assertEqual(t.render(c).strip(), 'advanced')
self.assertEqual(t.render(c).strip(), 'advanced')
def test_15070_use_l10n(self): def test_15070_use_l10n(self):
""" """

View File

@ -19,9 +19,9 @@ from django.template import TemplateDoesNotExist, Context
from django.template.loaders import cached, eggs from django.template.loaders import cached, eggs
from django.template.engine import Engine from django.template.engine import Engine
from django.template import loader from django.template import loader
from django.test import SimpleTestCase, override_settings from django.test import SimpleTestCase, ignore_warnings, override_settings
from django.test.utils import IgnorePendingDeprecationWarningsMixin
from django.utils import six from django.utils import six
from django.utils.deprecation import RemovedInDjango20Warning
from django.utils._os import upath from django.utils._os import upath
from django.utils.six import StringIO from django.utils.six import StringIO
@ -166,11 +166,12 @@ class RenderToStringTest(SimpleTestCase):
loader.select_template, []) loader.select_template, [])
@ignore_warnings(category=RemovedInDjango20Warning)
@override_settings(TEMPLATES=[{ @override_settings(TEMPLATES=[{
'BACKEND': 'django.template.backends.django.DjangoTemplates', 'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [TEMPLATES_DIR], 'DIRS': [TEMPLATES_DIR],
}]) }])
class DeprecatedRenderToStringTest(IgnorePendingDeprecationWarningsMixin, SimpleTestCase): class DeprecatedRenderToStringTest(SimpleTestCase):
def test_existing_context_kept_clean(self): def test_existing_context_kept_clean(self):
context = Context({'obj': 'before'}) context = Context({'obj': 'before'})
@ -192,10 +193,11 @@ class DeprecatedRenderToStringTest(IgnorePendingDeprecationWarningsMixin, Simple
loader.render_to_string('test_context_stack.html', context_instance=Context()).strip()) loader.render_to_string('test_context_stack.html', context_instance=Context()).strip())
@ignore_warnings(category=RemovedInDjango20Warning)
@override_settings(TEMPLATES=[{ @override_settings(TEMPLATES=[{
'BACKEND': 'django.template.backends.django.DjangoTemplates', '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_tuple = (os.path.join(os.path.dirname(upath(__file__)), 'other_templates'),)
dirs_list = list(dirs_tuple) dirs_list = list(dirs_tuple)

View File

@ -4,14 +4,13 @@ from datetime import datetime
import os import os
import pickle import pickle
import time import time
import warnings
from django.test import RequestFactory, SimpleTestCase from django.test import RequestFactory, SimpleTestCase
from django.conf import settings from django.conf import settings
from django.template import Template, Context from django.template import Template, Context
from django.template.response import (TemplateResponse, SimpleTemplateResponse, from django.template.response import (TemplateResponse, SimpleTemplateResponse,
ContentNotRenderedError) ContentNotRenderedError)
from django.test import override_settings from django.test import ignore_warnings, override_settings
from django.utils._os import upath from django.utils._os import upath
from django.utils.deprecation import RemovedInDjango20Warning from django.utils.deprecation import RemovedInDjango20Warning
@ -256,10 +255,9 @@ class TemplateResponseTest(SimpleTestCase):
self.assertEqual(response['content-type'], 'application/json') self.assertEqual(response['content-type'], 'application/json')
self.assertEqual(response.status_code, 504) self.assertEqual(response.status_code, 504)
@ignore_warnings(category=RemovedInDjango20Warning)
def test_custom_app(self): def test_custom_app(self):
with warnings.catch_warnings(): response = self._response('{{ foo }}', current_app="foobar")
warnings.filterwarnings("ignore", category=RemovedInDjango20Warning)
response = self._response('{{ foo }}', current_app="foobar")
rc = response.resolve_context(response.context_data) rc = response.resolve_context(response.context_data)

View File

@ -6,16 +6,15 @@ from __future__ import unicode_literals
import os import os
import itertools import itertools
import warnings
from django.core.urlresolvers import reverse, NoReverseMatch from django.core.urlresolvers import reverse, NoReverseMatch
from django.template import TemplateSyntaxError, Context, Template 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.client import RedirectCycleError, RequestFactory, encode_file
from django.test.utils import ContextList, str_prefix from django.test.utils import ContextList, str_prefix
from django.template.response import SimpleTemplateResponse from django.template.response import SimpleTemplateResponse
from django.utils.deprecation import RemovedInDjango19Warning, RemovedInDjango20Warning
from django.utils._os import upath from django.utils._os import upath
from django.utils.deprecation import RemovedInDjango20Warning
from django.utils.translation import ugettext_lazy from django.utils.translation import ugettext_lazy
from django.http import HttpResponse from django.http import HttpResponse
from django.contrib.auth.signals import user_logged_out, user_logged_in from django.contrib.auth.signals import user_logged_out, user_logged_in
@ -952,6 +951,7 @@ class zzUrlconfSubstitutionTests(TestCase):
class ContextTests(TestCase): class ContextTests(TestCase):
fixtures = ['testdata'] fixtures = ['testdata']
@ignore_warnings(category=RemovedInDjango19Warning) # `request.REQUEST` is deprecated
def test_single_context(self): def test_single_context(self):
"Context variables can be retrieved from a single context" "Context variables can be retrieved from a single context"
response = self.client.get("/request_data/", data={'foo': 'whiz'}) response = self.client.get("/request_data/", data={'foo': 'whiz'})
@ -967,6 +967,7 @@ class ContextTests(TestCase):
except KeyError as e: except KeyError as e:
self.assertEqual(e.args[0], 'does-not-exist') self.assertEqual(e.args[0], 'does-not-exist')
@ignore_warnings(category=RemovedInDjango19Warning) # `request.REQUEST` is deprecated
def test_inherited_context(self): def test_inherited_context(self):
"Context variables can be retrieved from a list of contexts" "Context variables can be retrieved from a list of contexts"
response = self.client.get("/request_data_extended/", data={'foo': 'whiz'}) response = self.client.get("/request_data_extended/", data={'foo': 'whiz'})
@ -998,23 +999,22 @@ class ContextTests(TestCase):
'python', 'dolly'}, 'python', 'dolly'},
l.keys()) l.keys())
@ignore_warnings(category=RemovedInDjango20Warning)
def test_15368(self): def test_15368(self):
with warnings.catch_warnings(): # Need to insert a context processor that assumes certain things about
warnings.filterwarnings("ignore", category=RemovedInDjango20Warning) # the request instance. This triggers a bug caused by some ways of
# Need to insert a context processor that assumes certain things about # copying RequestContext.
# the request instance. This triggers a bug caused by some ways of with self.settings(TEMPLATES=[{
# copying RequestContext. 'BACKEND': 'django.template.backends.django.DjangoTemplates',
with self.settings(TEMPLATES=[{ 'APP_DIRS': True,
'BACKEND': 'django.template.backends.django.DjangoTemplates', 'OPTIONS': {
'APP_DIRS': True, 'context_processors': [
'OPTIONS': { 'test_client_regress.context_processors.special',
'context_processors': [ ],
'test_client_regress.context_processors.special', },
], }]):
}, response = self.client.get("/request_context_view/")
}]): self.assertContains(response, 'Path: /request_context_view/')
response = self.client.get("/request_context_view/")
self.assertContains(response, 'Path: /request_context_view/')
def test_nested_requests(self): def test_nested_requests(self):
""" """
@ -1250,6 +1250,7 @@ class RequestMethodStringDataTests(TestCase):
@override_settings(ROOT_URLCONF='test_client_regress.urls',) @override_settings(ROOT_URLCONF='test_client_regress.urls',)
class QueryStringTests(TestCase): class QueryStringTests(TestCase):
@ignore_warnings(category=RemovedInDjango19Warning) # `request.REQUEST` is deprecated
def test_get_like_requests(self): def test_get_like_requests(self):
# See: https://code.djangoproject.com/ticket/10571. # See: https://code.djangoproject.com/ticket/10571.
for method_name in ('get', 'head'): 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-foo'], None)
self.assertEqual(response.context['request-bar'], 'bang') self.assertEqual(response.context['request-bar'], 'bang')
@ignore_warnings(category=RemovedInDjango19Warning) # `request.REQUEST` is deprecated
def test_post_like_requests(self): def test_post_like_requests(self):
# A POST-like request can pass a query string as data # A POST-like request can pass a query string as data
response = self.client.post("/request_data/", data={'foo': 'whiz'}) response = self.client.post("/request_data/", data={'foo': 'whiz'})

View File

@ -1,5 +1,4 @@
import json import json
import warnings
from django.conf import settings from django.conf import settings
from django.contrib.auth.decorators import login_required 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'): def request_data(request, template='base.html', data='sausage'):
"A simple view that returns the request data in the context" "A simple view that returns the request data in the context"
# request.REQUEST is deprecated, but needs testing until removed. request_foo = request.REQUEST.get('foo')
with warnings.catch_warnings(record=True): request_bar = request.REQUEST.get('bar')
warnings.simplefilter("always")
request_foo = request.REQUEST.get('foo')
request_bar = request.REQUEST.get('bar')
return render_to_response(template, { return render_to_response(template, {
'get-foo': request.GET.get('foo'), 'get-foo': request.GET.get('foo'),

View File

@ -6,7 +6,6 @@ from __future__ import unicode_literals
import sys import sys
import unittest import unittest
import warnings
from django.contrib.auth.models import User from django.contrib.auth.models import User
from django.conf import settings from django.conf import settings
@ -16,7 +15,7 @@ from django.core.urlresolvers import (reverse, reverse_lazy, resolve, get_callab
RegexURLPattern) RegexURLPattern)
from django.http import HttpRequest, HttpResponseRedirect, HttpResponsePermanentRedirect from django.http import HttpRequest, HttpResponseRedirect, HttpResponsePermanentRedirect
from django.shortcuts import redirect 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 import six
from django.utils.deprecation import RemovedInDjango20Warning from django.utils.deprecation import RemovedInDjango20Warning
@ -177,16 +176,15 @@ class NoURLPatternsTests(TestCase):
@override_settings(ROOT_URLCONF='urlpatterns_reverse.urls') @override_settings(ROOT_URLCONF='urlpatterns_reverse.urls')
class URLPatternReverse(TestCase): class URLPatternReverse(TestCase):
@ignore_warnings(category=RemovedInDjango20Warning)
def test_urlpattern_reverse(self): def test_urlpattern_reverse(self):
with warnings.catch_warnings(): for name, expected, args, kwargs in test_data:
warnings.filterwarnings("ignore", category=RemovedInDjango20Warning) try:
for name, expected, args, kwargs in test_data: got = reverse(name, args=args, kwargs=kwargs)
try: except NoReverseMatch:
got = reverse(name, args=args, kwargs=kwargs) self.assertEqual(expected, NoReverseMatch)
except NoReverseMatch: else:
self.assertEqual(expected, NoReverseMatch) self.assertEqual(got, expected)
else:
self.assertEqual(got, expected)
def test_reverse_none(self): def test_reverse_none(self):
# Reversing None should raise an error, not return the last un-named view. # 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") redirect("urlpatterns_reverse.nonimported_module.view")
self.assertNotIn("urlpatterns_reverse.nonimported_module", sys.modules) self.assertNotIn("urlpatterns_reverse.nonimported_module", sys.modules)
@ignore_warnings(category=RemovedInDjango20Warning)
def test_reverse_by_path_nested(self): def test_reverse_by_path_nested(self):
# Views that are added to urlpatterns using include() should be # Views that are added to urlpatterns using include() should be
# reversible by doted path. # reversible by doted path.
with warnings.catch_warnings(): self.assertEqual(reverse('urlpatterns_reverse.views.nested_view'), '/includes/nested_path/')
warnings.filterwarnings("ignore", category=RemovedInDjango20Warning)
self.assertEqual(reverse('urlpatterns_reverse.views.nested_view'), '/includes/nested_path/')
def test_redirect_view_object(self): def test_redirect_view_object(self):
from .views import absolute_kwargs_view from .views import absolute_kwargs_view

View File

@ -1,11 +1,10 @@
import os import os
import warnings
from django.db import connection from django.db import connection
from django.core import management from django.core import management
from django.core.management import BaseCommand, CommandError from django.core.management import BaseCommand, CommandError
from django.core.management.utils import find_command, popen_wrapper 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.test.utils import captured_stderr, captured_stdout
from django.utils import translation from django.utils import translation
from django.utils.deprecation import RemovedInDjango20Warning 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())
self.assertNotIn("opt-3", out.getvalue()) self.assertNotIn("opt-3", out.getvalue())
@ignore_warnings(category=RemovedInDjango20Warning)
def test_optparse_compatibility(self): def test_optparse_compatibility(self):
""" """
optparse should be supported during Django 1.8/1.9 releases. optparse should be supported during Django 1.8/1.9 releases.
""" """
out = StringIO() out = StringIO()
with warnings.catch_warnings(): management.call_command('optparse_cmd', stdout=out)
warnings.filterwarnings("ignore", category=RemovedInDjango20Warning)
management.call_command('optparse_cmd', stdout=out)
self.assertEqual(out.getvalue(), "All right, let's dance Rock'n'Roll.\n") self.assertEqual(out.getvalue(), "All right, let's dance Rock'n'Roll.\n")
# Simulate command line execution # Simulate command line execution

View File

@ -1,14 +1,8 @@
import unittest import unittest
import warnings
from django.test import ignore_warnings
from django.utils.deprecation import RemovedInDjango20Warning 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): class TestUtilsChecksums(unittest.TestCase):
@ -21,7 +15,9 @@ class TestUtilsChecksums(unittest.TestCase):
output = value output = value
self.assertEqual(function(value), output) self.assertEqual(function(value), output)
@ignore_warnings(category=RemovedInDjango20Warning)
def test_luhn(self): def test_luhn(self):
from django.utils import checksums
f = checksums.luhn f = checksums.luhn
items = ( items = (
(4111111111111111, True), ('4111111111111111', True), (4111111111111111, True), ('4111111111111111', True),

View File

@ -5,14 +5,15 @@ Tests for stuff in django.utils.datastructures.
import copy import copy
import pickle import pickle
from django.test import SimpleTestCase from django.test import SimpleTestCase, ignore_warnings
from django.test.utils import IgnoreDeprecationWarningsMixin
from django.utils.datastructures import (DictWrapper, ImmutableList, from django.utils.datastructures import (DictWrapper, ImmutableList,
MultiValueDict, MultiValueDictKeyError, MergeDict, OrderedSet, SortedDict) MultiValueDict, MultiValueDictKeyError, MergeDict, OrderedSet, SortedDict)
from django.utils.deprecation import RemovedInDjango19Warning
from django.utils import six from django.utils import six
class SortedDictTests(IgnoreDeprecationWarningsMixin, SimpleTestCase): @ignore_warnings(category=RemovedInDjango19Warning)
class SortedDictTests(SimpleTestCase):
def setUp(self): def setUp(self):
super(SortedDictTests, self).setUp() super(SortedDictTests, self).setUp()
self.d1 = SortedDict() self.d1 = SortedDict()
@ -136,7 +137,8 @@ class SortedDictTests(IgnoreDeprecationWarningsMixin, SimpleTestCase):
self.assertEqual(list(reversed(self.d2)), [7, 0, 9, 1]) 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): def test_simple_mergedict(self):
d1 = {'chris': 'cool', 'camri': 'cute', 'cotton': 'adorable', d1 = {'chris': 'cool', 'camri': 'cute', 'cotton': 'adorable',

View File

@ -4,10 +4,11 @@ from __future__ import unicode_literals
from datetime import datetime from datetime import datetime
import os import os
from unittest import TestCase from unittest import TestCase
import warnings
from django.test import ignore_warnings
from django.utils import html, safestring from django.utils import html, safestring
from django.utils._os import upath from django.utils._os import upath
from django.utils.deprecation import RemovedInDjango20Warning
from django.utils.encoding import force_text from django.utils.encoding import force_text
@ -120,14 +121,13 @@ class TestUtilsHtml(TestCase):
for value, output in items: for value, output in items:
self.check_output(f, value, output) self.check_output(f, value, output)
@ignore_warnings(category=RemovedInDjango20Warning)
def test_strip_entities(self): def test_strip_entities(self):
f = html.strip_entities f = html.strip_entities
# Strings that should come out untouched. # Strings that should come out untouched.
values = ("&", "&a", "&a", "a&#a") values = ("&", "&a", "&a", "a&#a")
for value in values: for value in values:
with warnings.catch_warnings(record=True): self.check_output(f, value)
warnings.simplefilter("always")
self.check_output(f, value)
# Valid entities that should be stripped from the patterns. # Valid entities that should be stripped from the patterns.
entities = ("&#1;", "&#12;", "&a;", "&fdasdfasdfasdf;") entities = ("&#1;", "&#12;", "&a;", "&fdasdfasdfasdf;")
patterns = ( patterns = (
@ -138,9 +138,7 @@ class TestUtilsHtml(TestCase):
) )
for entity in entities: for entity in entities:
for in_pattern, output in patterns: for in_pattern, output in patterns:
with warnings.catch_warnings(record=True): self.check_output(f, in_pattern % {'entity': entity}, output)
warnings.simplefilter("always")
self.check_output(f, in_pattern % {'entity': entity}, output)
def test_escapejs(self): def test_escapejs(self):
f = html.escapejs f = html.escapejs
@ -154,6 +152,7 @@ class TestUtilsHtml(TestCase):
for value, output in items: for value, output in items:
self.check_output(f, value, output) self.check_output(f, value, output)
@ignore_warnings(category=RemovedInDjango20Warning)
def test_remove_tags(self): def test_remove_tags(self):
f = html.remove_tags f = html.remove_tags
items = ( items = (
@ -161,9 +160,7 @@ class TestUtilsHtml(TestCase):
("<a>x</a> <p><b>y</b></p>", "a b", "x <p>y</p>"), ("<a>x</a> <p><b>y</b></p>", "a b", "x <p>y</p>"),
) )
for value, tags, output in items: for value, tags, output in items:
with warnings.catch_warnings(record=True): self.assertEqual(f(value, tags), output)
warnings.simplefilter("always")
self.assertEqual(f(value, tags), output)
def test_smart_urlquote(self): def test_smart_urlquote(self):
quote = html.smart_urlquote quote = html.smart_urlquote

View File

@ -7,8 +7,8 @@ import warnings
from zipimport import zipimporter from zipimport import zipimporter
from django.core.exceptions import ImproperlyConfigured from django.core.exceptions import ImproperlyConfigured
from django.test import SimpleTestCase, modify_settings from django.test import SimpleTestCase, ignore_warnings, modify_settings
from django.test.utils import IgnoreDeprecationWarningsMixin, extend_sys_path from django.test.utils import extend_sys_path
from django.utils import six from django.utils import six
from django.utils.deprecation import RemovedInDjango19Warning from django.utils.deprecation import RemovedInDjango19Warning
from django.utils.module_loading import (autodiscover_modules, import_by_path, import_string, 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') 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): def test_import_by_path(self):
cls = import_by_path('django.utils.module_loading.import_by_path') cls = import_by_path('django.utils.module_loading.import_by_path')
self.assertEqual(cls, import_by_path) self.assertEqual(cls, import_by_path)

View File

@ -4,7 +4,7 @@ from __future__ import unicode_literals
from unittest import skipUnless from unittest import skipUnless
import warnings import warnings
from django.test import SimpleTestCase from django.test import SimpleTestCase, ignore_warnings
from django.test.utils import reset_warning_registry from django.test.utils import reset_warning_registry
from django.utils import six, text from django.utils import six, text
from django.utils.deprecation import RemovedInDjango19Warning from django.utils.deprecation import RemovedInDjango19Warning
@ -198,26 +198,24 @@ class TestUtilsText(SimpleTestCase):
filename = "^&'@{}[],$=!-#()%+~_123.txt" filename = "^&'@{}[],$=!-#()%+~_123.txt"
self.assertEqual(text.get_valid_filename(filename), "-_123.txt") self.assertEqual(text.get_valid_filename(filename), "-_123.txt")
@ignore_warnings(category=RemovedInDjango19Warning)
def test_javascript_quote(self): def test_javascript_quote(self):
input = "<script>alert('Hello \\xff.\n Welcome\there\r');</script>" input = "<script>alert('Hello \\xff.\n Welcome\there\r');</script>"
output = r"<script>alert(\'Hello \\xff.\n Welcome\there\r\');<\/script>" output = r"<script>alert(\'Hello \\xff.\n Welcome\there\r\');<\/script>"
with warnings.catch_warnings(): self.assertEqual(text.javascript_quote(input), output)
warnings.simplefilter("ignore", RemovedInDjango19Warning)
self.assertEqual(text.javascript_quote(input), output)
# Exercising quote_double_quotes keyword argument # Exercising quote_double_quotes keyword argument
input = '"Text"' input = '"Text"'
self.assertEqual(text.javascript_quote(input), '"Text"') self.assertEqual(text.javascript_quote(input), '"Text"')
self.assertEqual(text.javascript_quote(input, quote_double_quotes=True), self.assertEqual(text.javascript_quote(input, quote_double_quotes=True),
'&quot;Text&quot;') '&quot;Text&quot;')
@ignore_warnings(category=RemovedInDjango19Warning)
@skipUnless(IS_WIDE_BUILD, 'Not running in a wide build of Python') @skipUnless(IS_WIDE_BUILD, 'Not running in a wide build of Python')
def test_javascript_quote_unicode(self): def test_javascript_quote_unicode(self):
input = "<script>alert('Hello \\xff.\n Wel𝕃come\there\r');</script>" input = "<script>alert('Hello \\xff.\n Wel𝕃come\there\r');</script>"
output = r"<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(): self.assertEqual(text.javascript_quote(input), output)
warnings.simplefilter("ignore", RemovedInDjango19Warning)
self.assertEqual(text.javascript_quote(input), output)
def test_deprecation(self): def test_deprecation(self):
reset_warning_registry() reset_warning_registry()

View File

@ -6,7 +6,7 @@ import time
import unittest import unittest
import warnings import warnings
from django.test.utils import IgnoreDeprecationWarningsMixin from django.test import ignore_warnings
from django.utils.deprecation import RemovedInDjango19Warning from django.utils.deprecation import RemovedInDjango19Warning
@ -16,7 +16,8 @@ with warnings.catch_warnings():
from django.utils.tzinfo import FixedOffset, LocalTimezone from django.utils.tzinfo import FixedOffset, LocalTimezone
class TzinfoTests(IgnoreDeprecationWarningsMixin, unittest.TestCase): @ignore_warnings(category=RemovedInDjango19Warning)
class TzinfoTests(unittest.TestCase):
@classmethod @classmethod
def setUpClass(cls): def setUpClass(cls):