Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

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

  • Loading branch information...
commit 10cf3c64273db407402ea9723569dfc8d059e186 1 parent e9a5660
Claude Paroz claudep authored
27 django/contrib/formtools/tests/__init__.py
View
@@ -7,16 +7,12 @@
from django.contrib.formtools import preview, utils
from django.contrib.formtools.wizard import FormWizard
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.utils import unittest
from django.contrib.formtools.tests.wizard import *
from django.contrib.formtools.tests.forms import *
-warnings.filterwarnings('ignore', category=PendingDeprecationWarning,
- module='django.contrib.formtools.wizard')
-
success_string = "Done was called!"
class TestFormPreview(preview.FormPreview):
@@ -41,20 +37,12 @@ class PreviewTests(TestCase):
def setUp(self):
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
self.preview = preview.FormPreview(TestForm)
input_template = '<input type="hidden" name="%s" value="%s" />'
self.input = input_template % (self.preview.unused_name('stage'), "%d")
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):
"""
Verifies name mangling to get uniue field name.
@@ -130,8 +118,9 @@ def test_bool_submit(self):
self.test_data.update({'stage':2})
hash = self.preview.security_hash(None, TestForm(self.test_data))
self.test_data.update({'hash':hash, 'bool1':u'False'})
- response = self.client.post('/preview/', self.test_data)
- self.assertEqual(response.content, success_string)
+ with warnings.catch_warnings(record=True):
+ response = self.client.post('/preview/', self.test_data)
+ self.assertEqual(response.content, success_string)
def test_form_submit_good_hash(self):
"""
@@ -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):
"""
step should be zero for the first form
23 django/contrib/sessions/tests.py
View
@@ -12,11 +12,10 @@
from django.contrib.sessions.backends.signed_cookies import SessionStore as CookieSession
from django.contrib.sessions.models import Session
from django.contrib.sessions.middleware import SessionMiddleware
-from django.core.cache.backends.base import CacheKeyWarning
from django.core.exceptions import ImproperlyConfigured, SuspiciousOperation
from django.http import HttpResponse
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 unittest
@@ -302,12 +301,10 @@ def test_exists_searches_cache_first(self):
self.assertTrue(self.session.exists(self.session.session_key))
def test_load_overlong_key(self):
- warnings_state = get_warnings_state()
- warnings.filterwarnings('ignore',
- category=CacheKeyWarning)
- self.session._session_key = (string.ascii_letters + string.digits) * 20
- self.assertEqual(self.session.load(), {})
- restore_warnings_state(warnings_state)
+ with warnings.catch_warnings(record=True) as w:
+ self.session._session_key = (string.ascii_letters + string.digits) * 20
+ self.assertEqual(self.session.load(), {})
+ self.assertEqual(len(w), 1)
@override_settings(USE_TZ=True)
@@ -353,12 +350,10 @@ class CacheSessionTests(SessionTestsMixin, unittest.TestCase):
backend = CacheSession
def test_load_overlong_key(self):
- warnings_state = get_warnings_state()
- warnings.filterwarnings('ignore',
- category=CacheKeyWarning)
- self.session._session_key = (string.ascii_letters + string.digits) * 20
- self.assertEqual(self.session.load(), {})
- restore_warnings_state(warnings_state)
+ with warnings.catch_warnings(record=True) as w:
+ self.session._session_key = (string.ascii_letters + string.digits) * 20
+ self.assertEqual(self.session.load(), {})
+ self.assertEqual(len(w), 1)
class SessionMiddlewareTests(unittest.TestCase):
24 tests/regressiontests/cache/tests.py
View
@@ -466,20 +466,19 @@ def func(key, *args):
old_func = self.cache.key_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:
- # memcached does not allow whitespace or control characters in keys
- self.assertRaises(CacheKeyWarning, self.cache.set, 'key with spaces', 'value')
- # memcached limits key length to 250
- self.assertRaises(CacheKeyWarning, self.cache.set, 'a' * 251, 'value')
+ with warnings.catch_warnings(record=True) as w:
+ # memcached does not allow whitespace or control characters in keys
+ 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
+ self.cache.set('a' * 251, 'value')
+ self.assertEqual(len(w), 1)
+ self.assertTrue(isinstance(w[0].message, CacheKeyWarning))
finally:
- restore_warnings_state(_warnings_state)
self.cache.key_func = old_func
def test_cache_versioning_get_set(self):
@@ -1450,7 +1449,8 @@ def setUp(self):
self.default_cache = get_cache('default')
self.other_cache = get_cache('other')
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):
self.restore_warnings_state()
27 tests/regressiontests/decorators/tests.py
View
@@ -5,7 +5,6 @@
from django.contrib.auth.decorators import login_required, permission_required, user_passes_test
from django.http import HttpResponse, HttpRequest, HttpResponseNotAllowed
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.functional import allow_lazy, lazy, memoize
from django.utils.unittest import TestCase
@@ -68,14 +67,6 @@ def _inner(*args, **kwargs):
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):
"""
Tests that django decorators set certain attributes of the wrapped
@@ -131,14 +122,16 @@ def test_cache_page_old_style(self):
"""
def my_view(request):
return "response"
- my_view_cached = cache_page(my_view, 123)
- self.assertEqual(my_view_cached(HttpRequest()), "response")
- my_view_cached2 = cache_page(my_view, 123, key_prefix="test")
- self.assertEqual(my_view_cached2(HttpRequest()), "response")
- my_view_cached3 = cache_page(my_view)
- self.assertEqual(my_view_cached3(HttpRequest()), "response")
- my_view_cached4 = cache_page()(my_view)
- self.assertEqual(my_view_cached4(HttpRequest()), "response")
+ with warnings.catch_warnings(record=True) as w:
+ my_view_cached = cache_page(my_view, 123)
+ self.assertEqual(my_view_cached(HttpRequest()), "response")
+ my_view_cached2 = cache_page(my_view, 123, key_prefix="test")
+ self.assertEqual(my_view_cached2(HttpRequest()), "response")
+ my_view_cached3 = cache_page(my_view)
+ self.assertEqual(my_view_cached3(HttpRequest()), "response")
+ my_view_cached4 = cache_page()(my_view)
+ self.assertEqual(my_view_cached4(HttpRequest()), "response")
+ self.assertEqual(len(w), 4)
def test_require_safe_accepts_only_safe_methods(self):
"""
1  tests/regressiontests/forms/tests/fields.py
View
@@ -28,7 +28,6 @@
import pickle
import re
import os
-import warnings
from decimal import Decimal
from django.core.files.uploadedfile import SimpleUploadedFile
8 tests/regressiontests/generic_views/dates.py
View
@@ -10,14 +10,6 @@
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):
fixtures = ['generic-views-test-data.json']
urls = 'regressiontests.generic_views.urls'
1  tests/regressiontests/i18n/patterns/tests.py
View
@@ -1,5 +1,4 @@
import os
-import warnings
from django.core.exceptions import ImproperlyConfigured
from django.core.urlresolvers import reverse, clear_url_caches
12 tests/regressiontests/logging_tests/tests.py
View
@@ -4,7 +4,7 @@
from django.conf import compat_patch_logging_config
from django.core import mail
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
@@ -42,12 +42,9 @@ def test_filter_added(self):
"""
config = copy.deepcopy(OLD_LOGGING)
- warnings_state = get_warnings_state()
- warnings.filterwarnings('ignore', category=DeprecationWarning, module='django.conf')
- try:
+ with warnings.catch_warnings(record=True) as w:
compat_patch_logging_config(config)
- finally:
- restore_warnings_state(warnings_state)
+ self.assertEqual(len(w), 1)
self.assertEqual(
config["handlers"]["mail_admins"]["filters"],
@@ -60,7 +57,8 @@ def test_filter_configuration(self):
"""
config = copy.deepcopy(OLD_LOGGING)
- compat_patch_logging_config(config)
+ with warnings.catch_warnings(record=True):
+ compat_patch_logging_config(config)
flt = config["filters"]["require_debug_false"]
self.assertEqual(flt["()"], "django.utils.log.RequireDebugFalse")
16 tests/regressiontests/requests/tests.py
View
@@ -6,7 +6,6 @@
from django.conf import settings
from django.core.handlers.wsgi import WSGIRequest, LimitedStream
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.http import cookie_date
from django.utils.timezone import utc
@@ -398,13 +397,9 @@ def test_raw_post_data_returns_body(self):
'wsgi.input': StringIO(payload)
})
- warnings_state = get_warnings_state()
- warnings.filterwarnings('ignore', category=DeprecationWarning, module='django.http')
- try:
+ with warnings.catch_warnings(record=True) as w:
self.assertEqual(request.body, request.raw_post_data)
- finally:
- restore_warnings_state(warnings_state)
-
+ self.assertEqual(len(w), 1)
def test_POST_connection_error(self):
"""
@@ -420,10 +415,7 @@ def read(self, len=0):
'CONTENT_LENGTH': len(payload),
'wsgi.input': ExplodingStringIO(payload)})
- warnings_state = get_warnings_state()
- warnings.filterwarnings('ignore', category=DeprecationWarning, module='django.http')
- try:
+ with warnings.catch_warnings(record=True) as w:
with self.assertRaises(UnreadablePostError):
request.raw_post_data
- finally:
- restore_warnings_state(warnings_state)
+ self.assertEqual(len(w), 1)
4 tests/regressiontests/staticfiles_tests/tests.py
View
@@ -6,7 +6,6 @@
import shutil
import sys
import tempfile
-import warnings
from StringIO import StringIO
from django.template import loader, Context
@@ -511,11 +510,8 @@ def test_cache_key_memcache_validation(self):
"""
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)
- self.save_warnings_state()
cache_validator = BaseCache({})
- warnings.filterwarnings('error', category=CacheKeyWarning)
cache_validator.validate_key(cache_key)
- self.restore_warnings_state()
self.assertEqual(cache_key, 'staticfiles:e95bbc36387084582df2a70750d7b351')
1  tests/regressiontests/test_client_regress/views.py
View
@@ -1,5 +1,4 @@
import json
-import warnings
from django.conf import settings
from django.contrib.auth.decorators import login_required
39 tests/regressiontests/utils/text.py
View
@@ -8,13 +8,6 @@ class TestUtilsText(SimpleTestCase):
# In Django 1.6 truncate_words() and truncate_html_words() will be removed
# 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):
truncator = text.Truncator(
u'The quick brown fox jumped over the lazy dog.'
@@ -79,22 +72,26 @@ def test_truncate_html_words(self):
'id="mylink">brown...</a></p>', truncator.words(3, '...', html=True))
def test_old_truncate_words(self):
- 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))
- self.assertEqual(u'The quick brown fox ...',
- text.truncate_words('The quick brown fox jumped over the lazy dog.', 4))
- self.assertEqual(u'The quick brown fox ....',
- text.truncate_words('The quick brown fox jumped over the lazy dog.', 4, '....'))
+ with warnings.catch_warnings(record=True) as w:
+ 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))
+ self.assertEqual(u'The quick brown fox ...',
+ text.truncate_words('The quick brown fox jumped over the lazy dog.', 4))
+ self.assertEqual(u'The quick brown fox ....',
+ 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):
- 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))
- 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))
- 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, '....'))
- 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))
+ 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>',
+ 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>',
+ 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>',
+ 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>',
+ 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):
digits = '1234 67 9'
Please sign in to comment.
Something went wrong with that request. Please try again.