Ticket #17049: 17049-1.diff

File 17049-1.diff, 20.4 KB (added by Claude Paroz, 13 years ago)

Use catch_warnings more extensively

  • django/contrib/formtools/tests/__init__.py

    diff --git a/django/contrib/formtools/tests/__init__.py b/django/contrib/formtools/tests/__init__.py
    index 96d1dda..88828e8 100644
    a b from django.conf import settings  
    77from django.contrib.formtools import preview, utils
    88from django.contrib.formtools.wizard import FormWizard
    99from django.test import TestCase
    10 from django.test.utils import get_warnings_state, restore_warnings_state
    1110from django.test.utils import override_settings
    1211from django.utils import unittest
    1312
    1413from django.contrib.formtools.tests.wizard import *
    1514from django.contrib.formtools.tests.forms import *
    1615
    17 warnings.filterwarnings('ignore', category=PendingDeprecationWarning,
    18                         module='django.contrib.formtools.wizard')
    19 
    2016success_string = "Done was called!"
    2117
    2218class TestFormPreview(preview.FormPreview):
    class PreviewTests(TestCase):  
    4137
    4238    def setUp(self):
    4339        super(PreviewTests, self).setUp()
    44         self.save_warnings_state()
    45         warnings.filterwarnings('ignore', category=DeprecationWarning,
    46                                 module='django.contrib.formtools.wizard.legacy')
    47 
    4840        # Create a FormPreview instance to share between tests
    4941        self.preview = preview.FormPreview(TestForm)
    5042        input_template = '<input type="hidden" name="%s" value="%s" />'
    5143        self.input = input_template % (self.preview.unused_name('stage'), "%d")
    5244        self.test_data = {'field1':u'foo', 'field1_':u'asdf'}
    5345
    54     def tearDown(self):
    55         super(PreviewTests, self).tearDown()
    56         self.restore_warnings_state()
    57 
    5846    def test_unused_name(self):
    5947        """
    6048        Verifies name mangling to get uniue field name.
    class PreviewTests(TestCase):  
    130118        self.test_data.update({'stage':2})
    131119        hash = self.preview.security_hash(None, TestForm(self.test_data))
    132120        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)
    135124
    136125    def test_form_submit_good_hash(self):
    137126        """
    class WizardTests(TestCase):  
    241230        }
    242231    )
    243232
     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
    244243    def test_step_starts_at_zero(self):
    245244        """
    246245        step should be zero for the first form
  • django/contrib/sessions/tests.py

    diff --git a/django/contrib/sessions/tests.py b/django/contrib/sessions/tests.py
    index dbcaea2..f31c056 100644
    a b from django.contrib.sessions.backends.file import SessionStore as FileSession  
    1212from django.contrib.sessions.backends.signed_cookies import SessionStore as CookieSession
    1313from django.contrib.sessions.models import Session
    1414from django.contrib.sessions.middleware import SessionMiddleware
    15 from django.core.cache.backends.base import CacheKeyWarning
    1615from django.core.exceptions import ImproperlyConfigured, SuspiciousOperation
    1716from django.http import HttpResponse
    1817from django.test import TestCase, RequestFactory
    19 from django.test.utils import override_settings, get_warnings_state, restore_warnings_state
     18from django.test.utils import override_settings
    2019from django.utils import timezone
    2120from django.utils import unittest
    2221
    class CacheDBSessionTests(SessionTestsMixin, TestCase):  
    302301            self.assertTrue(self.session.exists(self.session.session_key))
    303302
    304303    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)
    311308
    312309
    313310@override_settings(USE_TZ=True)
    class CacheSessionTests(SessionTestsMixin, unittest.TestCase):  
    353350    backend = CacheSession
    354351
    355352    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)
    362357
    363358
    364359class SessionMiddlewareTests(unittest.TestCase):
  • tests/regressiontests/cache/tests.py

    diff --git a/tests/regressiontests/cache/tests.py b/tests/regressiontests/cache/tests.py
    index 16368c6..f0e2977 100644
    a b class BaseCacheTests(object):  
    466466
    467467        old_func = self.cache.key_func
    468468        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)
    475469
    476470        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))
    481481        finally:
    482             restore_warnings_state(_warnings_state)
    483482            self.cache.key_func = old_func
    484483
    485484    def test_cache_versioning_get_set(self):
    class CacheMiddlewareTest(TestCase):  
    14501449        self.default_cache = get_cache('default')
    14511450        self.other_cache = get_cache('other')
    14521451        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')
    14541454
    14551455    def tearDown(self):
    14561456        self.restore_warnings_state()
  • tests/regressiontests/decorators/tests.py

    diff --git a/tests/regressiontests/decorators/tests.py b/tests/regressiontests/decorators/tests.py
    index ecec281..9755022 100644
    a b from django.contrib.admin.views.decorators import staff_member_required  
    55from django.contrib.auth.decorators import login_required, permission_required, user_passes_test
    66from django.http import HttpResponse, HttpRequest, HttpResponseNotAllowed
    77from django.middleware.clickjacking import XFrameOptionsMiddleware
    8 from django.test.utils import get_warnings_state, restore_warnings_state
    98from django.utils.decorators import method_decorator
    109from django.utils.functional import allow_lazy, lazy, memoize
    1110from django.utils.unittest import TestCase
    fully_decorated = full_decorator(fully_decorated)  
    6867
    6968class DecoratorsTest(TestCase):
    7069
    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 
    7970    def test_attributes(self):
    8071        """
    8172        Tests that django decorators set certain attributes of the wrapped
    class DecoratorsTest(TestCase):  
    131122        """
    132123        def my_view(request):
    133124            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)
    142135
    143136    def test_require_safe_accepts_only_safe_methods(self):
    144137        """
  • tests/regressiontests/forms/tests/fields.py

    diff --git a/tests/regressiontests/forms/tests/fields.py b/tests/regressiontests/forms/tests/fields.py
    index 3c91cdc..a7d98ec 100644
    a b import datetime  
    2828import pickle
    2929import re
    3030import os
    31 import warnings
    3231from decimal import Decimal
    3332
    3433from django.core.files.uploadedfile import SimpleUploadedFile
  • tests/regressiontests/generic_views/dates.py

    diff --git a/tests/regressiontests/generic_views/dates.py b/tests/regressiontests/generic_views/dates.py
    index eb1f7d0..91d4c29 100644
    a b from django.utils import timezone  
    1010from .models import Book, BookSigning
    1111
    1212
    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 
    2113class ArchiveIndexViewTests(TestCase):
    2214    fixtures = ['generic-views-test-data.json']
    2315    urls = 'regressiontests.generic_views.urls'
  • tests/regressiontests/i18n/patterns/tests.py

    diff --git a/tests/regressiontests/i18n/patterns/tests.py b/tests/regressiontests/i18n/patterns/tests.py
    index e59994a..8ef7377 100644
    a b  
    11import os
    2 import warnings
    32
    43from django.core.exceptions import ImproperlyConfigured
    54from django.core.urlresolvers import reverse, clear_url_caches
  • tests/regressiontests/logging_tests/tests.py

    diff --git a/tests/regressiontests/logging_tests/tests.py b/tests/regressiontests/logging_tests/tests.py
    index 6ec7f2a..e4c045b 100644
    a b import warnings  
    44from django.conf import compat_patch_logging_config
    55from django.core import mail
    66from django.test import TestCase, RequestFactory
    7 from django.test.utils import override_settings, get_warnings_state, restore_warnings_state
     7from django.test.utils import override_settings
    88from django.utils.log import CallbackFilter, RequireDebugFalse, getLogger
    99
    1010
    class PatchLoggingConfigTest(TestCase):  
    4242        """
    4343        config = copy.deepcopy(OLD_LOGGING)
    4444
    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:
    4846            compat_patch_logging_config(config)
    49         finally:
    50             restore_warnings_state(warnings_state)
     47            self.assertEqual(len(w), 1)
    5148
    5249        self.assertEqual(
    5350            config["handlers"]["mail_admins"]["filters"],
    class PatchLoggingConfigTest(TestCase):  
    6057
    6158        """
    6259        config = copy.deepcopy(OLD_LOGGING)
    63         compat_patch_logging_config(config)
     60        with warnings.catch_warnings(record=True):
     61            compat_patch_logging_config(config)
    6462
    6563        flt = config["filters"]["require_debug_false"]
    6664        self.assertEqual(flt["()"], "django.utils.log.RequireDebugFalse")
  • tests/regressiontests/requests/tests.py

    diff --git a/tests/regressiontests/requests/tests.py b/tests/regressiontests/requests/tests.py
    index c838832..d1c0896 100644
    a b from StringIO import StringIO  
    66from django.conf import settings
    77from django.core.handlers.wsgi import WSGIRequest, LimitedStream
    88from django.http import HttpRequest, HttpResponse, parse_cookie, build_request_repr, UnreadablePostError
    9 from django.test.utils import get_warnings_state, restore_warnings_state
    109from django.utils import unittest
    1110from django.utils.http import cookie_date
    1211from django.utils.timezone import utc
    class RequestsTests(unittest.TestCase):  
    398397            'wsgi.input': StringIO(payload)
    399398        })
    400399
    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:
    404401            self.assertEqual(request.body, request.raw_post_data)
    405         finally:
    406             restore_warnings_state(warnings_state)
    407 
     402            self.assertEqual(len(w), 1)
    408403
    409404    def test_POST_connection_error(self):
    410405        """
    class RequestsTests(unittest.TestCase):  
    420415                               'CONTENT_LENGTH': len(payload),
    421416                               'wsgi.input': ExplodingStringIO(payload)})
    422417
    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:
    426419            with self.assertRaises(UnreadablePostError):
    427420                request.raw_post_data
    428         finally:
    429             restore_warnings_state(warnings_state)
     421            self.assertEqual(len(w), 1)
  • tests/regressiontests/staticfiles_tests/tests.py

    diff --git a/tests/regressiontests/staticfiles_tests/tests.py b/tests/regressiontests/staticfiles_tests/tests.py
    index 6914128..7f30cb9 100644
    a b import posixpath  
    66import shutil
    77import sys
    88import tempfile
    9 import warnings
    109from StringIO import StringIO
    1110
    1211from django.template import loader, Context
    class TestCollectionCachedStorage(BaseCollectionTestCase,  
    511510        """
    512511        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)
    513512        cache_key = storage.staticfiles_storage.cache_key(name)
    514         self.save_warnings_state()
    515513        cache_validator = BaseCache({})
    516         warnings.filterwarnings('error', category=CacheKeyWarning)
    517514        cache_validator.validate_key(cache_key)
    518         self.restore_warnings_state()
    519515        self.assertEqual(cache_key, 'staticfiles:e95bbc36387084582df2a70750d7b351')
    520516
    521517
  • tests/regressiontests/test_client_regress/views.py

    diff --git a/tests/regressiontests/test_client_regress/views.py b/tests/regressiontests/test_client_regress/views.py
    index ffd4166..ab625a9 100644
    a b  
    11import json
    2 import warnings
    32
    43from django.conf import settings
    54from django.contrib.auth.decorators import login_required
  • tests/regressiontests/utils/text.py

    diff --git a/tests/regressiontests/utils/text.py b/tests/regressiontests/utils/text.py
    index bce7f99..6457845 100644
    a b class TestUtilsText(SimpleTestCase):  
    88
    99    # In Django 1.6 truncate_words() and truncate_html_words() will be removed
    1010    # 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 
    1811    def test_truncate_chars(self):
    1912        truncator = text.Truncator(
    2013            u'The quick brown fox jumped over the lazy dog.'
    class TestUtilsText(SimpleTestCase):  
    7972            'id="mylink">brown...</a></p>', truncator.words(3, '...', html=True))
    8073
    8174    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)
    8883
    8984    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)
    9895
    9996    def test_wrap(self):
    10097        digits = '1234 67 9'
Back to Top