|
| 1 | +from django.contrib.auth.models import User |
| 2 | +from django.test import Client, TestCase, tag |
| 3 | +from django.urls import reverse |
| 4 | + |
| 5 | +from project.newsletter.models import Category, Post |
| 6 | + |
| 7 | + |
| 8 | +@tag("lab_test") |
| 9 | +class TestAdminListViewNPlusOne(TestCase): |
| 10 | + def test_verify_broken(self): |
| 11 | + author = User.objects.create_superuser(username="u1") |
| 12 | + categories = [ |
| 13 | + Category.objects.create(slug=f"c{i}", title=f"Cat {i}") for i in range(5) |
| 14 | + ] |
| 15 | + for i in range(5): |
| 16 | + post = Post.objects.create( |
| 17 | + author=author, slug=f"post{i}", title=f"Post {i}" |
| 18 | + ) |
| 19 | + post.categories.set(categories) |
| 20 | + client = Client() |
| 21 | + client.force_login(author) |
| 22 | + |
| 23 | + with self.assertNumQueries(11): |
| 24 | + # This should contain duplicate queries on category |
| 25 | + client.get("/admin/newsletter/post/") |
| 26 | + |
| 27 | + |
| 28 | +@tag("lab_test") |
| 29 | +class TestListViewsCategoriesNPlusOne(TestCase): |
| 30 | + def setUp(self) -> None: |
| 31 | + author = User.objects.create_superuser(username="u1") |
| 32 | + categories = [ |
| 33 | + Category.objects.create(slug=f"c{i}", title=f"Cat {i}") for i in range(5) |
| 34 | + ] |
| 35 | + for i in range(5): |
| 36 | + post = Post.objects.create( |
| 37 | + author=author, |
| 38 | + slug=f"post{i}", |
| 39 | + title=f"Post {i}", |
| 40 | + is_public=True, |
| 41 | + is_published=True, |
| 42 | + ) |
| 43 | + post.categories.set(categories) |
| 44 | + self.client = Client() |
| 45 | + self.client.force_login(author) |
| 46 | + |
| 47 | + def test_list_posts(self): |
| 48 | + with self.assertNumQueries(9): |
| 49 | + # This should contain duplicate queries on category |
| 50 | + self.client.get(reverse("newsletter:list_posts")) |
| 51 | + |
| 52 | + def test_landing(self): |
| 53 | + with self.assertNumQueries(7): |
| 54 | + # This should contain duplicate queries on category |
| 55 | + self.client.get(reverse("newsletter:landing")) |
| 56 | + |
| 57 | + |
| 58 | +@tag("lab_test") |
| 59 | +class TestPostSlugMissingIndex(TestCase): |
| 60 | + def test_sql_uses_scan_without_index(self): |
| 61 | + self.assertIn("scan", Post.objects.filter(slug="test").explain().lower()) |
| 62 | + self.assertNotIn("index", Post.objects.filter(slug="test").explain().lower()) |
0 commit comments