Ticket #15561: 15561.2.diff
File 15561.2.diff, 12.2 KB (added by , 13 years ago) |
---|
-
django/test/testcases.py
diff --git a/django/test/testcases.py b/django/test/testcases.py index d85bc27..4597034 100644
a b from __future__ import with_statement 2 2 3 3 import re 4 4 import sys 5 from contextlib import contextmanager6 5 from functools import wraps 7 6 from urlparse import urlsplit, urlunsplit 8 7 from xml.dom.minidom import parseString, Node … … from django.db import (transaction, connection, connections, DEFAULT_DB_ALIAS, 17 16 from django.http import QueryDict 18 17 from django.test import _doctest as doctest 19 18 from django.test.client import Client 20 from django.test.utils import get_warnings_state, restore_warnings_state 19 from django.test.utils import get_warnings_state, restore_warnings_state, with_settings 21 20 from django.utils import simplejson, unittest as ut2 22 21 from django.utils.encoding import smart_str 23 22 … … class TransactionTestCase(ut2.TestCase): 342 341 """ 343 342 restore_warnings_state(self._warnings_state) 344 343 345 @contextmanager 346 def settings(self, **options): 344 def settings(self, **kwargs): 347 345 """ 348 346 A context manager that temporarily sets a setting and reverts 349 347 back to the original value when exiting the context. 350 348 """ 351 old_wrapped = settings._wrapped 352 override = UserSettingsHolder(settings._wrapped) 353 try: 354 for key, new_value in options.items(): 355 setattr(override, key, new_value) 356 settings._wrapped = override 357 yield 358 finally: 359 settings._wrapped = old_wrapped 349 return with_settings(**kwargs) 360 350 361 351 def assertRedirects(self, response, expected_url, status_code=302, 362 352 target_status_code=200, host=None, msg_prefix=''): -
django/test/utils.py
diff --git a/django/test/utils.py b/django/test/utils.py index bf1dc4f..f4bb0a3 100644
a b import sys 2 2 import time 3 3 import os 4 4 import warnings 5 from django.conf import settings 5 from django.conf import settings, UserSettingsHolder 6 6 from django.core import mail 7 7 from django.core.mail.backends import locmem 8 8 from django.test import signals 9 9 from django.template import Template, loader, TemplateDoesNotExist 10 10 from django.template.loaders import cached 11 11 from django.utils.translation import deactivate 12 from django.utils.functional import wraps 12 13 13 __all__ = ('Approximate', 'ContextList', 'setup_test_environment', 14 'teardown_test_environment', 'get_runner') 14 15 __all__ = ( 16 'Approximate', 'ContextList', 'get_runner', 'with_settings', 17 'setup_test_environment', 'teardown_test_environment', 18 'setup_test_template_loader', 'restore_template_loaders', 19 ) 15 20 16 21 RESTORE_LOADERS_ATTR = '_original_template_source_loaders' 17 22 … … def restore_template_loaders(): 160 165 """ 161 166 loader.template_source_loaders = getattr(loader, RESTORE_LOADERS_ATTR) 162 167 delattr(loader, RESTORE_LOADERS_ATTR) 168 169 170 class with_settings(object): 171 """ 172 Acts as either a decorator, or a context manager. If it's a decorator it 173 takes a function and returns a wrapped function. If it's a contextmanager 174 it's used with the ``with`` statement. In either event entering/exiting 175 are called before and after, respectively, the function/block is executed. 176 """ 177 178 def __init__(self, **kwargs): 179 self.options = kwargs 180 self.wrapped = settings._wrapped 181 182 def __enter__(self): 183 self.enable() 184 185 def __exit__(self, exc_type, exc_value, traceback): 186 self.disable() 187 188 def __call__(self, func): 189 @wraps(func) 190 def inner(*args, **kwargs): 191 self.enable() 192 result = func(*args, **kwargs) 193 self.disable() 194 return result 195 return inner 196 197 def enable(self): 198 override = UserSettingsHolder(settings._wrapped) 199 for key, new_value in self.options.items(): 200 setattr(override, key, new_value) 201 settings._wrapped = override 202 203 def disable(self): 204 settings._wrapped = self.wrapped -
tests/regressiontests/mail/tests.py
diff --git a/tests/regressiontests/mail/tests.py b/tests/regressiontests/mail/tests.py index 706b3af..c4d727a 100644
a b from StringIO import StringIO 9 9 import tempfile 10 10 import threading 11 11 12 from django.conf import settings13 12 from django.core import mail 14 13 from django.core.mail import (EmailMessage, mail_admins, mail_managers, 15 14 EmailMultiAlternatives, send_mail, send_mass_mail) 16 15 from django.core.mail.backends import console, dummy, locmem, filebased, smtp 17 16 from django.core.mail.message import BadHeaderError 18 17 from django.test import TestCase 18 from django.test.utils import with_settings 19 19 from django.utils.translation import ugettext_lazy 20 from django.utils.functional import wraps21 22 23 def alter_django_settings(**kwargs):24 oldvalues = {}25 nonexistant = []26 for setting, newvalue in kwargs.iteritems():27 try:28 oldvalues[setting] = getattr(settings, setting)29 except AttributeError:30 nonexistant.append(setting)31 setattr(settings, setting, newvalue)32 return oldvalues, nonexistant33 34 35 def restore_django_settings(state):36 oldvalues, nonexistant = state37 for setting, oldvalue in oldvalues.iteritems():38 setattr(settings, setting, oldvalue)39 for setting in nonexistant:40 delattr(settings, setting)41 42 43 def with_django_settings(**kwargs):44 def decorator(test):45 @wraps(test)46 def decorated_test(self):47 state = alter_django_settings(**kwargs)48 try:49 return test(self)50 finally:51 restore_django_settings(state)52 return decorated_test53 return decorator54 20 55 21 56 22 class MailTests(TestCase): … … class MailTests(TestCase): 251 217 shutil.rmtree(tmp_dir) 252 218 self.assertTrue(isinstance(mail.get_connection(), locmem.EmailBackend)) 253 219 254 @with_ django_settings(220 @with_settings( 255 221 EMAIL_BACKEND='django.core.mail.backends.locmem.EmailBackend', 256 222 ADMINS=[('nobody', 'nobody@example.com')], 257 223 MANAGERS=[('nobody', 'nobody@example.com')]) … … class BaseEmailBackendTests(object): 323 289 email_backend = None 324 290 325 291 def setUp(self): 326 self.__settings_state = alter_django_settings(EMAIL_BACKEND=self.email_backend) 292 self.settings_override = with_settings(EMAIL_BACKEND=self.email_backend) 293 self.settings_override.enable() 327 294 328 295 def tearDown(self): 329 restore_django_settings(self.__settings_state)296 self.settings_override.disable() 330 297 331 298 def assertStartsWith(self, first, second): 332 299 if not first.startswith(second): … … class BaseEmailBackendTests(object): 375 342 self.assertEqual(message.get_payload(), "Content") 376 343 self.assertEqual(message["from"], "=?utf-8?q?Firstname_S=C3=BCrname?= <from@example.com>") 377 344 378 @with_ django_settings(MANAGERS=[('nobody', 'nobody@example.com')])345 @with_settings(MANAGERS=[('nobody', 'nobody@example.com')]) 379 346 def test_html_mail_managers(self): 380 347 """Test html_message argument to mail_managers""" 381 348 mail_managers('Subject', 'Content', html_message='HTML Content') … … class BaseEmailBackendTests(object): 390 357 self.assertEqual(message.get_payload(1).get_payload(), 'HTML Content') 391 358 self.assertEqual(message.get_payload(1).get_content_type(), 'text/html') 392 359 393 @with_ django_settings(ADMINS=[('nobody', 'nobody@example.com')])360 @with_settings(ADMINS=[('nobody', 'nobody@example.com')]) 394 361 def test_html_mail_admins(self): 395 362 """Test html_message argument to mail_admins """ 396 363 mail_admins('Subject', 'Content', html_message='HTML Content') … … class BaseEmailBackendTests(object): 405 372 self.assertEqual(message.get_payload(1).get_payload(), 'HTML Content') 406 373 self.assertEqual(message.get_payload(1).get_content_type(), 'text/html') 407 374 408 @with_django_settings(ADMINS=[('nobody', 'nobody+admin@example.com')], 409 MANAGERS=[('nobody', 'nobody+manager@example.com')]) 375 @with_settings( 376 ADMINS=[('nobody', 'nobody+admin@example.com')], 377 MANAGERS=[('nobody', 'nobody+manager@example.com')]) 410 378 def test_manager_and_admin_mail_prefix(self): 411 379 """ 412 380 String prefix + lazy translated subject = bad output … … class BaseEmailBackendTests(object): 421 389 message = self.get_the_message() 422 390 self.assertEqual(message.get('subject'), '[Django] Subject') 423 391 424 @with_ django_settings(ADMINS=(), MANAGERS=())392 @with_settings(ADMINS=(), MANAGERS=()) 425 393 def test_empty_admins(self): 426 394 """ 427 395 Test that mail_admins/mail_managers doesn't connect to the mail server … … class FileBackendTests(BaseEmailBackendTests, TestCase): 501 469 email_backend = 'django.core.mail.backends.filebased.EmailBackend' 502 470 503 471 def setUp(self): 504 super(FileBackendTests, self).setUp()505 472 self.tmp_dir = tempfile.mkdtemp() 506 self.__settings_state = alter_django_settings(EMAIL_FILE_PATH=self.tmp_dir) 473 self.addCleanup(shutil.rmtree, self.tmp_dir) 474 self.settings_override = with_settings(EMAIL_FILE_PATH=self.tmp_dir) 475 self.settings_override.enable() 476 super(FileBackendTests, self).setUp() 507 477 508 478 def tearDown(self): 509 restore_django_settings(self.__settings_state) 510 shutil.rmtree(self.tmp_dir) 479 self.settings_override.disable() 511 480 super(FileBackendTests, self).tearDown() 512 481 513 482 def flush_mailbox(self): … … class SMTPBackendTests(BaseEmailBackendTests, TestCase): 642 611 @classmethod 643 612 def setUpClass(cls): 644 613 cls.server = FakeSMTPServer(('127.0.0.1', 0), None) 645 cls.settings = alter_django_settings(614 cls.settings_override = with_settings( 646 615 EMAIL_HOST="127.0.0.1", 647 616 EMAIL_PORT=cls.server.socket.getsockname()[1]) 617 cls.settings_override.enable() 648 618 cls.server.start() 649 619 650 620 @classmethod 651 621 def tearDownClass(cls): 622 cls.settings_override.disable() 652 623 cls.server.stop() 653 624 654 625 def setUp(self): -
tests/regressiontests/settings_tests/tests.py
diff --git a/tests/regressiontests/settings_tests/tests.py b/tests/regressiontests/settings_tests/tests.py index 750ccc6..dc9c5e4 100644
a b 1 1 from __future__ import with_statement 2 import os 2 import os, sys 3 3 from django.conf import settings, global_settings 4 4 from django.test import TestCase 5 from django.test.utils import with_settings 6 from django.utils.unittest import skipIf 7 8 9 class SettingGetter(object): 10 def __init__(self): 11 self.test = getattr(settings, 'TEST', 'undefined') 12 5 13 6 14 class SettingsTests(TestCase): 7 15 … … class SettingsTests(TestCase): 29 37 settings.TEST = 'test' 30 38 self.assertRaises(AttributeError, getattr, settings, 'TEST') 31 39 40 @with_settings(TEST='override') 41 def test_decorator(self): 42 self.assertEqual('override', settings.TEST) 43 44 def test_context_manager(self): 45 self.assertRaises(AttributeError, getattr, settings, 'TEST') 46 override = with_settings(TEST='override') 47 self.assertRaises(AttributeError, getattr, settings, 'TEST') 48 override.enable() 49 self.assertEqual('override', settings.TEST) 50 override.disable() 51 self.assertRaises(AttributeError, getattr, settings, 'TEST') 52 53 def test_class_decorator(self): 54 self.assertEqual(SettingGetter().test, 'undefined') 55 DecoratedSettingGetter = with_settings(TEST='override')(SettingGetter) 56 self.assertEqual(DecoratedSettingGetter().test, 'override') 57 self.assertRaises(AttributeError, getattr, settings, 'TEST') 58 59 @skipIf(sys.version_info[:2] < (2, 6), "Python version is lower than 2.6") 60 def test_new_class_decorator(self): 61 self.assertEqual(SettingGetter().test, 'undefined') 62 @with_settings(TEST='override') 63 class DecoratedSettingGetter(SettingGetter): 64 pass 65 self.assertEqual(DecoratedSettingGetter().test, 'override') 66 self.assertRaises(AttributeError, getattr, settings, 'TEST') 67 68 32 69 # 33 70 # Regression tests for #10130: deleting settings. 34 71 #