Used catch_warnings instead of save/restore methods. Refs #17049.

This commit is contained in:
Claude Paroz 2012-05-03 18:19:18 +02:00
parent e9a56606e7
commit 10cf3c6427
12 changed files with 71 additions and 112 deletions

View File

@ -7,16 +7,12 @@ from django.conf import settings
from django.contrib.formtools import preview, utils from django.contrib.formtools import preview, utils
from django.contrib.formtools.wizard import FormWizard from django.contrib.formtools.wizard import FormWizard
from django.test import TestCase from django.test import TestCase
from django.test.utils import get_warnings_state, restore_warnings_state
from django.test.utils import override_settings from django.test.utils import override_settings
from django.utils import unittest from django.utils import unittest
from django.contrib.formtools.tests.wizard import * from django.contrib.formtools.tests.wizard import *
from django.contrib.formtools.tests.forms import * from django.contrib.formtools.tests.forms import *
warnings.filterwarnings('ignore', category=PendingDeprecationWarning,
module='django.contrib.formtools.wizard')
success_string = "Done was called!" success_string = "Done was called!"
class TestFormPreview(preview.FormPreview): class TestFormPreview(preview.FormPreview):
@ -41,20 +37,12 @@ class PreviewTests(TestCase):
def setUp(self): def setUp(self):
super(PreviewTests, self).setUp() super(PreviewTests, self).setUp()
self.save_warnings_state()
warnings.filterwarnings('ignore', category=DeprecationWarning,
module='django.contrib.formtools.wizard.legacy')
# Create a FormPreview instance to share between tests # Create a FormPreview instance to share between tests
self.preview = preview.FormPreview(TestForm) self.preview = preview.FormPreview(TestForm)
input_template = '<input type="hidden" name="%s" value="%s" />' input_template = '<input type="hidden" name="%s" value="%s" />'
self.input = input_template % (self.preview.unused_name('stage'), "%d") self.input = input_template % (self.preview.unused_name('stage'), "%d")
self.test_data = {'field1':u'foo', 'field1_':u'asdf'} self.test_data = {'field1':u'foo', 'field1_':u'asdf'}
def tearDown(self):
super(PreviewTests, self).tearDown()
self.restore_warnings_state()
def test_unused_name(self): def test_unused_name(self):
""" """
Verifies name mangling to get uniue field name. Verifies name mangling to get uniue field name.
@ -130,6 +118,7 @@ class PreviewTests(TestCase):
self.test_data.update({'stage':2}) self.test_data.update({'stage':2})
hash = self.preview.security_hash(None, TestForm(self.test_data)) hash = self.preview.security_hash(None, TestForm(self.test_data))
self.test_data.update({'hash':hash, 'bool1':u'False'}) self.test_data.update({'hash':hash, 'bool1':u'False'})
with warnings.catch_warnings(record=True):
response = self.client.post('/preview/', self.test_data) response = self.client.post('/preview/', self.test_data)
self.assertEqual(response.content, success_string) self.assertEqual(response.content, success_string)
@ -241,6 +230,16 @@ class WizardTests(TestCase):
} }
) )
def setUp(self):
super(WizardTests, self).setUp()
self.save_warnings_state()
warnings.filterwarnings('ignore', category=DeprecationWarning,
module='django.contrib.formtools.wizard')
def tearDown(self):
super(WizardTests, self).tearDown()
self.restore_warnings_state()
def test_step_starts_at_zero(self): def test_step_starts_at_zero(self):
""" """
step should be zero for the first form step should be zero for the first form

View File

@ -12,11 +12,10 @@ from django.contrib.sessions.backends.file import SessionStore as FileSession
from django.contrib.sessions.backends.signed_cookies import SessionStore as CookieSession from django.contrib.sessions.backends.signed_cookies import SessionStore as CookieSession
from django.contrib.sessions.models import Session from django.contrib.sessions.models import Session
from django.contrib.sessions.middleware import SessionMiddleware from django.contrib.sessions.middleware import SessionMiddleware
from django.core.cache.backends.base import CacheKeyWarning
from django.core.exceptions import ImproperlyConfigured, SuspiciousOperation from django.core.exceptions import ImproperlyConfigured, SuspiciousOperation
from django.http import HttpResponse from django.http import HttpResponse
from django.test import TestCase, RequestFactory from django.test import TestCase, RequestFactory
from django.test.utils import override_settings, get_warnings_state, restore_warnings_state from django.test.utils import override_settings
from django.utils import timezone from django.utils import timezone
from django.utils import unittest from django.utils import unittest
@ -302,12 +301,10 @@ class CacheDBSessionTests(SessionTestsMixin, TestCase):
self.assertTrue(self.session.exists(self.session.session_key)) self.assertTrue(self.session.exists(self.session.session_key))
def test_load_overlong_key(self): def test_load_overlong_key(self):
warnings_state = get_warnings_state() with warnings.catch_warnings(record=True) as w:
warnings.filterwarnings('ignore',
category=CacheKeyWarning)
self.session._session_key = (string.ascii_letters + string.digits) * 20 self.session._session_key = (string.ascii_letters + string.digits) * 20
self.assertEqual(self.session.load(), {}) self.assertEqual(self.session.load(), {})
restore_warnings_state(warnings_state) self.assertEqual(len(w), 1)
@override_settings(USE_TZ=True) @override_settings(USE_TZ=True)
@ -353,12 +350,10 @@ class CacheSessionTests(SessionTestsMixin, unittest.TestCase):
backend = CacheSession backend = CacheSession
def test_load_overlong_key(self): def test_load_overlong_key(self):
warnings_state = get_warnings_state() with warnings.catch_warnings(record=True) as w:
warnings.filterwarnings('ignore',
category=CacheKeyWarning)
self.session._session_key = (string.ascii_letters + string.digits) * 20 self.session._session_key = (string.ascii_letters + string.digits) * 20
self.assertEqual(self.session.load(), {}) self.assertEqual(self.session.load(), {})
restore_warnings_state(warnings_state) self.assertEqual(len(w), 1)
class SessionMiddlewareTests(unittest.TestCase): class SessionMiddlewareTests(unittest.TestCase):

View File

@ -466,20 +466,19 @@ class BaseCacheTests(object):
old_func = self.cache.key_func old_func = self.cache.key_func
self.cache.key_func = func self.cache.key_func = func
# On Python 2.6+ we could use the catch_warnings context
# manager to test this warning nicely. Since we can't do that
# yet, the cleanest option is to temporarily ask for
# CacheKeyWarning to be raised as an exception.
_warnings_state = get_warnings_state()
warnings.simplefilter("error", CacheKeyWarning)
try: try:
with warnings.catch_warnings(record=True) as w:
# memcached does not allow whitespace or control characters in keys # memcached does not allow whitespace or control characters in keys
self.assertRaises(CacheKeyWarning, self.cache.set, 'key with spaces', 'value') self.cache.set('key with spaces', 'value')
self.assertEqual(len(w), 2)
self.assertTrue(isinstance(w[0].message, CacheKeyWarning))
with warnings.catch_warnings(record=True) as w:
# memcached limits key length to 250 # memcached limits key length to 250
self.assertRaises(CacheKeyWarning, self.cache.set, 'a' * 251, 'value') self.cache.set('a' * 251, 'value')
self.assertEqual(len(w), 1)
self.assertTrue(isinstance(w[0].message, CacheKeyWarning))
finally: finally:
restore_warnings_state(_warnings_state)
self.cache.key_func = old_func self.cache.key_func = old_func
def test_cache_versioning_get_set(self): def test_cache_versioning_get_set(self):
@ -1450,7 +1449,8 @@ class CacheMiddlewareTest(TestCase):
self.default_cache = get_cache('default') self.default_cache = get_cache('default')
self.other_cache = get_cache('other') self.other_cache = get_cache('other')
self.save_warnings_state() self.save_warnings_state()
warnings.filterwarnings('ignore', category=DeprecationWarning, module='django.views.decorators.cache') warnings.filterwarnings('ignore', category=DeprecationWarning,
module='django.views.decorators.cache')
def tearDown(self): def tearDown(self):
self.restore_warnings_state() self.restore_warnings_state()

View File

@ -5,7 +5,6 @@ from django.contrib.admin.views.decorators import staff_member_required
from django.contrib.auth.decorators import login_required, permission_required, user_passes_test from django.contrib.auth.decorators import login_required, permission_required, user_passes_test
from django.http import HttpResponse, HttpRequest, HttpResponseNotAllowed from django.http import HttpResponse, HttpRequest, HttpResponseNotAllowed
from django.middleware.clickjacking import XFrameOptionsMiddleware from django.middleware.clickjacking import XFrameOptionsMiddleware
from django.test.utils import get_warnings_state, restore_warnings_state
from django.utils.decorators import method_decorator from django.utils.decorators import method_decorator
from django.utils.functional import allow_lazy, lazy, memoize from django.utils.functional import allow_lazy, lazy, memoize
from django.utils.unittest import TestCase from django.utils.unittest import TestCase
@ -68,14 +67,6 @@ fully_decorated = full_decorator(fully_decorated)
class DecoratorsTest(TestCase): class DecoratorsTest(TestCase):
def setUp(self):
self.warning_state = get_warnings_state()
warnings.filterwarnings('ignore', category=DeprecationWarning,
module='django.views.decorators.cache')
def tearDown(self):
restore_warnings_state(self.warning_state)
def test_attributes(self): def test_attributes(self):
""" """
Tests that django decorators set certain attributes of the wrapped Tests that django decorators set certain attributes of the wrapped
@ -131,6 +122,7 @@ class DecoratorsTest(TestCase):
""" """
def my_view(request): def my_view(request):
return "response" return "response"
with warnings.catch_warnings(record=True) as w:
my_view_cached = cache_page(my_view, 123) my_view_cached = cache_page(my_view, 123)
self.assertEqual(my_view_cached(HttpRequest()), "response") self.assertEqual(my_view_cached(HttpRequest()), "response")
my_view_cached2 = cache_page(my_view, 123, key_prefix="test") my_view_cached2 = cache_page(my_view, 123, key_prefix="test")
@ -139,6 +131,7 @@ class DecoratorsTest(TestCase):
self.assertEqual(my_view_cached3(HttpRequest()), "response") self.assertEqual(my_view_cached3(HttpRequest()), "response")
my_view_cached4 = cache_page()(my_view) my_view_cached4 = cache_page()(my_view)
self.assertEqual(my_view_cached4(HttpRequest()), "response") self.assertEqual(my_view_cached4(HttpRequest()), "response")
self.assertEqual(len(w), 4)
def test_require_safe_accepts_only_safe_methods(self): def test_require_safe_accepts_only_safe_methods(self):
""" """

View File

@ -28,7 +28,6 @@ import datetime
import pickle import pickle
import re import re
import os import os
import warnings
from decimal import Decimal from decimal import Decimal
from django.core.files.uploadedfile import SimpleUploadedFile from django.core.files.uploadedfile import SimpleUploadedFile

View File

@ -10,14 +10,6 @@ from django.utils import timezone
from .models import Book, BookSigning from .models import Book, BookSigning
import warnings
warnings.filterwarnings(
'error', r"DateTimeField received a naive datetime",
RuntimeWarning, r'django\.db\.models\.fields')
class ArchiveIndexViewTests(TestCase): class ArchiveIndexViewTests(TestCase):
fixtures = ['generic-views-test-data.json'] fixtures = ['generic-views-test-data.json']
urls = 'regressiontests.generic_views.urls' urls = 'regressiontests.generic_views.urls'

View File

@ -1,5 +1,4 @@
import os import os
import warnings
from django.core.exceptions import ImproperlyConfigured from django.core.exceptions import ImproperlyConfigured
from django.core.urlresolvers import reverse, clear_url_caches from django.core.urlresolvers import reverse, clear_url_caches

View File

@ -4,7 +4,7 @@ import warnings
from django.conf import compat_patch_logging_config from django.conf import compat_patch_logging_config
from django.core import mail from django.core import mail
from django.test import TestCase, RequestFactory from django.test import TestCase, RequestFactory
from django.test.utils import override_settings, get_warnings_state, restore_warnings_state from django.test.utils import override_settings
from django.utils.log import CallbackFilter, RequireDebugFalse, getLogger from django.utils.log import CallbackFilter, RequireDebugFalse, getLogger
@ -42,12 +42,9 @@ class PatchLoggingConfigTest(TestCase):
""" """
config = copy.deepcopy(OLD_LOGGING) config = copy.deepcopy(OLD_LOGGING)
warnings_state = get_warnings_state() with warnings.catch_warnings(record=True) as w:
warnings.filterwarnings('ignore', category=DeprecationWarning, module='django.conf')
try:
compat_patch_logging_config(config) compat_patch_logging_config(config)
finally: self.assertEqual(len(w), 1)
restore_warnings_state(warnings_state)
self.assertEqual( self.assertEqual(
config["handlers"]["mail_admins"]["filters"], config["handlers"]["mail_admins"]["filters"],
@ -60,6 +57,7 @@ class PatchLoggingConfigTest(TestCase):
""" """
config = copy.deepcopy(OLD_LOGGING) config = copy.deepcopy(OLD_LOGGING)
with warnings.catch_warnings(record=True):
compat_patch_logging_config(config) compat_patch_logging_config(config)
flt = config["filters"]["require_debug_false"] flt = config["filters"]["require_debug_false"]

View File

@ -6,7 +6,6 @@ from StringIO import StringIO
from django.conf import settings from django.conf import settings
from django.core.handlers.wsgi import WSGIRequest, LimitedStream from django.core.handlers.wsgi import WSGIRequest, LimitedStream
from django.http import HttpRequest, HttpResponse, parse_cookie, build_request_repr, UnreadablePostError from django.http import HttpRequest, HttpResponse, parse_cookie, build_request_repr, UnreadablePostError
from django.test.utils import get_warnings_state, restore_warnings_state
from django.utils import unittest from django.utils import unittest
from django.utils.http import cookie_date from django.utils.http import cookie_date
from django.utils.timezone import utc from django.utils.timezone import utc
@ -398,13 +397,9 @@ class RequestsTests(unittest.TestCase):
'wsgi.input': StringIO(payload) 'wsgi.input': StringIO(payload)
}) })
warnings_state = get_warnings_state() with warnings.catch_warnings(record=True) as w:
warnings.filterwarnings('ignore', category=DeprecationWarning, module='django.http')
try:
self.assertEqual(request.body, request.raw_post_data) self.assertEqual(request.body, request.raw_post_data)
finally: self.assertEqual(len(w), 1)
restore_warnings_state(warnings_state)
def test_POST_connection_error(self): def test_POST_connection_error(self):
""" """
@ -420,10 +415,7 @@ class RequestsTests(unittest.TestCase):
'CONTENT_LENGTH': len(payload), 'CONTENT_LENGTH': len(payload),
'wsgi.input': ExplodingStringIO(payload)}) 'wsgi.input': ExplodingStringIO(payload)})
warnings_state = get_warnings_state() with warnings.catch_warnings(record=True) as w:
warnings.filterwarnings('ignore', category=DeprecationWarning, module='django.http')
try:
with self.assertRaises(UnreadablePostError): with self.assertRaises(UnreadablePostError):
request.raw_post_data request.raw_post_data
finally: self.assertEqual(len(w), 1)
restore_warnings_state(warnings_state)

View File

@ -6,7 +6,6 @@ import posixpath
import shutil import shutil
import sys import sys
import tempfile import tempfile
import warnings
from StringIO import StringIO from StringIO import StringIO
from django.template import loader, Context from django.template import loader, Context
@ -511,11 +510,8 @@ class TestCollectionCachedStorage(BaseCollectionTestCase,
""" """
name = "/some crazy/long filename/ with spaces Here and ?#%#$/other/stuff/some crazy/long filename/ with spaces Here and ?#%#$/other/stuff/some crazy/long filename/ with spaces Here and ?#%#$/other/stuff/some crazy/long filename/ with spaces Here and ?#%#$/other/stuff/some crazy/long filename/ with spaces Here and ?#%#$/other/stuff/some crazy/" + chr(22) + chr(180) name = "/some crazy/long filename/ with spaces Here and ?#%#$/other/stuff/some crazy/long filename/ with spaces Here and ?#%#$/other/stuff/some crazy/long filename/ with spaces Here and ?#%#$/other/stuff/some crazy/long filename/ with spaces Here and ?#%#$/other/stuff/some crazy/long filename/ with spaces Here and ?#%#$/other/stuff/some crazy/" + chr(22) + chr(180)
cache_key = storage.staticfiles_storage.cache_key(name) cache_key = storage.staticfiles_storage.cache_key(name)
self.save_warnings_state()
cache_validator = BaseCache({}) cache_validator = BaseCache({})
warnings.filterwarnings('error', category=CacheKeyWarning)
cache_validator.validate_key(cache_key) cache_validator.validate_key(cache_key)
self.restore_warnings_state()
self.assertEqual(cache_key, 'staticfiles:e95bbc36387084582df2a70750d7b351') self.assertEqual(cache_key, 'staticfiles:e95bbc36387084582df2a70750d7b351')

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

View File

@ -8,13 +8,6 @@ class TestUtilsText(SimpleTestCase):
# In Django 1.6 truncate_words() and truncate_html_words() will be removed # In Django 1.6 truncate_words() and truncate_html_words() will be removed
# so these tests will need to be adapted accordingly # so these tests will need to be adapted accordingly
def setUp(self):
self.save_warnings_state()
warnings.filterwarnings('ignore', category=DeprecationWarning, module='django.utils.text')
def tearDown(self):
self.restore_warnings_state()
def test_truncate_chars(self): def test_truncate_chars(self):
truncator = text.Truncator( truncator = text.Truncator(
u'The quick brown fox jumped over the lazy dog.' u'The quick brown fox jumped over the lazy dog.'
@ -79,14 +72,17 @@ class TestUtilsText(SimpleTestCase):
'id="mylink">brown...</a></p>', truncator.words(3, '...', html=True)) 'id="mylink">brown...</a></p>', truncator.words(3, '...', html=True))
def test_old_truncate_words(self): def test_old_truncate_words(self):
with warnings.catch_warnings(record=True) as w:
self.assertEqual(u'The quick brown fox jumped over the lazy dog.', self.assertEqual(u'The quick brown fox jumped over the lazy dog.',
text.truncate_words(u'The quick brown fox jumped over the lazy dog.', 10)) text.truncate_words(u'The quick brown fox jumped over the lazy dog.', 10))
self.assertEqual(u'The quick brown fox ...', self.assertEqual(u'The quick brown fox ...',
text.truncate_words('The quick brown fox jumped over the lazy dog.', 4)) text.truncate_words('The quick brown fox jumped over the lazy dog.', 4))
self.assertEqual(u'The quick brown fox ....', self.assertEqual(u'The quick brown fox ....',
text.truncate_words('The quick brown fox jumped over the lazy dog.', 4, '....')) text.truncate_words('The quick brown fox jumped over the lazy dog.', 4, '....'))
self.assertEqual(len(w), 3)
def test_old_truncate_html_words(self): def test_old_truncate_html_words(self):
with warnings.catch_warnings(record=True) as w:
self.assertEqual(u'<p><strong><em>The quick brown fox jumped over the lazy dog.</em></strong></p>', self.assertEqual(u'<p><strong><em>The quick brown fox jumped over the lazy dog.</em></strong></p>',
text.truncate_html_words('<p><strong><em>The quick brown fox jumped over the lazy dog.</em></strong></p>', 10)) text.truncate_html_words('<p><strong><em>The quick brown fox jumped over the lazy dog.</em></strong></p>', 10))
self.assertEqual(u'<p><strong><em>The quick brown fox ...</em></strong></p>', self.assertEqual(u'<p><strong><em>The quick brown fox ...</em></strong></p>',
@ -95,6 +91,7 @@ class TestUtilsText(SimpleTestCase):
text.truncate_html_words('<p><strong><em>The quick brown fox jumped over the lazy dog.</em></strong></p>', 4, '....')) text.truncate_html_words('<p><strong><em>The quick brown fox jumped over the lazy dog.</em></strong></p>', 4, '....'))
self.assertEqual(u'<p><strong><em>The quick brown fox</em></strong></p>', self.assertEqual(u'<p><strong><em>The quick brown fox</em></strong></p>',
text.truncate_html_words('<p><strong><em>The quick brown fox jumped over the lazy dog.</em></strong></p>', 4, None)) text.truncate_html_words('<p><strong><em>The quick brown fox jumped over the lazy dog.</em></strong></p>', 4, None))
self.assertEqual(len(w), 4)
def test_wrap(self): def test_wrap(self):
digits = '1234 67 9' digits = '1234 67 9'