Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

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

  • Loading branch information...
commit 10cf3c64273db407402ea9723569dfc8d059e186 1 parent e9a5660
Claude Paroz authored May 03, 2012
27  django/contrib/formtools/tests/__init__.py
@@ -7,16 +7,12 @@
7 7
 from django.contrib.formtools import preview, utils
8 8
 from django.contrib.formtools.wizard import FormWizard
9 9
 from django.test import TestCase
10  
-from django.test.utils import get_warnings_state, restore_warnings_state
11 10
 from django.test.utils import override_settings
12 11
 from django.utils import unittest
13 12
 
14 13
 from django.contrib.formtools.tests.wizard import *
15 14
 from django.contrib.formtools.tests.forms import *
16 15
 
17  
-warnings.filterwarnings('ignore', category=PendingDeprecationWarning,
18  
-                        module='django.contrib.formtools.wizard')
19  
-
20 16
 success_string = "Done was called!"
21 17
 
22 18
 class TestFormPreview(preview.FormPreview):
@@ -41,20 +37,12 @@ class PreviewTests(TestCase):
41 37
 
42 38
     def setUp(self):
43 39
         super(PreviewTests, self).setUp()
44  
-        self.save_warnings_state()
45  
-        warnings.filterwarnings('ignore', category=DeprecationWarning,
46  
-                                module='django.contrib.formtools.wizard.legacy')
47  
-
48 40
         # Create a FormPreview instance to share between tests
49 41
         self.preview = preview.FormPreview(TestForm)
50 42
         input_template = '<input type="hidden" name="%s" value="%s" />'
51 43
         self.input = input_template % (self.preview.unused_name('stage'), "%d")
52 44
         self.test_data = {'field1':u'foo', 'field1_':u'asdf'}
53 45
 
54  
-    def tearDown(self):
55  
-        super(PreviewTests, self).tearDown()
56  
-        self.restore_warnings_state()
57  
-
58 46
     def test_unused_name(self):
59 47
         """
60 48
         Verifies name mangling to get uniue field name.
@@ -130,8 +118,9 @@ def test_bool_submit(self):
130 118
         self.test_data.update({'stage':2})
131 119
         hash = self.preview.security_hash(None, TestForm(self.test_data))
132 120
         self.test_data.update({'hash':hash, 'bool1':u'False'})
133  
-        response = self.client.post('/preview/', self.test_data)
134  
-        self.assertEqual(response.content, success_string)
  121
+        with warnings.catch_warnings(record=True):
  122
+            response = self.client.post('/preview/', self.test_data)
  123
+            self.assertEqual(response.content, success_string)
135 124
 
136 125
     def test_form_submit_good_hash(self):
137 126
         """
@@ -241,6 +230,16 @@ class WizardTests(TestCase):
241 230
         }
242 231
     )
243 232
 
  233
+    def setUp(self):
  234
+        super(WizardTests, self).setUp()
  235
+        self.save_warnings_state()
  236
+        warnings.filterwarnings('ignore', category=DeprecationWarning,
  237
+                                module='django.contrib.formtools.wizard')
  238
+
  239
+    def tearDown(self):
  240
+        super(WizardTests, self).tearDown()
  241
+        self.restore_warnings_state()
  242
+
244 243
     def test_step_starts_at_zero(self):
245 244
         """
246 245
         step should be zero for the first form
23  django/contrib/sessions/tests.py
@@ -12,11 +12,10 @@
12 12
 from django.contrib.sessions.backends.signed_cookies import SessionStore as CookieSession
13 13
 from django.contrib.sessions.models import Session
14 14
 from django.contrib.sessions.middleware import SessionMiddleware
15  
-from django.core.cache.backends.base import CacheKeyWarning
16 15
 from django.core.exceptions import ImproperlyConfigured, SuspiciousOperation
17 16
 from django.http import HttpResponse
18 17
 from django.test import TestCase, RequestFactory
19  
-from django.test.utils import override_settings, get_warnings_state, restore_warnings_state
  18
+from django.test.utils import override_settings
20 19
 from django.utils import timezone
21 20
 from django.utils import unittest
22 21
 
@@ -302,12 +301,10 @@ def test_exists_searches_cache_first(self):
302 301
             self.assertTrue(self.session.exists(self.session.session_key))
303 302
 
304 303
     def test_load_overlong_key(self):
305  
-        warnings_state = get_warnings_state()
306  
-        warnings.filterwarnings('ignore',
307  
-                                category=CacheKeyWarning)
308  
-        self.session._session_key = (string.ascii_letters + string.digits) * 20
309  
-        self.assertEqual(self.session.load(), {})
310  
-        restore_warnings_state(warnings_state)
  304
+        with warnings.catch_warnings(record=True) as w:
  305
+            self.session._session_key = (string.ascii_letters + string.digits) * 20
  306
+            self.assertEqual(self.session.load(), {})
  307
+            self.assertEqual(len(w), 1)
311 308
 
312 309
 
313 310
 @override_settings(USE_TZ=True)
@@ -353,12 +350,10 @@ class CacheSessionTests(SessionTestsMixin, unittest.TestCase):
353 350
     backend = CacheSession
354 351
 
355 352
     def test_load_overlong_key(self):
356  
-        warnings_state = get_warnings_state()
357  
-        warnings.filterwarnings('ignore',
358  
-                                category=CacheKeyWarning)
359  
-        self.session._session_key = (string.ascii_letters + string.digits) * 20
360  
-        self.assertEqual(self.session.load(), {})
361  
-        restore_warnings_state(warnings_state)
  353
+        with warnings.catch_warnings(record=True) as w:
  354
+            self.session._session_key = (string.ascii_letters + string.digits) * 20
  355
+            self.assertEqual(self.session.load(), {})
  356
+            self.assertEqual(len(w), 1)
362 357
 
363 358
 
364 359
 class SessionMiddlewareTests(unittest.TestCase):
24  tests/regressiontests/cache/tests.py
@@ -466,20 +466,19 @@ def func(key, *args):
466 466
 
467 467
         old_func = self.cache.key_func
468 468
         self.cache.key_func = func
469  
-        # On Python 2.6+ we could use the catch_warnings context
470  
-        # manager to test this warning nicely. Since we can't do that
471  
-        # yet, the cleanest option is to temporarily ask for
472  
-        # CacheKeyWarning to be raised as an exception.
473  
-        _warnings_state = get_warnings_state()
474  
-        warnings.simplefilter("error", CacheKeyWarning)
475 469
 
476 470
         try:
477  
-            # memcached does not allow whitespace or control characters in keys
478  
-            self.assertRaises(CacheKeyWarning, self.cache.set, 'key with spaces', 'value')
479  
-            # memcached limits key length to 250
480  
-            self.assertRaises(CacheKeyWarning, self.cache.set, 'a' * 251, 'value')
  471
+            with warnings.catch_warnings(record=True) as w:
  472
+                # memcached does not allow whitespace or control characters in keys
  473
+                self.cache.set('key with spaces', 'value')
  474
+                self.assertEqual(len(w), 2)
  475
+                self.assertTrue(isinstance(w[0].message, CacheKeyWarning))
  476
+            with warnings.catch_warnings(record=True) as w:
  477
+                # memcached limits key length to 250
  478
+                self.cache.set('a' * 251, 'value')
  479
+                self.assertEqual(len(w), 1)
  480
+                self.assertTrue(isinstance(w[0].message, CacheKeyWarning))
481 481
         finally:
482  
-            restore_warnings_state(_warnings_state)
483 482
             self.cache.key_func = old_func
484 483
 
485 484
     def test_cache_versioning_get_set(self):
@@ -1450,7 +1449,8 @@ def setUp(self):
1450 1449
         self.default_cache = get_cache('default')
1451 1450
         self.other_cache = get_cache('other')
1452 1451
         self.save_warnings_state()
1453  
-        warnings.filterwarnings('ignore', category=DeprecationWarning, module='django.views.decorators.cache')
  1452
+        warnings.filterwarnings('ignore', category=DeprecationWarning,
  1453
+            module='django.views.decorators.cache')
1454 1454
 
1455 1455
     def tearDown(self):
1456 1456
         self.restore_warnings_state()
27  tests/regressiontests/decorators/tests.py
@@ -5,7 +5,6 @@
5 5
 from django.contrib.auth.decorators import login_required, permission_required, user_passes_test
6 6
 from django.http import HttpResponse, HttpRequest, HttpResponseNotAllowed
7 7
 from django.middleware.clickjacking import XFrameOptionsMiddleware
8  
-from django.test.utils import get_warnings_state, restore_warnings_state
9 8
 from django.utils.decorators import method_decorator
10 9
 from django.utils.functional import allow_lazy, lazy, memoize
11 10
 from django.utils.unittest import TestCase
@@ -68,14 +67,6 @@ def _inner(*args, **kwargs):
68 67
 
69 68
 class DecoratorsTest(TestCase):
70 69
 
71  
-    def setUp(self):
72  
-        self.warning_state = get_warnings_state()
73  
-        warnings.filterwarnings('ignore', category=DeprecationWarning,
74  
-                                module='django.views.decorators.cache')
75  
-
76  
-    def tearDown(self):
77  
-        restore_warnings_state(self.warning_state)
78  
-
79 70
     def test_attributes(self):
80 71
         """
81 72
         Tests that django decorators set certain attributes of the wrapped
@@ -131,14 +122,16 @@ def test_cache_page_old_style(self):
131 122
         """
132 123
         def my_view(request):
133 124
             return "response"
134  
-        my_view_cached = cache_page(my_view, 123)
135  
-        self.assertEqual(my_view_cached(HttpRequest()), "response")
136  
-        my_view_cached2 = cache_page(my_view, 123, key_prefix="test")
137  
-        self.assertEqual(my_view_cached2(HttpRequest()), "response")
138  
-        my_view_cached3 = cache_page(my_view)
139  
-        self.assertEqual(my_view_cached3(HttpRequest()), "response")
140  
-        my_view_cached4 = cache_page()(my_view)
141  
-        self.assertEqual(my_view_cached4(HttpRequest()), "response")
  125
+        with warnings.catch_warnings(record=True) as w:
  126
+            my_view_cached = cache_page(my_view, 123)
  127
+            self.assertEqual(my_view_cached(HttpRequest()), "response")
  128
+            my_view_cached2 = cache_page(my_view, 123, key_prefix="test")
  129
+            self.assertEqual(my_view_cached2(HttpRequest()), "response")
  130
+            my_view_cached3 = cache_page(my_view)
  131
+            self.assertEqual(my_view_cached3(HttpRequest()), "response")
  132
+            my_view_cached4 = cache_page()(my_view)
  133
+            self.assertEqual(my_view_cached4(HttpRequest()), "response")
  134
+            self.assertEqual(len(w), 4)
142 135
 
143 136
     def test_require_safe_accepts_only_safe_methods(self):
144 137
         """
1  tests/regressiontests/forms/tests/fields.py
@@ -28,7 +28,6 @@
28 28
 import pickle
29 29
 import re
30 30
 import os
31  
-import warnings
32 31
 from decimal import Decimal
33 32
 
34 33
 from django.core.files.uploadedfile import SimpleUploadedFile
8  tests/regressiontests/generic_views/dates.py
@@ -10,14 +10,6 @@
10 10
 from .models import Book, BookSigning
11 11
 
12 12
 
13  
-import warnings
14  
-warnings.filterwarnings(
15  
-        'error', r"DateTimeField received a naive datetime",
16  
-        RuntimeWarning, r'django\.db\.models\.fields')
17  
-
18  
-
19  
-
20  
-
21 13
 class ArchiveIndexViewTests(TestCase):
22 14
     fixtures = ['generic-views-test-data.json']
23 15
     urls = 'regressiontests.generic_views.urls'
1  tests/regressiontests/i18n/patterns/tests.py
... ...
@@ -1,5 +1,4 @@
1 1
 import os
2  
-import warnings
3 2
 
4 3
 from django.core.exceptions import ImproperlyConfigured
5 4
 from django.core.urlresolvers import reverse, clear_url_caches
12  tests/regressiontests/logging_tests/tests.py
@@ -4,7 +4,7 @@
4 4
 from django.conf import compat_patch_logging_config
5 5
 from django.core import mail
6 6
 from django.test import TestCase, RequestFactory
7  
-from django.test.utils import override_settings, get_warnings_state, restore_warnings_state
  7
+from django.test.utils import override_settings
8 8
 from django.utils.log import CallbackFilter, RequireDebugFalse, getLogger
9 9
 
10 10
 
@@ -42,12 +42,9 @@ def test_filter_added(self):
42 42
         """
43 43
         config = copy.deepcopy(OLD_LOGGING)
44 44
 
45  
-        warnings_state = get_warnings_state()
46  
-        warnings.filterwarnings('ignore', category=DeprecationWarning, module='django.conf')
47  
-        try:
  45
+        with warnings.catch_warnings(record=True) as w:
48 46
             compat_patch_logging_config(config)
49  
-        finally:
50  
-            restore_warnings_state(warnings_state)
  47
+            self.assertEqual(len(w), 1)
51 48
 
52 49
         self.assertEqual(
53 50
             config["handlers"]["mail_admins"]["filters"],
@@ -60,7 +57,8 @@ def test_filter_configuration(self):
60 57
 
61 58
         """
62 59
         config = copy.deepcopy(OLD_LOGGING)
63  
-        compat_patch_logging_config(config)
  60
+        with warnings.catch_warnings(record=True):
  61
+            compat_patch_logging_config(config)
64 62
 
65 63
         flt = config["filters"]["require_debug_false"]
66 64
         self.assertEqual(flt["()"], "django.utils.log.RequireDebugFalse")
16  tests/regressiontests/requests/tests.py
@@ -6,7 +6,6 @@
6 6
 from django.conf import settings
7 7
 from django.core.handlers.wsgi import WSGIRequest, LimitedStream
8 8
 from django.http import HttpRequest, HttpResponse, parse_cookie, build_request_repr, UnreadablePostError
9  
-from django.test.utils import get_warnings_state, restore_warnings_state
10 9
 from django.utils import unittest
11 10
 from django.utils.http import cookie_date
12 11
 from django.utils.timezone import utc
@@ -398,13 +397,9 @@ def test_raw_post_data_returns_body(self):
398 397
             'wsgi.input': StringIO(payload)
399 398
         })
400 399
 
401  
-        warnings_state = get_warnings_state()
402  
-        warnings.filterwarnings('ignore', category=DeprecationWarning, module='django.http')
403  
-        try:
  400
+        with warnings.catch_warnings(record=True) as w:
404 401
             self.assertEqual(request.body, request.raw_post_data)
405  
-        finally:
406  
-            restore_warnings_state(warnings_state)
407  
-
  402
+            self.assertEqual(len(w), 1)
408 403
 
409 404
     def test_POST_connection_error(self):
410 405
         """
@@ -420,10 +415,7 @@ def read(self, len=0):
420 415
                                'CONTENT_LENGTH': len(payload),
421 416
                                'wsgi.input': ExplodingStringIO(payload)})
422 417
 
423  
-        warnings_state = get_warnings_state()
424  
-        warnings.filterwarnings('ignore', category=DeprecationWarning, module='django.http')
425  
-        try:
  418
+        with warnings.catch_warnings(record=True) as w:
426 419
             with self.assertRaises(UnreadablePostError):
427 420
                 request.raw_post_data
428  
-        finally:
429  
-            restore_warnings_state(warnings_state)
  421
+            self.assertEqual(len(w), 1)
4  tests/regressiontests/staticfiles_tests/tests.py
@@ -6,7 +6,6 @@
6 6
 import shutil
7 7
 import sys
8 8
 import tempfile
9  
-import warnings
10 9
 from StringIO import StringIO
11 10
 
12 11
 from django.template import loader, Context
@@ -511,11 +510,8 @@ def test_cache_key_memcache_validation(self):
511 510
         """
512 511
         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)
513 512
         cache_key = storage.staticfiles_storage.cache_key(name)
514  
-        self.save_warnings_state()
515 513
         cache_validator = BaseCache({})
516  
-        warnings.filterwarnings('error', category=CacheKeyWarning)
517 514
         cache_validator.validate_key(cache_key)
518  
-        self.restore_warnings_state()
519 515
         self.assertEqual(cache_key, 'staticfiles:e95bbc36387084582df2a70750d7b351')
520 516
 
521 517
 
1  tests/regressiontests/test_client_regress/views.py
... ...
@@ -1,5 +1,4 @@
1 1
 import json
2  
-import warnings
3 2
 
4 3
 from django.conf import settings
5 4
 from django.contrib.auth.decorators import login_required
39  tests/regressiontests/utils/text.py
@@ -8,13 +8,6 @@ class TestUtilsText(SimpleTestCase):
8 8
 
9 9
     # In Django 1.6 truncate_words() and truncate_html_words() will be removed
10 10
     # so these tests will need to be adapted accordingly
11  
-    def setUp(self):
12  
-        self.save_warnings_state()
13  
-        warnings.filterwarnings('ignore', category=DeprecationWarning, module='django.utils.text')
14  
-
15  
-    def tearDown(self):
16  
-        self.restore_warnings_state()
17  
-
18 11
     def test_truncate_chars(self):
19 12
         truncator = text.Truncator(
20 13
             u'The quick brown fox jumped over the lazy dog.'
@@ -79,22 +72,26 @@ def test_truncate_html_words(self):
79 72
             'id="mylink">brown...</a></p>', truncator.words(3, '...', html=True))
80 73
 
81 74
     def test_old_truncate_words(self):
82  
-        self.assertEqual(u'The quick brown fox jumped over the lazy dog.',
83  
-            text.truncate_words(u'The quick brown fox jumped over the lazy dog.', 10))
84  
-        self.assertEqual(u'The quick brown fox ...',
85  
-            text.truncate_words('The quick brown fox jumped over the lazy dog.', 4))
86  
-        self.assertEqual(u'The quick brown fox ....',
87  
-            text.truncate_words('The quick brown fox jumped over the lazy dog.', 4, '....'))
  75
+        with warnings.catch_warnings(record=True) as w:
  76
+            self.assertEqual(u'The quick brown fox jumped over the lazy dog.',
  77
+                text.truncate_words(u'The quick brown fox jumped over the lazy dog.', 10))
  78
+            self.assertEqual(u'The quick brown fox ...',
  79
+                text.truncate_words('The quick brown fox jumped over the lazy dog.', 4))
  80
+            self.assertEqual(u'The quick brown fox ....',
  81
+                text.truncate_words('The quick brown fox jumped over the lazy dog.', 4, '....'))
  82
+            self.assertEqual(len(w), 3)
88 83
 
89 84
     def test_old_truncate_html_words(self):
90  
-        self.assertEqual(u'<p><strong><em>The quick brown fox jumped over the lazy dog.</em></strong></p>',
91  
-            text.truncate_html_words('<p><strong><em>The quick brown fox jumped over the lazy dog.</em></strong></p>', 10))
92  
-        self.assertEqual(u'<p><strong><em>The quick brown fox ...</em></strong></p>',
93  
-            text.truncate_html_words('<p><strong><em>The quick brown fox jumped over the lazy dog.</em></strong></p>', 4))
94  
-        self.assertEqual(u'<p><strong><em>The quick brown fox ....</em></strong></p>',
95  
-            text.truncate_html_words('<p><strong><em>The quick brown fox jumped over the lazy dog.</em></strong></p>', 4, '....'))
96  
-        self.assertEqual(u'<p><strong><em>The quick brown fox</em></strong></p>',
97  
-            text.truncate_html_words('<p><strong><em>The quick brown fox jumped over the lazy dog.</em></strong></p>', 4, None))
  85
+        with warnings.catch_warnings(record=True) as w:
  86
+            self.assertEqual(u'<p><strong><em>The quick brown fox jumped over the lazy dog.</em></strong></p>',
  87
+                text.truncate_html_words('<p><strong><em>The quick brown fox jumped over the lazy dog.</em></strong></p>', 10))
  88
+            self.assertEqual(u'<p><strong><em>The quick brown fox ...</em></strong></p>',
  89
+                text.truncate_html_words('<p><strong><em>The quick brown fox jumped over the lazy dog.</em></strong></p>', 4))
  90
+            self.assertEqual(u'<p><strong><em>The quick brown fox ....</em></strong></p>',
  91
+                text.truncate_html_words('<p><strong><em>The quick brown fox jumped over the lazy dog.</em></strong></p>', 4, '....'))
  92
+            self.assertEqual(u'<p><strong><em>The quick brown fox</em></strong></p>',
  93
+                text.truncate_html_words('<p><strong><em>The quick brown fox jumped over the lazy dog.</em></strong></p>', 4, None))
  94
+            self.assertEqual(len(w), 4)
98 95
 
99 96
     def test_wrap(self):
100 97
         digits = '1234 67 9'

0 notes on commit 10cf3c6

Please sign in to comment.
Something went wrong with that request. Please try again.