tests.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  1. from django.db.models import Q, Sum
  2. from django.db.utils import IntegrityError
  3. from django.test import TestCase, skipIfDBFeature
  4. from django.forms.models import modelform_factory
  5. from django.db.models.deletion import ProtectedError
  6. from .models import (
  7. Address, Place, Restaurant, Link, CharLink, TextLink,
  8. Person, Contact, Note, Organization, OddRelation1, OddRelation2, Company,
  9. Developer, Team, Guild, Tag, Board, HasLinkThing, A, B, C, D,
  10. Related, Content, Node,
  11. )
  12. class GenericRelationTests(TestCase):
  13. def test_inherited_models_content_type(self):
  14. """
  15. Test that GenericRelations on inherited classes use the correct content
  16. type.
  17. """
  18. p = Place.objects.create(name="South Park")
  19. r = Restaurant.objects.create(name="Chubby's")
  20. l1 = Link.objects.create(content_object=p)
  21. l2 = Link.objects.create(content_object=r)
  22. self.assertEqual(list(p.links.all()), [l1])
  23. self.assertEqual(list(r.links.all()), [l2])
  24. def test_reverse_relation_pk(self):
  25. """
  26. Test that the correct column name is used for the primary key on the
  27. originating model of a query. See #12664.
  28. """
  29. p = Person.objects.create(account=23, name='Chef')
  30. Address.objects.create(street='123 Anywhere Place',
  31. city='Conifer', state='CO',
  32. zipcode='80433', content_object=p)
  33. qs = Person.objects.filter(addresses__zipcode='80433')
  34. self.assertEqual(1, qs.count())
  35. self.assertEqual('Chef', qs[0].name)
  36. def test_charlink_delete(self):
  37. oddrel = OddRelation1.objects.create(name='clink')
  38. CharLink.objects.create(content_object=oddrel)
  39. oddrel.delete()
  40. def test_textlink_delete(self):
  41. oddrel = OddRelation2.objects.create(name='tlink')
  42. TextLink.objects.create(content_object=oddrel)
  43. oddrel.delete()
  44. def test_q_object_or(self):
  45. """
  46. Tests that SQL query parameters for generic relations are properly
  47. grouped when OR is used.
  48. Test for bug http://code.djangoproject.com/ticket/11535
  49. In this bug the first query (below) works while the second, with the
  50. query parameters the same but in reverse order, does not.
  51. The issue is that the generic relation conditions do not get properly
  52. grouped in parentheses.
  53. """
  54. note_contact = Contact.objects.create()
  55. org_contact = Contact.objects.create()
  56. Note.objects.create(note='note', content_object=note_contact)
  57. org = Organization.objects.create(name='org name')
  58. org.contacts.add(org_contact)
  59. # search with a non-matching note and a matching org name
  60. qs = Contact.objects.filter(Q(notes__note__icontains=r'other note') |
  61. Q(organizations__name__icontains=r'org name'))
  62. self.assertIn(org_contact, qs)
  63. # search again, with the same query parameters, in reverse order
  64. qs = Contact.objects.filter(
  65. Q(organizations__name__icontains=r'org name') |
  66. Q(notes__note__icontains=r'other note'))
  67. self.assertIn(org_contact, qs)
  68. def test_join_reuse(self):
  69. qs = Person.objects.filter(
  70. addresses__street='foo'
  71. ).filter(
  72. addresses__street='bar'
  73. )
  74. self.assertEqual(str(qs.query).count('JOIN'), 2)
  75. def test_generic_relation_ordering(self):
  76. """
  77. Test that ordering over a generic relation does not include extraneous
  78. duplicate results, nor excludes rows not participating in the relation.
  79. """
  80. p1 = Place.objects.create(name="South Park")
  81. p2 = Place.objects.create(name="The City")
  82. c = Company.objects.create(name="Chubby's Intl.")
  83. Link.objects.create(content_object=p1)
  84. Link.objects.create(content_object=c)
  85. places = list(Place.objects.order_by('links__id'))
  86. def count_places(place):
  87. return len([p for p in places if p.id == place.id])
  88. self.assertEqual(len(places), 2)
  89. self.assertEqual(count_places(p1), 1)
  90. self.assertEqual(count_places(p2), 1)
  91. def test_target_model_is_unsaved(self):
  92. """Test related to #13085"""
  93. # Fails with another, ORM-level error
  94. dev1 = Developer(name='Joe')
  95. note = Note(note='Deserves promotion', content_object=dev1)
  96. self.assertRaises(IntegrityError, note.save)
  97. def test_target_model_len_zero(self):
  98. """Test for #13085 -- __len__() returns 0"""
  99. team1 = Team.objects.create(name='Backend devs')
  100. try:
  101. note = Note(note='Deserve a bonus', content_object=team1)
  102. except Exception as e:
  103. if (issubclass(type(e), Exception) and
  104. str(e) == 'Impossible arguments to GFK.get_content_type!'):
  105. self.fail("Saving model with GenericForeignKey to model instance whose "
  106. "__len__ method returns 0 shouldn't fail.")
  107. raise e
  108. note.save()
  109. def test_target_model_nonzero_false(self):
  110. """Test related to #13085"""
  111. # __nonzero__() returns False -- This actually doesn't currently fail.
  112. # This test validates that
  113. g1 = Guild.objects.create(name='First guild')
  114. note = Note(note='Note for guild', content_object=g1)
  115. note.save()
  116. @skipIfDBFeature('interprets_empty_strings_as_nulls')
  117. def test_gfk_to_model_with_empty_pk(self):
  118. """Test related to #13085"""
  119. # Saving model with GenericForeignKey to model instance with an
  120. # empty CharField PK
  121. b1 = Board.objects.create(name='')
  122. tag = Tag(label='VP', content_object=b1)
  123. tag.save()
  124. def test_ticket_20378(self):
  125. hs1 = HasLinkThing.objects.create()
  126. hs2 = HasLinkThing.objects.create()
  127. l1 = Link.objects.create(content_object=hs1)
  128. l2 = Link.objects.create(content_object=hs2)
  129. self.assertQuerysetEqual(
  130. HasLinkThing.objects.filter(links=l1),
  131. [hs1], lambda x: x)
  132. self.assertQuerysetEqual(
  133. HasLinkThing.objects.filter(links=l2),
  134. [hs2], lambda x: x)
  135. self.assertQuerysetEqual(
  136. HasLinkThing.objects.exclude(links=l2),
  137. [hs1], lambda x: x)
  138. self.assertQuerysetEqual(
  139. HasLinkThing.objects.exclude(links=l1),
  140. [hs2], lambda x: x)
  141. def test_ticket_20564(self):
  142. b1 = B.objects.create()
  143. b2 = B.objects.create()
  144. b3 = B.objects.create()
  145. c1 = C.objects.create(b=b1)
  146. c2 = C.objects.create(b=b2)
  147. c3 = C.objects.create(b=b3)
  148. A.objects.create(flag=None, content_object=b1)
  149. A.objects.create(flag=True, content_object=b2)
  150. self.assertQuerysetEqual(
  151. C.objects.filter(b__a__flag=None),
  152. [c1, c3], lambda x: x
  153. )
  154. self.assertQuerysetEqual(
  155. C.objects.exclude(b__a__flag=None),
  156. [c2], lambda x: x
  157. )
  158. def test_ticket_20564_nullable_fk(self):
  159. b1 = B.objects.create()
  160. b2 = B.objects.create()
  161. b3 = B.objects.create()
  162. d1 = D.objects.create(b=b1)
  163. d2 = D.objects.create(b=b2)
  164. d3 = D.objects.create(b=b3)
  165. d4 = D.objects.create()
  166. A.objects.create(flag=None, content_object=b1)
  167. A.objects.create(flag=True, content_object=b1)
  168. A.objects.create(flag=True, content_object=b2)
  169. self.assertQuerysetEqual(
  170. D.objects.exclude(b__a__flag=None),
  171. [d2], lambda x: x
  172. )
  173. self.assertQuerysetEqual(
  174. D.objects.filter(b__a__flag=None),
  175. [d1, d3, d4], lambda x: x
  176. )
  177. self.assertQuerysetEqual(
  178. B.objects.filter(a__flag=None),
  179. [b1, b3], lambda x: x
  180. )
  181. self.assertQuerysetEqual(
  182. B.objects.exclude(a__flag=None),
  183. [b2], lambda x: x
  184. )
  185. def test_extra_join_condition(self):
  186. # A crude check that content_type_id is taken in account in the
  187. # join/subquery condition.
  188. self.assertIn("content_type_id", str(B.objects.exclude(a__flag=None).query).lower())
  189. # No need for any joins - the join from inner query can be trimmed in
  190. # this case (but not in the above case as no a objects at all for given
  191. # B would then fail).
  192. self.assertNotIn(" join ", str(B.objects.exclude(a__flag=True).query).lower())
  193. self.assertIn("content_type_id", str(B.objects.exclude(a__flag=True).query).lower())
  194. def test_annotate(self):
  195. hs1 = HasLinkThing.objects.create()
  196. hs2 = HasLinkThing.objects.create()
  197. HasLinkThing.objects.create()
  198. b = Board.objects.create(name=str(hs1.pk))
  199. Link.objects.create(content_object=hs2)
  200. l = Link.objects.create(content_object=hs1)
  201. Link.objects.create(content_object=b)
  202. qs = HasLinkThing.objects.annotate(Sum('links')).filter(pk=hs1.pk)
  203. # If content_type restriction isn't in the query's join condition,
  204. # then wrong results are produced here as the link to b will also match
  205. # (b and hs1 have equal pks).
  206. self.assertEqual(qs.count(), 1)
  207. self.assertEqual(qs[0].links__sum, l.id)
  208. l.delete()
  209. # Now if we don't have proper left join, we will not produce any
  210. # results at all here.
  211. # clear cached results
  212. qs = qs.all()
  213. self.assertEqual(qs.count(), 1)
  214. # Note - 0 here would be a nicer result...
  215. self.assertIs(qs[0].links__sum, None)
  216. # Finally test that filtering works.
  217. self.assertEqual(qs.filter(links__sum__isnull=True).count(), 1)
  218. self.assertEqual(qs.filter(links__sum__isnull=False).count(), 0)
  219. def test_filter_targets_related_pk(self):
  220. HasLinkThing.objects.create()
  221. hs2 = HasLinkThing.objects.create()
  222. l = Link.objects.create(content_object=hs2)
  223. self.assertNotEqual(l.object_id, l.pk)
  224. self.assertQuerysetEqual(
  225. HasLinkThing.objects.filter(links=l.pk),
  226. [hs2], lambda x: x)
  227. def test_editable_generic_rel(self):
  228. GenericRelationForm = modelform_factory(HasLinkThing, fields='__all__')
  229. form = GenericRelationForm()
  230. self.assertIn('links', form.fields)
  231. form = GenericRelationForm({'links': None})
  232. self.assertTrue(form.is_valid())
  233. form.save()
  234. links = HasLinkThing._meta.get_field('links')
  235. self.assertEqual(links.save_form_data_calls, 1)
  236. def test_ticket_22998(self):
  237. related = Related.objects.create()
  238. content = Content.objects.create(related_obj=related)
  239. Node.objects.create(content=content)
  240. # deleting the Related cascades to the Content cascades to the Node,
  241. # where the pre_delete signal should fire and prevent deletion.
  242. with self.assertRaises(ProtectedError):
  243. related.delete()
  244. def test_ticket_22982(self):
  245. place = Place.objects.create(name='My Place')
  246. self.assertIn('GenericRelatedObjectManager', str(place.links))