Removed some direct settings manipulations in tests; refs #21230.

This commit is contained in:
Bouke Haarsma 2013-10-14 15:14:17 +02:00 committed by Tim Graham
parent 499cd912ca
commit 3565efaa45
16 changed files with 137 additions and 223 deletions

View File

@ -56,7 +56,8 @@ ERROR_MESSAGE = "Please enter the correct username and password \
for a staff account. Note that both fields may be case-sensitive."
@override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',))
@override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',),
USE_I18N=True, USE_L10N=False, LANGUAGE_CODE='en')
class AdminViewBasicTestCase(TestCase):
fixtures = ['admin-views-users.xml', 'admin-views-colors.xml',
'admin-views-fabrics.xml', 'admin-views-books.xml']
@ -69,16 +70,9 @@ class AdminViewBasicTestCase(TestCase):
urls = "admin_views.urls"
def setUp(self):
self.old_USE_I18N = settings.USE_I18N
self.old_USE_L10N = settings.USE_L10N
self.old_LANGUAGE_CODE = settings.LANGUAGE_CODE
self.client.login(username='super', password='secret')
settings.USE_I18N = True
def tearDown(self):
settings.USE_I18N = self.old_USE_I18N
settings.USE_L10N = self.old_USE_L10N
settings.LANGUAGE_CODE = self.old_LANGUAGE_CODE
self.client.logout()
formats.reset_format_cache()
@ -2410,15 +2404,12 @@ class AdminActionsTest(TestCase):
self.client.post('/test_admin/admin/admin_views/subscriber/', delete_confirmation_data)
self.assertEqual(Subscriber.objects.count(), 0)
@override_settings(USE_THOUSAND_SEPARATOR=True, USE_L10N=True)
def test_non_localized_pk(self):
"""If USE_THOUSAND_SEPARATOR is set, make sure that the ids for
the objects selected for deletion are rendered without separators.
Refs #14895.
"""
self.old_USE_THOUSAND_SEPARATOR = settings.USE_THOUSAND_SEPARATOR
self.old_USE_L10N = settings.USE_L10N
settings.USE_THOUSAND_SEPARATOR = True
settings.USE_L10N = True
subscriber = Subscriber.objects.get(id=1)
subscriber.id = 9999
subscriber.save()
@ -2431,8 +2422,6 @@ class AdminActionsTest(TestCase):
self.assertTemplateUsed(response, 'admin/delete_selected_confirmation.html')
self.assertContains(response, 'value="9999"') # Instead of 9,999
self.assertContains(response, 'value="2"')
settings.USE_THOUSAND_SEPARATOR = self.old_USE_THOUSAND_SEPARATOR
settings.USE_L10N = self.old_USE_L10N
def test_model_admin_default_delete_action_protected(self):
"""
@ -4127,21 +4116,16 @@ class ValidXHTMLTests(TestCase):
self.assertNotContains(response, ' xml:lang=""')
@override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',))
@override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',),
USE_THOUSAND_SEPARATOR=True, USE_L10N=True)
class DateHierarchyTests(TestCase):
urls = "admin_views.urls"
fixtures = ['admin-views-users.xml']
def setUp(self):
self.client.login(username='super', password='secret')
self.old_USE_THOUSAND_SEPARATOR = settings.USE_THOUSAND_SEPARATOR
self.old_USE_L10N = settings.USE_L10N
settings.USE_THOUSAND_SEPARATOR = True
settings.USE_L10N = True
def tearDown(self):
settings.USE_THOUSAND_SEPARATOR = self.old_USE_THOUSAND_SEPARATOR
settings.USE_L10N = self.old_USE_L10N
formats.reset_format_cache()
def assert_non_localized_year(self, response, year):

View File

@ -3,6 +3,7 @@ import time
from django.conf import settings
from django.contrib.comments.forms import CommentForm
from django.contrib.comments.models import Comment
from django.test.utils import override_settings
from . import CommentTestCase
from ..models import Article
@ -58,26 +59,18 @@ class CommentFormTests(CommentTestCase):
c.save()
self.assertEqual(Comment.objects.count(), 1)
@override_settings(PROFANITIES_LIST=["rooster"])
def testProfanities(self):
"""Test COMMENTS_ALLOW_PROFANITIES and PROFANITIES_LIST settings"""
a = Article.objects.get(pk=1)
d = self.getValidData(a)
# Save settings in case other tests need 'em
saved = settings.PROFANITIES_LIST, settings.COMMENTS_ALLOW_PROFANITIES
# Don't wanna swear in the unit tests if we don't have to...
settings.PROFANITIES_LIST = ["rooster"]
# Try with COMMENTS_ALLOW_PROFANITIES off
settings.COMMENTS_ALLOW_PROFANITIES = False
f = CommentForm(a, data=dict(d, comment="What a rooster!"))
self.assertFalse(f.is_valid())
with self.settings(COMMENTS_ALLOW_PROFANITIES=False):
f = CommentForm(a, data=dict(d, comment="What a rooster!"))
self.assertFalse(f.is_valid())
# Now with COMMENTS_ALLOW_PROFANITIES on
settings.COMMENTS_ALLOW_PROFANITIES = True
f = CommentForm(a, data=dict(d, comment="What a rooster!"))
self.assertTrue(f.is_valid())
# Restore settings
settings.PROFANITIES_LIST, settings.COMMENTS_ALLOW_PROFANITIES = saved
with self.settings(COMMENTS_ALLOW_PROFANITIES=True):
f = CommentForm(a, data=dict(d, comment="What a rooster!"))
self.assertTrue(f.is_valid())

View File

@ -83,22 +83,19 @@ class CommentViewTests(CommentTestCase):
def testDebugCommentErrors(self):
"""The debug error template should be shown only if DEBUG is True"""
olddebug = settings.DEBUG
settings.DEBUG = True
a = Article.objects.get(pk=1)
data = self.getValidData(a)
data["security_hash"] = "Nobody expects the Spanish Inquisition!"
response = self.client.post("/post/", data)
self.assertEqual(response.status_code, 400)
self.assertTemplateUsed(response, "comments/400-debug.html")
settings.DEBUG = False
response = self.client.post("/post/", data)
self.assertEqual(response.status_code, 400)
self.assertTemplateNotUsed(response, "comments/400-debug.html")
with self.settings(DEBUG=True):
response = self.client.post("/post/", data)
self.assertEqual(response.status_code, 400)
self.assertTemplateUsed(response, "comments/400-debug.html")
settings.DEBUG = olddebug
with self.settings(DEBUG=False):
response = self.client.post("/post/", data)
self.assertEqual(response.status_code, 400)
self.assertTemplateNotUsed(response, "comments/400-debug.html")
def testCreateValidComment(self):
address = "1.2.3.4"

View File

@ -18,7 +18,8 @@ from .models import (Episode, EpisodeExtra, EpisodeMaxNum, Media,
EpisodePermanent, Category)
@override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',))
@override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',),
TEMPLATE_DEBUG=True)
class GenericAdminViewTest(TestCase):
urls = "generic_inline_admin.urls"
fixtures = ['users.xml']
@ -27,8 +28,7 @@ class GenericAdminViewTest(TestCase):
# set TEMPLATE_DEBUG to True to ensure {% include %} will raise
# exceptions since that is how inlines are rendered and #9498 will
# bubble up if it is an issue.
self.original_template_debug = settings.TEMPLATE_DEBUG
settings.TEMPLATE_DEBUG = True
self.client.login(username='super', password='secret')
# Can't load content via a fixture (since the GenericForeignKey
@ -46,7 +46,6 @@ class GenericAdminViewTest(TestCase):
def tearDown(self):
self.client.logout()
settings.TEMPLATE_DEBUG = self.original_template_debug
def testBasicAddGet(self):
"""

View File

@ -968,17 +968,9 @@ class ResolutionOrderI18NTests(TransRealMixin, TestCase):
self.assertTrue(msgstr in result, ("The string '%s' isn't in the "
"translation of '%s'; the actual result is '%s'." % (msgstr, msgid, result)))
@override_settings(INSTALLED_APPS=['i18n.resolution'] + list(settings.INSTALLED_APPS))
class AppResolutionOrderI18NTests(ResolutionOrderI18NTests):
def setUp(self):
self.old_installed_apps = settings.INSTALLED_APPS
settings.INSTALLED_APPS = ['i18n.resolution'] + list(settings.INSTALLED_APPS)
super(AppResolutionOrderI18NTests, self).setUp()
def tearDown(self):
settings.INSTALLED_APPS = self.old_installed_apps
super(AppResolutionOrderI18NTests, self).tearDown()
def test_app_translation(self):
self.assertUgettext('Date/time', 'APP')

View File

@ -6,6 +6,7 @@ from django.db import models
from django.db.models.loading import cache
from django.template import Context, Template
from django.test import TestCase
from django.test.utils import override_settings
from django.utils.encoding import force_text
from .models import (
@ -108,6 +109,7 @@ class ManagersRegressionTests(TestCase):
except AttributeError as e:
self.assertEqual(str(e), "Manager isn't available; AbstractBase1 is abstract")
@override_settings(TEST_SWAPPABLE_MODEL='managers_regress.Parent')
def test_swappable_manager(self):
try:
# This test adds dummy models to the app cache. These
@ -116,8 +118,6 @@ class ManagersRegressionTests(TestCase):
old_app_models = copy.deepcopy(cache.app_models)
old_app_store = copy.deepcopy(cache.app_store)
settings.TEST_SWAPPABLE_MODEL = 'managers_regress.Parent'
class SwappableModel(models.Model):
class Meta:
swappable = 'TEST_SWAPPABLE_MODEL'
@ -131,10 +131,10 @@ class ManagersRegressionTests(TestCase):
self.assertEqual(str(e), "Manager isn't available; SwappableModel has been swapped for 'managers_regress.Parent'")
finally:
del settings.TEST_SWAPPABLE_MODEL
cache.app_models = old_app_models
cache.app_store = old_app_store
@override_settings(TEST_SWAPPABLE_MODEL='managers_regress.Parent')
def test_custom_swappable_manager(self):
try:
# This test adds dummy models to the app cache. These
@ -143,8 +143,6 @@ class ManagersRegressionTests(TestCase):
old_app_models = copy.deepcopy(cache.app_models)
old_app_store = copy.deepcopy(cache.app_store)
settings.TEST_SWAPPABLE_MODEL = 'managers_regress.Parent'
class SwappableModel(models.Model):
stuff = models.Manager()
@ -162,10 +160,10 @@ class ManagersRegressionTests(TestCase):
self.assertEqual(str(e), "Manager isn't available; SwappableModel has been swapped for 'managers_regress.Parent'")
finally:
del settings.TEST_SWAPPABLE_MODEL
cache.app_models = old_app_models
cache.app_store = old_app_store
@override_settings(TEST_SWAPPABLE_MODEL='managers_regress.Parent')
def test_explicit_swappable_manager(self):
try:
# This test adds dummy models to the app cache. These
@ -174,8 +172,6 @@ class ManagersRegressionTests(TestCase):
old_app_models = copy.deepcopy(cache.app_models)
old_app_store = copy.deepcopy(cache.app_store)
settings.TEST_SWAPPABLE_MODEL = 'managers_regress.Parent'
class SwappableModel(models.Model):
objects = models.Manager()
@ -193,7 +189,6 @@ class ManagersRegressionTests(TestCase):
self.assertEqual(str(e), "Manager isn't available; SwappableModel has been swapped for 'managers_regress.Parent'")
finally:
del settings.TEST_SWAPPABLE_MODEL
cache.app_models = old_app_models
cache.app_store = old_app_store

View File

@ -6,6 +6,7 @@ from django.http import HttpResponse
from django.template.response import TemplateResponse
from django.template import Template
from django.test import TestCase
from django.test.utils import override_settings
class TestException(Exception):
pass
@ -772,15 +773,11 @@ _missing = object()
class RootUrlconfTests(TestCase):
urls = 'middleware_exceptions.urls'
@override_settings(ROOT_URLCONF=None)
def test_missing_root_urlconf(self):
try:
original_ROOT_URLCONF = settings.ROOT_URLCONF
del settings.ROOT_URLCONF
except AttributeError:
original_ROOT_URLCONF = _missing
# Removing ROOT_URLCONF is safe, as override_settings will restore
# the previously defined settings.
del settings.ROOT_URLCONF
self.assertRaises(AttributeError,
self.client.get, "/middleware_exceptions/view/"
)
if original_ROOT_URLCONF is not _missing:
settings.ROOT_URLCONF = original_ROOT_URLCONF

View File

@ -15,7 +15,7 @@ from django.core.exceptions import ImproperlyConfigured
from django.forms.models import BaseModelFormSet
from django.forms.widgets import Select
from django.test import TestCase
from django.test.utils import str_prefix
from django.test.utils import str_prefix, override_settings
from django.utils import six
from .models import Band, Concert, ValidationTestModel, ValidationTestInlineModel
@ -540,9 +540,7 @@ class ModelAdminTests(TestCase):
class ValidationTests(unittest.TestCase):
def test_validation_only_runs_in_debug(self):
# Ensure validation only runs when DEBUG = True
try:
settings.DEBUG = True
with override_settings(DEBUG=True):
class ValidationTestModelAdmin(ModelAdmin):
raw_id_fields = 10
@ -555,11 +553,10 @@ class ValidationTests(unittest.TestCase):
ValidationTestModel,
ValidationTestModelAdmin,
)
finally:
settings.DEBUG = False
site = AdminSite()
site.register(ValidationTestModel, ValidationTestModelAdmin)
with override_settings(DEBUG=False):
site = AdminSite()
site.register(ValidationTestModel, ValidationTestModelAdmin)
def test_raw_id_fields_validation(self):

View File

@ -150,6 +150,7 @@ class ProxyModelTests(TestCase):
proxy = True
self.assertRaises(FieldError, build_new_fields)
@override_settings(TEST_SWAPPABLE_MODEL='proxy_models.AlternateModel')
def test_swappable(self):
try:
# This test adds dummy applications to the app cache. These
@ -158,8 +159,6 @@ class ProxyModelTests(TestCase):
old_app_models = copy.deepcopy(cache.app_models)
old_app_store = copy.deepcopy(cache.app_store)
settings.TEST_SWAPPABLE_MODEL = 'proxy_models.AlternateModel'
class SwappableModel(models.Model):
class Meta:
@ -175,7 +174,6 @@ class ProxyModelTests(TestCase):
class Meta:
proxy = True
finally:
del settings.TEST_SWAPPABLE_MODEL
cache.app_models = old_app_models
cache.app_store = old_app_store

View File

@ -9,6 +9,7 @@ from django.db import transaction, connection, router
from django.db.utils import ConnectionHandler, DEFAULT_DB_ALIAS, DatabaseError
from django.test import (TransactionTestCase, skipIfDBFeature,
skipUnlessDBFeature)
from django.test.utils import override_settings
from multiple_database.routers import TestRouter
@ -23,6 +24,9 @@ except ImportError:
requires_threading = unittest.skipUnless(threading, 'requires threading')
# We need to set settings.DEBUG to True so we can capture the output SQL
# to examine.
@override_settings(DEBUG=True)
class SelectForUpdateTests(TransactionTestCase):
available_apps = ['select_for_update']
@ -41,11 +45,6 @@ class SelectForUpdateTests(TransactionTestCase):
self.new_connection = new_connections[DEFAULT_DB_ALIAS]
self.new_connection.enter_transaction_management()
# We need to set settings.DEBUG to True so we can capture
# the output SQL to examine.
self._old_debug = settings.DEBUG
settings.DEBUG = True
def tearDown(self):
try:
# We don't really care if this fails - some of the tests will set
@ -55,7 +54,6 @@ class SelectForUpdateTests(TransactionTestCase):
except transaction.TransactionManagementError:
pass
self.new_connection.close()
settings.DEBUG = self._old_debug
try:
self.end_blocking_transaction()
except (DatabaseError, AttributeError):

View File

@ -18,7 +18,7 @@ from django.conf import settings
from django.core import management, serializers
from django.db import transaction, connection
from django.test import TestCase, TransactionTestCase
from django.test.utils import Approximate
from django.test.utils import Approximate, override_settings
from django.utils import six
from django.utils.six import StringIO
@ -26,22 +26,18 @@ from .models import (Category, Author, Article, AuthorProfile, Actor, Movie,
Score, Player, Team)
class SerializerRegistrationTests(unittest.TestCase):
@override_settings(
SERIALIZATION_MODULES = {
"json2" : "django.core.serializers.json",
}
)
class SerializerRegistrationTests(TestCase):
def setUp(self):
self.old_SERIALIZATION_MODULES = getattr(settings, 'SERIALIZATION_MODULES', None)
self.old_serializers = serializers._serializers
serializers._serializers = {}
settings.SERIALIZATION_MODULES = {
"json2" : "django.core.serializers.json",
}
def tearDown(self):
serializers._serializers = self.old_serializers
if self.old_SERIALIZATION_MODULES:
settings.SERIALIZATION_MODULES = self.old_SERIALIZATION_MODULES
else:
delattr(settings, 'SERIALIZATION_MODULES')
def test_register(self):
"Registering a new serializer populates the full registry. Refs #14823"

View File

@ -23,6 +23,8 @@ except ImportError:
from django.template import TemplateDoesNotExist, Context
from django.template.loaders.eggs import Loader as EggLoader
from django.template import loader
from django.test import TestCase
from django.test.utils import override_settings
from django.utils import six
from django.utils._os import upath
from django.utils.six import StringIO
@ -46,7 +48,8 @@ def create_egg(name, resources):
@unittest.skipUnless(pkg_resources, 'setuptools is not installed')
class EggLoaderTest(unittest.TestCase):
@override_settings(INSTALLED_APPS=[])
class EggLoaderTest(TestCase):
def setUp(self):
# Defined here b/c at module scope we may not have pkg_resources
class MockProvider(pkg_resources.NullProvider):
@ -73,51 +76,42 @@ class EggLoaderTest(unittest.TestCase):
os.path.normcase('templates/y.html'): StringIO("y"),
os.path.normcase('templates/x.txt'): StringIO("x"),
})
self._old_installed_apps = settings.INSTALLED_APPS
settings.INSTALLED_APPS = []
def tearDown(self):
settings.INSTALLED_APPS = self._old_installed_apps
@override_settings(INSTALLED_APPS=['egg_empty'])
def test_empty(self):
"Loading any template on an empty egg should fail"
settings.INSTALLED_APPS = ['egg_empty']
egg_loader = EggLoader()
self.assertRaises(TemplateDoesNotExist, egg_loader.load_template_source, "not-existing.html")
@override_settings(INSTALLED_APPS=['egg_1'])
def test_non_existing(self):
"Template loading fails if the template is not in the egg"
settings.INSTALLED_APPS = ['egg_1']
egg_loader = EggLoader()
self.assertRaises(TemplateDoesNotExist, egg_loader.load_template_source, "not-existing.html")
@override_settings(INSTALLED_APPS=['egg_1'])
def test_existing(self):
"A template can be loaded from an egg"
settings.INSTALLED_APPS = ['egg_1']
egg_loader = EggLoader()
contents, template_name = egg_loader.load_template_source("y.html")
self.assertEqual(contents, "y")
self.assertEqual(template_name, "egg:egg_1:templates/y.html")
@override_settings(INSTALLED_APPS=[])
def test_not_installed(self):
"Loading an existent template from an egg not included in INSTALLED_APPS should fail"
settings.INSTALLED_APPS = []
egg_loader = EggLoader()
self.assertRaises(TemplateDoesNotExist, egg_loader.load_template_source, "y.html")
class CachedLoader(unittest.TestCase):
def setUp(self):
self.old_TEMPLATE_LOADERS = settings.TEMPLATE_LOADERS
settings.TEMPLATE_LOADERS = (
('django.template.loaders.cached.Loader', (
'django.template.loaders.filesystem.Loader',
)
),
)
def tearDown(self):
settings.TEMPLATE_LOADERS = self.old_TEMPLATE_LOADERS
@override_settings(
TEMPLATE_LOADERS = (
('django.template.loaders.cached.Loader', (
'django.template.loaders.filesystem.Loader',
)),
)
)
class CachedLoader(TestCase):
def test_templatedir_caching(self):
"Check that the template directories form part of the template cache key. Refs #13573"
# Retrive a template specifying a template directory to check
@ -144,17 +138,12 @@ class CachedLoader(unittest.TestCase):
"Cached template loader doesn't cache file lookup misses. It should.")
class RenderToStringTest(unittest.TestCase):
def setUp(self):
self._old_TEMPLATE_DIRS = settings.TEMPLATE_DIRS
settings.TEMPLATE_DIRS = (
os.path.join(os.path.dirname(upath(__file__)), 'templates'),
)
def tearDown(self):
settings.TEMPLATE_DIRS = self._old_TEMPLATE_DIRS
@override_settings(
TEMPLATE_DIRS = (
os.path.join(os.path.dirname(upath(__file__)), 'templates'),
)
)
class RenderToStringTest(TestCase):
def test_basic(self):
self.assertEqual(loader.render_to_string('test_context.html'), 'obj:')

View File

@ -296,41 +296,30 @@ class TemplateResponseTest(TestCase):
pickle.dumps(unpickled_response)
@override_settings(
MIDDLEWARE_CLASSES=list(settings.MIDDLEWARE_CLASSES) + [
'template_tests.test_response.CustomURLConfMiddleware'
]
)
class CustomURLConfTest(TestCase):
urls = 'template_tests.urls'
def setUp(self):
self.old_MIDDLEWARE_CLASSES = settings.MIDDLEWARE_CLASSES
settings.MIDDLEWARE_CLASSES = list(settings.MIDDLEWARE_CLASSES) + [
'template_tests.test_response.CustomURLConfMiddleware'
]
def tearDown(self):
settings.MIDDLEWARE_CLASSES = self.old_MIDDLEWARE_CLASSES
def test_custom_urlconf(self):
response = self.client.get('/template_response_view/')
self.assertEqual(response.status_code, 200)
self.assertContains(response, 'This is where you can find the snark: /snark/')
@override_settings(
CACHE_MIDDLEWARE_SECONDS=2.0,
MIDDLEWARE_CLASSES=list(settings.MIDDLEWARE_CLASSES) + [
'django.middleware.cache.FetchFromCacheMiddleware',
'django.middleware.cache.UpdateCacheMiddleware',
]
)
class CacheMiddlewareTest(TestCase):
urls = 'template_tests.alternate_urls'
def setUp(self):
self.old_MIDDLEWARE_CLASSES = settings.MIDDLEWARE_CLASSES
self.CACHE_MIDDLEWARE_SECONDS = settings.CACHE_MIDDLEWARE_SECONDS
settings.CACHE_MIDDLEWARE_SECONDS = 2.0
settings.MIDDLEWARE_CLASSES = list(settings.MIDDLEWARE_CLASSES) + [
'django.middleware.cache.FetchFromCacheMiddleware',
'django.middleware.cache.UpdateCacheMiddleware',
]
def tearDown(self):
settings.MIDDLEWARE_CLASSES = self.old_MIDDLEWARE_CLASSES
settings.CACHE_MIDDLEWARE_SECONDS = self.CACHE_MIDDLEWARE_SECONDS
def test_middleware_caching(self):
response = self.client.get('/template_response_view/')
self.assertEqual(response.status_code, 200)

View File

@ -201,10 +201,10 @@ class TemplateLoaderTests(TestCase):
test_template_sources('/DIR1/index.HTML', template_dirs,
['/DIR1/index.HTML'])
# Turn TEMPLATE_DEBUG on, so that the origin file name will be kept with
# the compiled templates.
@override_settings(TEMPLATE_DEBUG=True)
def test_loader_debug_origin(self):
# Turn TEMPLATE_DEBUG on, so that the origin file name will be kept with
# the compiled templates.
old_td, settings.TEMPLATE_DEBUG = settings.TEMPLATE_DEBUG, True
old_loaders = loader.template_source_loaders
try:
@ -237,7 +237,6 @@ class TemplateLoaderTests(TestCase):
'Cached template loaded through cached loader has incorrect name for debug page: %s' % template_name)
finally:
loader.template_source_loaders = old_loaders
settings.TEMPLATE_DEBUG = old_td
def test_loader_origin(self):
with self.settings(TEMPLATE_DEBUG=True):
@ -253,15 +252,14 @@ class TemplateLoaderTests(TestCase):
template = loader.get_template('login.html')
self.assertEqual(template.origin, None)
# TEMPLATE_DEBUG must be true, otherwise the exception raised
# during {% include %} processing will be suppressed.
@override_settings(TEMPLATE_DEBUG=True)
def test_include_missing_template(self):
"""
Tests that the correct template is identified as not existing
when {% include %} specifies a template that does not exist.
"""
# TEMPLATE_DEBUG must be true, otherwise the exception raised
# during {% include %} processing will be suppressed.
old_td, settings.TEMPLATE_DEBUG = settings.TEMPLATE_DEBUG, True
old_loaders = loader.template_source_loaders
try:
@ -276,13 +274,14 @@ class TemplateLoaderTests(TestCase):
tmpl = loader.select_template([load_name])
r = tmpl.render(template.Context({}))
except template.TemplateDoesNotExist as e:
settings.TEMPLATE_DEBUG = old_td
self.assertEqual(e.args[0], 'missing.html')
self.assertEqual(r, None, 'Template rendering unexpectedly succeeded, produced: ->%r<-' % r)
finally:
loader.template_source_loaders = old_loaders
settings.TEMPLATE_DEBUG = old_td
# TEMPLATE_DEBUG must be true, otherwise the exception raised
# during {% include %} processing will be suppressed.
@override_settings(TEMPLATE_DEBUG=True)
def test_extends_include_missing_baseloader(self):
"""
Tests that the correct template is identified as not existing
@ -290,10 +289,6 @@ class TemplateLoaderTests(TestCase):
that template has an {% include %} of something that does not
exist. See #12787.
"""
# TEMPLATE_DEBUG must be true, otherwise the exception raised
# during {% include %} processing will be suppressed.
old_td, settings.TEMPLATE_DEBUG = settings.TEMPLATE_DEBUG, True
old_loaders = loader.template_source_loaders
try:
@ -308,20 +303,18 @@ class TemplateLoaderTests(TestCase):
try:
r = tmpl.render(template.Context({}))
except template.TemplateDoesNotExist as e:
settings.TEMPLATE_DEBUG = old_td
self.assertEqual(e.args[0], 'missing.html')
self.assertEqual(r, None, 'Template rendering unexpectedly succeeded, produced: ->%r<-' % r)
finally:
loader.template_source_loaders = old_loaders
settings.TEMPLATE_DEBUG = old_td
@override_settings(TEMPLATE_DEBUG=True)
def test_extends_include_missing_cachedloader(self):
"""
Same as test_extends_include_missing_baseloader, only tests
behavior of the cached loader instead of BaseLoader.
"""
old_td, settings.TEMPLATE_DEBUG = settings.TEMPLATE_DEBUG, True
old_loaders = loader.template_source_loaders
try:
@ -348,7 +341,6 @@ class TemplateLoaderTests(TestCase):
self.assertEqual(r, None, 'Template rendering unexpectedly succeeded, produced: ->%r<-' % r)
finally:
loader.template_source_loaders = old_loaders
settings.TEMPLATE_DEBUG = old_td
def test_include_template_argument(self):
"""
@ -1822,17 +1814,15 @@ class TemplateTests(TransRealMixin, TestCase):
return tests
class TemplateTagLoading(unittest.TestCase):
class TemplateTagLoading(TestCase):
def setUp(self):
self.old_path = sys.path[:]
self.old_apps = settings.INSTALLED_APPS
self.egg_dir = '%s/eggs' % os.path.dirname(upath(__file__))
self.old_tag_modules = template_base.templatetags_modules
template_base.templatetags_modules = []
def tearDown(self):
settings.INSTALLED_APPS = self.old_apps
sys.path = self.old_path
template_base.templatetags_modules = self.old_tag_modules
@ -1845,11 +1835,11 @@ class TemplateTagLoading(unittest.TestCase):
self.assertTrue('ImportError' in e.args[0])
self.assertTrue('Xtemplate' in e.args[0])
@override_settings(INSTALLED_APPS=('tagsegg',))
def test_load_error_egg(self):
ttext = "{% load broken_egg %}"
egg_name = '%s/tagsegg.egg' % self.egg_dir
sys.path.append(egg_name)
settings.INSTALLED_APPS = ('tagsegg',)
self.assertRaises(template.TemplateSyntaxError, template.Template, ttext)
try:
template.Template(ttext)
@ -1857,11 +1847,11 @@ class TemplateTagLoading(unittest.TestCase):
self.assertTrue('ImportError' in e.args[0])
self.assertTrue('Xtemplate' in e.args[0])
@override_settings(INSTALLED_APPS=('tagsegg',))
def test_load_working_egg(self):
ttext = "{% load working_egg %}"
egg_name = '%s/tagsegg.egg' % self.egg_dir
sys.path.append(egg_name)
settings.INSTALLED_APPS = ('tagsegg',)
template.Template(ttext)

View File

@ -467,17 +467,11 @@ class ClientTest(TestCase):
self.assertEqual(mail.outbox[1].to[0], 'second@example.com')
self.assertEqual(mail.outbox[1].to[1], 'third@example.com')
@override_settings(
MIDDLEWARE_CLASSES = ('django.middleware.csrf.CsrfViewMiddleware',)
)
class CSRFEnabledClientTests(TestCase):
def setUp(self):
# Enable the CSRF middleware for this test
self.old_MIDDLEWARE_CLASSES = settings.MIDDLEWARE_CLASSES
csrf_middleware_class = 'django.middleware.csrf.CsrfViewMiddleware'
if csrf_middleware_class not in settings.MIDDLEWARE_CLASSES:
settings.MIDDLEWARE_CLASSES += (csrf_middleware_class,)
def tearDown(self):
settings.MIDDLEWARE_CLASSES = self.old_MIDDLEWARE_CLASSES
def test_csrf_enabled_client(self):
"A client can be instantiated with CSRF checks enabled"
csrf_client = Client(enforce_csrf_checks=True)

View File

@ -14,6 +14,7 @@ from django.core.urlresolvers import (reverse, reverse_lazy, resolve, get_callab
from django.http import HttpRequest, HttpResponseRedirect, HttpResponsePermanentRedirect
from django.shortcuts import redirect
from django.test import TestCase
from django.test.utils import override_settings
from django.utils import six
from . import urlconf_outer, middleware, views
@ -453,16 +454,9 @@ class NamespaceTests(TestCase):
self.assertEqual('/inc70/', reverse('inc-ns5:inner-nothing', args=['70']))
self.assertEqual('/inc78/extra/foobar/', reverse('inc-ns5:inner-extra', args=['78','foobar']))
@override_settings(ROOT_URLCONF = urlconf_outer.__name__)
class RequestURLconfTests(TestCase):
def setUp(self):
self.root_urlconf = settings.ROOT_URLCONF
self.middleware_classes = settings.MIDDLEWARE_CLASSES
settings.ROOT_URLCONF = urlconf_outer.__name__
def tearDown(self):
settings.ROOT_URLCONF = self.root_urlconf
settings.MIDDLEWARE_CLASSES = self.middleware_classes
def test_urlconf(self):
response = self.client.get('/test/me/')
self.assertEqual(response.status_code, 200)
@ -473,10 +467,12 @@ class RequestURLconfTests(TestCase):
response = self.client.get('/second_test/')
self.assertEqual(response.status_code, 404)
def test_urlconf_overridden(self):
settings.MIDDLEWARE_CLASSES += (
@override_settings(
MIDDLEWARE_CLASSES=(
'%s.ChangeURLconfMiddleware' % middleware.__name__,
)
)
def test_urlconf_overridden(self):
response = self.client.get('/test/me/')
self.assertEqual(response.status_code, 404)
response = self.client.get('/inner_urlconf/second_test/')
@ -485,60 +481,70 @@ class RequestURLconfTests(TestCase):
self.assertEqual(response.status_code, 200)
self.assertEqual(response.content, b'outer:,inner:/second_test/')
def test_urlconf_overridden_with_null(self):
settings.MIDDLEWARE_CLASSES += (
@override_settings(
MIDDLEWARE_CLASSES=(
'%s.NullChangeURLconfMiddleware' % middleware.__name__,
)
)
def test_urlconf_overridden_with_null(self):
self.assertRaises(ImproperlyConfigured, self.client.get, '/test/me/')
@override_settings(
MIDDLEWARE_CLASSES=(
'%s.ChangeURLconfMiddleware' % middleware.__name__,
'%s.ReverseInnerInResponseMiddleware' % middleware.__name__,
)
)
def test_reverse_inner_in_response_middleware(self):
"""
Test reversing an URL from the *overridden* URLconf from inside
a response middleware.
"""
settings.MIDDLEWARE_CLASSES += (
'%s.ChangeURLconfMiddleware' % middleware.__name__,
'%s.ReverseInnerInResponseMiddleware' % middleware.__name__,
)
response = self.client.get('/second_test/')
self.assertEqual(response.status_code, 200)
self.assertEqual(response.content, b'/second_test/')
@override_settings(
MIDDLEWARE_CLASSES=(
'%s.ChangeURLconfMiddleware' % middleware.__name__,
'%s.ReverseOuterInResponseMiddleware' % middleware.__name__,
)
)
def test_reverse_outer_in_response_middleware(self):
"""
Test reversing an URL from the *default* URLconf from inside
a response middleware.
"""
settings.MIDDLEWARE_CLASSES += (
'%s.ChangeURLconfMiddleware' % middleware.__name__,
'%s.ReverseOuterInResponseMiddleware' % middleware.__name__,
)
message = "Reverse for 'outer' with arguments '()' and keyword arguments '{}' not found."
with self.assertRaisesMessage(NoReverseMatch, message):
self.client.get('/second_test/')
@override_settings(
MIDDLEWARE_CLASSES=(
'%s.ChangeURLconfMiddleware' % middleware.__name__,
'%s.ReverseInnerInStreaming' % middleware.__name__,
)
)
def test_reverse_inner_in_streaming(self):
"""
Test reversing an URL from the *overridden* URLconf from inside
a streaming response.
"""
settings.MIDDLEWARE_CLASSES += (
'%s.ChangeURLconfMiddleware' % middleware.__name__,
'%s.ReverseInnerInStreaming' % middleware.__name__,
)
response = self.client.get('/second_test/')
self.assertEqual(response.status_code, 200)
self.assertEqual(b''.join(response), b'/second_test/')
@override_settings(
MIDDLEWARE_CLASSES=(
'%s.ChangeURLconfMiddleware' % middleware.__name__,
'%s.ReverseOuterInStreaming' % middleware.__name__,
)
)
def test_reverse_outer_in_streaming(self):
"""
Test reversing an URL from the *default* URLconf from inside
a streaming response.
"""
settings.MIDDLEWARE_CLASSES += (
'%s.ChangeURLconfMiddleware' % middleware.__name__,
'%s.ReverseOuterInStreaming' % middleware.__name__,
)
message = "Reverse for 'outer' with arguments '()' and keyword arguments '{}' not found."
with self.assertRaisesMessage(NoReverseMatch, message):
self.client.get('/second_test/')