~linuxgoose/bocpress

ref: a20aa2ef91a954f4c5da63166885e94bb2a0087b bocpress/main/tests/test_management.py -rw-r--r-- 7.0 KiB
a20aa2ef — Jordan update readme wording 2 months ago
                                                                                
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
from datetime import datetime
from io import StringIO
from unittest.mock import patch

from django.conf import settings
from django.core import mail
from django.core.management import call_command
from django.test import TestCase
from django.utils import timezone

from main import models
from main.management.commands import mailexports, processnotifications


class ProcessNotificationsTest(TestCase):
    """
    Test processnotifications sends emails to the blog's subscibers.
    """

    def setUp(self):
        self.user = models.User.objects.create(
            username="alice", email="alice@mataroa.blog", notifications_on=True
        )

        post_data = {
            "title": "Yesterday post",
            "slug": "yesterday-post",
            "body": "Content sentence.",
            "published_at": timezone.make_aware(datetime(2020, 1, 1)),
        }
        self.post_yesterday = models.Post.objects.create(owner=self.user, **post_data)

        post_data = {
            "title": "Today post",
            "slug": "today-post",
            "body": "Content sentence.",
            "published_at": timezone.make_aware(datetime(2020, 1, 2)),
        }
        self.post_today = models.Post.objects.create(owner=self.user, **post_data)

        self.notification = models.Notification.objects.create(
            blog_user=self.user, email="subscriber@example.com"
        )

    def test_mail_backend(self):
        connection = processnotifications.get_mail_connection()
        self.assertEqual(connection.host, settings.EMAIL_HOST_BROADCASTS)

    def test_command(self):
        output = StringIO()

        with (
            patch.object(timezone, "now", return_value=datetime(2020, 1, 2, 13, 00)),
            patch.object(
                # Django default test runner overrides SMTP EmailBackend with locmem,
                # but because we re-import the SMTP backend in
                # processnotifications.get_mail_connection, we need to mock it here too.
                processnotifications,
                "get_mail_connection",
                return_value=mail.get_connection(
                    "django.core.mail.backends.locmem.EmailBackend"
                ),
            ),
        ):
            call_command("processnotifications", "--no-dryrun", stdout=output)

        # notification records
        records = models.NotificationRecord.objects.all()
        self.assertEqual(len(records), 1)
        record = records[0]

        # notification record for yesterday's post
        self.assertEqual(record.notification.email, self.notification.email)
        self.assertEqual(record.post.title, "Yesterday post")

        # logging
        self.assertIn("Processing notifications.", output.getvalue())
        self.assertIn(
            "Email sent for 'Yesterday post' to 'subscriber@example.com'",
            output.getvalue(),
        )

        # email
        self.assertEqual(len(mail.outbox), 1)
        self.assertEqual(mail.outbox[0].subject, "Yesterday post")
        self.assertIn("Unsubscribe", mail.outbox[0].body)

        # email headers
        self.assertEqual(mail.outbox[0].to, [self.notification.email])
        self.assertEqual(mail.outbox[0].reply_to, [])
        self.assertEqual(
            mail.outbox[0].from_email,
            f"{self.user.username} <{self.user.username}@{settings.EMAIL_FROM_HOST}>",
        )

        self.assertEqual(
            mail.outbox[0].extra_headers["X-PM-Message-Stream"], "newsletters"
        )
        self.assertIn(
            "/newsletter/unsubscribe/",
            mail.outbox[0].extra_headers["List-Unsubscribe"],
        )
        self.assertEqual(
            mail.outbox[0].extra_headers["List-Unsubscribe-Post"],
            "List-Unsubscribe=One-Click",
        )

    def tearDown(self):
        models.User.objects.all().delete()
        models.Post.objects.all().delete()


class MailExportsTest(TestCase):
    """
    Test mail_export sends emails to users with `mail_export_on` enabled.
    """

    def setUp(self):
        self.user = models.User.objects.create(
            username="alice", email="alice@mataroa.blog", mail_export_on=True
        )

        post_data = {
            "title": "A post",
            "slug": "a-post",
            "body": "Content sentence.",
            "published_at": timezone.make_aware(datetime(2020, 1, 1)),
        }
        self.post_a = models.Post.objects.create(owner=self.user, **post_data)

        post_data = {
            "title": "Second post",
            "slug": "second-post",
            "body": "Content sentence two.",
            "published_at": timezone.make_aware(datetime(2020, 1, 2)),
        }
        self.post_b = models.Post.objects.create(owner=self.user, **post_data)

    def test_mail_backend(self):
        connection = mailexports.get_mail_connection()
        self.assertEqual(connection.host, settings.EMAIL_HOST_BROADCASTS)

    def test_command(self):
        output = StringIO()

        with (
            patch.object(timezone, "now", return_value=datetime(2020, 1, 1, 00, 00)),
            patch.object(
                # Django default test runner overrides SMTP EmailBackend with locmem,
                # but because we re-import the SMTP backend in
                # processnotifications.get_mail_connection, we need to mock it here too.
                mailexports,
                "get_mail_connection",
                return_value=mail.get_connection(
                    "django.core.mail.backends.locmem.EmailBackend"
                ),
            ),
        ):
            call_command("mailexports", stdout=output)

        # export records
        records = models.ExportRecord.objects.all()
        self.assertEqual(len(records), 1)
        self.assertEqual(records[0].user, self.user)
        self.assertIn("export-markdown-", records[0].name)

        # logging
        self.assertIn("Processing email exports.", output.getvalue())
        self.assertIn(f"Processing user {self.user.username}.", output.getvalue())
        self.assertIn(f"Export sent to {self.user.username}.", output.getvalue())
        self.assertIn(
            f"Logging export record for '{records[0].name}'.", output.getvalue()
        )
        self.assertIn("Emailing all exports complete.", output.getvalue())

        # email
        self.assertEqual(len(mail.outbox), 1)
        self.assertIn("Mataroa export", mail.outbox[0].subject)
        self.assertIn("Stop receiving exports", mail.outbox[0].body)

        # email headers
        self.assertEqual(mail.outbox[0].to, [self.user.email])
        self.assertEqual(
            mail.outbox[0].from_email,
            settings.DEFAULT_FROM_EMAIL,
        )

        self.assertEqual(mail.outbox[0].extra_headers["X-PM-Message-Stream"], "exports")
        self.assertIn(
            "/export/unsubscribe/",
            mail.outbox[0].extra_headers["List-Unsubscribe"],
        )
        self.assertEqual(
            mail.outbox[0].extra_headers["List-Unsubscribe-Post"],
            "List-Unsubscribe=One-Click",
        )

    def tearDown(self):
        models.User.objects.all().delete()
        models.Post.objects.all().delete()