Use the class decorator syntax available in Python >= 2.6. Refs #17965.

git-svn-id: http://code.djangoproject.com/svn/django/trunk@17829 bcc190cf-cafb-0310-a4f2-bffc1f526a37
This commit is contained in:
Aymeric Augustin 2012-03-30 09:08:29 +00:00
parent 9383a2761c
commit eb163f37cb
20 changed files with 147 additions and 199 deletions

View File

@ -8,6 +8,12 @@ from django.test import TestCase
from django.test.utils import override_settings from django.test.utils import override_settings
@override_settings(
TEMPLATE_DIRS=(
os.path.join(os.path.dirname(__file__), 'templates'),
),
USE_TZ=False, # required for loading the fixture
)
class AuthContextProcessorTests(TestCase): class AuthContextProcessorTests(TestCase):
""" """
Tests for the ``django.contrib.auth.context_processors.auth`` processor Tests for the ``django.contrib.auth.context_processors.auth`` processor
@ -95,10 +101,3 @@ class AuthContextProcessorTests(TestCase):
# See bug #12060 # See bug #12060
self.assertEqual(response.context['user'], user) self.assertEqual(response.context['user'], user)
self.assertEqual(user, response.context['user']) self.assertEqual(user, response.context['user'])
AuthContextProcessorTests = override_settings(
TEMPLATE_DIRS=(
os.path.join(os.path.dirname(__file__), 'templates'),
),
USE_TZ=False, # required for loading the fixture
)(AuthContextProcessorTests)

View File

@ -11,6 +11,7 @@ from django.utils import translation
from django.utils.translation import ugettext as _ from django.utils.translation import ugettext as _
@override_settings(USE_TZ=False)
class UserCreationFormTest(TestCase): class UserCreationFormTest(TestCase):
fixtures = ['authtestdata.json'] fixtures = ['authtestdata.json']
@ -75,9 +76,8 @@ class UserCreationFormTest(TestCase):
u = form.save() u = form.save()
self.assertEqual(repr(u), '<User: jsmith@example.com>') self.assertEqual(repr(u), '<User: jsmith@example.com>')
UserCreationFormTest = override_settings(USE_TZ=False)(UserCreationFormTest)
@override_settings(USE_TZ=False)
class AuthenticationFormTest(TestCase): class AuthenticationFormTest(TestCase):
fixtures = ['authtestdata.json'] fixtures = ['authtestdata.json']
@ -128,9 +128,8 @@ class AuthenticationFormTest(TestCase):
self.assertTrue(form.is_valid()) self.assertTrue(form.is_valid())
self.assertEqual(form.non_field_errors(), []) self.assertEqual(form.non_field_errors(), [])
AuthenticationFormTest = override_settings(USE_TZ=False)(AuthenticationFormTest)
@override_settings(USE_TZ=False)
class SetPasswordFormTest(TestCase): class SetPasswordFormTest(TestCase):
fixtures = ['authtestdata.json'] fixtures = ['authtestdata.json']
@ -156,9 +155,8 @@ class SetPasswordFormTest(TestCase):
form = SetPasswordForm(user, data) form = SetPasswordForm(user, data)
self.assertTrue(form.is_valid()) self.assertTrue(form.is_valid())
SetPasswordFormTest = override_settings(USE_TZ=False)(SetPasswordFormTest)
@override_settings(USE_TZ=False)
class PasswordChangeFormTest(TestCase): class PasswordChangeFormTest(TestCase):
fixtures = ['authtestdata.json'] fixtures = ['authtestdata.json']
@ -205,9 +203,8 @@ class PasswordChangeFormTest(TestCase):
self.assertEqual(PasswordChangeForm(user, {}).fields.keys(), self.assertEqual(PasswordChangeForm(user, {}).fields.keys(),
['old_password', 'new_password1', 'new_password2']) ['old_password', 'new_password1', 'new_password2'])
PasswordChangeFormTest = override_settings(USE_TZ=False)(PasswordChangeFormTest)
@override_settings(USE_TZ=False)
class UserChangeFormTest(TestCase): class UserChangeFormTest(TestCase):
fixtures = ['authtestdata.json'] fixtures = ['authtestdata.json']
@ -254,9 +251,7 @@ class UserChangeFormTest(TestCase):
form.as_table() form.as_table()
UserChangeFormTest = override_settings(USE_TZ=False)(UserChangeFormTest) @override_settings(USE_TZ=False)
class PasswordResetFormTest(TestCase): class PasswordResetFormTest(TestCase):
fixtures = ['authtestdata.json'] fixtures = ['authtestdata.json']
@ -334,5 +329,3 @@ class PasswordResetFormTest(TestCase):
self.assertFalse(form.is_valid()) self.assertFalse(form.is_valid())
self.assertEqual(form["email"].errors, self.assertEqual(form["email"].errors,
[_(u"The user account associated with this e-mail address cannot reset the password.")]) [_(u"The user account associated with this e-mail address cannot reset the password.")])
PasswordResetFormTest = override_settings(USE_TZ=False)(PasswordResetFormTest)

View File

@ -4,7 +4,6 @@ from django.contrib.auth.hashers import (is_password_usable,
PBKDF2SHA1PasswordHasher, get_hasher, UNUSABLE_PASSWORD) PBKDF2SHA1PasswordHasher, get_hasher, UNUSABLE_PASSWORD)
from django.utils import unittest from django.utils import unittest
from django.utils.unittest import skipUnless from django.utils.unittest import skipUnless
from django.test.utils import override_settings
try: try:
@ -19,6 +18,7 @@ except ImportError:
class TestUtilsHashPass(unittest.TestCase): class TestUtilsHashPass(unittest.TestCase):
def setUp(self): def setUp(self):
load_hashers(password_hashers=default_hashers) load_hashers(password_hashers=default_hashers)

View File

@ -5,6 +5,7 @@ from django.contrib.auth.models import (Group, User,
SiteProfileNotAvailable, UserManager) SiteProfileNotAvailable, UserManager)
@override_settings(USE_TZ=False)
class ProfileTestCase(TestCase): class ProfileTestCase(TestCase):
fixtures = ['authtestdata.json'] fixtures = ['authtestdata.json']
@ -38,9 +39,8 @@ class ProfileTestCase(TestCase):
settings.AUTH_PROFILE_MODULE = 'foo.bar' settings.AUTH_PROFILE_MODULE = 'foo.bar'
self.assertRaises(SiteProfileNotAvailable, user.get_profile) self.assertRaises(SiteProfileNotAvailable, user.get_profile)
ProfileTestCase = override_settings(USE_TZ=False)(ProfileTestCase)
@override_settings(USE_TZ=False)
class NaturalKeysTestCase(TestCase): class NaturalKeysTestCase(TestCase):
fixtures = ['authtestdata.json'] fixtures = ['authtestdata.json']
@ -53,9 +53,8 @@ class NaturalKeysTestCase(TestCase):
users_group = Group.objects.create(name='users') users_group = Group.objects.create(name='users')
self.assertEquals(Group.objects.get_by_natural_key('users'), users_group) self.assertEquals(Group.objects.get_by_natural_key('users'), users_group)
NaturalKeysTestCase = override_settings(USE_TZ=False)(NaturalKeysTestCase)
@override_settings(USE_TZ=False)
class LoadDataWithoutNaturalKeysTestCase(TestCase): class LoadDataWithoutNaturalKeysTestCase(TestCase):
fixtures = ['regular.json'] fixtures = ['regular.json']
@ -64,9 +63,8 @@ class LoadDataWithoutNaturalKeysTestCase(TestCase):
group = Group.objects.get(name='my_group') group = Group.objects.get(name='my_group')
self.assertEquals(group, user.groups.get()) self.assertEquals(group, user.groups.get())
LoadDataWithoutNaturalKeysTestCase = override_settings(USE_TZ=False)(LoadDataWithoutNaturalKeysTestCase)
@override_settings(USE_TZ=False)
class LoadDataWithNaturalKeysTestCase(TestCase): class LoadDataWithNaturalKeysTestCase(TestCase):
fixtures = ['natural.json'] fixtures = ['natural.json']
@ -75,8 +73,6 @@ class LoadDataWithNaturalKeysTestCase(TestCase):
group = Group.objects.get(name='my_group') group = Group.objects.get(name='my_group')
self.assertEquals(group, user.groups.get()) self.assertEquals(group, user.groups.get())
LoadDataWithNaturalKeysTestCase = override_settings(USE_TZ=False)(LoadDataWithNaturalKeysTestCase)
class UserManagerTestCase(TestCase): class UserManagerTestCase(TestCase):

View File

@ -3,6 +3,7 @@ from django.test.utils import override_settings
from django.contrib.auth import signals from django.contrib.auth import signals
@override_settings(USE_TZ=False)
class SignalTestCase(TestCase): class SignalTestCase(TestCase):
urls = 'django.contrib.auth.tests.urls' urls = 'django.contrib.auth.tests.urls'
fixtures = ['authtestdata.json'] fixtures = ['authtestdata.json']
@ -46,5 +47,3 @@ class SignalTestCase(TestCase):
self.client.get('/logout/next_page/') self.client.get('/logout/next_page/')
self.assertEqual(len(self.logged_out), 1) self.assertEqual(len(self.logged_out), 1)
self.assertEqual(self.logged_out[0].username, 'testclient') self.assertEqual(self.logged_out[0].username, 'testclient')
SignalTestCase = override_settings(USE_TZ=False)(SignalTestCase)

View File

@ -18,6 +18,7 @@ from django.contrib.auth.forms import (AuthenticationForm, PasswordChangeForm,
SetPasswordForm, PasswordResetForm) SetPasswordForm, PasswordResetForm)
@override_settings(USE_TZ=False)
class AuthViewsTestCase(TestCase): class AuthViewsTestCase(TestCase):
""" """
Helper base class for all the follow test cases. Helper base class for all the follow test cases.
@ -52,8 +53,6 @@ class AuthViewsTestCase(TestCase):
def assertContainsEscaped(self, response, text, **kwargs): def assertContainsEscaped(self, response, text, **kwargs):
return self.assertContains(response, escape(force_unicode(text)), **kwargs) return self.assertContains(response, escape(force_unicode(text)), **kwargs)
AuthViewsTestCase = override_settings(USE_TZ=False)(AuthViewsTestCase)
class AuthViewNamedURLTests(AuthViewsTestCase): class AuthViewNamedURLTests(AuthViewsTestCase):
urls = 'django.contrib.auth.urls' urls = 'django.contrib.auth.urls'

View File

@ -38,6 +38,7 @@ def stored_cookie_messages_count(storage, response):
return len(data) return len(data)
@override_settings(SESSION_COOKIE_DOMAIN='.lawrence.com')
class CookieTest(BaseTest): class CookieTest(BaseTest):
storage_class = CookieStorage storage_class = CookieStorage
@ -130,6 +131,3 @@ class CookieTest(BaseTest):
value = encoder.encode(messages) value = encoder.encode(messages)
decoded_messages = json.loads(value, cls=MessageDecoder) decoded_messages = json.loads(value, cls=MessageDecoder)
self.assertEqual(messages, decoded_messages) self.assertEqual(messages, decoded_messages)
CookieTest = override_settings(
SESSION_COOKIE_DOMAIN='.lawrence.com')(CookieTest)

View File

@ -287,7 +287,9 @@ class DatabaseSessionTests(SessionTestsMixin, TestCase):
self.assertEqual(self.session['y'], 2) self.assertEqual(self.session['y'], 2)
DatabaseSessionWithTimeZoneTests = override_settings(USE_TZ=True)(DatabaseSessionTests) @override_settings(USE_TZ=True)
class DatabaseSessionWithTimeZoneTests(DatabaseSessionTests):
pass
class CacheDBSessionTests(SessionTestsMixin, TestCase): class CacheDBSessionTests(SessionTestsMixin, TestCase):
@ -308,7 +310,9 @@ class CacheDBSessionTests(SessionTestsMixin, TestCase):
restore_warnings_state(warnings_state) restore_warnings_state(warnings_state)
CacheDBSessionWithTimeZoneTests = override_settings(USE_TZ=True)(CacheDBSessionTests) @override_settings(USE_TZ=True)
class CacheDBSessionWithTimeZoneTests(CacheDBSessionTests):
pass
# Don't need DB flushing for these tests, so can use unittest.TestCase as base class # Don't need DB flushing for these tests, so can use unittest.TestCase as base class

View File

@ -26,7 +26,8 @@ class HTTPSSitemapTests(SitemapTestsBase):
</urlset> </urlset>
""" % (self.base_url, date.today())) """ % (self.base_url, date.today()))
#@override_settings(SECURE_PROXY_SSL_HEADER=False)
@override_settings(SECURE_PROXY_SSL_HEADER=False)
class HTTPSDetectionSitemapTests(SitemapTestsBase): class HTTPSDetectionSitemapTests(SitemapTestsBase):
extra = {'wsgi.url_scheme': 'https'} extra = {'wsgi.url_scheme': 'https'}
@ -47,5 +48,3 @@ class HTTPSDetectionSitemapTests(SitemapTestsBase):
<url><loc>%s/location/</loc><lastmod>%s</lastmod><changefreq>never</changefreq><priority>0.5</priority></url> <url><loc>%s/location/</loc><lastmod>%s</lastmod><changefreq>never</changefreq><priority>0.5</priority></url>
</urlset> </urlset>
""" % (self.base_url.replace('http://', 'https://'), date.today())) """ % (self.base_url.replace('http://', 'https://'), date.today()))
HTTPSDetectionSitemapTests = override_settings(SECURE_PROXY_SSL_HEADER=False)(HTTPSDetectionSitemapTests)

View File

@ -1450,14 +1450,13 @@ The decorator can also be applied to test case classes::
from django.test import TestCase from django.test import TestCase
from django.test.utils import override_settings from django.test.utils import override_settings
@override_settings(LOGIN_URL='/other/login/')
class LoginTestCase(TestCase): class LoginTestCase(TestCase):
def test_login(self): def test_login(self):
response = self.client.get('/sekrit/') response = self.client.get('/sekrit/')
self.assertRedirects(response, '/other/login/?next=/sekrit/') self.assertRedirects(response, '/other/login/?next=/sekrit/')
LoginTestCase = override_settings(LOGIN_URL='/other/login/')(LoginTestCase)
.. note:: .. note::
When given a class, the decorator modifies the class directly and When given a class, the decorator modifies the class directly and
@ -1467,19 +1466,6 @@ The decorator can also be applied to test case classes::
the original ``LoginTestCase`` is still equally affected by the the original ``LoginTestCase`` is still equally affected by the
decorator. decorator.
On Python 2.6 and higher you can also use the well known decorator syntax to
decorate the class::
from django.test import TestCase
from django.test.utils import override_settings
@override_settings(LOGIN_URL='/other/login/')
class LoginTestCase(TestCase):
def test_login(self):
response = self.client.get('/sekrit/')
self.assertRedirects(response, '/other/login/?next=/sekrit/')
.. note:: .. note::
When overriding settings, make sure to handle the cases in which your app's When overriding settings, make sure to handle the cases in which your app's

View File

@ -18,7 +18,7 @@ from django.test import TransactionTestCase
from django.test.utils import override_settings from django.test.utils import override_settings
# @override_settings(INSTALLED_APPS=('app1', 'app2')) @override_settings(INSTALLED_APPS=('app1', 'app2'))
class ProxyModelInheritanceTests(TransactionTestCase): class ProxyModelInheritanceTests(TransactionTestCase):
def setUp(self): def setUp(self):
@ -41,5 +41,3 @@ class ProxyModelInheritanceTests(TransactionTestCase):
from .app2.models import NiceModel from .app2.models import NiceModel
self.assertEqual(NiceModel.objects.all().count(), 0) self.assertEqual(NiceModel.objects.all().count(), 0)
self.assertEqual(ProxyModel.objects.all().count(), 0) self.assertEqual(ProxyModel.objects.all().count(), 0)
ProxyModelInheritanceTests = override_settings(INSTALLED_APPS=('app1', 'app2'))(ProxyModelInheritanceTests)

View File

@ -74,7 +74,7 @@ class BaseDateTimeTests(TestCase):
time.tzset() time.tzset()
#@override_settings(USE_TZ=False) @override_settings(USE_TZ=False)
class LegacyDatabaseTests(BaseDateTimeTests): class LegacyDatabaseTests(BaseDateTimeTests):
def test_naive_datetime(self): def test_naive_datetime(self):
@ -268,14 +268,11 @@ class LegacyDatabaseTests(BaseDateTimeTests):
[event], [event],
transform=lambda d: d) transform=lambda d: d)
LegacyDatabaseTests = override_settings(USE_TZ=False)(LegacyDatabaseTests)
@override_settings(USE_TZ=True)
#@override_settings(USE_TZ=True)
class NewDatabaseTests(BaseDateTimeTests): class NewDatabaseTests(BaseDateTimeTests):
@requires_tz_support @requires_tz_support
@skipIf(sys.version_info < (2, 6), "this test requires Python >= 2.6")
def test_naive_datetime(self): def test_naive_datetime(self):
dt = datetime.datetime(2011, 9, 1, 13, 20, 30) dt = datetime.datetime(2011, 9, 1, 13, 20, 30)
with warnings.catch_warnings(record=True) as recorded: with warnings.catch_warnings(record=True) as recorded:
@ -289,7 +286,6 @@ class NewDatabaseTests(BaseDateTimeTests):
self.assertEqual(event.dt, dt.replace(tzinfo=EAT)) self.assertEqual(event.dt, dt.replace(tzinfo=EAT))
@requires_tz_support @requires_tz_support
@skipIf(sys.version_info < (2, 6), "this test requires Python >= 2.6")
def test_datetime_from_date(self): def test_datetime_from_date(self):
dt = datetime.date(2011, 9, 1) dt = datetime.date(2011, 9, 1)
with warnings.catch_warnings(record=True) as recorded: with warnings.catch_warnings(record=True) as recorded:
@ -302,7 +298,6 @@ class NewDatabaseTests(BaseDateTimeTests):
self.assertEqual(event.dt, datetime.datetime(2011, 9, 1, tzinfo=EAT)) self.assertEqual(event.dt, datetime.datetime(2011, 9, 1, tzinfo=EAT))
@requires_tz_support @requires_tz_support
@skipIf(sys.version_info < (2, 6), "this test requires Python >= 2.6")
@skipUnlessDBFeature('supports_microsecond_precision') @skipUnlessDBFeature('supports_microsecond_precision')
def test_naive_datetime_with_microsecond(self): def test_naive_datetime_with_microsecond(self):
dt = datetime.datetime(2011, 9, 1, 13, 20, 30, 405060) dt = datetime.datetime(2011, 9, 1, 13, 20, 30, 405060)
@ -317,7 +312,6 @@ class NewDatabaseTests(BaseDateTimeTests):
self.assertEqual(event.dt, dt.replace(tzinfo=EAT)) self.assertEqual(event.dt, dt.replace(tzinfo=EAT))
@requires_tz_support @requires_tz_support
@skipIf(sys.version_info < (2, 6), "this test requires Python >= 2.6")
@skipIfDBFeature('supports_microsecond_precision') @skipIfDBFeature('supports_microsecond_precision')
def test_naive_datetime_with_microsecond_unsupported(self): def test_naive_datetime_with_microsecond_unsupported(self):
dt = datetime.datetime(2011, 9, 1, 13, 20, 30, 405060) dt = datetime.datetime(2011, 9, 1, 13, 20, 30, 405060)
@ -400,7 +394,6 @@ class NewDatabaseTests(BaseDateTimeTests):
self.assertEqual(Event.objects.filter(dt__range=(prev, next)).count(), 1) self.assertEqual(Event.objects.filter(dt__range=(prev, next)).count(), 1)
@requires_tz_support @requires_tz_support
@skipIf(sys.version_info < (2, 6), "this test requires Python >= 2.6")
def test_query_filter_with_naive_datetime(self): def test_query_filter_with_naive_datetime(self):
dt = datetime.datetime(2011, 9, 1, 12, 20, 30, tzinfo=EAT) dt = datetime.datetime(2011, 9, 1, 12, 20, 30, tzinfo=EAT)
Event.objects.create(dt=dt) Event.objects.create(dt=dt)
@ -492,8 +485,6 @@ class NewDatabaseTests(BaseDateTimeTests):
e = MaybeEvent.objects.create() e = MaybeEvent.objects.create()
self.assertEqual(e.dt, None) self.assertEqual(e.dt, None)
NewDatabaseTests = override_settings(USE_TZ=True)(NewDatabaseTests)
class SerializationTests(BaseDateTimeTests): class SerializationTests(BaseDateTimeTests):
@ -648,7 +639,7 @@ class SerializationTests(BaseDateTimeTests):
obj = serializers.deserialize('yaml', data).next().object obj = serializers.deserialize('yaml', data).next().object
self.assertEqual(obj.dt.replace(tzinfo=UTC), dt) self.assertEqual(obj.dt.replace(tzinfo=UTC), dt)
#@override_settings(DATETIME_FORMAT='c', USE_L10N=False, USE_TZ=True) @override_settings(DATETIME_FORMAT='c', USE_L10N=False, USE_TZ=True)
class TemplateTests(BaseDateTimeTests): class TemplateTests(BaseDateTimeTests):
@requires_tz_support @requires_tz_support
@ -887,9 +878,8 @@ class TemplateTests(BaseDateTimeTests):
with timezone.override(ICT): with timezone.override(ICT):
self.assertEqual(tpl.render(Context({})), "+0700") self.assertEqual(tpl.render(Context({})), "+0700")
TemplateTests = override_settings(DATETIME_FORMAT='c', USE_L10N=False, USE_TZ=True)(TemplateTests)
#@override_settings(DATETIME_FORMAT='c', USE_L10N=False, USE_TZ=False) @override_settings(DATETIME_FORMAT='c', USE_L10N=False, USE_TZ=False)
class LegacyFormsTests(BaseDateTimeTests): class LegacyFormsTests(BaseDateTimeTests):
def test_form(self): def test_form(self):
@ -923,9 +913,8 @@ class LegacyFormsTests(BaseDateTimeTests):
e = Event.objects.get() e = Event.objects.get()
self.assertEqual(e.dt, datetime.datetime(2011, 9, 1, 13, 20, 30)) self.assertEqual(e.dt, datetime.datetime(2011, 9, 1, 13, 20, 30))
LegacyFormsTests = override_settings(DATETIME_FORMAT='c', USE_L10N=False, USE_TZ=False)(LegacyFormsTests)
#@override_settings(DATETIME_FORMAT='c', USE_L10N=False, USE_TZ=True) @override_settings(DATETIME_FORMAT='c', USE_L10N=False, USE_TZ=True)
class NewFormsTests(BaseDateTimeTests): class NewFormsTests(BaseDateTimeTests):
@requires_tz_support @requires_tz_support
@ -970,9 +959,8 @@ class NewFormsTests(BaseDateTimeTests):
e = Event.objects.get() e = Event.objects.get()
self.assertEqual(e.dt, datetime.datetime(2011, 9, 1, 10, 20, 30, tzinfo=UTC)) self.assertEqual(e.dt, datetime.datetime(2011, 9, 1, 10, 20, 30, tzinfo=UTC))
NewFormsTests = override_settings(DATETIME_FORMAT='c', USE_L10N=False, USE_TZ=True)(NewFormsTests)
#@override_settings(DATETIME_FORMAT='c', USE_L10N=False, USE_TZ=True) @override_settings(DATETIME_FORMAT='c', USE_L10N=False, USE_TZ=True)
class AdminTests(BaseDateTimeTests): class AdminTests(BaseDateTimeTests):
urls = 'modeltests.timezones.urls' urls = 'modeltests.timezones.urls'
@ -1023,8 +1011,6 @@ class AdminTests(BaseDateTimeTests):
response = self.client.get(reverse('admin:timezones_timestamp_change', args=(t.pk,))) response = self.client.get(reverse('admin:timezones_timestamp_change', args=(t.pk,)))
self.assertContains(response, t.created.astimezone(ICT).isoformat()) self.assertContains(response, t.created.astimezone(ICT).isoformat())
AdminTests = override_settings(DATETIME_FORMAT='c', USE_L10N=False, USE_TZ=True)(AdminTests)
class UtilitiesTests(BaseDateTimeTests): class UtilitiesTests(BaseDateTimeTests):

View File

@ -3315,7 +3315,7 @@ try:
except ImportError: except ImportError:
docutils = None docutils = None
#@unittest.skipUnless(docutils, "no docutils installed.") @unittest.skipUnless(docutils, "no docutils installed.")
class AdminDocsTest(TestCase): class AdminDocsTest(TestCase):
urls = "regressiontests.admin_views.urls" urls = "regressiontests.admin_views.urls"
fixtures = ['admin-views-users.xml'] fixtures = ['admin-views-users.xml']
@ -3357,7 +3357,6 @@ class AdminDocsTest(TestCase):
self.assertContains(response, '<h3 id="built_in-add">add</h3>', html=True) self.assertContains(response, '<h3 id="built_in-add">add</h3>', html=True)
self.assertContains(response, '<li><a href="#built_in-add">add</a></li>', html=True) self.assertContains(response, '<li><a href="#built_in-add">add</a></li>', html=True)
AdminDocsTest = unittest.skipUnless(docutils, "no docutils installed.")(AdminDocsTest)
class ValidXHTMLTests(TestCase): class ValidXHTMLTests(TestCase):
urls = "regressiontests.admin_views.urls" urls = "regressiontests.admin_views.urls"

View File

@ -824,7 +824,9 @@ class DBCacheTests(BaseCacheTests, TransactionTestCase):
self.assertTrue("Cache table 'test cache table' could not be created" in err.getvalue()) self.assertTrue("Cache table 'test cache table' could not be created" in err.getvalue())
DBCacheWithTimeZoneTests = override_settings(USE_TZ=True)(DBCacheTests) @override_settings(USE_TZ=True)
class DBCacheWithTimeZoneTests(DBCacheTests):
pass
class DBCacheRouter(object): class DBCacheRouter(object):
@ -927,6 +929,9 @@ class LocMemCacheTests(unittest.TestCase, BaseCacheTests):
# 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
# your memcache server. # your memcache server.
@unittest.skipUnless(
settings.CACHES[DEFAULT_CACHE_ALIAS]['BACKEND'].startswith('django.core.cache.backends.memcached.'),
"memcached not available")
class MemcachedCacheTests(unittest.TestCase, BaseCacheTests): class MemcachedCacheTests(unittest.TestCase, BaseCacheTests):
backend_name = 'django.core.cache.backends.memcached.MemcachedCache' backend_name = 'django.core.cache.backends.memcached.MemcachedCache'
@ -956,8 +961,6 @@ class MemcachedCacheTests(unittest.TestCase, BaseCacheTests):
# memcached limits key length to 250 # memcached limits key length to 250
self.assertRaises(Exception, self.cache.set, 'a' * 251, 'value') self.assertRaises(Exception, self.cache.set, 'a' * 251, 'value')
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):
""" """
@ -1048,6 +1051,16 @@ class GetCacheTests(unittest.TestCase):
self.assertTrue(cache.closed) self.assertTrue(cache.closed)
@override_settings(
CACHE_MIDDLEWARE_KEY_PREFIX='settingsprefix',
CACHE_MIDDLEWARE_SECONDS=1,
CACHES={
'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
},
},
USE_I18N=False,
)
class CacheUtils(TestCase): class CacheUtils(TestCase):
"""TestCase for django.utils.cache functions.""" """TestCase for django.utils.cache functions."""
@ -1144,27 +1157,28 @@ class CacheUtils(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)
CacheUtils = override_settings(
CACHE_MIDDLEWARE_KEY_PREFIX='settingsprefix',
CACHE_MIDDLEWARE_SECONDS=1,
CACHES={
'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
},
},
USE_I18N=False,
)(CacheUtils)
PrefixedCacheUtils = override_settings( @override_settings(
CACHES={ CACHES={
'default': { 'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
'KEY_PREFIX': 'cacheprefix', 'KEY_PREFIX': 'cacheprefix',
}, },
}, },
)(CacheUtils) )
class PrefixedCacheUtils(CacheUtils):
pass
@override_settings(
CACHE_MIDDLEWARE_SECONDS=60,
CACHE_MIDDLEWARE_KEY_PREFIX='test',
CACHES={
'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
},
},
)
class CacheHEADTest(TestCase): class CacheHEADTest(TestCase):
def setUp(self): def setUp(self):
@ -1216,17 +1230,19 @@ class CacheHEADTest(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, @override_settings(
CACHE_MIDDLEWARE_KEY_PREFIX='test', CACHE_MIDDLEWARE_KEY_PREFIX='settingsprefix',
CACHES={ CACHES={
'default': { 'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
}, },
}, },
)(CacheHEADTest) LANGUAGES=(
('en', 'English'),
('es', 'Spanish'),
),
)
class CacheI18nTest(TestCase): class CacheI18nTest(TestCase):
def setUp(self): def setUp(self):
@ -1391,33 +1407,39 @@ class CacheI18nTest(TestCase):
# reset the language # reset the language
translation.deactivate() translation.deactivate()
CacheI18nTest = override_settings(
CACHE_MIDDLEWARE_KEY_PREFIX='settingsprefix',
CACHES={
'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
},
},
LANGUAGES=(
('en', 'English'),
('es', 'Spanish'),
),
)(CacheI18nTest)
PrefixedCacheI18nTest = override_settings( @override_settings(
CACHES={ CACHES={
'default': { 'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
'KEY_PREFIX': 'cacheprefix' 'KEY_PREFIX': 'cacheprefix'
}, },
}, },
)(CacheI18nTest) )
class PrefixedCacheI18nTest(CacheI18nTest):
pass
def hello_world_view(request, value): def hello_world_view(request, value):
return HttpResponse('Hello World %s' % value) return HttpResponse('Hello World %s' % value)
@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',
},
},
)
class CacheMiddlewareTest(TestCase): class CacheMiddlewareTest(TestCase):
def setUp(self): def setUp(self):
@ -1635,24 +1657,17 @@ class CacheMiddlewareTest(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', @override_settings(
CACHE_MIDDLEWARE_KEY_PREFIX='middlewareprefix', CACHE_MIDDLEWARE_KEY_PREFIX='settingsprefix',
CACHE_MIDDLEWARE_SECONDS=30, CACHE_MIDDLEWARE_SECONDS=1,
CACHE_MIDDLEWARE_ANONYMOUS_ONLY=False,
CACHES={ CACHES={
'default': { 'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
}, },
'other': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
'LOCATION': 'other',
'TIMEOUT': '1',
},
}, },
)(CacheMiddlewareTest) USE_I18N=False,
)
class TestWithTemplateResponse(TestCase): class TestWithTemplateResponse(TestCase):
""" """
Tests various headers w/ TemplateResponse. Tests various headers w/ TemplateResponse.
@ -1740,17 +1755,6 @@ class TestWithTemplateResponse(TestCase):
response = response.render() response = response.render()
self.assertTrue(response.has_header('ETag')) self.assertTrue(response.has_header('ETag'))
TestWithTemplateResponse = override_settings(
CACHE_MIDDLEWARE_KEY_PREFIX='settingsprefix',
CACHE_MIDDLEWARE_SECONDS=1,
CACHES={
'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
},
},
USE_I18N=False,
)(TestWithTemplateResponse)
class TestEtagWithAdmin(TestCase): class TestEtagWithAdmin(TestCase):
# See https://code.djangoproject.com/ticket/16003 # See https://code.djangoproject.com/ticket/16003

View File

@ -5,6 +5,10 @@ from django.test import TestCase
from django.test.utils import override_settings from django.test.utils import override_settings
@override_settings(
STATIC_URL=None,
MEDIA_URL='http://media.example.com/media/',
)
class FormsMediaTestCase(TestCase): class FormsMediaTestCase(TestCase):
"""Tests for the media handling on widgets and forms""" """Tests for the media handling on widgets and forms"""
@ -451,12 +455,11 @@ class FormsMediaTestCase(TestCase):
<link href="/path/to/css3" type="text/css" media="all" rel="stylesheet" /> <link href="/path/to/css3" type="text/css" media="all" rel="stylesheet" />
<link href="/some/form/css" type="text/css" media="all" rel="stylesheet" />""") <link href="/some/form/css" type="text/css" media="all" rel="stylesheet" />""")
FormsMediaTestCase = override_settings(
STATIC_URL=None, @override_settings(
STATIC_URL='http://media.example.com/static/',
MEDIA_URL='http://media.example.com/media/', MEDIA_URL='http://media.example.com/media/',
)(FormsMediaTestCase) )
class StaticFormsMediaTestCase(TestCase): class StaticFormsMediaTestCase(TestCase):
"""Tests for the media handling on widgets and forms""" """Tests for the media handling on widgets and forms"""
@ -902,9 +905,3 @@ class StaticFormsMediaTestCase(TestCase):
<link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" /> <link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" />
<link href="/path/to/css3" type="text/css" media="all" rel="stylesheet" /> <link href="/path/to/css3" type="text/css" media="all" rel="stylesheet" />
<link href="/some/form/css" type="text/css" media="all" rel="stylesheet" />""") <link href="/some/form/css" type="text/css" media="all" rel="stylesheet" />""")
StaticFormsMediaTestCase = override_settings(
STATIC_URL='http://media.example.com/static/',
MEDIA_URL='http://media.example.com/media/',
)(StaticFormsMediaTestCase)

View File

@ -8,6 +8,17 @@ from django.test.utils import override_settings
from django.utils import translation from django.utils import translation
@override_settings(
USE_I18N=True,
LOCALE_PATHS=(
os.path.join(os.path.dirname(__file__), 'locale'),
),
LANGUAGE_CODE='en',
LANGUAGES=(
('en', 'English'),
('fr', 'French'),
),
)
class ContentTypeTests(TestCase): class ContentTypeTests(TestCase):
def test_verbose_name(self): def test_verbose_name(self):
company_type = ContentType.objects.get(app_label='i18n', model='company') company_type = ContentType.objects.get(app_label='i18n', model='company')
@ -20,15 +31,3 @@ class ContentTypeTests(TestCase):
company_type = ContentType.objects.get(app_label='i18n', model='company') company_type = ContentType.objects.get(app_label='i18n', model='company')
company_type.name = 'Other' company_type.name = 'Other'
self.assertEqual(unicode(company_type), 'Other') self.assertEqual(unicode(company_type), 'Other')
ContentTypeTests = override_settings(
USE_I18N=True,
LOCALE_PATHS=(
os.path.join(os.path.dirname(__file__), 'locale'),
),
LANGUAGE_CODE='en',
LANGUAGES=(
('en', 'English'),
('fr', 'French'),
),
)(ContentTypeTests)

View File

@ -9,21 +9,7 @@ from django.template import Template, Context
from django.utils import translation from django.utils import translation
class URLTestCaseBase(TestCase): @override_settings(
"""
TestCase base-class for the URL tests.
"""
urls = 'regressiontests.i18n.patterns.urls.default'
def setUp(self):
# Make sure the cache is empty before we are doing our tests.
clear_url_caches()
def tearDown(self):
# Make sure we will leave an empty cache for other testcases.
clear_url_caches()
URLTestCaseBase = override_settings(
USE_I18N=True, USE_I18N=True,
LOCALE_PATHS=( LOCALE_PATHS=(
os.path.join(os.path.dirname(__file__), 'locale'), os.path.join(os.path.dirname(__file__), 'locale'),
@ -41,7 +27,20 @@ URLTestCaseBase = override_settings(
'django.middleware.locale.LocaleMiddleware', 'django.middleware.locale.LocaleMiddleware',
'django.middleware.common.CommonMiddleware', 'django.middleware.common.CommonMiddleware',
), ),
)(URLTestCaseBase) )
class URLTestCaseBase(TestCase):
"""
TestCase base-class for the URL tests.
"""
urls = 'regressiontests.i18n.patterns.urls.default'
def setUp(self):
# Make sure the cache is empty before we are doing our tests.
clear_url_caches()
def tearDown(self):
# Make sure we will leave an empty cache for other testcases.
clear_url_caches()
class URLPrefixTests(URLTestCaseBase): class URLPrefixTests(URLTestCaseBase):

View File

@ -584,6 +584,7 @@ class GZipMiddlewareTest(TestCase):
self.assertEqual(r.get('Content-Encoding'), None) self.assertEqual(r.get('Content-Encoding'), None)
@override_settings(USE_ETAGS=True)
class ETagGZipMiddlewareTest(TestCase): class ETagGZipMiddlewareTest(TestCase):
""" """
Tests if the ETag middleware behaves correctly with GZip middleware. Tests if the ETag middleware behaves correctly with GZip middleware.
@ -610,6 +611,3 @@ class ETagGZipMiddlewareTest(TestCase):
nogzip_etag = response.get('ETag') nogzip_etag = response.get('ETag')
self.assertNotEqual(gzip_etag, nogzip_etag) self.assertNotEqual(gzip_etag, nogzip_etag)
ETagGZipMiddlewareTest = override_settings(
USE_ETAGS=True,
)(ETagGZipMiddlewareTest)

View File

@ -6,7 +6,7 @@ from django.test import TransactionTestCase, TestCase, signals
from django.test.utils import override_settings from django.test.utils import override_settings
# @override_settings(TEST='override') @override_settings(TEST='override')
class FullyDecoratedTranTestCase(TransactionTestCase): class FullyDecoratedTranTestCase(TransactionTestCase):
def test_override(self): def test_override(self):
@ -22,9 +22,8 @@ class FullyDecoratedTranTestCase(TransactionTestCase):
def test_decorated_testcase_module(self): def test_decorated_testcase_module(self):
self.assertEquals(FullyDecoratedTranTestCase.__module__, __name__) self.assertEquals(FullyDecoratedTranTestCase.__module__, __name__)
FullyDecoratedTranTestCase = override_settings(TEST='override')(FullyDecoratedTranTestCase)
# @override_settings(TEST='override') @override_settings(TEST='override')
class FullyDecoratedTestCase(TestCase): class FullyDecoratedTestCase(TestCase):
def test_override(self): def test_override(self):
@ -34,8 +33,6 @@ class FullyDecoratedTestCase(TestCase):
def test_method_override(self): def test_method_override(self):
self.assertEqual(settings.TEST, 'override2') self.assertEqual(settings.TEST, 'override2')
FullyDecoratedTestCase = override_settings(TEST='override')(FullyDecoratedTestCase)
class ClassDecoratedTestCaseSuper(TestCase): class ClassDecoratedTestCaseSuper(TestCase):
""" """
@ -47,6 +44,7 @@ class ClassDecoratedTestCaseSuper(TestCase):
pass pass
@override_settings(TEST='override')
class ClassDecoratedTestCase(ClassDecoratedTestCaseSuper): class ClassDecoratedTestCase(ClassDecoratedTestCaseSuper):
def test_override(self): def test_override(self):
self.assertEqual(settings.TEST, 'override') self.assertEqual(settings.TEST, 'override')
@ -66,7 +64,6 @@ class ClassDecoratedTestCase(ClassDecoratedTestCaseSuper):
except RuntimeError, e: except RuntimeError, e:
self.fail() self.fail()
ClassDecoratedTestCase = override_settings(TEST='override')(ClassDecoratedTestCase)
class SettingGetter(object): class SettingGetter(object):
def __init__(self): def __init__(self):

View File

@ -98,9 +98,9 @@ class BaseStaticFilesTestCase(object):
self.assertRaises(exc, self.assertStaticRenders, path, result, **kwargs) self.assertRaises(exc, self.assertStaticRenders, path, result, **kwargs)
@override_settings(**TEST_SETTINGS)
class StaticFilesTestCase(BaseStaticFilesTestCase, TestCase): class StaticFilesTestCase(BaseStaticFilesTestCase, TestCase):
pass pass
StaticFilesTestCase = override_settings(**TEST_SETTINGS)(StaticFilesTestCase)
class BaseCollectionTestCase(BaseStaticFilesTestCase): class BaseCollectionTestCase(BaseStaticFilesTestCase):
@ -343,17 +343,21 @@ class TestCollectionFilesOverride(CollectionTestCase):
self.assertFileContains('file2.txt', 'duplicate of file2.txt') self.assertFileContains('file2.txt', 'duplicate of file2.txt')
@override_settings(
STATICFILES_STORAGE='regressiontests.staticfiles_tests.storage.DummyStorage',
)
class TestCollectionNonLocalStorage(CollectionTestCase, TestNoFilesCreated): class TestCollectionNonLocalStorage(CollectionTestCase, TestNoFilesCreated):
""" """
Tests for #15035 Tests for #15035
""" """
pass pass
TestCollectionNonLocalStorage = override_settings(
STATICFILES_STORAGE='regressiontests.staticfiles_tests.storage.DummyStorage',
)(TestCollectionNonLocalStorage)
# we set DEBUG to False here since the template tag wouldn't work otherwise
@override_settings(**dict(TEST_SETTINGS,
STATICFILES_STORAGE='django.contrib.staticfiles.storage.CachedStaticFilesStorage',
DEBUG=False,
))
class TestCollectionCachedStorage(BaseCollectionTestCase, class TestCollectionCachedStorage(BaseCollectionTestCase,
BaseStaticFilesTestCase, TestCase): BaseStaticFilesTestCase, TestCase):
""" """
@ -515,12 +519,6 @@ class TestCollectionCachedStorage(BaseCollectionTestCase,
self.assertEqual(cache_key, 'staticfiles:e95bbc36387084582df2a70750d7b351') self.assertEqual(cache_key, 'staticfiles:e95bbc36387084582df2a70750d7b351')
# we set DEBUG to False here since the template tag wouldn't work otherwise
TestCollectionCachedStorage = override_settings(**dict(TEST_SETTINGS,
STATICFILES_STORAGE='django.contrib.staticfiles.storage.CachedStaticFilesStorage',
DEBUG=False,
))(TestCollectionCachedStorage)
if sys.platform != 'win32': if sys.platform != 'win32':
class TestCollectionLinks(CollectionTestCase, TestDefaults): class TestCollectionLinks(CollectionTestCase, TestDefaults):