summaryrefslogtreecommitdiff
path: root/blog/tests.py
blob: 5b6b0ea65b30e109f2012344250581300b444715 (plain)
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
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
from contextlib import redirect_stderr
from datetime import date, timedelta
from io import StringIO

import time_machine
from django.conf import settings
from django.contrib import admin
from django.contrib.auth.models import Permission, User
from django.contrib.contenttypes.models import ContentType
from django.core.files.base import ContentFile
from django.test import TestCase
from django.test.utils import override_settings
from django.urls import reverse
from django.utils import timezone, translation

from djangoproject.tests import ReleaseMixin
from members.models import (
    BRONZE_MEMBERSHIP,
    DIAMOND_MEMBERSHIP,
    GOLD_MEMBERSHIP,
    PLATINUM_MEMBERSHIP,
    SILVER_MEMBERSHIP,
    CorporateMember,
)

from .models import ContentFormat, Entry, Event, ImageUpload
from .sitemaps import WeblogSitemap


class DateTimeMixin:
    def setUp(self):
        self.now = timezone.now()
        self.yesterday = self.now - timedelta(days=1)
        self.tomorrow = self.now + timedelta(days=1)


class EntryTestCase(DateTimeMixin, TestCase):
    def test_manager_active(self):
        """
        Make sure that the Entry manager's `active` method works
        """
        Entry.objects.create(
            pub_date=self.now, is_active=False, headline="inactive", slug="a"
        )
        Entry.objects.create(
            pub_date=self.now, is_active=True, headline="active", slug="b"
        )

        self.assertQuerySetEqual(
            Entry.objects.published(),
            ["active"],
            transform=lambda entry: entry.headline,
        )

    def test_manager_published(self):
        """
        Make sure that the Entry manager's `published` method works
        """
        Entry.objects.create(
            pub_date=self.yesterday, is_active=False, headline="past inactive", slug="a"
        )
        Entry.objects.create(
            pub_date=self.yesterday, is_active=True, headline="past active", slug="b"
        )
        Entry.objects.create(
            pub_date=self.tomorrow,
            is_active=False,
            headline="future inactive",
            slug="c",
        )
        Entry.objects.create(
            pub_date=self.tomorrow, is_active=True, headline="future active", slug="d"
        )

        self.assertQuerySetEqual(
            Entry.objects.published(),
            ["past active"],
            transform=lambda entry: entry.headline,
        )

    def test_docutils_safe(self):
        """
        Make sure docutils' file inclusion directives are disabled by default.
        """
        with redirect_stderr(StringIO()):
            entry = Entry.objects.create(
                pub_date=self.now,
                is_active=True,
                headline="active",
                content_format="reST",
                body=".. raw:: html\n    :file: somefile\n",
                slug="a",
            )
        self.assertIn("<p>&quot;raw&quot; directive disabled.</p>", entry.body_html)
        self.assertIn(".. raw:: html\n    :file: somefile", entry.body_html)

    def test_content_format_html(self):
        entry = Entry.objects.create(
            pub_date=self.now,
            slug="a",
            body="<strong>test</strong>",
            content_format=ContentFormat.HTML,
        )
        self.assertHTMLEqual(entry.body_html, "<strong>test</strong>")

    def test_content_format_reST(self):
        entry = Entry.objects.create(
            pub_date=self.now,
            slug="a",
            body="**test**",
            content_format=ContentFormat.REST,
        )
        self.assertHTMLEqual(entry.body_html, "<p><strong>test</strong></p>")

    def test_content_format_markdown(self):
        entry = Entry.objects.create(
            pub_date=self.now,
            slug="a",
            body="**test**",
            content_format=ContentFormat.MARKDOWN,
        )
        self.assertHTMLEqual(entry.body_html, "<p><strong>test</strong></p>")

    def test_header_base_level_reST(self):
        entry = Entry.objects.create(
            pub_date=self.now,
            slug="a",
            body="test\n====",
            content_format=ContentFormat.REST,
        )
        self.assertHTMLEqual(
            entry.body_html, '<div class="section" id="s-test"><h3>test</h3></div>'
        )

    def test_header_base_level_markdown(self):
        entry = Entry.objects.create(
            pub_date=self.now,
            slug="a",
            body="# test",
            content_format=ContentFormat.MARKDOWN,
        )
        self.assertHTMLEqual(entry.body_html, '<h3 id="s-test">test</h3>')

    def test_pub_date_localized(self):
        entry = Entry(pub_date=date(2005, 7, 21))
        self.assertEqual(entry.pub_date_localized, "July 21, 2005")
        with translation.override("nn"):
            self.assertEqual(entry.pub_date_localized, "21. juli 2005")

    def test_markdown_table_conversion(self):
        body = (
            "| Framework | Language |\n"
            "|-----------|----------|\n"
            "| Django    | Python   |\n"
            "| Flask     | Python   |"
        )

        entry = Entry.objects.create(
            pub_date=self.now,
            slug="markdown-table",
            body=body,
            content_format=ContentFormat.MARKDOWN,
        )
        expected_html = (
            "<table>\n"
            "<thead>\n<tr>\n<th>Framework</th>\n<th>Language</th>\n</tr>\n</thead>\n"
            "<tbody>\n<tr>\n<td>Django</td>\n<td>Python</td>\n</tr>\n"
            "<tr>\n<td>Flask</td>\n<td>Python</td>\n</tr>\n</tbody>\n</table>"
        )
        self.assertInHTML(expected_html, entry.body_html)


class EventTestCase(DateTimeMixin, TestCase):
    def test_manager_past_future(self):
        """
        Make sure that the Event manager's `past` and `future` methods works
        """
        Event.objects.create(date=self.yesterday, pub_date=self.now, headline="past")
        Event.objects.create(date=self.tomorrow, pub_date=self.now, headline="future")

        self.assertQuerySetEqual(
            Event.objects.future(), ["future"], transform=lambda event: event.headline
        )
        self.assertQuerySetEqual(
            Event.objects.past(), ["past"], transform=lambda event: event.headline
        )

    def test_manager_past_future_include_today(self):
        """
        Make sure that both .future() and .past() include today's events.
        """
        Event.objects.create(date=self.now, pub_date=self.now, headline="today")

        self.assertQuerySetEqual(
            Event.objects.future(), ["today"], transform=lambda event: event.headline
        )
        self.assertQuerySetEqual(
            Event.objects.past(), ["today"], transform=lambda event: event.headline
        )

    def test_past_future_ordering(self):
        """
        Make sure the that .future() and .past() use the actual date for ordering
        (and not the pub_date).
        """
        D = timedelta(days=1)
        Event.objects.create(
            date=self.yesterday - D, pub_date=self.yesterday - D, headline="a"
        )
        Event.objects.create(date=self.yesterday, pub_date=self.yesterday, headline="b")

        Event.objects.create(date=self.tomorrow, pub_date=self.tomorrow, headline="c")
        Event.objects.create(
            date=self.tomorrow + D, pub_date=self.tomorrow + D, headline="d"
        )

        self.assertQuerySetEqual(
            Event.objects.future(), ["c", "d"], transform=lambda event: event.headline
        )
        self.assertQuerySetEqual(
            Event.objects.past(), ["b", "a"], transform=lambda event: event.headline
        )


class ViewsTestCase(ReleaseMixin, DateTimeMixin, TestCase):
    def test_detail_view_html_meta(self):
        headline = "Pride and Prejudice - Review"
        author = "Jane Austen"
        pub_date = date(2005, 7, 21)
        blog_entry = Entry.objects.create(
            pub_date=pub_date,
            is_active=True,
            headline=headline,
            slug="a",
            author=author,
        )
        blog_description = "Posted by Jane Austen on July 21, 2005"
        self.assertEqual(blog_entry.description, blog_description)

        blog_url = blog_entry.get_absolute_url()
        response = self.client.get(blog_url)
        self.assertEqual(response.status_code, 200)

        expected_html_meta_tags = [
            f'<meta name="description" content="{blog_description}" />',
            '<meta property="og:type" content="article" />',
            f'<meta property="og:title" content="{headline}" />',
            f'<meta property="og:description" content="{blog_description}" />',
            '<meta property="og:article:published_time" content="2005-07-21T00:00:00" />',
            f'<meta property="og:article:author" content="{author}" />',
            '<meta property="og:image:alt" content="Django logo" />',
            f'<meta property="og:url" content="{blog_url}" />',
            '<meta property="og:site_name" content="Django Project" />',
            '<meta property="twitter:card" content="summary" />',
            '<meta property="twitter:creator" content="djangoproject" />',
            '<meta property="twitter:site" content="djangoproject" />',
        ]
        for expected_html_meta_tag in expected_html_meta_tags:
            self.assertContains(response, expected_html_meta_tag, html=True)

    def test_staff_with_change_permission_can_see_unpublished_detail_view(self):
        """
        Staff users with change permission on BlogEntry can't see unpublished entries
        in the list, but can view the detail page
        """
        e1 = Entry.objects.create(
            pub_date=self.yesterday, is_active=False, headline="inactive", slug="a"
        )
        user = User.objects.create(username="staff", is_staff=True)
        # Add blog entry change permission

        content_type = ContentType.objects.get_for_model(Entry)
        change_permission = Permission.objects.get(
            content_type=content_type, codename="change_entry"
        )
        user.user_permissions.add(change_permission)
        self.client.force_login(user)
        self.assertEqual(Entry.objects.all().count(), 1)
        response = self.client.get(reverse("weblog:index"))
        self.assertEqual(response.status_code, 404)

        response = self.client.get(
            reverse(
                "weblog:entry",
                kwargs={
                    "year": e1.pub_date.year,
                    "month": e1.pub_date.strftime("%b").lower(),
                    "day": e1.pub_date.day,
                    "slug": e1.slug,
                },
            )
        )
        request = response.context["request"]
        self.assertTrue(request.user.is_staff)
        self.assertTrue(request.user.has_perm("blog.change_entry"))
        self.assertEqual(response.status_code, 200)

    def test_staff_without_change_permission_cannot_see_unpublished_detail_view(self):
        """
        Staff users without change permission on BlogEntry can't see unpublished entries
        """
        e1 = Entry.objects.create(
            pub_date=self.yesterday, is_active=False, headline="inactive", slug="a"
        )
        user = User.objects.create(username="staff-no-perm", is_staff=True)
        # No permissions added
        self.client.force_login(user)
        self.assertEqual(Entry.objects.all().count(), 1)

        # Test detail view for unpublished entry - should return 404
        response = self.client.get(
            reverse(
                "weblog:entry",
                kwargs={
                    "year": e1.pub_date.year,
                    "month": e1.pub_date.strftime("%b").lower(),
                    "day": e1.pub_date.day,
                    "slug": e1.slug,
                },
            )
        )
        request = response.context["request"]
        self.assertTrue(request.user.is_staff)
        self.assertFalse(request.user.has_perm("blog.change_entry"))
        self.assertEqual(response.status_code, 404)

    def test_no_past_upcoming_events(self):
        """
        Make sure there are no past event in the "upcoming events" sidebar (#399)
        """
        # We need a published entry on the index page so that it doesn't return a 404
        Entry.objects.create(pub_date=self.yesterday, is_active=True, slug="a")
        Event.objects.create(
            date=self.yesterday, pub_date=self.now, is_active=True, headline="Jezdezcon"
        )
        response = self.client.get(reverse("weblog:index"))
        self.assertEqual(response.status_code, 200)
        self.assertQuerySetEqual(response.context["events"], [])

    def test_no_unpublished_future_events(self):
        """
        Make sure there are no unpublished future events in the "upcoming events" sidebar
        """
        # We need a published entry on the index page so that it doesn't return a 404
        Entry.objects.create(pub_date=self.yesterday, is_active=True, slug="a")
        Event.objects.create(
            date=self.tomorrow,
            pub_date=self.yesterday,
            is_active=False,
            headline="inactive",
        )
        Event.objects.create(
            date=self.tomorrow,
            pub_date=self.tomorrow,
            is_active=True,
            headline="future publish date",
        )

        for user in [
            None,
            User.objects.create(username="non-staff", is_staff=False),
            User.objects.create(username="staff", is_staff=True),
            User.objects.create_superuser(username="superuser"),
        ]:
            if user:
                self.client.force_login(user)
            response = self.client.get(reverse("weblog:index"))
            with self.subTest(user=user):
                self.assertEqual(response.status_code, 200)
                self.assertQuerySetEqual(response.context["events"], [])

    def test_corporate_sponsors_displayed(self):
        objs = CorporateMember.objects.bulk_create(
            [
                CorporateMember(
                    display_name="Platinum company",
                    membership_level=PLATINUM_MEMBERSHIP,
                ),
                CorporateMember(
                    display_name="Diamond company", membership_level=DIAMOND_MEMBERSHIP
                ),
                CorporateMember(
                    display_name="Gold company", membership_level=GOLD_MEMBERSHIP
                ),
                CorporateMember(
                    display_name="Silver company", membership_level=SILVER_MEMBERSHIP
                ),
                CorporateMember(
                    display_name="Bronze company", membership_level=BRONZE_MEMBERSHIP
                ),
            ]
        )
        for obj in objs:
            obj.invoice_set.create(amount=4, expiration_date=date(3000, 1, 1))

        blog_entry = Entry.objects.create(
            pub_date=date(2005, 7, 21),
            is_active=True,
            headline="Django election results",
            slug="a",
            author="DSF Board",
        )
        urls = [
            reverse("weblog:index"),
            reverse(
                "weblog:entry",
                kwargs={
                    "year": blog_entry.pub_date.year,
                    "month": blog_entry.pub_date.strftime("%b").lower(),
                    "day": blog_entry.pub_date.day,
                    "slug": blog_entry.slug,
                },
            ),
            reverse(
                "weblog:archive-year",
                kwargs={"year": blog_entry.pub_date.year},
            ),
            reverse(
                "weblog:archive-month",
                kwargs={
                    "year": blog_entry.pub_date.year,
                    "month": blog_entry.pub_date.strftime("%b").lower(),
                },
            ),
            reverse(
                "weblog:archive-day",
                kwargs={
                    "year": blog_entry.pub_date.year,
                    "month": blog_entry.pub_date.strftime("%b").lower(),
                    "day": blog_entry.pub_date.day,
                },
            ),
        ]
        for url in urls:
            with self.subTest(url=url):
                response = self.client.get(url)
                self.assertContains(response, "Diamond and Platinum Members")
                self.assertContains(response, "Platinum company")
                self.assertContains(response, "Diamond company")
                self.assertNotContains(response, "Gold company")
                self.assertNotContains(response, "Silver company")
                self.assertNotContains(response, "Bronze company")

    def test_anonymous_user_cannot_see_unpublished_entries(self):
        """
        Anonymous users can't see unpublished entries at all (list or detail view)
        """
        # Create a published entry to ensure the list view works
        published_entry = Entry.objects.create(
            pub_date=self.yesterday,
            is_active=True,
            headline="published",
            slug="published",
        )

        # Create an unpublished entry
        unpublished_entry = Entry.objects.create(
            pub_date=self.tomorrow,
            is_active=True,
            headline="unpublished",
            slug="unpublished",
        )

        # Test list view - should return 200 but not include the unpublished entry
        response = self.client.get(reverse("weblog:index"))
        self.assertEqual(response.status_code, 200)
        self.assertContains(response, "published")
        self.assertNotContains(response, "unpublished")

        # Test detail view for unpublished entry - should return 404
        unpublished_url = reverse(
            "weblog:entry",
            kwargs={
                "year": unpublished_entry.pub_date.year,
                "month": unpublished_entry.pub_date.strftime("%b").lower(),
                "day": unpublished_entry.pub_date.day,
                "slug": unpublished_entry.slug,
            },
        )
        response = self.client.get(unpublished_url)
        self.assertEqual(response.status_code, 404)

        # Test detail view for published entry - should return 200
        published_url = reverse(
            "weblog:entry",
            kwargs={
                "year": published_entry.pub_date.year,
                "month": published_entry.pub_date.strftime("%b").lower(),
                "day": published_entry.pub_date.day,
                "slug": published_entry.slug,
            },
        )
        response = self.client.get(published_url)
        self.assertEqual(response.status_code, 200)

    def test_user_cannot_see_unpublished_entries(self):
        """
        Non-staff users can't see unpublished entries at all (list or detail view)
        """
        user = User.objects.create(username="non-staff", is_staff=False)
        self.client.force_login(user)

        # Create a published entry to ensure the list view works
        published_entry = Entry.objects.create(
            pub_date=self.yesterday,
            is_active=True,
            headline="published",
            slug="published",
        )

        # Create an unpublished entry
        unpublished_entry = Entry.objects.create(
            pub_date=self.tomorrow,
            is_active=True,
            headline="unpublished",
            slug="unpublished",
        )

        # Test list view - should return 200 but not include the unpublished entry
        response = self.client.get(reverse("weblog:index"))
        self.assertEqual(response.status_code, 200)
        self.assertContains(response, "published")
        self.assertNotContains(response, "unpublished")

        # Test detail view for unpublished entry - should return 404
        unpublished_url = reverse(
            "weblog:entry",
            kwargs={
                "year": unpublished_entry.pub_date.year,
                "month": unpublished_entry.pub_date.strftime("%b").lower(),
                "day": unpublished_entry.pub_date.day,
                "slug": unpublished_entry.slug,
            },
        )
        response = self.client.get(unpublished_url)
        self.assertEqual(response.status_code, 404)

        # Test detail view for published entry - should return 200
        published_url = reverse(
            "weblog:entry",
            kwargs={
                "year": published_entry.pub_date.year,
                "month": published_entry.pub_date.strftime("%b").lower(),
                "day": published_entry.pub_date.day,
                "slug": published_entry.slug,
            },
        )
        response = self.client.get(published_url)
        self.assertEqual(response.status_code, 200)

    def test_archive_view_titles(self):
        headline = "Pride and Prejudice - Review"
        pub_date = date(2005, 7, 21)
        Entry.objects.create(
            pub_date=pub_date,
            is_active=True,
            headline=headline,
            slug="a",
            author="Jane Austen",
        )
        year = pub_date.strftime("%Y")
        month = pub_date.strftime("%b").lower()
        day = pub_date.strftime("%d")
        for testcase in [
            {
                "view": "weblog:archive-year",
                "kwargs": {"year": year},
                "header": "<h1>2005 archive</h1>",
            },
            {
                "view": "weblog:archive-month",
                "kwargs": {"year": year, "month": month},
                "header": "<h1>July 2005 archive</h1>",
            },
            {
                "view": "weblog:archive-day",
                "kwargs": {"year": year, "month": month, "day": day},
                "header": "<h1>July 21, 2005 archive</h1>",
            },
        ]:
            with self.subTest(view=testcase["view"]):
                response = self.client.get(
                    reverse(testcase["view"], kwargs=testcase["kwargs"])
                )
                self.assertEqual(response.status_code, 200)
                self.assertContains(response, testcase["header"])
                self.assertContains(response, headline)


@override_settings(
    # Caching middleware is added in the production settings file;
    # simulate that here for the tests.
    MIDDLEWARE=(
        ["django.middleware.cache.UpdateCacheMiddleware"]
        + settings.MIDDLEWARE
        + ["django.middleware.cache.FetchFromCacheMiddleware"]
    ),
)
class ViewsCachingTestCase(ReleaseMixin, DateTimeMixin, TestCase):
    def test_drafts_have_no_cache_headers(self):
        """
        Draft (unpublished) entries have no-cache headers.
        """
        user = User.objects.create(username="staff", is_staff=True)
        content_type = ContentType.objects.get_for_model(Entry)
        change_permission = Permission.objects.get(
            content_type=content_type, codename="change_entry"
        )
        user.user_permissions.add(change_permission)
        self.client.force_login(user)

        unpublished_entry = Entry.objects.create(
            pub_date=self.tomorrow,
            is_active=True,
            headline="unpublished",
            slug="unpublished",
        )
        unpublished_url = reverse(
            "weblog:entry",
            kwargs={
                "year": unpublished_entry.pub_date.year,
                "month": unpublished_entry.pub_date.strftime("%b").lower(),
                "day": unpublished_entry.pub_date.day,
                "slug": unpublished_entry.slug,
            },
        )

        response = self.client.get(unpublished_url)

        self.assertEqual(response.status_code, 200)
        self.assertIn("Cache-Control", response.headers)
        self.assertEqual(
            response.headers["Cache-Control"],
            "max-age=0, no-cache, no-store, must-revalidate, private",
        )

    def test_published_blogs_have_cache_control_headers(self):
        """
        Published blog posts has Cache-Control header.
        """
        entry = Entry.objects.create(
            pub_date=self.yesterday,
            is_active=True,
            headline="published",
            slug="published",
        )
        url = reverse(
            "weblog:entry",
            kwargs={
                "year": entry.pub_date.year,
                "month": entry.pub_date.strftime("%b").lower(),
                "day": entry.pub_date.day,
                "slug": entry.slug,
            },
        )
        response = self.client.get(url)
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.headers["Cache-Control"], "max-age=300")


class SitemapTests(DateTimeMixin, TestCase):
    def test_sitemap(self):
        entry = Entry.objects.create(
            pub_date=self.yesterday, is_active=True, headline="foo", slug="foo"
        )
        sitemap = WeblogSitemap()
        urls = sitemap.get_urls()
        self.assertEqual(len(urls), 1)
        url_info = urls[0]
        self.assertEqual(url_info["location"], entry.get_absolute_url())


class ImageUploadTestCase(TestCase):
    @classmethod
    def setUpTestData(cls):
        cls.user = User.objects.create_superuser("test")

    def setUp(self):
        super().setUp()
        self.client.force_login(self.user)

    def test_uploaded_by(self):
        # Can't test the ModelForm directly because the logic in
        # ModelAdmin.save_model()
        data = {
            "title": "test",
            "alt_text": "test",
            "image": ContentFile(b".", name="test.png"),
        }
        response = self.client.post(
            reverse("admin:blog_imageupload_add"),
            data=data,
        )
        self.assertEqual(response.status_code, 302)
        upload = ImageUpload.objects.get()
        self.assertEqual(upload.uploaded_by, self.user)

    def test_contentformat_image_tags(self):
        for cf, expected in [
            (ContentFormat.REST, ".. image:: /test/image.png\n   :alt: TEST"),
            (ContentFormat.HTML, '<img src="/test/image.png" alt="TEST">'),
            (ContentFormat.MARKDOWN, "![TEST](/test/image.png)"),
        ]:
            with self.subTest(contentformat=cf):
                self.assertEqual(
                    cf.img(url="/test/image.png", alt_text="TEST"),
                    expected,
                )

    @time_machine.travel("2005-07-21")
    def test_full_url(self):
        i = ImageUpload.objects.create(
            title="test",
            alt_text="test",
            image=ContentFile(b".", name="test.png"),
        )
        # Because the storage is persistent between test runs, running this
        # test twice will trigger a filename clash and the storage will append
        # a random suffix to the filename, hence the use of assertRegex here.
        self.assertRegex(
            i.full_url,
            r"http://www\.djangoproject\.localhost:8000"
            r"/m/blog/images/2005/07/test(_\w+)?\.png",
        )

    def test_alt_text_html_escape(self):
        testdata = [
            (ContentFormat.HTML, 'te"st', '<img src="." alt="te&quot;st">'),
            (ContentFormat.HTML, "te<st>", '<img src="." alt="te&lt;st&gt;">'),
            (ContentFormat.MARKDOWN, 'te"st', '<img src="." alt="te&quot;st">'),
            (ContentFormat.MARKDOWN, "te[st]", '<img src="." alt="te[st]">'),
            (ContentFormat.MARKDOWN, "te{st}", '<img src="." alt="te{st}">'),
            (ContentFormat.MARKDOWN, "te<st>", '<img src="." alt="te&lt;st&gt;">'),
            (ContentFormat.MARKDOWN, "test*", '<img src="." alt="test*">'),
            (ContentFormat.MARKDOWN, "test_", '<img src="." alt="test_">'),
            (ContentFormat.MARKDOWN, "test`", '<img src="." alt="test`">'),
            (ContentFormat.MARKDOWN, "test+", '<img src="." alt="test+">'),
            (ContentFormat.MARKDOWN, "test-", '<img src="." alt="test-">'),
            (ContentFormat.MARKDOWN, "test.", '<img src="." alt="test.">'),
            (ContentFormat.MARKDOWN, "test!", '<img src="." alt="test!">'),
            (ContentFormat.MARKDOWN, "te\nst", '<img src="." alt="te\nst">'),
            (ContentFormat.REST, 'te"st', '<img src="." alt="te&quot;st">'),
            (ContentFormat.REST, "te[st]", '<img src="." alt="te[st]">'),
            (ContentFormat.REST, "te{st}", '<img src="." alt="te{st}">'),
            (ContentFormat.REST, "te<st>", '<img src="." alt="te&lt;st&gt;">'),
            (ContentFormat.REST, "te:st", '<img src="." alt="te:st">'),
            (ContentFormat.REST, "test*", '<img src="." alt="test*">'),
            (ContentFormat.REST, "test_", '<img src="." alt="test_">'),
            (ContentFormat.REST, "test`", '<img src="." alt="test`">'),
            (ContentFormat.REST, "test+", '<img src="." alt="test+">'),
            (ContentFormat.REST, "test-", '<img src="." alt="test-">'),
            (ContentFormat.REST, "test.", '<img src="." alt="test.">'),
            (ContentFormat.REST, "test!", '<img src="." alt="test!">'),
        ]
        for cf, alt_text, expected in testdata:
            # RST doesn't like an empty src, so we use . instead
            img_tag = cf.img(url=".", alt_text=alt_text)
            if cf is ContentFormat.MARKDOWN:
                expected = f"<p>{expected}</p>"
            with self.subTest(cf=cf, alt_text=alt_text):
                self.assertHTMLEqual(
                    ContentFormat.to_html(cf, img_tag),
                    expected,
                )

    def test_copy_button(self):
        i = ImageUpload.objects.create(
            title="test",
            alt_text='Alt text "here"',
            image=ContentFile(b".", name="test.png"),
        )
        self.assertInHTML(
            '<button type="button" data-clipboard-content='
            f'"&lt;img src=&quot;/m/{i.image}&quot; '
            'alt=&quot;Alt text &amp;quot;here&amp;quot;&quot;&gt;">'
            "Raw HTML"
            "</button>",
            admin.site.get_model_admin(ImageUpload).copy_buttons(i),
        )