Ticket #10521: 10521-remote-user-tests-enh.diff

File 10521-remote-user-tests-enh.diff, 18.9 KB (added by Ramiro Morales, 16 years ago)

Patch that allows django.contrib.auth tests to run w/o errors from a project when using manage.py and the auth app is in INSTALLED_APPS

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

    diff -r f69520e5a824 django/contrib/auth/tests/__init__.py
    a b  
    11from django.contrib.auth.tests.basic import BASIC_TESTS
    2 from django.contrib.auth.tests.views \
     2from django.contrib.auth.tests.views_tests \
    33        import PasswordResetTest, ChangePasswordTest
    44from django.contrib.auth.tests.forms import FORM_TESTS
    55from django.contrib.auth.tests.remote_user \
  • django/contrib/auth/tests/remote_user.py

    diff -r f69520e5a824 django/contrib/auth/tests/remote_user.py
    a b  
    1414    # Usernames to be passed in REMOTE_USER for the test_known_user test case.
    1515    known_user = 'knownuser'
    1616    known_user2 = 'knownuser2'
     17
     18    urls = 'django.contrib.auth.tests.test_urls'
    1719
    1820    def setUp(self):
    1921        self.curr_middleware = settings.MIDDLEWARE_CLASSES
     
    2830        """
    2931        num_users = User.objects.count()
    3032
    31         response = self.client.get('/')
     33        response = self.client.get('/remote_user/')
    3234        self.assert_(isinstance(response.context['user'], AnonymousUser))
    3335        self.assertEqual(User.objects.count(), num_users)
    3436
    35         response = self.client.get('/', REMOTE_USER=None)
     37        response = self.client.get('/remote_user/', REMOTE_USER=None)
    3638        self.assert_(isinstance(response.context['user'], AnonymousUser))
    3739        self.assertEqual(User.objects.count(), num_users)
    3840
    39         response = self.client.get('/', REMOTE_USER='')
     41        response = self.client.get('/remote_user/', REMOTE_USER='')
    4042        self.assert_(isinstance(response.context['user'], AnonymousUser))
    4143        self.assertEqual(User.objects.count(), num_users)
    4244
     
    4648        as a User.
    4749        """
    4850        num_users = User.objects.count()
    49         response = self.client.get('/', REMOTE_USER='newuser')
     51        response = self.client.get('/remote_user/', REMOTE_USER='newuser')
    5052        self.assertEqual(response.context['user'].username, 'newuser')
    5153        self.assertEqual(User.objects.count(), num_users + 1)
    5254        User.objects.get(username='newuser')
    5355
    5456        # Another request with same user should not create any new users.
    55         response = self.client.get('/', REMOTE_USER='newuser')
     57        response = self.client.get('/remote_user/', REMOTE_USER='newuser')
    5658        self.assertEqual(User.objects.count(), num_users + 1)
    5759
    5860    def test_known_user(self):
     
    6264        User.objects.create(username='knownuser')
    6365        User.objects.create(username='knownuser2')
    6466        num_users = User.objects.count()
    65         response = self.client.get('/', REMOTE_USER=self.known_user)
     67        response = self.client.get('/remote_user/', REMOTE_USER=self.known_user)
    6668        self.assertEqual(response.context['user'].username, 'knownuser')
    6769        self.assertEqual(User.objects.count(), num_users)
    6870        # Test that a different user passed in the headers causes the new user
    6971        # to be logged in.
    70         response = self.client.get('/', REMOTE_USER=self.known_user2)
     72        response = self.client.get('/remote_user/', REMOTE_USER=self.known_user2)
    7173        self.assertEqual(response.context['user'].username, 'knownuser2')
    7274        self.assertEqual(User.objects.count(), num_users)
    7375
     
    8284        user.last_login = default_login
    8385        user.save()
    8486
    85         response = self.client.get('/', REMOTE_USER=self.known_user)
     87        response = self.client.get('/remote_user/', REMOTE_USER=self.known_user)
    8688        self.assertNotEqual(default_login, response.context['user'].last_login)
    8789
    8890        user = User.objects.get(username='knownuser')
    8991        user.last_login = default_login
    9092        user.save()
    91         response = self.client.get('/', REMOTE_USER=self.known_user)
     93        response = self.client.get('/remote_user/', REMOTE_USER=self.known_user)
    9294        self.assertEqual(default_login, response.context['user'].last_login)
    9395
    9496    def tearDown(self):
     
    113115
    114116    def test_unknown_user(self):
    115117        num_users = User.objects.count()
    116         response = self.client.get('/', REMOTE_USER='newuser')
     118        response = self.client.get('/remote_user/', REMOTE_USER='newuser')
    117119        self.assert_(isinstance(response.context['user'], AnonymousUser))
    118120        self.assertEqual(User.objects.count(), num_users)
    119121
  • new file django/contrib/auth/tests/test_urls.py

    diff -r f69520e5a824 django/contrib/auth/tests/test_urls.py
    - +  
     1"""
     2
     3This is a urlconf to be loaded by remote_user.py. Add any urls needed
     4for tests only.
     5
     6"""
     7from django.conf.urls.defaults import *
     8from django.contrib.auth.tests.views import remote_user_auth_view
     9
     10urlpatterns = patterns('',
     11                       (r'^remote_user/', remote_user_auth_view),
     12                      )
  • django/contrib/auth/tests/views.py

    diff -r f69520e5a824 django/contrib/auth/tests/views.py
    a b  
     1from django.http import HttpResponse
     2from django.shortcuts import render_to_response
     3from django.template import Template, RequestContext
    14
    2 import os
    3 import re
    4 
    5 from django.conf import settings
    6 from django.contrib.auth.models import User
    7 from django.test import TestCase
    8 from django.core import mail
    9 
    10 class PasswordResetTest(TestCase):
    11     fixtures = ['authtestdata.json']
    12     urls = 'django.contrib.auth.urls'
    13 
    14     def test_email_not_found(self):
    15         "Error is raised if the provided email address isn't currently registered"
    16         response = self.client.get('/password_reset/')
    17         self.assertEquals(response.status_code, 200)
    18         response = self.client.post('/password_reset/', {'email': 'not_a_real_email@email.com'})
    19         self.assertContains(response, "That e-mail address doesn't have an associated user account")
    20         self.assertEquals(len(mail.outbox), 0)
    21 
    22     def test_email_found(self):
    23         "Email is sent if a valid email address is provided for password reset"
    24         response = self.client.post('/password_reset/', {'email': 'staffmember@example.com'})
    25         self.assertEquals(response.status_code, 302)
    26         self.assertEquals(len(mail.outbox), 1)
    27         self.assert_("http://" in mail.outbox[0].body)
    28 
    29     def _test_confirm_start(self):
    30         # Start by creating the email
    31         response = self.client.post('/password_reset/', {'email': 'staffmember@example.com'})
    32         self.assertEquals(response.status_code, 302)
    33         self.assertEquals(len(mail.outbox), 1)
    34         return self._read_signup_email(mail.outbox[0])
    35 
    36     def _read_signup_email(self, email):
    37         urlmatch = re.search(r"https?://[^/]*(/.*reset/\S*)", email.body)
    38         self.assert_(urlmatch is not None, "No URL found in sent email")
    39         return urlmatch.group(), urlmatch.groups()[0]
    40 
    41     def test_confirm_valid(self):
    42         url, path = self._test_confirm_start()
    43         response = self.client.get(path)
    44         # redirect to a 'complete' page:
    45         self.assertEquals(response.status_code, 200)
    46         self.assert_("Please enter your new password" in response.content)
    47 
    48     def test_confirm_invalid(self):
    49         url, path = self._test_confirm_start()
    50         # Lets munge the token in the path, but keep the same length,
    51         # in case the URL conf will reject a different length
    52         path = path[:-5] + ("0"*4) + path[-1]
    53 
    54         response = self.client.get(path)
    55         self.assertEquals(response.status_code, 200)
    56         self.assert_("The password reset link was invalid" in response.content)
    57 
    58     def test_confirm_invalid_post(self):
    59         # Same as test_confirm_invalid, but trying
    60         # to do a POST instead.
    61         url, path = self._test_confirm_start()
    62         path = path[:-5] + ("0"*4) + path[-1]
    63 
    64         response = self.client.post(path, {'new_password1': 'anewpassword',
    65                                            'new_password2':' anewpassword'})
    66         # Check the password has not been changed
    67         u = User.objects.get(email='staffmember@example.com')
    68         self.assert_(not u.check_password("anewpassword"))
    69 
    70     def test_confirm_complete(self):
    71         url, path = self._test_confirm_start()
    72         response = self.client.post(path, {'new_password1': 'anewpassword',
    73                                            'new_password2': 'anewpassword'})
    74         # It redirects us to a 'complete' page:
    75         self.assertEquals(response.status_code, 302)
    76         # Check the password has been changed
    77         u = User.objects.get(email='staffmember@example.com')
    78         self.assert_(u.check_password("anewpassword"))
    79 
    80         # Check we can't use the link again
    81         response = self.client.get(path)
    82         self.assertEquals(response.status_code, 200)
    83         self.assert_("The password reset link was invalid" in response.content)
    84 
    85     def test_confirm_different_passwords(self):
    86         url, path = self._test_confirm_start()
    87         response = self.client.post(path, {'new_password1': 'anewpassword',
    88                                            'new_password2':' x'})
    89         self.assertEquals(response.status_code, 200)
    90         self.assert_("The two password fields didn't match" in response.content)
    91 
    92 
    93 class ChangePasswordTest(TestCase):
    94     fixtures = ['authtestdata.json']
    95     urls = 'django.contrib.auth.urls'
    96 
    97     def setUp(self):
    98         self.old_TEMPLATE_DIRS = settings.TEMPLATE_DIRS
    99         settings.TEMPLATE_DIRS = (
    100             os.path.join(
    101                 os.path.dirname(__file__),
    102                 'templates'
    103             )
    104         ,)
    105 
    106     def tearDown(self):
    107         settings.TEMPLATE_DIRS = self.old_TEMPLATE_DIRS
    108 
    109     def login(self, password='password'):
    110         response = self.client.post('/login/', {
    111             'username': 'testclient',
    112             'password': password
    113             }
    114         )
    115         self.assertEquals(response.status_code, 302)
    116         self.assert_(response['Location'].endswith(settings.LOGIN_REDIRECT_URL))
    117 
    118     def fail_login(self, password='password'):
    119         response = self.client.post('/login/', {
    120             'username': 'testclient',
    121             'password': password
    122             }
    123         )
    124         self.assertEquals(response.status_code, 200)
    125         self.assert_("Please enter a correct username and password. Note that both fields are case-sensitive." in response.content)
    126 
    127     def logout(self):
    128         response = self.client.get('/logout/')
    129 
    130     def test_password_change_fails_with_invalid_old_password(self):
    131         self.login()
    132         response = self.client.post('/password_change/', {
    133             'old_password': 'donuts',
    134             'new_password1': 'password1',
    135             'new_password2': 'password1',
    136             }
    137         )
    138         self.assertEquals(response.status_code, 200)
    139         self.assert_("Your old password was entered incorrectly. Please enter it again." in response.content)
    140 
    141     def test_password_change_fails_with_mismatched_passwords(self):
    142         self.login()
    143         response = self.client.post('/password_change/', {
    144             'old_password': 'password',
    145             'new_password1': 'password1',
    146             'new_password2': 'donuts',
    147             }
    148         )
    149         self.assertEquals(response.status_code, 200)
    150         self.assert_("The two password fields didn't match." in response.content)
    151 
    152     def test_password_change_succeeds(self):
    153         self.login()
    154         response = self.client.post('/password_change/', {
    155             'old_password': 'password',
    156             'new_password1': 'password1',
    157             'new_password2': 'password1',
    158             }
    159         )
    160         self.assertEquals(response.status_code, 302)
    161         self.assert_(response['Location'].endswith('/password_change/done/'))
    162         self.fail_login()
    163         self.login(password='password1')
    164 
     5def remote_user_auth_view(request):
     6    t = Template("Username is {{ user }}.")
     7    c = RequestContext(request, {})
     8    return HttpResponse(t.render(c))
  • new file django/contrib/auth/tests/views_tests.py

    diff -r f69520e5a824 django/contrib/auth/tests/views_tests.py
    - +  
     1
     2import os
     3import re
     4
     5from django.conf import settings
     6from django.contrib.auth.models import User
     7from django.test import TestCase
     8from django.core import mail
     9
     10class PasswordResetTest(TestCase):
     11    fixtures = ['authtestdata.json']
     12    urls = 'django.contrib.auth.urls'
     13
     14    def test_email_not_found(self):
     15        "Error is raised if the provided email address isn't currently registered"
     16        response = self.client.get('/password_reset/')
     17        self.assertEquals(response.status_code, 200)
     18        response = self.client.post('/password_reset/', {'email': 'not_a_real_email@email.com'})
     19        self.assertContains(response, "That e-mail address doesn't have an associated user account")
     20        self.assertEquals(len(mail.outbox), 0)
     21
     22    def test_email_found(self):
     23        "Email is sent if a valid email address is provided for password reset"
     24        response = self.client.post('/password_reset/', {'email': 'staffmember@example.com'})
     25        self.assertEquals(response.status_code, 302)
     26        self.assertEquals(len(mail.outbox), 1)
     27        self.assert_("http://" in mail.outbox[0].body)
     28
     29    def _test_confirm_start(self):
     30        # Start by creating the email
     31        response = self.client.post('/password_reset/', {'email': 'staffmember@example.com'})
     32        self.assertEquals(response.status_code, 302)
     33        self.assertEquals(len(mail.outbox), 1)
     34        return self._read_signup_email(mail.outbox[0])
     35
     36    def _read_signup_email(self, email):
     37        urlmatch = re.search(r"https?://[^/]*(/.*reset/\S*)", email.body)
     38        self.assert_(urlmatch is not None, "No URL found in sent email")
     39        return urlmatch.group(), urlmatch.groups()[0]
     40
     41    def test_confirm_valid(self):
     42        url, path = self._test_confirm_start()
     43        response = self.client.get(path)
     44        # redirect to a 'complete' page:
     45        self.assertEquals(response.status_code, 200)
     46        self.assert_("Please enter your new password" in response.content)
     47
     48    def test_confirm_invalid(self):
     49        url, path = self._test_confirm_start()
     50        # Lets munge the token in the path, but keep the same length,
     51        # in case the URL conf will reject a different length
     52        path = path[:-5] + ("0"*4) + path[-1]
     53
     54        response = self.client.get(path)
     55        self.assertEquals(response.status_code, 200)
     56        self.assert_("The password reset link was invalid" in response.content)
     57
     58    def test_confirm_invalid_post(self):
     59        # Same as test_confirm_invalid, but trying
     60        # to do a POST instead.
     61        url, path = self._test_confirm_start()
     62        path = path[:-5] + ("0"*4) + path[-1]
     63
     64        response = self.client.post(path, {'new_password1': 'anewpassword',
     65                                           'new_password2':' anewpassword'})
     66        # Check the password has not been changed
     67        u = User.objects.get(email='staffmember@example.com')
     68        self.assert_(not u.check_password("anewpassword"))
     69
     70    def test_confirm_complete(self):
     71        url, path = self._test_confirm_start()
     72        response = self.client.post(path, {'new_password1': 'anewpassword',
     73                                           'new_password2': 'anewpassword'})
     74        # It redirects us to a 'complete' page:
     75        self.assertEquals(response.status_code, 302)
     76        # Check the password has been changed
     77        u = User.objects.get(email='staffmember@example.com')
     78        self.assert_(u.check_password("anewpassword"))
     79
     80        # Check we can't use the link again
     81        response = self.client.get(path)
     82        self.assertEquals(response.status_code, 200)
     83        self.assert_("The password reset link was invalid" in response.content)
     84
     85    def test_confirm_different_passwords(self):
     86        url, path = self._test_confirm_start()
     87        response = self.client.post(path, {'new_password1': 'anewpassword',
     88                                           'new_password2':' x'})
     89        self.assertEquals(response.status_code, 200)
     90        self.assert_("The two password fields didn't match" in response.content)
     91
     92
     93class ChangePasswordTest(TestCase):
     94    fixtures = ['authtestdata.json']
     95    urls = 'django.contrib.auth.urls'
     96
     97    def setUp(self):
     98        self.old_TEMPLATE_DIRS = settings.TEMPLATE_DIRS
     99        settings.TEMPLATE_DIRS = (
     100            os.path.join(
     101                os.path.dirname(__file__),
     102                'templates'
     103            )
     104        ,)
     105
     106    def tearDown(self):
     107        settings.TEMPLATE_DIRS = self.old_TEMPLATE_DIRS
     108
     109    def login(self, password='password'):
     110        response = self.client.post('/login/', {
     111            'username': 'testclient',
     112            'password': password
     113            }
     114        )
     115        self.assertEquals(response.status_code, 302)
     116        self.assert_(response['Location'].endswith(settings.LOGIN_REDIRECT_URL))
     117
     118    def fail_login(self, password='password'):
     119        response = self.client.post('/login/', {
     120            'username': 'testclient',
     121            'password': password
     122            }
     123        )
     124        self.assertEquals(response.status_code, 200)
     125        self.assert_("Please enter a correct username and password. Note that both fields are case-sensitive." in response.content)
     126
     127    def logout(self):
     128        response = self.client.get('/logout/')
     129
     130    def test_password_change_fails_with_invalid_old_password(self):
     131        self.login()
     132        response = self.client.post('/password_change/', {
     133            'old_password': 'donuts',
     134            'new_password1': 'password1',
     135            'new_password2': 'password1',
     136            }
     137        )
     138        self.assertEquals(response.status_code, 200)
     139        self.assert_("Your old password was entered incorrectly. Please enter it again." in response.content)
     140
     141    def test_password_change_fails_with_mismatched_passwords(self):
     142        self.login()
     143        response = self.client.post('/password_change/', {
     144            'old_password': 'password',
     145            'new_password1': 'password1',
     146            'new_password2': 'donuts',
     147            }
     148        )
     149        self.assertEquals(response.status_code, 200)
     150        self.assert_("The two password fields didn't match." in response.content)
     151
     152    def test_password_change_succeeds(self):
     153        self.login()
     154        response = self.client.post('/password_change/', {
     155            'old_password': 'password',
     156            'new_password1': 'password1',
     157            'new_password2': 'password1',
     158            }
     159        )
     160        self.assertEquals(response.status_code, 302)
     161        self.assert_(response['Location'].endswith('/password_change/done/'))
     162        self.fail_login()
     163        self.login(password='password1')
     164
Back to Top