File: tests.py

package info (click to toggle)
django-invitations 2.1.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 456 kB
  • sloc: python: 1,484; makefile: 27; sh: 6
file content (548 lines) | stat: -rw-r--r-- 17,879 bytes parent folder | download
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
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
import datetime
import json
import re
from unittest.mock import patch

from django.test import Client
from django.test.client import RequestFactory
from django.test.utils import override_settings
from django.utils import timezone

try:
    from django.urls import reverse
except ImportError:
    from django.core.urlresolvers import reverse

import pytest
from django.contrib.auth.models import AnonymousUser
from django.core import mail
from freezegun import freeze_time

from invitations.adapters import BaseInvitationsAdapter, get_invitations_adapter
from invitations.app_settings import app_settings
from invitations.forms import InviteForm
from invitations.utils import get_invitation_model
from invitations.views import AcceptInvite, SendJSONInvite

Invitation = get_invitation_model()


class TestInvitationModel:
    @freeze_time("2015-07-30 12:00:06")
    def test_create_invitation(self, invitation_a):
        assert invitation_a.email == "email@example.com"
        assert invitation_a.key
        assert invitation_a.accepted is False
        assert invitation_a.created == timezone.now()

    def test_invitation_key_expiry(self, invitation_a):
        invitation_a.sent = timezone.now() - datetime.timedelta(
            days=app_settings.INVITATION_EXPIRY,
            minutes=1,
        )
        assert invitation_a.key_expired() is True

        invitation_a.sent = timezone.now() - datetime.timedelta(
            days=app_settings.INVITATION_EXPIRY,
            minutes=-1,
        )
        assert invitation_a.key_expired() is False


class TestInvitationsAdapter:
    def test_fetch_adapter(self):
        adapter = get_invitations_adapter()
        assert isinstance(adapter, BaseInvitationsAdapter)

    def test_email_subject_prefix_settings_with_site(self):
        adapter = get_invitations_adapter()
        result = adapter.format_email_subject("Bar", context={"site_name": "Foo.com"})
        assert result == "[Foo.com] Bar"

    @override_settings(INVITATIONS_EMAIL_SUBJECT_PREFIX="")
    def test_email_subject_prefix_settings_with_custom_override(self):
        adapter = get_invitations_adapter()
        result = adapter.format_email_subject("Bar", context={"site_name": "Foo.com"})
        assert result == "Bar"


class TestInvitationsSendView:
    client = Client()

    @pytest.mark.django_db
    def test_auth(self):
        response = self.client.post(
            reverse("invitations:send-invite"),
            {"email": "valid@example.com"},
            follow=True,
        )

        assert response.status_code == 404

    @pytest.mark.parametrize(
        "email, error",
        [
            ("invalid@example", "Enter a valid email address"),
            ("invited@example.com", "This e-mail address has already been"),
            ("flobble@example.com", "An active user is"),
        ],
    )
    def test_invalid_form_submissions(self, user_a, user_b, invitation_b, email, error):
        self.client.login(username="flibble", password="password")
        resp = self.client.post(reverse("invitations:send-invite"), {"email": email})

        form = resp.context_data["form"]
        assert error in form.errors["email"][0]

    @freeze_time("2015-07-30 12:00:06")
    def test_valid_form_submission(self, user_a):
        self.client.login(username="flibble", password="password")
        resp = self.client.post(
            reverse("invitations:send-invite"),
            {"email": "email@example.com"},
        )
        invitation = Invitation.objects.get(email="email@example.com")

        assert resp.status_code == 200
        assert "success_message" in resp.context_data.keys()

        assert invitation.sent == timezone.now()
        assert len(mail.outbox) == 1
        assert mail.outbox[0].to[0] == "email@example.com"
        assert "Invitation to join example.com" in mail.outbox[0].subject
        url = re.search(r"(?P<url>/invitations/[^\s]+)", mail.outbox[0].body).group(
            "url",
        )
        assert url == reverse(
            app_settings.CONFIRMATION_URL_NAME,
            kwargs={"key": invitation.key},
        )

    @override_settings(INVITATION_MODEL="ExampleSwappableInvitation")
    @freeze_time("2015-07-30 12:00:06")
    def test_valid_form_submission_with_swapped_model(self, user_a):
        self.client.login(username="flibble", password="password")
        resp = self.client.post(
            reverse("invitations:send-invite"),
            {"email": "email@example.com"},
        )
        invitation = Invitation.objects.get(email="email@example.com")

        assert resp.status_code == 200
        assert "success_message" in resp.context_data.keys()

        assert invitation.sent == timezone.now()
        assert len(mail.outbox) == 1
        assert mail.outbox[0].to[0] == "email@example.com"
        assert "Invitation to join example.com" in mail.outbox[0].subject
        url = re.search(r"(?P<url>/invitations/[^\s]+)", mail.outbox[0].body).group(
            "url",
        )
        assert url == reverse(
            app_settings.CONFIRMATION_URL_NAME,
            kwargs={"key": invitation.key},
        )


@pytest.mark.django_db
class TestInvitationsAcceptView:
    client = Client()

    def test_accept_invite_get_is_404(self, settings, invitation_b):
        settings.INVITATIONS_CONFIRM_INVITE_ON_GET = False
        resp = self.client.get(
            reverse(
                app_settings.CONFIRMATION_URL_NAME,
                kwargs={"key": invitation_b.key},
            ),
            follow=True,
        )
        assert resp.status_code == 404

    @pytest.mark.parametrize(
        "method",
        [
            ("get"),
            ("post"),
        ],
    )
    def test_accept_invite_invalid_key(self, method):
        client_with_method = getattr(self.client, method)
        resp = client_with_method(
            reverse(app_settings.CONFIRMATION_URL_NAME, kwargs={"key": "invalidKey"}),
            follow=True,
        )
        assert resp.status_code == 410

    @pytest.mark.parametrize(
        "method",
        [
            ("get"),
            ("post"),
        ],
    )
    def test_accept_invite_invalid_key_error_disabled(self, settings, method):
        settings.INVITATIONS_GONE_ON_ACCEPT_ERROR = False
        settings.INVITATIONS_LOGIN_REDIRECT = "/login-url/"
        client_with_method = getattr(self.client, method)
        resp = client_with_method(
            reverse(app_settings.CONFIRMATION_URL_NAME, kwargs={"key": "invalidKey"}),
            follow=True,
        )
        assert resp.request["PATH_INFO"] == "/login-url/"

    @pytest.mark.parametrize(
        "method",
        [
            ("get"),
            ("post"),
        ],
    )
    def test_accept_invite_accepted_key(self, accepted_invitation, method):
        client_with_method = getattr(self.client, method)
        resp = client_with_method(
            reverse(
                app_settings.CONFIRMATION_URL_NAME,
                kwargs={"key": accepted_invitation.key},
            ),
            follow=True,
        )
        assert resp.status_code == 410

    @pytest.mark.parametrize(
        "method",
        [
            ("get"),
            ("post"),
        ],
    )
    def test_accept_invite_accepted_key_error_disabled(
        self,
        settings,
        accepted_invitation,
        method,
    ):
        settings.INVITATIONS_GONE_ON_ACCEPT_ERROR = False
        settings.INVITATIONS_LOGIN_REDIRECT = "/login-url/"
        client_with_method = getattr(self.client, method)
        resp = client_with_method(
            reverse(
                app_settings.CONFIRMATION_URL_NAME,
                kwargs={"key": accepted_invitation.key},
            ),
            follow=True,
        )
        assert resp.request["PATH_INFO"] == "/login-url/"

    @pytest.mark.parametrize(
        "method",
        [
            ("get"),
            ("post"),
        ],
    )
    def test_accept_invite_expired_key(
        self,
        settings,
        sent_invitation_by_user_a,
        method,
    ):
        settings.INVITATIONS_INVITATION_EXPIRY = 0
        client_with_method = getattr(self.client, method)
        resp = client_with_method(
            reverse(
                app_settings.CONFIRMATION_URL_NAME,
                kwargs={"key": sent_invitation_by_user_a.key},
            ),
            follow=True,
        )
        assert resp.status_code == 410

    @pytest.mark.parametrize(
        "method",
        [
            ("get"),
            ("post"),
        ],
    )
    def test_accept_invite_expired_key_error_disabled(
        self,
        sent_invitation_by_user_a,
        method,
        settings,
    ):
        settings.INVITATIONS_INVITATION_EXPIRY = 0
        settings.INVITATIONS_GONE_ON_ACCEPT_ERROR = False
        settings.INVITATIONS_SIGNUP_REDIRECT = "/signup-url/"
        client_with_method = getattr(self.client, method)
        resp = client_with_method(
            reverse(
                app_settings.CONFIRMATION_URL_NAME,
                kwargs={"key": sent_invitation_by_user_a.key},
            ),
            follow=True,
        )
        assert resp.request["PATH_INFO"] == "/signup-url/"

    @pytest.mark.parametrize(
        "method",
        [
            ("get"),
            ("post"),
        ],
    )
    def test_accept_invite(self, settings, sent_invitation_by_user_a, user_a, method):
        settings.INVITATIONS_SIGNUP_REDIRECT = "/non-existent-url/"
        client_with_method = getattr(self.client, method)
        resp = client_with_method(
            reverse(
                app_settings.CONFIRMATION_URL_NAME,
                kwargs={"key": sent_invitation_by_user_a.key},
            ),
            follow=True,
        )
        invite = Invitation.objects.get(email="email@example.com")
        assert invite.accepted is True
        assert invite.inviter == user_a
        assert resp.request["PATH_INFO"] == "/non-existent-url/"

    def test_signup_redirect(self, settings, sent_invitation_by_user_a):
        settings.INVITATIONS_SIGNUP_REDIRECT = "/non-existent-url/"
        resp = self.client.post(
            reverse(
                app_settings.CONFIRMATION_URL_NAME,
                kwargs={"key": sent_invitation_by_user_a.key},
            ),
            follow=True,
        )
        invite = Invitation.objects.get(email="email@example.com")
        assert invite.accepted is True
        assert resp.request["PATH_INFO"] == "/non-existent-url/"


class TestInvitationSignals:
    client = Client()

    @patch("invitations.signals.invite_url_sent.send")
    def test_invite_url_sent_triggered_correctly(
        self,
        mock_signal,
        sent_invitation_by_user_a,
        user_a,
    ):
        invite_url = reverse(
            app_settings.CONFIRMATION_URL_NAME,
            args=[sent_invitation_by_user_a.key],
        )
        request = RequestFactory().get("/")
        invite_url = request.build_absolute_uri(invite_url)

        sent_invitation_by_user_a.send_invitation(request)

        assert mock_signal.called
        assert mock_signal.call_count == 1

        mock_signal.assert_called_with(
            instance=sent_invitation_by_user_a,
            invite_url_sent=invite_url,
            inviter=user_a,
            sender=Invitation,
        )

    @override_settings(INVITATIONS_SIGNUP_REDIRECT="/non-existent-url/")
    @patch("invitations.signals.invite_accepted.send")
    def test_invite_invite_accepted_triggered_correctly(
        self,
        mock_signal,
        sent_invitation_by_user_a,
    ):
        request = RequestFactory().get("/")
        sent_invitation_by_user_a.send_invitation(request)

        self.client.post(
            reverse(
                app_settings.CONFIRMATION_URL_NAME,
                kwargs={"key": sent_invitation_by_user_a.key},
            ),
            follow=True,
        )
        assert mock_signal.called
        assert mock_signal.call_count == 1

        assert mock_signal.call_args[1]["email"] == "email@example.com"
        assert mock_signal.call_args[1]["sender"] == AcceptInvite


class TestInvitationsForm:
    @pytest.mark.parametrize(
        "email, form_validity, errors",
        [
            ("bogger@example.com", True, None),
            ("accepted@example.com", False, "has already accepted an invite"),
            ("pending@example.com", False, "has already been invited"),
            ("flobble@example.com", False, "active user is using this"),
        ],
    )
    def test_form(
        self,
        email,
        form_validity,
        errors,
        accepted_invitation,
        pending_invitation,
        user_b,
    ):
        form = InviteForm(data={"email": email})
        if errors:
            assert errors in str(form.errors)
        else:
            assert form.errors == {}
        assert form.is_valid() is form_validity


@pytest.mark.django_db
class TestInvitationsManager:
    def test_managers(
        self,
        sent_invitation_by_user_a,
        accepted_invitation,
        expired_invitation,
        invitation_b,
    ):
        valid = Invitation.objects.all_valid().values_list("email", flat=True)
        expired = Invitation.objects.all_expired().values_list("email", flat=True)
        expected_valid = ["email@example.com", "invited@example.com"]
        expected_expired = ["accepted@example.com", "expired@example.com"]

        assert sorted(valid) == sorted(expected_valid)
        assert sorted(expired) == sorted(expected_expired)

    def test_delete_all(self):
        valid = Invitation.objects.all_valid().values_list("email", flat=True)
        Invitation.objects.delete_expired_confirmations()
        remaining_invites = Invitation.objects.all().values_list("email", flat=True)
        assert sorted(valid) == sorted(remaining_invites)


class TestInvitationsJSON:
    client = Client()

    @pytest.mark.parametrize(
        "data, expected, status_code",
        [
            (
                ["accepted@example.com"],
                {
                    "valid": [],
                    "invalid": [{"accepted@example.com": "already accepted"}],
                },
                400,
            ),
            (
                ["xample.com"],
                {"valid": [], "invalid": [{"xample.com": "invalid email"}]},
                400,
            ),
            ("xample.com", {"valid": [], "invalid": []}, 400),
            (
                ["pending@example.com"],
                {"valid": [], "invalid": [{"pending@example.com": "pending invite"}]},
                400,
            ),
            (
                ["flobble@example.com"],
                {
                    "valid": [],
                    "invalid": [{"flobble@example.com": "user registered email"}],
                },
                400,
            ),
            (
                ["example@example.com"],
                {"valid": [{"example@example.com": "invited"}], "invalid": []},
                201,
            ),
        ],
    )
    def test_post(
        self,
        settings,
        data,
        expected,
        status_code,
        user_a,
        accepted_invitation,
        pending_invitation,
        user_b,
    ):
        settings.INVITATIONS_ALLOW_JSON_INVITES = True
        self.client.login(username="flibble", password="password")
        response = self.client.post(
            reverse("invitations:send-json-invite"),
            data=json.dumps(data),
            content_type="application/json",
        )

        assert response.status_code == status_code
        assert json.loads(response.content.decode()) == expected

    def test_json_setting(self, user_a):
        self.client.login(username="flibble", password="password")
        response = self.client.post(
            reverse("invitations:send-json-invite"),
            data=json.dumps(["example@example.com"]),
            content_type="application/json",
        )

        assert response.status_code == 404

    @override_settings(INVITATIONS_ALLOW_JSON_INVITES=True)
    def test_anonymous_get(self):
        request = RequestFactory().get(
            reverse("invitations:send-json-invite"),
            content_type="application/json",
        )
        request.user = AnonymousUser()
        response = SendJSONInvite.as_view()(request)

        assert response.status_code == 302

    def test_authenticated_get(self, settings, user_a):
        settings.INVITATIONS_ALLOW_JSON_INVITES = True
        request = RequestFactory().get(
            reverse("invitations:send-json-invite"),
            content_type="application/json",
        )
        request.user = user_a
        response = SendJSONInvite.as_view()(request)

        assert response.status_code == 405


class TestInvitationsAdmin:
    client = Client()

    def test_admin_form_add(self, super_user):
        self.client.login(username="flibble", password="password")
        response = self.client.post(
            reverse("admin:invitations_invitation_add"),
            {"email": "valid@example.com", "inviter": super_user.id},
            follow=True,
        )
        invite = Invitation.objects.get(email="valid@example.com")

        assert response.status_code == 200
        assert invite.sent
        assert invite.inviter == super_user

    def test_admin_form_change(self, super_user, invitation_b):
        self.client.login(username="flibble", password="password")
        response = self.client.get(
            reverse("admin:invitations_invitation_change", args=(invitation_b.id,)),
            follow=True,
        )

        assert response.status_code == 200
        fields = list(response.context_data["adminform"].form.fields.keys())
        expected_fields = ["accepted", "key", "sent", "inviter", "email", "created"]
        assert fields == expected_fields