Ticket #17194: 17194-3.diff

File 17194-3.diff, 30.7 KB (added by Claude Paroz, 13 years ago)

Alternate approach with DefaultSettingsTestCase

  • django/contrib/auth/tests/auth_backends.py

    diff --git a/django/contrib/auth/tests/auth_backends.py b/django/contrib/auth/tests/auth_backends.py
    index afef0e7..d203fc8 100644
    a b from django.conf import settings  
    22from django.contrib.auth.models import User, Group, Permission, AnonymousUser
    33from django.contrib.contenttypes.models import ContentType
    44from django.core.exceptions import ImproperlyConfigured
    5 from django.test import TestCase
     5from django.test import DefaultSettingsTestCase
     6from django.test.utils import override_settings
    67
    78
    8 class BackendTest(TestCase):
     9class CustomBackendTestCase(DefaultSettingsTestCase):
     10    def setUp(self):
     11        self.settings_override = override_settings(
     12            AUTHENTICATION_BACKENDS=(self.backend,)
     13        )
     14        self.settings_override.enable()
    915
    10     backend = 'django.contrib.auth.backends.ModelBackend'
     16    def tearDown(self):
     17        self.settings_override.disable()
     18        # Some tests (e.g. custom_perms) mess with ContentTypes, which will
     19        # be cached; flush the cache to ensure there are no side effects
     20        # Refs #14975, #14925
     21        ContentType.objects.clear_cache()
    1122
     23
     24class AdditionalBackendTestCase(DefaultSettingsTestCase):
    1225    def setUp(self):
    13         self.curr_auth = settings.AUTHENTICATION_BACKENDS
    14         settings.AUTHENTICATION_BACKENDS = (self.backend,)
    15         User.objects.create_user('test', 'test@example.com', 'test')
    16         User.objects.create_superuser('test2', 'test2@example.com', 'test')
     26        self.settings_override = override_settings(
     27            AUTHENTICATION_BACKENDS = settings.AUTHENTICATION_BACKENDS + (self.backend,)
     28        )
     29        self.settings_override.enable()
    1730
    1831    def tearDown(self):
    19         settings.AUTHENTICATION_BACKENDS = self.curr_auth
    20         # The custom_perms test messes with ContentTypes, which will
     32        self.settings_override.disable()
     33        # Some tests (e.g. custom_perms) mess with ContentTypes, which will
    2134        # be cached; flush the cache to ensure there are no side effects
    2235        # Refs #14975, #14925
    2336        ContentType.objects.clear_cache()
    2437
     38
     39class BackendTest(CustomBackendTestCase):
     40
     41    backend = 'django.contrib.auth.backends.ModelBackend'
     42
     43    def setUp(self):
     44        super(BackendTest, self).setUp()
     45        User.objects.create_user('test', 'test@example.com', 'test')
     46        User.objects.create_superuser('test2', 'test2@example.com', 'test')
     47
    2548    def test_has_perm(self):
    2649        user = User.objects.get(username='test')
    2750        self.assertEqual(user.has_perm('auth.test'), False)
    class SimpleRowlevelBackend(object):  
    154177            return ['none']
    155178
    156179
    157 class RowlevelBackendTest(TestCase):
     180class RowlevelBackendTest(AdditionalBackendTestCase):
    158181    """
    159182    Tests for auth backend that supports object level permissions
    160183    """
    161184    backend = 'django.contrib.auth.tests.auth_backends.SimpleRowlevelBackend'
    162185
    163186    def setUp(self):
    164         self.curr_auth = settings.AUTHENTICATION_BACKENDS
    165         settings.AUTHENTICATION_BACKENDS = tuple(self.curr_auth) + (self.backend,)
     187        super(RowlevelBackendTest, self).setUp()
    166188        self.user1 = User.objects.create_user('test', 'test@example.com', 'test')
    167189        self.user2 = User.objects.create_user('test2', 'test2@example.com', 'test')
    168190        self.user3 = User.objects.create_user('test3', 'test3@example.com', 'test')
    169191
    170     def tearDown(self):
    171         settings.AUTHENTICATION_BACKENDS = self.curr_auth
    172         # The get_group_permissions test messes with ContentTypes, which will
    173         # be cached; flush the cache to ensure there are no side effects
    174         # Refs #14975, #14925
    175         ContentType.objects.clear_cache()
    176 
    177192    def test_has_perm(self):
    178193        self.assertEqual(self.user1.has_perm('perm', TestObj()), False)
    179194        self.assertEqual(self.user2.has_perm('perm', TestObj()), True)
    class RowlevelBackendTest(TestCase):  
    189204        self.assertEqual(self.user2.get_all_permissions(), set([]))
    190205
    191206    def test_get_group_permissions(self):
    192         content_type=ContentType.objects.get_for_model(Group)
    193207        group = Group.objects.create(name='test_group')
    194208        self.user3.groups.add(group)
    195209        self.assertEqual(self.user3.get_group_permissions(TestObj()), set(['group_perm']))
    class AnonymousUserBackend(SimpleRowlevelBackend):  
    199213    supports_inactive_user = False
    200214
    201215
    202 class AnonymousUserBackendTest(TestCase):
     216class AnonymousUserBackendTest(CustomBackendTestCase):
    203217    """
    204218    Tests for AnonymousUser delegating to backend.
    205219    """
    class AnonymousUserBackendTest(TestCase):  
    207221    backend = 'django.contrib.auth.tests.auth_backends.AnonymousUserBackend'
    208222
    209223    def setUp(self):
    210         self.curr_auth = settings.AUTHENTICATION_BACKENDS
    211         settings.AUTHENTICATION_BACKENDS = (self.backend,)
     224        super(AnonymousUserBackendTest, self).setUp()
    212225        self.user1 = AnonymousUser()
    213226
    214     def tearDown(self):
    215         settings.AUTHENTICATION_BACKENDS = self.curr_auth
    216 
    217227    def test_has_perm(self):
    218228        self.assertEqual(self.user1.has_perm('perm', TestObj()), False)
    219229        self.assertEqual(self.user1.has_perm('anon', TestObj()), True)
    class AnonymousUserBackendTest(TestCase):  
    232242
    233243
    234244
    235 class NoBackendsTest(TestCase):
     245class NoBackendsTest(DefaultSettingsTestCase):
    236246    """
    237247    Tests that an appropriate error is raised if no auth backends are provided.
    238248    """
    239249    def setUp(self):
    240         self.old_AUTHENTICATION_BACKENDS = settings.AUTHENTICATION_BACKENDS
    241         settings.AUTHENTICATION_BACKENDS = []
    242250        self.user = User.objects.create_user('test', 'test@example.com', 'test')
    243251
    244     def tearDown(self):
    245         settings.AUTHENTICATION_BACKENDS = self.old_AUTHENTICATION_BACKENDS
    246 
     252    @override_settings(AUTHENTICATION_BACKENDS=[])
    247253    def test_raises_exception(self):
    248254        self.assertRaises(ImproperlyConfigured, self.user.has_perm, ('perm', TestObj(),))
    249255
    class NoInActiveUserBackend(SimpleRowlevelBackend):  
    256262    supports_inactive_user = False
    257263
    258264
    259 class InActiveUserBackendTest(TestCase):
     265class InActiveUserBackendTest(CustomBackendTestCase):
    260266    """
    261267    Tests for a inactive user delegating to backend if it has 'supports_inactive_user' = True
    262268    """
    class InActiveUserBackendTest(TestCase):  
    264270    backend = 'django.contrib.auth.tests.auth_backends.InActiveUserBackend'
    265271
    266272    def setUp(self):
    267         self.curr_auth = settings.AUTHENTICATION_BACKENDS
    268         settings.AUTHENTICATION_BACKENDS = (self.backend,)
     273        super(InActiveUserBackendTest, self).setUp()
    269274        self.user1 = User.objects.create_user('test', 'test@example.com', 'test')
    270275        self.user1.is_active = False
    271276        self.user1.save()
    272277
    273     def tearDown(self):
    274         settings.AUTHENTICATION_BACKENDS = self.curr_auth
    275 
    276278    def test_has_perm(self):
    277279        self.assertEqual(self.user1.has_perm('perm', TestObj()), False)
    278280        self.assertEqual(self.user1.has_perm('inactive', TestObj()), True)
    class InActiveUserBackendTest(TestCase):  
    282284        self.assertEqual(self.user1.has_module_perms("app2"), False)
    283285
    284286
    285 class NoInActiveUserBackendTest(TestCase):
     287class NoInActiveUserBackendTest(AdditionalBackendTestCase):
    286288    """
    287289    Tests that an inactive user does not delegate to backend if it has 'supports_inactive_user' = False
    288290    """
    289291    backend = 'django.contrib.auth.tests.auth_backends.NoInActiveUserBackend'
    290292
    291293    def setUp(self):
    292         self.curr_auth = settings.AUTHENTICATION_BACKENDS
    293         settings.AUTHENTICATION_BACKENDS = tuple(self.curr_auth) + (self.backend,)
     294        super(NoInActiveUserBackendTest, self).setUp()
    294295        self.user1 = User.objects.create_user('test', 'test@example.com', 'test')
    295296        self.user1.is_active = False
    296297        self.user1.save()
    297298
    298     def tearDown(self):
    299         settings.AUTHENTICATION_BACKENDS = self.curr_auth
    300 
    301299    def test_has_perm(self):
    302300        self.assertEqual(self.user1.has_perm('perm', TestObj()), False)
    303301        self.assertEqual(self.user1.has_perm('inactive', TestObj()), True)
    class NoInActiveUserBackendTest(TestCase):  
    305303    def test_has_module_perms(self):
    306304        self.assertEqual(self.user1.has_module_perms("app1"), False)
    307305        self.assertEqual(self.user1.has_module_perms("app2"), False)
    308 
  • django/contrib/auth/tests/basic.py

    diff --git a/django/contrib/auth/tests/basic.py b/django/contrib/auth/tests/basic.py
    index 9f94c2a..f44be08 100644
    a b  
    1 from django.test import TestCase
    2 from django.utils.unittest import skipUnless
    3 from django.contrib.auth.models import User, AnonymousUser
     1from StringIO import StringIO
     2
    43from django.contrib.auth import utils
     4from django.contrib.auth.models import User, AnonymousUser
    55from django.core.management import call_command
    6 from StringIO import StringIO
     6from django.test import DefaultSettingsTestCase
     7from django.utils.unittest import skipUnless
    78
    89try:
    910    import crypt as crypt_module
    except ImportError:  
    1112    crypt_module = None
    1213
    1314
    14 class BasicTestCase(TestCase):
     15class BasicTestCase(DefaultSettingsTestCase):
    1516    def test_user(self):
    1617        "Check that users can be created and can set their password"
    1718        u = User.objects.create_user('testuser', 'test@example.com', 'testpw')
    class BasicTestCase(TestCase):  
    113114        self.assertFalse(u.has_usable_password())
    114115
    115116
    116 class PasswordUtilsTestCase(TestCase):
     117class PasswordUtilsTestCase(DefaultSettingsTestCase):
    117118
    118119    def _test_make_password(self, algo):
    119120        password = utils.make_password(algo, "foobar")
  • django/contrib/auth/tests/context_processors.py

    diff --git a/django/contrib/auth/tests/context_processors.py b/django/contrib/auth/tests/context_processors.py
    index 49172c6..0e1f5ac 100644
    a b  
    1 import os
    2 
    3 from django.conf import settings
    41from django.contrib.auth import authenticate
     2from django.contrib.auth.tests.views import AuthViewsTestCase
    53from django.db.models import Q
    6 from django.test import TestCase
    74
    85
    9 class AuthContextProcessorTests(TestCase):
     6class AuthContextProcessorTests(AuthViewsTestCase):
    107    """
    118    Tests for the ``django.contrib.auth.context_processors.auth`` processor
    129    """
    13     urls = 'django.contrib.auth.tests.urls'
    1410    fixtures = ['context-processors-users.xml']
    1511
    16     def setUp(self):
    17         self.old_TEMPLATE_DIRS = settings.TEMPLATE_DIRS
    18         settings.TEMPLATE_DIRS = (
    19             os.path.join(os.path.dirname(__file__), 'templates'),
    20         )
    21 
    22     def tearDown(self):
    23         settings.TEMPLATE_DIRS = self.old_TEMPLATE_DIRS
    24 
    2512    def test_session_not_accessed(self):
    2613        """
    2714        Tests that the session is not accessed simply by including
  • django/contrib/auth/tests/forms.py

    diff --git a/django/contrib/auth/tests/forms.py b/django/contrib/auth/tests/forms.py
    index 429967c..85f7d4b 100644
    a b import os  
    33from django.core import mail
    44from django.contrib.auth.models import User
    55from django.contrib.auth.forms import UserCreationForm, AuthenticationForm,  PasswordChangeForm, SetPasswordForm, UserChangeForm, PasswordResetForm
    6 from django.test import TestCase
     6from django.test import DefaultSettingsTestCase
    77
    88
    9 class UserCreationFormTest(TestCase):
     9class UserCreationFormTest(DefaultSettingsTestCase):
    1010
    1111    fixtures = ['authtestdata.json']
    1212
    class UserCreationFormTest(TestCase):  
    7777        self.assertEqual(repr(u), '<User: jsmith@example.com>')
    7878
    7979
    80 class AuthenticationFormTest(TestCase):
     80class AuthenticationFormTest(DefaultSettingsTestCase):
    8181
    8282    fixtures = ['authtestdata.json']
    8383
    class AuthenticationFormTest(TestCase):  
    116116        self.assertEqual(form.non_field_errors(), [])
    117117
    118118
    119 class SetPasswordFormTest(TestCase):
     119class SetPasswordFormTest(DefaultSettingsTestCase):
    120120
    121121    fixtures = ['authtestdata.json']
    122122
    class SetPasswordFormTest(TestCase):  
    142142        self.assertTrue(form.is_valid())
    143143
    144144
    145 class PasswordChangeFormTest(TestCase):
     145class PasswordChangeFormTest(DefaultSettingsTestCase):
    146146
    147147    fixtures = ['authtestdata.json']
    148148
    class PasswordChangeFormTest(TestCase):  
    190190        self.assertEqual(PasswordChangeForm(user, {}).fields.keys(),
    191191                         ['old_password', 'new_password1', 'new_password2'])
    192192
    193 class UserChangeFormTest(TestCase):
     193class UserChangeFormTest(DefaultSettingsTestCase):
    194194
    195195    fixtures = ['authtestdata.json']
    196196
    class UserChangeFormTest(TestCase):  
    218218        form = MyUserForm({})
    219219
    220220
    221 class PasswordResetFormTest(TestCase):
     221class PasswordResetFormTest(DefaultSettingsTestCase):
    222222
    223223    fixtures = ['authtestdata.json']
    224224
  • django/contrib/auth/tests/management.py

    diff --git a/django/contrib/auth/tests/management.py b/django/contrib/auth/tests/management.py
    index 0af6873..bec15b4 100644
    a b  
    1 from django.test import TestCase
    21from django.contrib.auth import models, management
     2from django.test import DefaultSettingsTestCase
    33
    44
    5 class GetDefaultUsernameTestCase(TestCase):
     5class GetDefaultUsernameTestCase(DefaultSettingsTestCase):
    66
    77    def setUp(self):
    88        self._getpass_getuser = management.get_system_username
  • django/contrib/auth/tests/models.py

    diff --git a/django/contrib/auth/tests/models.py b/django/contrib/auth/tests/models.py
    index 754c6db..8a25224 100644
    a b  
    1 from django.conf import settings
    2 from django.test import TestCase
    31from django.contrib.auth.models import User, SiteProfileNotAvailable
     2from django.test import DefaultSettingsTestCase
     3from django.test.utils import override_settings
    44
    5 class ProfileTestCase(TestCase):
    6     fixtures = ['authtestdata.json']
    7     def setUp(self):
    8         """Backs up the AUTH_PROFILE_MODULE"""
    9         self.old_AUTH_PROFILE_MODULE = getattr(settings,
    10                                                'AUTH_PROFILE_MODULE', None)
    11 
    12     def tearDown(self):
    13         """Restores the AUTH_PROFILE_MODULE -- if it was not set it is deleted,
    14         otherwise the old value is restored"""
    15         if self.old_AUTH_PROFILE_MODULE is None and \
    16                 hasattr(settings, 'AUTH_PROFILE_MODULE'):
    17             del settings.AUTH_PROFILE_MODULE
    185
    19         if self.old_AUTH_PROFILE_MODULE is not None:
    20             settings.AUTH_PROFILE_MODULE = self.old_AUTH_PROFILE_MODULE
     6class ProfileTestCase(DefaultSettingsTestCase):
     7    fixtures = ['authtestdata.json']
    218
     9    @override_settings(AUTH_PROFILE_MODULE='')
    2210    def test_site_profile_not_available(self):
    2311        # calling get_profile without AUTH_PROFILE_MODULE set
    24         if hasattr(settings, 'AUTH_PROFILE_MODULE'):
    25             del settings.AUTH_PROFILE_MODULE
    2612        user = User.objects.get(username='testclient')
    2713        self.assertRaises(SiteProfileNotAvailable, user.get_profile)
    2814
     15    @override_settings(AUTH_PROFILE_MODULE='foobar')
     16    def test_site_profile_bad_syntax(self):
    2917        # Bad syntax in AUTH_PROFILE_MODULE:
    30         settings.AUTH_PROFILE_MODULE = 'foobar'
     18        user = User.objects.get(username='testclient')
    3119        self.assertRaises(SiteProfileNotAvailable, user.get_profile)
    3220
     21    @override_settings(AUTH_PROFILE_MODULE='foo.bar')
     22    def test_site_profile_missing_module(self):
    3323        # module that doesn't exist
    34         settings.AUTH_PROFILE_MODULE = 'foo.bar'
     24        user = User.objects.get(username='testclient')
    3525        self.assertRaises(SiteProfileNotAvailable, user.get_profile)
  • django/contrib/auth/tests/remote_user.py

    diff --git a/django/contrib/auth/tests/remote_user.py b/django/contrib/auth/tests/remote_user.py
    index 6ca6a2b..201a434 100644
    a b from datetime import datetime  
    33from django.conf import settings
    44from django.contrib.auth.backends import RemoteUserBackend
    55from django.contrib.auth.models import User
    6 from django.test import TestCase
     6from django.test import DefaultSettingsTestCase
     7from django.test.utils import override_settings
    78
    89
    9 class RemoteUserTest(TestCase):
     10class RemoteUserTest(DefaultSettingsTestCase):
    1011
    1112    urls = 'django.contrib.auth.tests.urls'
    1213    middleware = 'django.contrib.auth.middleware.RemoteUserMiddleware'
    class RemoteUserTest(TestCase):  
    1718    known_user2 = 'knownuser2'
    1819
    1920    def setUp(self):
    20         self.curr_middleware = settings.MIDDLEWARE_CLASSES
    21         self.curr_auth = settings.AUTHENTICATION_BACKENDS
    22         settings.MIDDLEWARE_CLASSES += (self.middleware,)
    23         settings.AUTHENTICATION_BACKENDS = (self.backend,)
     21        self.settings_override = override_settings(
     22            MIDDLEWARE_CLASSES = settings.MIDDLEWARE_CLASSES + (self.middleware,),
     23            AUTHENTICATION_BACKENDS = (self.backend,),
     24        )
     25        self.settings_override.enable()
     26
     27    def tearDown(self):
     28        self.settings_override.disable()
    2429
    2530    def test_no_remote_user(self):
    2631        """
    class RemoteUserTest(TestCase):  
    9297        response = self.client.get('/remote_user/', REMOTE_USER=self.known_user)
    9398        self.assertEqual(default_login, response.context['user'].last_login)
    9499
    95     def tearDown(self):
    96         """Restores settings to avoid breaking other tests."""
    97         settings.MIDDLEWARE_CLASSES = self.curr_middleware
    98         settings.AUTHENTICATION_BACKENDS = self.curr_auth
    99 
    100100
    101101class RemoteUserNoCreateBackend(RemoteUserBackend):
    102102    """Backend that doesn't create unknown users."""
  • django/contrib/auth/tests/signals.py

    diff --git a/django/contrib/auth/tests/signals.py b/django/contrib/auth/tests/signals.py
    index 3806021..4b507a1 100644
    a b  
    1 from django.test import TestCase
    21from django.contrib.auth import signals
     2from django.test import DefaultSettingsTestCase
    33
    44
    5 class SignalTestCase(TestCase):
     5class SignalTestCase(DefaultSettingsTestCase):
    66    urls = 'django.contrib.auth.tests.urls'
    77    fixtures = ['authtestdata.json']
    88
  • django/contrib/auth/tests/tokens.py

    diff --git a/django/contrib/auth/tests/tokens.py b/django/contrib/auth/tests/tokens.py
    index f7fc32e..b26646a 100644
    a b from datetime import date, timedelta  
    33from django.conf import settings
    44from django.contrib.auth.models import User
    55from django.contrib.auth.tokens import PasswordResetTokenGenerator
    6 from django.test import TestCase
     6from django.test import DefaultSettingsTestCase
    77
    88
    9 class TokenGeneratorTest(TestCase):
     9class TokenGeneratorTest(DefaultSettingsTestCase):
    1010
    1111    def test_make_token(self):
    1212        """
  • django/contrib/auth/tests/views.py

    diff --git a/django/contrib/auth/tests/views.py b/django/contrib/auth/tests/views.py
    index 9fccb3e..da598b0 100644
    a b import urllib  
    66from django.conf import settings
    77from django.contrib.auth import SESSION_KEY, REDIRECT_FIELD_NAME
    88from django.contrib.auth.forms import AuthenticationForm
    9 from django.contrib.sites.models import Site, RequestSite
    109from django.contrib.auth.models import User
    11 from django.core.urlresolvers import NoReverseMatch
    12 from django.test import TestCase
     10from django.contrib.sites.models import Site, RequestSite
    1311from django.core import mail
    14 from django.core.urlresolvers import reverse
     12from django.core.urlresolvers import reverse, NoReverseMatch
    1513from django.http import QueryDict
     14from django.test import DefaultSettingsTestCase
     15from django.test.utils import override_settings
    1616
    1717
    18 class AuthViewsTestCase(TestCase):
     18class AuthViewsTestCase(DefaultSettingsTestCase):
    1919    """
    2020    Helper base class for all the follow test cases.
    2121    """
    2222    fixtures = ['authtestdata.json']
    2323    urls = 'django.contrib.auth.tests.urls'
    2424
    25     def setUp(self):
    26         self.old_LANGUAGES = settings.LANGUAGES
    27         self.old_LANGUAGE_CODE = settings.LANGUAGE_CODE
    28         settings.LANGUAGES = (('en', 'English'),)
    29         settings.LANGUAGE_CODE = 'en'
    30         self.old_TEMPLATE_DIRS = settings.TEMPLATE_DIRS
    31         settings.TEMPLATE_DIRS = (
    32             os.path.join(os.path.dirname(__file__), 'templates'),
    33         )
    34 
    35     def tearDown(self):
    36         settings.LANGUAGES = self.old_LANGUAGES
    37         settings.LANGUAGE_CODE = self.old_LANGUAGE_CODE
    38         settings.TEMPLATE_DIRS = self.old_TEMPLATE_DIRS
    39 
    4025    def login(self, password='password'):
    4126        response = self.client.post('/login/', {
    4227            'username': 'testclient',
    class AuthViewsTestCase(TestCase):  
    4732        self.assertTrue(response['Location'].endswith(settings.LOGIN_REDIRECT_URL))
    4833        self.assertTrue(SESSION_KEY in self.client.session)
    4934
     35AuthViewsTestCase = override_settings(
     36    SITE_ID = 1,
     37    TEMPLATE_DIRS = (
     38        os.path.join(os.path.dirname(__file__), 'templates'),
     39    ),
     40)(AuthViewsTestCase)
     41
    5042
    5143class AuthViewNamedURLTests(AuthViewsTestCase):
    5244    urls = 'django.contrib.auth.urls'
    class PasswordResetTest(AuthViewsTestCase):  
    145137        url, path = self._test_confirm_start()
    146138        path = path[:-5] + ("0"*4) + path[-1]
    147139
    148         response = self.client.post(path, {'new_password1': 'anewpassword',
    149                                            'new_password2':' anewpassword'})
     140        self.client.post(path, {'new_password1': 'anewpassword',
     141                                'new_password2':' anewpassword'})
    150142        # Check the password has not been changed
    151143        u = User.objects.get(email='staffmember@example.com')
    152144        self.assertTrue(not u.check_password("anewpassword"))
    class ChangePasswordTest(AuthViewsTestCase):  
    185177        self.assertTrue("Please enter a correct username and password. Note that both fields are case-sensitive." in response.content)
    186178
    187179    def logout(self):
    188         response = self.client.get('/logout/')
     180        self.client.get('/logout/')
    189181
    190182    def test_password_change_fails_with_invalid_old_password(self):
    191183        self.login()
    class LoginTest(AuthViewsTestCase):  
    304296class LoginURLSettings(AuthViewsTestCase):
    305297    urls = 'django.contrib.auth.tests.urls'
    306298
    307     def setUp(self):
    308         super(LoginURLSettings, self).setUp()
    309         self.old_LOGIN_URL = settings.LOGIN_URL
    310 
    311     def tearDown(self):
    312         super(LoginURLSettings, self).tearDown()
    313         settings.LOGIN_URL = self.old_LOGIN_URL
    314 
    315     def get_login_required_url(self, login_url):
    316         settings.LOGIN_URL = login_url
     299    def get_login_required_url(self, login=settings.LOGIN_URL):
    317300        response = self.client.get('/login_required/')
    318301        self.assertEqual(response.status_code, 302)
    319302        return response['Location']
    320303
     304    @override_settings(LOGIN_URL='/login/')
    321305    def test_standard_login_url(self):
    322         login_url = '/login/'
    323         login_required_url = self.get_login_required_url(login_url)
     306        login_required_url = self.get_login_required_url()
    324307        querystring = QueryDict('', mutable=True)
    325308        querystring['next'] = '/login_required/'
    326309        self.assertEqual(login_required_url,
    327              'http://testserver%s?%s' % (login_url, querystring.urlencode('/')))
     310             'http://testserver%s?%s' % (settings.LOGIN_URL, querystring.urlencode('/')))
    328311
     312    @override_settings(LOGIN_URL='http://remote.example.com/login')
    329313    def test_remote_login_url(self):
    330         login_url = 'http://remote.example.com/login'
    331         login_required_url = self.get_login_required_url(login_url)
     314        login_required_url = self.get_login_required_url()
    332315        querystring = QueryDict('', mutable=True)
    333316        querystring['next'] = 'http://testserver/login_required/'
    334317        self.assertEqual(login_required_url,
    335                          '%s?%s' % (login_url, querystring.urlencode('/')))
     318                         '%s?%s' % (settings.LOGIN_URL, querystring.urlencode('/')))
    336319
     320    @override_settings(LOGIN_URL='https:///login/')
    337321    def test_https_login_url(self):
    338         login_url = 'https:///login/'
    339         login_required_url = self.get_login_required_url(login_url)
     322        login_required_url = self.get_login_required_url()
    340323        querystring = QueryDict('', mutable=True)
    341324        querystring['next'] = 'http://testserver/login_required/'
    342325        self.assertEqual(login_required_url,
    343                          '%s?%s' % (login_url, querystring.urlencode('/')))
     326                         '%s?%s' % (settings.LOGIN_URL, querystring.urlencode('/')))
    344327
     328    @override_settings(LOGIN_URL='/login/?pretty=1')
    345329    def test_login_url_with_querystring(self):
    346         login_url = '/login/?pretty=1'
    347         login_required_url = self.get_login_required_url(login_url)
     330        login_required_url = self.get_login_required_url()
    348331        querystring = QueryDict('pretty=1', mutable=True)
    349332        querystring['next'] = '/login_required/'
    350333        self.assertEqual(login_required_url, 'http://testserver/login/?%s' %
    351334                         querystring.urlencode('/'))
    352335
     336    @override_settings(LOGIN_URL='http://remote.example.com/login/?next=/default/')
    353337    def test_remote_login_url_with_next_querystring(self):
    354         login_url = 'http://remote.example.com/login/'
    355         login_required_url = self.get_login_required_url('%s?next=/default/' %
    356                                                          login_url)
     338        login_required_url = self.get_login_required_url()
    357339        querystring = QueryDict('', mutable=True)
    358340        querystring['next'] = 'http://testserver/login_required/'
    359         self.assertEqual(login_required_url, '%s?%s' % (login_url,
    360                                                     querystring.urlencode('/')))
     341        self.assertEqual(login_required_url, settings.LOGIN_URL.replace(
     342            'next=/default/', querystring.urlencode('/')))
    361343
    362344
    363345class LogoutTest(AuthViewsTestCase):
  • django/test/__init__.py

    diff --git a/django/test/__init__.py b/django/test/__init__.py
    index a3a03e3..df75a21 100644
    a b Django Unit Test and Doctest framework.  
    44
    55from django.test.client import Client, RequestFactory
    66from django.test.testcases import (TestCase, TransactionTestCase,
    7         SimpleTestCase, skipIfDBFeature, skipUnlessDBFeature)
     7        SimpleTestCase, DefaultSettingsTestCase, skipIfDBFeature, skipUnlessDBFeature)
    88from django.test.utils import Approximate
  • django/test/testcases.py

    diff --git a/django/test/testcases.py b/django/test/testcases.py
    index ee22ac2..b9b851f 100644
    a b from functools import wraps  
    66from urlparse import urlsplit, urlunsplit
    77from xml.dom.minidom import parseString, Node
    88
    9 from django.conf import settings
     9from django.conf import settings, global_settings, UserSettingsHolder
    1010from django.core import mail
    1111from django.core.exceptions import ValidationError
    1212from django.core.management import call_command
    from django.test.utils import (get_warnings_state, restore_warnings_state,  
    2323    override_settings)
    2424from django.utils import simplejson, unittest as ut2
    2525from django.utils.encoding import smart_str
     26from django.utils.translation import deactivate
    2627
    2728__all__ = ('DocTestRunner', 'OutputChecker', 'TestCase', 'TransactionTestCase',
    2829           'SimpleTestCase', 'skipIfDBFeature', 'skipUnlessDBFeature')
    class TransactionTestCase(SimpleTestCase):  
    350351              ROOT_URLCONF with it.
    351352            * Clearing the mail test outbox.
    352353        """
     354        self._settings_setup()
    353355        self._fixture_setup()
    354356        self._urlconf_setup()
    355357        mail.outbox = []
    356358
     359    def _settings_setup(self):
     360        pass
     361
    357362    def _fixture_setup(self):
    358363        # If the test case has a multi_db=True flag, flush all databases.
    359364        # Otherwise, just flush default.
    class TransactionTestCase(SimpleTestCase):  
    414419        """
    415420        self._fixture_teardown()
    416421        self._urlconf_teardown()
     422        self._settings_teardown()
    417423        # Some DB cursors include SQL statements as part of cursor
    418424        # creation. If you have a test that does rollback, the effect
    419425        # of these statements is lost, which can effect the operation
    class TransactionTestCase(SimpleTestCase):  
    432438            settings.ROOT_URLCONF = self._old_root_urlconf
    433439            clear_url_caches()
    434440
     441    def _settings_teardown(self):
     442        pass
     443
    435444    def assertRedirects(self, response, expected_url, status_code=302,
    436445                        target_status_code=200, host=None, msg_prefix=''):
    437446        """Asserts that a response redirected to a specific URL, and that the
    class TestCase(TransactionTestCase):  
    703712            transaction.rollback(using=db)
    704713            transaction.leave_transaction_management(using=db)
    705714
     715
     716class DefaultSettingsTestCase(TestCase):
     717    """
     718    A testcase class that reset settings to Django defaults for its tests
     719    """
     720    def _settings_setup(self):
     721        self.wrapped = settings._wrapped
     722        holder = UserSettingsHolder(global_settings)
     723        for setting_name in ('ROOT_URLCONF', 'EMAIL_BACKEND'):
     724            setattr(holder, setting_name, getattr(settings, setting_name, ""))
     725        settings._wrapped = holder
     726        deactivate()
     727        super(DefaultSettingsTestCase, self)._settings_setup()
     728
     729    def _settings_teardown(self):
     730        super(DefaultSettingsTestCase, self)._settings_teardown()
     731        settings._wrapped = self.wrapped
     732        # Damned cached global variables :-(
     733        from django.template import base
     734        base.templatetags_modules = []
     735
     736
    706737def _deferredSkip(condition, reason):
    707738    def decorator(test_func):
    708739        if not (isinstance(test_func, type) and
  • django/test/utils.py

    diff --git a/django/test/utils.py b/django/test/utils.py
    index 87f2311..421a726 100644
    a b class override_settings(object):  
    196196    def __call__(self, test_func):
    197197        from django.test import TransactionTestCase
    198198        if isinstance(test_func, type) and issubclass(test_func, TransactionTestCase):
    199             original_pre_setup = test_func._pre_setup
    200             original_post_teardown = test_func._post_teardown
    201             def _pre_setup(innerself):
     199            original_settings_setup = test_func._settings_setup
     200            original_settings_teardown = test_func._settings_teardown
     201            def _settings_setup(innerself):
     202                original_settings_setup(innerself)
    202203                self.enable()
    203                 original_pre_setup(innerself)
    204             def _post_teardown(innerself):
    205                 original_post_teardown(innerself)
     204            def _settings_teardown(innerself):
    206205                self.disable()
    207             test_func._pre_setup = _pre_setup
    208             test_func._post_teardown = _post_teardown
     206                original_settings_teardown(innerself)
     207            test_func._settings_setup = _settings_setup
     208            test_func._settings_teardown = _settings_teardown
    209209            return test_func
    210210        else:
    211211            @wraps(test_func)
Back to Top