~ubuntu-branches/debian/sid/python-django/sid

« back to all changes in this revision

Viewing changes to tests/modeltests/select_related/tests.py

  • Committer: Package Import Robot
  • Author(s): Luke Faraone
  • Date: 2013-11-07 15:33:49 UTC
  • mfrom: (1.3.12)
  • Revision ID: package-import@ubuntu.com-20131107153349-e31sc149l2szs3jb
Tags: 1.6-1
* New upstream version. Closes: #557474, #724637.
* python-django now also suggests the installation of ipython,
  bpython, python-django-doc, and libgdal1.
  Closes: #636511, #686333, #704203
* Set package maintainer to Debian Python Modules Team.
* Bump standards version to 3.9.5, no changes needed.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
from __future__ import absolute_import, unicode_literals
2
 
 
3
 
from django.test import TestCase
4
 
 
5
 
from .models import Domain, Kingdom, Phylum, Klass, Order, Family, Genus, Species
6
 
 
7
 
 
8
 
class SelectRelatedTests(TestCase):
9
 
 
10
 
    def create_tree(self, stringtree):
11
 
        """
12
 
        Helper to create a complete tree.
13
 
        """
14
 
        names = stringtree.split()
15
 
        models = [Domain, Kingdom, Phylum, Klass, Order, Family, Genus, Species]
16
 
        assert len(names) == len(models), (names, models)
17
 
 
18
 
        parent = None
19
 
        for name, model in zip(names, models):
20
 
            try:
21
 
                obj = model.objects.get(name=name)
22
 
            except model.DoesNotExist:
23
 
                obj = model(name=name)
24
 
            if parent:
25
 
                setattr(obj, parent.__class__.__name__.lower(), parent)
26
 
            obj.save()
27
 
            parent = obj
28
 
 
29
 
    def create_base_data(self):
30
 
        self.create_tree("Eukaryota Animalia Anthropoda Insecta Diptera Drosophilidae Drosophila melanogaster")
31
 
        self.create_tree("Eukaryota Animalia Chordata Mammalia Primates Hominidae Homo sapiens")
32
 
        self.create_tree("Eukaryota Plantae Magnoliophyta Magnoliopsida Fabales Fabaceae Pisum sativum")
33
 
        self.create_tree("Eukaryota Fungi Basidiomycota Homobasidiomycatae Agaricales Amanitacae Amanita muscaria")
34
 
 
35
 
    def setUp(self):
36
 
        # The test runner sets settings.DEBUG to False, but we want to gather
37
 
        # queries so we'll set it to True here and reset it at the end of the
38
 
        # test case.
39
 
        self.create_base_data()
40
 
 
41
 
    def test_access_fks_without_select_related(self):
42
 
        """
43
 
        Normally, accessing FKs doesn't fill in related objects
44
 
        """
45
 
        with self.assertNumQueries(8):
46
 
            fly = Species.objects.get(name="melanogaster")
47
 
            domain = fly.genus.family.order.klass.phylum.kingdom.domain
48
 
            self.assertEqual(domain.name, 'Eukaryota')
49
 
 
50
 
    def test_access_fks_with_select_related(self):
51
 
        """
52
 
        A select_related() call will fill in those related objects without any
53
 
        extra queries
54
 
        """
55
 
        with self.assertNumQueries(1):
56
 
            person = Species.objects.select_related(depth=10).get(name="sapiens")
57
 
            domain = person.genus.family.order.klass.phylum.kingdom.domain
58
 
            self.assertEqual(domain.name, 'Eukaryota')
59
 
 
60
 
    def test_list_without_select_related(self):
61
 
        """
62
 
        select_related() also of course applies to entire lists, not just
63
 
        items. This test verifies the expected behavior without select_related.
64
 
        """
65
 
        with self.assertNumQueries(9):
66
 
            world = Species.objects.all()
67
 
            families = [o.genus.family.name for o in world]
68
 
            self.assertEqual(sorted(families), [
69
 
                'Amanitacae',
70
 
                'Drosophilidae',
71
 
                'Fabaceae',
72
 
                'Hominidae',
73
 
            ])
74
 
 
75
 
    def test_list_with_select_related(self):
76
 
        """
77
 
        select_related() also of course applies to entire lists, not just
78
 
        items. This test verifies the expected behavior with select_related.
79
 
        """
80
 
        with self.assertNumQueries(1):
81
 
            world = Species.objects.all().select_related()
82
 
            families = [o.genus.family.name for o in world]
83
 
            self.assertEqual(sorted(families), [
84
 
                'Amanitacae',
85
 
                'Drosophilidae',
86
 
                'Fabaceae',
87
 
                'Hominidae',
88
 
            ])
89
 
 
90
 
    def test_depth(self, depth=1, expected=7):
91
 
        """
92
 
        The "depth" argument to select_related() will stop the descent at a
93
 
        particular level.
94
 
        """
95
 
        # Notice: one fewer queries than above because of depth=1
96
 
        with self.assertNumQueries(expected):
97
 
            pea = Species.objects.select_related(depth=depth).get(name="sativum")
98
 
            self.assertEqual(
99
 
                pea.genus.family.order.klass.phylum.kingdom.domain.name,
100
 
                'Eukaryota'
101
 
            )
102
 
 
103
 
    def test_larger_depth(self):
104
 
        """
105
 
        The "depth" argument to select_related() will stop the descent at a
106
 
        particular level.  This tests a larger depth value.
107
 
        """
108
 
        self.test_depth(depth=5, expected=3)
109
 
 
110
 
    def test_list_with_depth(self):
111
 
        """
112
 
        The "depth" argument to select_related() will stop the descent at a
113
 
        particular level. This can be used on lists as well.
114
 
        """
115
 
        with self.assertNumQueries(5):
116
 
            world = Species.objects.all().select_related(depth=2)
117
 
            orders = [o.genus.family.order.name for o in world]
118
 
            self.assertEqual(sorted(orders),
119
 
                ['Agaricales', 'Diptera', 'Fabales', 'Primates'])
120
 
 
121
 
    def test_select_related_with_extra(self):
122
 
        s = Species.objects.all().select_related(depth=1)\
123
 
            .extra(select={'a': 'select_related_species.id + 10'})[0]
124
 
        self.assertEqual(s.id + 10, s.a)
125
 
 
126
 
    def test_certain_fields(self):
127
 
        """
128
 
        The optional fields passed to select_related() control which related
129
 
        models we pull in. This allows for smaller queries and can act as an
130
 
        alternative (or, in addition to) the depth parameter.
131
 
 
132
 
        In this case, we explicitly say to select the 'genus' and
133
 
        'genus.family' models, leading to the same number of queries as before.
134
 
        """
135
 
        with self.assertNumQueries(1):
136
 
            world = Species.objects.select_related('genus__family')
137
 
            families = [o.genus.family.name for o in world]
138
 
            self.assertEqual(sorted(families),
139
 
                ['Amanitacae', 'Drosophilidae', 'Fabaceae', 'Hominidae'])
140
 
 
141
 
    def test_more_certain_fields(self):
142
 
        """
143
 
        In this case, we explicitly say to select the 'genus' and
144
 
        'genus.family' models, leading to the same number of queries as before.
145
 
        """
146
 
        with self.assertNumQueries(2):
147
 
            world = Species.objects.filter(genus__name='Amanita')\
148
 
                .select_related('genus__family')
149
 
            orders = [o.genus.family.order.name for o in world]
150
 
            self.assertEqual(orders, ['Agaricales'])
151
 
 
152
 
    def test_field_traversal(self):
153
 
        with self.assertNumQueries(1):
154
 
            s = Species.objects.all().select_related('genus__family__order'
155
 
                ).order_by('id')[0:1].get().genus.family.order.name
156
 
            self.assertEqual(s, 'Diptera')
157
 
 
158
 
    def test_depth_fields_fails(self):
159
 
        self.assertRaises(TypeError,
160
 
            Species.objects.select_related,
161
 
            'genus__family__order', depth=4
162
 
        )