1. Marko Mrdjenovic
  2. django-registration-plus

Source

django-registration-plus / registration / tests / models.py

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
import datetime
import re

from django.conf import settings
from django.contrib.auth.models import User
from django.contrib.sites.models import Site
from django.core import mail
from django.core import management
from django.test import TestCase
from django.utils.hashcompat import sha_constructor

from registration.models import EmailValidation
from registration.models import RegistrationInvitation


class RegistrationModelTests(TestCase):
    """
    Test the model and manager used in the default backend.
    
    """
    user_info = {'username': 'alice',
                 'password': 'swordfish',
                 'email': 'alice@example.com'}
    other_user = {'username': 'bob',
                  'password': 'secret',
                  'email': u'bob@example.com'}
    
    def setUp(self):
        self.old_validation = getattr(settings, 'EMAIL_VALIDATION_DAYS', None)
        self.old_invitation = getattr(settings, 'EMAIL_INVITATION_DAYS', None)
        settings.EMAIL_VALIDATION_DAYS = 7
        settings.EMAIL_INVITATION_DAYS = 7

    def tearDown(self):
        settings.EMAIL_VALIDATION_DAYS = self.old_validation
        settings.EMAIL_INVITATION_DAYS = self.old_invitation

    def test_validation_creation(self):
        """
        Creating an email validation for a user populates the
        validation with the correct user and a SHA1 hash to use as
        validation key.
        
        """
        new_user = User.objects.create_user(**self.user_info)
        validation = EmailValidation.objects.create_validation(new_user)

        self.assertEqual(EmailValidation.objects.count(), 1)
        self.assertEqual(validation.user.id, new_user.id)
        self.assertEqual(validation.expiration_date(), 
                         validation.created + datetime.timedelta(days=settings.EMAIL_VALIDATION_DAYS))
        self.failUnless(re.match('^[a-f0-9]{40}$', validation.validation_key))
        self.assertEqual(unicode(validation),
                         "Email validation for %s/%s" % (self.user_info["username"],
                                                         self.user_info["email"]))

    def test_validation_email(self):
        """
        ``EmailValidation.send_validation_email`` sends an
        email.
        
        """
        new_user = User.objects.create_user(**self.user_info)
        validation = EmailValidation.objects.create_validation(new_user)
        validation.send_validation_email(Site.objects.get_current())
        self.assertEqual(len(mail.outbox), 1)
        self.assertEqual(mail.outbox[0].to, [self.user_info['email']])
    
    def test_expired_validation_email(self):
        """
        ``EmailValidation.send_validation_email`` does not send an
        email when validation already expired.
        
        """
        new_user = User.objects.create_user(**self.user_info)
        validation = EmailValidation.objects.create_validation(new_user)
        validation.created -= datetime.timedelta\
            (days=settings.EMAIL_VALIDATION_DAYS + 1)
        validation.save()
        expired_validation = EmailValidation.objects.get(user=new_user)
        expired_validation.send_validation_email(Site.objects.get_current())
        self.failIf(len(mail.outbox))
        
    def test_user_creation(self):
        """
        Creating a new user populates the correct data, and sets the
        user's account inactive.
        
        """
        new_user = EmailValidation.objects.create_inactive_user(site=Site.objects.get_current(),
                                                                    **self.user_info)
        self.assertEqual(new_user.username, self.user_info['username'])
        self.assertEqual(new_user.email, self.user_info['email'])
        self.failUnless(new_user.check_password(self.user_info['password']))
        self.failIf(new_user.is_active)

    def test_user_creation_email(self):
        """
        By default, creating a new user sends an validation email.
        
        """
        new_user = EmailValidation.objects.create_inactive_user(site=Site.objects.get_current(),
                                                                    **self.user_info)
        self.assertEqual(len(mail.outbox), 1)

    def test_user_creation_no_email(self):
        """
        Passing ``send_email=False`` when creating a new user will not
        send an validation email.
        
        """
        new_user = EmailValidation.objects.create_inactive_user(site=Site.objects.get_current(),
                                                                    send_email=False,
                                                                    **self.user_info)
        self.assertEqual(len(mail.outbox), 0)

    def test_unexpired_account(self):
        """
        ``EmailValidation.validation_key_expired()`` is ``False``
        within the validation window.
        
        """
        new_user = EmailValidation.objects.create_inactive_user(site=Site.objects.get_current(),
                                                                    **self.user_info)
        validation = EmailValidation.objects.get(user=new_user)
        self.failIf(validation.validation_key_expired())

    def test_expired_account(self):
        """
        ``EmailValidation.validation_key_expired()`` is ``True``
        outside the validation window.
        
        """
        new_user = EmailValidation.objects.create_inactive_user(site=Site.objects.get_current(),
                                                                    **self.user_info)
        validation = EmailValidation.objects.get(user=new_user)
        validation.created -= datetime.timedelta(days=settings.EMAIL_VALIDATION_DAYS + 1)
        validation.save()
        self.failUnless(validation.validation_key_expired())

    def test_valid_validation(self):
        """
        Validating a user within the permitted window makes the
        account active, and resets the validation key.
        
        """
        new_user = EmailValidation.objects.create_inactive_user(site=Site.objects.get_current(),
                                                                    **self.user_info)
        validation = EmailValidation.objects.get(user=new_user)
        validated = EmailValidation.objects.validate_email(validation.validation_key)

        self.failUnless(isinstance(validated, User))
        self.assertEqual(validated.id, new_user.id)
        self.failUnless(validated.is_active)

        validation = EmailValidation.objects.get(user=new_user)
        self.assertEqual(validation.validation_key, EmailValidation.VALIDATED)
        self.failUnless(EmailValidation.objects.is_valid(new_user))

    def test_expired_validation(self):
        """
        Attempting to validate outside the permitted window does not
        validate the account.
        
        """
        new_user = EmailValidation.objects.create_inactive_user(site=Site.objects.get_current(),
                                                                    **self.user_info)
        validation = EmailValidation.objects.get(user=new_user)
        validation.created -= datetime.timedelta(days=settings.EMAIL_VALIDATION_DAYS + 1)
        validation.save()
        
        validated = EmailValidation.objects.validate_email(validation
        .validation_key)

        self.failIf(isinstance(validated, User))
        self.failIf(validated)

        new_user = User.objects.get(username=self.user_info['username'])
        self.failIf(new_user.is_active)

        validation = EmailValidation.objects.get(user=new_user)
        self.assertNotEqual(validation.validation_key, EmailValidation.VALIDATED)
        self.failIf(EmailValidation.objects.is_valid(new_user))

    def test_validation_invalid_key(self):
        """
        Attempting to validate with a key which is not a SHA1 hash
        fails.
        
        """
        self.failIf(EmailValidation.objects.validate_email('foo'))

    def test_validation_already_validated(self):
        """
        Attempting to re-validate an already-validated account fails.
        
        """
        new_user = EmailValidation.objects.create_inactive_user(site=Site.objects.get_current(),
                                                                    **self.user_info)
        validation = EmailValidation.objects.get(user=new_user)
        EmailValidation.objects.validate_email(validation.validation_key)

        validation = EmailValidation.objects.get(user=new_user)
        self.failIf(EmailValidation.objects.validate_email(validation.validation_key))

    def test_validation_nonexistent_key(self):
        """
        Attempting to validate with a non-existent key (i.e., one not
        associated with any account) fails.
        
        """
        # Due to the way validation keys are constructed during
        # registration, this will never be a valid key.
        invalid_key = sha_constructor('foo').hexdigest()
        self.failIf(EmailValidation.objects.validate_email(invalid_key))

    def test_expired_user_deletion(self):
        """
        ``EmailValidation.objects.delete_expired_users()`` only
        deletes inactive users whose validation window has expired.
        
        """
        new_user = EmailValidation.objects.create_inactive_user(site=Site.objects.get_current(),
                                                                **self.user_info)
        expired_user = EmailValidation.objects.create_inactive_user(site=Site.objects.get_current(),
                                                                    **self.other_user)
        expired_validation = EmailValidation.objects.get(user=expired_user)
        expired_validation.created -= datetime.timedelta(days=settings.EMAIL_VALIDATION_DAYS + 1)
        expired_validation.save()

        EmailValidation.objects.delete_expired_users()
        self.assertEqual(EmailValidation.objects.count(), 1)
        self.assertRaises(User.DoesNotExist, User.objects.get, 
                          username=self.other_user['username'])
    
    def test_cleanupregistration_command(self):
        """
        The ``cleanupregistration`` management command properly
        deletes expired accounts.
        
        """
        new_user = EmailValidation.objects.create_inactive_user(site=Site.objects.get_current(),
                                                                **self.user_info)
        expired_user = EmailValidation.objects.create_inactive_user(site=Site.objects.get_current(),
                                                                    **self.other_user)
        expired_validation = EmailValidation.objects.get(user=expired_user)
        expired_validation.created -= datetime.timedelta(days=settings.EMAIL_VALIDATION_DAYS + 1)
        expired_validation.save()
        
        management.call_command('cleanupregistration')
        self.assertEqual(EmailValidation.objects.count(), 1)
        self.assertRaises(User.DoesNotExist, User.objects.get, 
                          username=self.other_user['username'])
        self.assertEqual(User.objects.get(username=self.user_info['username']), 
                         new_user)
    
    def test_createinvitations_command(self):
        """
        The ``createinvitations`` management command properly
        creates invitations.
        
        """
        new_user = EmailValidation.objects.create_user(site=Site.objects.get_current(),
                                                       **self.user_info)
        num_users = User.objects.filter(is_active=True).count()
        
        self.failIf(RegistrationInvitation.objects.has_invitations(new_user))
        management.call_command('createinvitations', '1', verbosity='0')
        self.assertEqual(RegistrationInvitation.objects.count(), num_users)
        self.assertEqual(RegistrationInvitation.objects.has_invitations(new_user), 1)

    def test_invitation_creation(self):
        """
        Creating an registration invitation for a user creates an empty 
        unused invitation.
        """
        new_user = EmailValidation.objects.create_user(site=Site.objects.get_current(),
                                                       **self.user_info)
        invitation = RegistrationInvitation.objects.create_invitation(new_user)
        
        self.assertEqual(invitation.owner, new_user)
        self.failUnless(invitation.created)
        self.failIf(invitation.email)
        self.assertEqual(invitation.status(), "Open")
        self.assertEqual(RegistrationInvitation.objects.has_invitations(new_user), 1)
        self.failIf(invitation.invitation_key_expired())
        self.assertEqual(unicode(invitation),
                         "Registration invitation by %s for %s" % 
                         (invitation.owner, invitation.email))
    
    def test_invitation_email(self):
        """
        ``RegistrationInvitation.send_invitation_email`` sends an
        email.
        """
        new_user = EmailValidation.objects.create_user(site=Site.objects.get_current(),
                                                       send_email=False,
                                                       **self.user_info)
        invitation = RegistrationInvitation.objects.create_invitation(new_user)
        invitation.email = self.other_user['email']
        invitation.sent = datetime.datetime.now()
        invitation.save()
        message = invitation.send_invitation_email(Site.objects.get_current())
        
        self.failUnless(message)
        self.assertEqual(len(mail.outbox), 1)
        self.assertEqual(mail.outbox[0].to, [self.other_user['email']])

    def test_invitation_email_expired(self):
        """
        Sending an invitation saves proper data on the invitation and sends 
        out the invitation mail.
        """
        new_user = EmailValidation.objects.create_user(site=Site.objects.get_current(), 
                                                       send_email=False,
                                                       **self.user_info)
        
        invitation = RegistrationInvitation.objects.create_invitation(new_user)
        invitation.email = self.other_user['email']
        invitation.sent = datetime.datetime.now() - datetime.timedelta(days=settings.EMAIL_INVITATION_DAYS + 1)
        invitation.save()
        message = invitation.send_invitation_email(Site.objects.get_current())
        
        self.failIf(message)
        self.failIf(len(mail.outbox))
    
    def test_invitation_send(self):
        """
        Sending an invitation saves proper data on the invitation and sends 
        out the invitation mail.
        """
        new_user = EmailValidation.objects.create_user(site=Site.objects.get_current(), 
                                                       **self.user_info)
        RegistrationInvitation.objects.create_invitation(new_user)
        sent_invitation = RegistrationInvitation.objects.send_invitation(new_user, 
                                                                         self.other_user['email'], 
                                                                         Site.objects.get_current())
        
        self.assertEqual(sent_invitation.email, self.other_user['email'])
        self.failUnless(sent_invitation.sent)
        self.assertEqual(sent_invitation.status(), "Sent to %s" % self.other_user['email'])
        self.failUnless(re.match('^[a-f0-9]{40}$', sent_invitation.invitation_key))
        self.failIf(sent_invitation.invitation_key_expired())
        self.assertEqual(unicode(sent_invitation),
                         "Registration invitation by %s for %s" % 
                         (sent_invitation.owner, sent_invitation.email))
    
    def test_invitation_send_failed(self):
        """
        Sending an invitation when user has no invitations should fail - 
        return nothing and send no emails.
        """
        new_user = EmailValidation.objects.create_user(site=Site.objects.get_current(),
                                                       send_email=False, 
                                                       **self.user_info)
        sent_invitation = RegistrationInvitation.objects.send_invitation(new_user, 
                                                       self.other_user['email'], 
                                                       Site.objects.get_current())
        
        self.failIf(sent_invitation)
        self.failIf(len(mail.outbox))
    
    def test_registration_with_invitation(self):
        """
        Registration with an invitation should autovalidate the new users' 
        email.
        """
        owner = EmailValidation.objects.create_user(site=Site.objects.get_current(),
                                                    send_email=False,
                                                    **self.user_info)
        invitation = RegistrationInvitation.objects.create_invitation(owner)
        RegistrationInvitation.objects.send_invitation(owner, 
                                                       self.other_user['email'], 
                                                       Site.objects.get_current())
        sent_invitation = RegistrationInvitation.objects.get(pk=invitation.pk)
        new_user = EmailValidation.objects.create_user(site=Site.objects.get_current(),
                                                       invitation_key=sent_invitation.invitation_key, 
                                                       **self.other_user)
        new_validation = EmailValidation.objects.get(user=new_user)
        exercised_invitation = RegistrationInvitation.objects.get(pk=invitation.pk)
        
        self.assertEqual(new_user.username, self.other_user['username'])
        self.assertEqual(new_user.email, self.other_user['email'])
        self.failUnless(new_user.check_password(self.other_user['password']))
        self.failUnless(new_user.is_active)
        self.failUnless(new_validation.validation_key_expired())
        self.failUnless(new_validation.validated)
        self.failUnless(exercised_invitation.invitation_key_expired())
        self.failUnless(exercised_invitation.exercised)
        self.assertEqual(exercised_invitation.status(), "Exercised by %s" % new_user.username)
        self.assertEqual(len(mail.outbox), 1) # Invitation
        self.assertEqual(mail.outbox[0].to, [self.other_user['email']])
        
    def test_registration_with_invitation_newemail(self):
        """
        Registration with an invitation but a different email should exercise 
        the invitation, create a new validation and send the validation email.
        """
        owner = EmailValidation.objects.create_user(site=Site.objects.get_current(),
                                                    send_email=False,
                                                    **self.user_info)
        RegistrationInvitation.objects.create_invitation(owner)
        sent_invitation = RegistrationInvitation.objects.send_invitation(owner, 
                                                                         "bobby@example.com", 
                                                                         Site.objects.get_current())
        new_user = EmailValidation.objects.create_user(site=Site.objects.get_current(),
                                                       invitation_key=sent_invitation.invitation_key, 
                                                       **self.other_user)
        new_validation = EmailValidation.objects.get(user=new_user)
        exercised_invitation = RegistrationInvitation.objects.get(pk=sent_invitation.pk)
        
        self.assertEqual(new_user.username, self.other_user['username'])
        self.assertEqual(new_user.email, self.other_user['email'])
        self.failUnless(new_user.check_password(self.other_user['password']))
        self.failUnless(new_user.is_active)
        self.failIf(new_validation.validation_key_expired())
        self.failIf(new_validation.validated)
        self.failUnless(exercised_invitation.invitation_key_expired())
        self.failUnless(exercised_invitation.exercised)
        self.assertEqual(exercised_invitation.status(), "Exercised by %s" % new_user.username)
        self.assertEqual(len(mail.outbox), 2) # Invitation + Validation
        self.assertEqual(mail.outbox[0].to, ["bobby@example.com"])
        self.assertEqual(mail.outbox[1].to, [new_user.email])
    
    def test_registration_with_wrong_invitation(self):
        """
        Registration with a wrong invitation key should fail.
        """
        invalid_key = sha_constructor('foo').hexdigest()
        owner = EmailValidation.objects.create_user(site=Site.objects.get_current(),
                                                    send_email=False,
                                                    **self.user_info)
        RegistrationInvitation.objects.create_invitation(owner)
        sent_invitation = RegistrationInvitation.objects.send_invitation(owner, 
                                                       self.other_user['email'], 
                                                       Site.objects.get_current())
        new_user = EmailValidation.objects.create_user(site=Site.objects.get_current(),
                                                       invitation_key=invalid_key, 
                                                       **self.other_user)
        
        self.failIf(new_user)
        self.failIf(User.objects.filter(username=self.other_user['username']).count())
        self.failIf(sent_invitation.invitation_key_expired())
        self.failIf(sent_invitation.exercised)
        self.assertEqual(len(mail.outbox), 1) # Invitation
        self.assertEqual(mail.outbox[0].to, [self.other_user['email']])
    
    def test_registration_with_expired_invitation(self):
        """
        Registration with an expired invitation should fail.
        """
        owner = EmailValidation.objects.create_user(site=Site.objects.get_current(),
                                                    send_email=False,
                                                    **self.user_info)
        RegistrationInvitation.objects.create_invitation(owner)
        sent_invitation = RegistrationInvitation.objects.send_invitation(owner, 
                                                       self.other_user['email'], 
                                                       Site.objects.get_current())
        sent_invitation.sent -= datetime.timedelta(days=settings.EMAIL_INVITATION_DAYS + 1)
        sent_invitation.save()
        new_user = EmailValidation.objects.create_user(site=Site.objects.get_current(),
                                                       invitation_key=sent_invitation.invitation_key, 
                                                       **self.other_user)
        
        self.failIf(new_user)
        self.failIf(User.objects.filter(username=self.other_user['username']).count())
        self.failUnless(sent_invitation.invitation_key_expired())
        self.failIf(sent_invitation.exercised)
        self.assertEqual(len(mail.outbox), 1) # Invitation
        self.assertEqual(mail.outbox[0].to, [self.other_user['email']])