Improved settings manipulation in the cache tests with the suitable decorators and context managers.

git-svn-id: http://code.djangoproject.com/svn/django/trunk@17039 bcc190cf-cafb-0310-a4f2-bffc1f526a37
This commit is contained in:
Aymeric Augustin 2011-10-26 20:55:36 +00:00
parent 5a16b64ed2
commit 4819797f70
1 changed files with 103 additions and 124 deletions

View File

@ -34,10 +34,12 @@ from .models import Poll, expensive_calculation
# functions/classes for complex data type tests # functions/classes for complex data type tests
def f(): def f():
return 42 return 42
class C: class C:
def m(n): def m(n):
return 24 return 24
class DummyCacheTests(unittest.TestCase): class DummyCacheTests(unittest.TestCase):
# The Dummy cache backend doesn't really behave like a test backend, # The Dummy cache backend doesn't really behave like a test backend,
# so it has different test requirements. # so it has different test requirements.
@ -737,10 +739,12 @@ class BaseCacheTests(object):
self.assertEqual(self.custom_key_cache.get('answer2'), 42) self.assertEqual(self.custom_key_cache.get('answer2'), 42)
self.assertEqual(self.custom_key_cache2.get('answer2'), 42) self.assertEqual(self.custom_key_cache2.get('answer2'), 42)
def custom_key_func(key, key_prefix, version): def custom_key_func(key, key_prefix, version):
"A customized cache key function" "A customized cache key function"
return 'CUSTOM-' + '-'.join([key_prefix, str(version), key]) return 'CUSTOM-' + '-'.join([key_prefix, str(version), key])
class DBCacheTests(unittest.TestCase, BaseCacheTests): class DBCacheTests(unittest.TestCase, BaseCacheTests):
backend_name = 'django.core.cache.backends.db.DatabaseCache' backend_name = 'django.core.cache.backends.db.DatabaseCache'
@ -818,6 +822,7 @@ class LocMemCacheTests(unittest.TestCase, BaseCacheTests):
self.assertEqual(mirror_cache.get('value1'), 42) self.assertEqual(mirror_cache.get('value1'), 42)
self.assertEqual(other_cache.get('value1'), None) self.assertEqual(other_cache.get('value1'), None)
# memcached backend isn't guaranteed to be available. # memcached backend isn't guaranteed to be available.
# To check the memcached backend, the test settings file will # To check the memcached backend, the test settings file will
# need to contain a cache backend setting that points at # need to contain a cache backend setting that points at
@ -853,6 +858,7 @@ class MemcachedCacheTests(unittest.TestCase, BaseCacheTests):
MemcachedCacheTests = unittest.skipUnless(settings.CACHES[DEFAULT_CACHE_ALIAS]['BACKEND'].startswith('django.core.cache.backends.memcached.'), "memcached not available")(MemcachedCacheTests) MemcachedCacheTests = unittest.skipUnless(settings.CACHES[DEFAULT_CACHE_ALIAS]['BACKEND'].startswith('django.core.cache.backends.memcached.'), "memcached not available")(MemcachedCacheTests)
class FileBasedCacheTests(unittest.TestCase, BaseCacheTests): class FileBasedCacheTests(unittest.TestCase, BaseCacheTests):
""" """
Specific test cases for the file-based cache. Specific test cases for the file-based cache.
@ -900,6 +906,7 @@ class FileBasedCacheTests(unittest.TestCase, BaseCacheTests):
self.cache = get_cache('file://%s?max_entries=30' % self.dirname) self.cache = get_cache('file://%s?max_entries=30' % self.dirname)
self.perform_cull_test(50, 29) self.perform_cull_test(50, 29)
class CustomCacheKeyValidationTests(unittest.TestCase): class CustomCacheKeyValidationTests(unittest.TestCase):
""" """
Tests for the ability to mixin a custom ``validate_key`` method to Tests for the ability to mixin a custom ``validate_key`` method to
@ -933,22 +940,12 @@ class GetCacheTests(unittest.TestCase):
self.assertRaises(InvalidCacheBackendError, get_cache, 'does_not_exist') self.assertRaises(InvalidCacheBackendError, get_cache, 'does_not_exist')
class CacheUtils(unittest.TestCase): class CacheUtils(unittest.TestCase):
"""TestCase for django.utils.cache functions.""" """TestCase for django.utils.cache functions."""
def setUp(self): def setUp(self):
self.path = '/cache/test/' self.path = '/cache/test/'
self.old_cache_middleware_key_prefix = settings.CACHE_MIDDLEWARE_KEY_PREFIX
self.old_cache_middleware_seconds = settings.CACHE_MIDDLEWARE_SECONDS
self.orig_use_i18n = settings.USE_I18N
settings.CACHE_MIDDLEWARE_KEY_PREFIX = 'settingsprefix'
settings.CACHE_MIDDLEWARE_SECONDS = 1
settings.USE_I18N = False
def tearDown(self):
settings.CACHE_MIDDLEWARE_KEY_PREFIX = self.old_cache_middleware_key_prefix
settings.CACHE_MIDDLEWARE_SECONDS = self.old_cache_middleware_seconds
settings.USE_I18N = self.orig_use_i18n
def _get_request(self, path, method='GET'): def _get_request(self, path, method='GET'):
request = HttpRequest() request = HttpRequest()
@ -1036,39 +1033,32 @@ class CacheUtils(unittest.TestCase):
parts = set(cc_delim_re.split(response['Cache-Control'])) parts = set(cc_delim_re.split(response['Cache-Control']))
self.assertEqual(parts, expected_cc) self.assertEqual(parts, expected_cc)
class PrefixedCacheUtils(CacheUtils): CacheUtils = override_settings(
def setUp(self): CACHE_MIDDLEWARE_KEY_PREFIX='settingsprefix',
super(PrefixedCacheUtils, self).setUp() CACHE_MIDDLEWARE_SECONDS=1,
self.old_cache_key_prefix = settings.CACHES['default'].get('KEY_PREFIX', None) CACHES={
settings.CACHES['default']['KEY_PREFIX'] = 'cacheprefix' 'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
},
},
USE_I18N=False,
)(CacheUtils)
PrefixedCacheUtils = override_settings(
CACHES={
'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
'KEY_PREFIX': 'cacheprefix',
},
},
)(CacheUtils)
def tearDown(self):
super(PrefixedCacheUtils, self).tearDown()
if self.old_cache_key_prefix is None:
del settings.CACHES['default']['KEY_PREFIX']
else:
settings.CACHES['default']['KEY_PREFIX'] = self.old_cache_key_prefix
class CacheHEADTest(unittest.TestCase): class CacheHEADTest(unittest.TestCase):
def setUp(self): def setUp(self):
self.orig_cache_middleware_seconds = settings.CACHE_MIDDLEWARE_SECONDS
self.orig_cache_middleware_key_prefix = settings.CACHE_MIDDLEWARE_KEY_PREFIX
self.orig_caches = settings.CACHES
settings.CACHE_MIDDLEWARE_SECONDS = 60
settings.CACHE_MIDDLEWARE_KEY_PREFIX = 'test'
settings.CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache'
}
}
self.path = '/cache/test/' self.path = '/cache/test/'
def tearDown(self):
settings.CACHE_MIDDLEWARE_SECONDS = self.orig_cache_middleware_seconds
settings.CACHE_MIDDLEWARE_KEY_PREFIX = self.orig_cache_middleware_key_prefix
settings.CACHES = self.orig_caches
def _get_request(self, method): def _get_request(self, method):
request = HttpRequest() request = HttpRequest()
request.META = { request.META = {
@ -1111,29 +1101,22 @@ class CacheHEADTest(unittest.TestCase):
self.assertNotEqual(get_cache_data, None) self.assertNotEqual(get_cache_data, None)
self.assertEqual(test_content, get_cache_data.content) self.assertEqual(test_content, get_cache_data.content)
CacheHEADTest = override_settings(
CACHE_MIDDLEWARE_SECONDS=60,
CACHE_MIDDLEWARE_KEY_PREFIX='test',
CACHES={
'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
},
},
)(CacheHEADTest)
class CacheI18nTest(unittest.TestCase): class CacheI18nTest(unittest.TestCase):
def setUp(self): def setUp(self):
self.orig_cache_middleware_seconds = settings.CACHE_MIDDLEWARE_SECONDS
self.orig_cache_middleware_key_prefix = settings.CACHE_MIDDLEWARE_KEY_PREFIX
self.orig_caches = settings.CACHES
self.orig_use_i18n = settings.USE_I18N
self.orig_languages = settings.LANGUAGES
settings.LANGUAGES = (
('en', 'English'),
('es', 'Spanish'),
)
settings.CACHE_MIDDLEWARE_KEY_PREFIX = 'settingsprefix'
self.path = '/cache/test/' self.path = '/cache/test/'
def tearDown(self):
settings.CACHE_MIDDLEWARE_SECONDS = self.orig_cache_middleware_seconds
settings.CACHE_MIDDLEWARE_KEY_PREFIX = self.orig_cache_middleware_key_prefix
settings.CACHES = self.orig_caches
settings.USE_I18N = self.orig_use_i18n
settings.LANGUAGES = self.orig_languages
translation.deactivate()
def _get_request(self): def _get_request(self):
request = HttpRequest() request = HttpRequest()
request.META = { request.META = {
@ -1158,8 +1141,8 @@ class CacheI18nTest(unittest.TestCase):
request.session = {} request.session = {}
return request return request
@override_settings(USE_I18N=True)
def test_cache_key_i18n(self): def test_cache_key_i18n(self):
settings.USE_I18N = True
request = self._get_request() request = self._get_request()
lang = translation.get_language() lang = translation.get_language()
response = HttpResponse() response = HttpResponse()
@ -1168,30 +1151,26 @@ class CacheI18nTest(unittest.TestCase):
key2 = get_cache_key(request) key2 = get_cache_key(request)
self.assertEqual(key, key2) self.assertEqual(key, key2)
@override_settings(USE_I18N=False)
def test_cache_key_no_i18n (self): def test_cache_key_no_i18n (self):
settings.USE_I18N = False
request = self._get_request() request = self._get_request()
lang = translation.get_language() lang = translation.get_language()
response = HttpResponse() response = HttpResponse()
key = learn_cache_key(request, response) key = learn_cache_key(request, response)
self.assertFalse(key.endswith(lang), "Cache keys shouldn't include the language name when i18n is inactive") self.assertFalse(key.endswith(lang), "Cache keys shouldn't include the language name when i18n is inactive")
@override_settings(
CACHE_MIDDLEWARE_KEY_PREFIX="test",
CACHE_MIDDLEWARE_SECONDS=60,
USE_ETAGS=True,
USE_I18N=True,
)
def test_middleware(self): def test_middleware(self):
def set_cache(request, lang, msg): def set_cache(request, lang, msg):
translation.activate(lang) with translation.override(lang):
response = HttpResponse() response = HttpResponse()
response.content= msg response.content= msg
return UpdateCacheMiddleware().process_response(request, response) return UpdateCacheMiddleware().process_response(request, response)
settings.CACHE_MIDDLEWARE_SECONDS = 60
settings.CACHE_MIDDLEWARE_KEY_PREFIX = "test"
settings.CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache'
}
}
settings.USE_ETAGS = True
settings.USE_I18N = True
# cache with non empty request.GET # cache with non empty request.GET
request = self._get_request_cache(query_string='foo=bar&other=true') request = self._get_request_cache(query_string='foo=bar&other=true')
@ -1224,74 +1203,56 @@ class CacheI18nTest(unittest.TestCase):
# Check that we use etags # Check that we use etags
self.assertTrue(get_cache_data.has_header('ETag')) self.assertTrue(get_cache_data.has_header('ETag'))
# Check that we can disable etags # Check that we can disable etags
settings.USE_ETAGS = False with self.settings(USE_ETAGS=False):
request._cache_update_cache = True request._cache_update_cache = True
set_cache(request, 'en', en_message) set_cache(request, 'en', en_message)
get_cache_data = FetchFromCacheMiddleware().process_request(request) get_cache_data = FetchFromCacheMiddleware().process_request(request)
self.assertFalse(get_cache_data.has_header('ETag')) self.assertFalse(get_cache_data.has_header('ETag'))
# change the session language and set content # change the session language and set content
request = self._get_request_cache() request = self._get_request_cache()
set_cache(request, 'es', es_message) set_cache(request, 'es', es_message)
# change again the language # change again the language
translation.activate('en') with translation.override('en'):
# retrieve the content from cache # retrieve the content from cache
get_cache_data = FetchFromCacheMiddleware().process_request(request) get_cache_data = FetchFromCacheMiddleware().process_request(request)
self.assertEqual(get_cache_data.content, en_message) self.assertEqual(get_cache_data.content, en_message)
# change again the language # change again the language
translation.activate('es') with translation.override('es'):
get_cache_data = FetchFromCacheMiddleware().process_request(request) get_cache_data = FetchFromCacheMiddleware().process_request(request)
self.assertEqual(get_cache_data.content, es_message) self.assertEqual(get_cache_data.content, es_message)
class PrefixedCacheI18nTest(CacheI18nTest): CacheI18nTest = override_settings(
def setUp(self): CACHE_MIDDLEWARE_KEY_PREFIX='settingsprefix',
super(PrefixedCacheI18nTest, self).setUp() CACHES={
self.old_cache_key_prefix = settings.CACHES['default'].get('KEY_PREFIX', None) 'default': {
settings.CACHES['default']['KEY_PREFIX'] = 'cacheprefix' 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
},
},
LANGUAGES=(
('en', 'English'),
('es', 'Spanish'),
),
)(CacheI18nTest)
def tearDown(self): PrefixedCacheI18nTest = override_settings(
super(PrefixedCacheI18nTest, self).tearDown() CACHES={
if self.old_cache_key_prefix is not None: 'default': {
del settings.CACHES['default']['KEY_PREFIX'] 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
else: 'KEY_PREFIX': 'cacheprefix'
settings.CACHES['default']['KEY_PREFIX'] = self.old_cache_key_prefix },
},
)(CacheI18nTest)
def hello_world_view(request, value): def hello_world_view(request, value):
return HttpResponse('Hello World %s' % value) return HttpResponse('Hello World %s' % value)
class CacheMiddlewareTest(unittest.TestCase): class CacheMiddlewareTest(unittest.TestCase):
def setUp(self): def setUp(self):
self.factory = RequestFactory() self.factory = RequestFactory()
self.orig_cache_middleware_alias = settings.CACHE_MIDDLEWARE_ALIAS
self.orig_cache_middleware_key_prefix = settings.CACHE_MIDDLEWARE_KEY_PREFIX
self.orig_cache_middleware_seconds = settings.CACHE_MIDDLEWARE_SECONDS
self.orig_cache_middleware_anonymous_only = getattr(settings, 'CACHE_MIDDLEWARE_ANONYMOUS_ONLY', False)
self.orig_caches = settings.CACHES
settings.CACHE_MIDDLEWARE_ALIAS = 'other'
settings.CACHE_MIDDLEWARE_KEY_PREFIX = 'middlewareprefix'
settings.CACHE_MIDDLEWARE_SECONDS = 30
settings.CACHE_MIDDLEWARE_ANONYMOUS_ONLY = False
settings.CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache'
},
'other': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
'LOCATION': 'other',
'TIMEOUT': '1'
}
}
def tearDown(self):
settings.CACHE_MIDDLEWARE_ALIAS = self.orig_cache_middleware_alias
settings.CACHE_MIDDLEWARE_KEY_PREFIX = self.orig_cache_middleware_key_prefix
settings.CACHE_MIDDLEWARE_SECONDS = self.orig_cache_middleware_seconds
settings.CACHE_MIDDLEWARE_ANONYMOUS_ONLY = self.orig_cache_middleware_anonymous_only
settings.CACHES = self.orig_caches
def test_constructor(self): def test_constructor(self):
""" """
Ensure the constructor is correctly distinguishing between usage of CacheMiddleware as Ensure the constructor is correctly distinguishing between usage of CacheMiddleware as
@ -1354,11 +1315,11 @@ class CacheMiddlewareTest(unittest.TestCase):
self.assertNotEquals(result, None) self.assertNotEquals(result, None)
self.assertEqual(result.content, 'Hello World 1') self.assertEqual(result.content, 'Hello World 1')
@override_settings(CACHE_MIDDLEWARE_ANONYMOUS_ONLY=True)
def test_cache_middleware_anonymous_only_wont_cause_session_access(self): def test_cache_middleware_anonymous_only_wont_cause_session_access(self):
""" The cache middleware shouldn't cause a session access due to """ The cache middleware shouldn't cause a session access due to
CACHE_MIDDLEWARE_ANONYMOUS_ONLY if nothing else has accessed the CACHE_MIDDLEWARE_ANONYMOUS_ONLY if nothing else has accessed the
session. Refs 13283 """ session. Refs 13283 """
settings.CACHE_MIDDLEWARE_ANONYMOUS_ONLY = True
from django.contrib.sessions.middleware import SessionMiddleware from django.contrib.sessions.middleware import SessionMiddleware
from django.contrib.auth.middleware import AuthenticationMiddleware from django.contrib.auth.middleware import AuthenticationMiddleware
@ -1383,11 +1344,11 @@ class CacheMiddlewareTest(unittest.TestCase):
self.assertEqual(request.session.accessed, False) self.assertEqual(request.session.accessed, False)
@override_settings(CACHE_MIDDLEWARE_ANONYMOUS_ONLY=True)
def test_cache_middleware_anonymous_only_with_cache_page(self): def test_cache_middleware_anonymous_only_with_cache_page(self):
"""CACHE_MIDDLEWARE_ANONYMOUS_ONLY should still be effective when used """CACHE_MIDDLEWARE_ANONYMOUS_ONLY should still be effective when used
with the cache_page decorator: the response to a request from an with the cache_page decorator: the response to a request from an
authenticated user should not be cached.""" authenticated user should not be cached."""
settings.CACHE_MIDDLEWARE_ANONYMOUS_ONLY = True
request = self.factory.get('/view_anon/') request = self.factory.get('/view_anon/')
@ -1498,6 +1459,23 @@ class CacheMiddlewareTest(unittest.TestCase):
response = other_with_timeout_view(request, '18') response = other_with_timeout_view(request, '18')
self.assertEqual(response.content, 'Hello World 18') self.assertEqual(response.content, 'Hello World 18')
CacheMiddlewareTest = override_settings(
CACHE_MIDDLEWARE_ALIAS='other',
CACHE_MIDDLEWARE_KEY_PREFIX='middlewareprefix',
CACHE_MIDDLEWARE_SECONDS=30,
CACHE_MIDDLEWARE_ANONYMOUS_ONLY=False,
CACHES={
'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
},
'other': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
'LOCATION': 'other',
'TIMEOUT': '1',
},
},
)(CacheMiddlewareTest)
class TestWithTemplateResponse(TestCase): class TestWithTemplateResponse(TestCase):
""" """
@ -1604,6 +1582,7 @@ class TestEtagWithAdmin(TestCase):
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
self.assertTrue(response.has_header('ETag')) self.assertTrue(response.has_header('ETag'))
if __name__ == '__main__': if __name__ == '__main__':
unittest.main() unittest.main()