File: tests.py

package info (click to toggle)
python-django 3%3A3.2.19-1%2Bdeb12u2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm-proposed-updates
  • size: 56,696 kB
  • sloc: python: 264,418; javascript: 18,362; xml: 193; makefile: 178; sh: 43
file content (54 lines) | stat: -rw-r--r-- 1,837 bytes parent folder | download | duplicates (3)
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
from django.core.exceptions import FieldError
from django.test import TestCase

from .models import Choice, Poll, User


class ReverseLookupTests(TestCase):

    @classmethod
    def setUpTestData(cls):
        john = User.objects.create(name="John Doe")
        jim = User.objects.create(name="Jim Bo")
        first_poll = Poll.objects.create(
            question="What's the first question?",
            creator=john
        )
        second_poll = Poll.objects.create(
            question="What's the second question?",
            creator=jim
        )
        Choice.objects.create(
            poll=first_poll,
            related_poll=second_poll,
            name="This is the answer."
        )

    def test_reverse_by_field(self):
        u1 = User.objects.get(
            poll__question__exact="What's the first question?"
        )
        self.assertEqual(u1.name, "John Doe")

        u2 = User.objects.get(
            poll__question__exact="What's the second question?"
        )
        self.assertEqual(u2.name, "Jim Bo")

    def test_reverse_by_related_name(self):
        p1 = Poll.objects.get(poll_choice__name__exact="This is the answer.")
        self.assertEqual(p1.question, "What's the first question?")

        p2 = Poll.objects.get(related_choice__name__exact='This is the answer.')
        self.assertEqual(p2.question, "What's the second question?")

    def test_reverse_field_name_disallowed(self):
        """
        If a related_name is given you can't use the field name instead
        """
        msg = (
            "Cannot resolve keyword 'choice' into field. Choices are: "
            "creator, creator_id, id, poll_choice, question, related_choice"
        )
        with self.assertRaisesMessage(FieldError, msg):
            Poll.objects.get(choice__name__exact="This is the answer")