tests.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443
  1. """
  2. Regression tests for Model inheritance behavior.
  3. """
  4. from __future__ import absolute_import, unicode_literals
  5. import datetime
  6. from operator import attrgetter
  7. from django import forms
  8. from django.test import TestCase
  9. from django.utils.unittest import expectedFailure
  10. from .models import (Place, Restaurant, ItalianRestaurant, ParkingLot,
  11. ParkingLot2, ParkingLot3, Supplier, Wholesaler, Child, SelfRefParent,
  12. SelfRefChild, ArticleWithAuthor, M2MChild, QualityControl, DerivedM,
  13. Person, BirthdayParty, BachelorParty, MessyBachelorParty,
  14. InternalCertificationAudit, BusStation, TrainStation, User, Profile)
  15. class ModelInheritanceTest(TestCase):
  16. def test_model_inheritance(self):
  17. # Regression for #7350, #7202
  18. # Check that when you create a Parent object with a specific reference
  19. # to an existent child instance, saving the Parent doesn't duplicate
  20. # the child. This behavior is only activated during a raw save - it
  21. # is mostly relevant to deserialization, but any sort of CORBA style
  22. # 'narrow()' API would require a similar approach.
  23. # Create a child-parent-grandparent chain
  24. place1 = Place(
  25. name="Guido's House of Pasta",
  26. address='944 W. Fullerton')
  27. place1.save_base(raw=True)
  28. restaurant = Restaurant(
  29. place_ptr=place1,
  30. serves_hot_dogs=True,
  31. serves_pizza=False)
  32. restaurant.save_base(raw=True)
  33. italian_restaurant = ItalianRestaurant(
  34. restaurant_ptr=restaurant,
  35. serves_gnocchi=True)
  36. italian_restaurant.save_base(raw=True)
  37. # Create a child-parent chain with an explicit parent link
  38. place2 = Place(name='Main St', address='111 Main St')
  39. place2.save_base(raw=True)
  40. park = ParkingLot(parent=place2, capacity=100)
  41. park.save_base(raw=True)
  42. # Check that no extra parent objects have been created.
  43. places = list(Place.objects.all())
  44. self.assertEqual(places, [place1, place2])
  45. dicts = list(Restaurant.objects.values('name','serves_hot_dogs'))
  46. self.assertEqual(dicts, [{
  47. 'name': "Guido's House of Pasta",
  48. 'serves_hot_dogs': True
  49. }])
  50. dicts = list(ItalianRestaurant.objects.values(
  51. 'name','serves_hot_dogs','serves_gnocchi'))
  52. self.assertEqual(dicts, [{
  53. 'name': "Guido's House of Pasta",
  54. 'serves_gnocchi': True,
  55. 'serves_hot_dogs': True,
  56. }])
  57. dicts = list(ParkingLot.objects.values('name','capacity'))
  58. self.assertEqual(dicts, [{
  59. 'capacity': 100,
  60. 'name': 'Main St',
  61. }])
  62. # You can also update objects when using a raw save.
  63. place1.name = "Guido's All New House of Pasta"
  64. place1.save_base(raw=True)
  65. restaurant.serves_hot_dogs = False
  66. restaurant.save_base(raw=True)
  67. italian_restaurant.serves_gnocchi = False
  68. italian_restaurant.save_base(raw=True)
  69. place2.name='Derelict lot'
  70. place2.save_base(raw=True)
  71. park.capacity = 50
  72. park.save_base(raw=True)
  73. # No extra parent objects after an update, either.
  74. places = list(Place.objects.all())
  75. self.assertEqual(places, [place2, place1])
  76. self.assertEqual(places[0].name, 'Derelict lot')
  77. self.assertEqual(places[1].name, "Guido's All New House of Pasta")
  78. dicts = list(Restaurant.objects.values('name','serves_hot_dogs'))
  79. self.assertEqual(dicts, [{
  80. 'name': "Guido's All New House of Pasta",
  81. 'serves_hot_dogs': False,
  82. }])
  83. dicts = list(ItalianRestaurant.objects.values(
  84. 'name', 'serves_hot_dogs', 'serves_gnocchi'))
  85. self.assertEqual(dicts, [{
  86. 'name': "Guido's All New House of Pasta",
  87. 'serves_gnocchi': False,
  88. 'serves_hot_dogs': False,
  89. }])
  90. dicts = list(ParkingLot.objects.values('name','capacity'))
  91. self.assertEqual(dicts, [{
  92. 'capacity': 50,
  93. 'name': 'Derelict lot',
  94. }])
  95. # If you try to raw_save a parent attribute onto a child object,
  96. # the attribute will be ignored.
  97. italian_restaurant.name = "Lorenzo's Pasta Hut"
  98. italian_restaurant.save_base(raw=True)
  99. # Note that the name has not changed
  100. # - name is an attribute of Place, not ItalianRestaurant
  101. dicts = list(ItalianRestaurant.objects.values(
  102. 'name','serves_hot_dogs','serves_gnocchi'))
  103. self.assertEqual(dicts, [{
  104. 'name': "Guido's All New House of Pasta",
  105. 'serves_gnocchi': False,
  106. 'serves_hot_dogs': False,
  107. }])
  108. def test_issue_7105(self):
  109. # Regressions tests for #7105: dates() queries should be able to use
  110. # fields from the parent model as easily as the child.
  111. obj = Child.objects.create(
  112. name='child',
  113. created=datetime.datetime(2008, 6, 26, 17, 0, 0))
  114. datetimes = list(Child.objects.datetimes('created', 'month'))
  115. self.assertEqual(datetimes, [datetime.datetime(2008, 6, 1, 0, 0)])
  116. def test_issue_7276(self):
  117. # Regression test for #7276: calling delete() on a model with
  118. # multi-table inheritance should delete the associated rows from any
  119. # ancestor tables, as well as any descendent objects.
  120. place1 = Place(
  121. name="Guido's House of Pasta",
  122. address='944 W. Fullerton')
  123. place1.save_base(raw=True)
  124. restaurant = Restaurant(
  125. place_ptr=place1,
  126. serves_hot_dogs=True,
  127. serves_pizza=False)
  128. restaurant.save_base(raw=True)
  129. italian_restaurant = ItalianRestaurant(
  130. restaurant_ptr=restaurant,
  131. serves_gnocchi=True)
  132. italian_restaurant.save_base(raw=True)
  133. ident = ItalianRestaurant.objects.all()[0].id
  134. self.assertEqual(Place.objects.get(pk=ident), place1)
  135. xx = Restaurant.objects.create(
  136. name='a',
  137. address='xx',
  138. serves_hot_dogs=True,
  139. serves_pizza=False)
  140. # This should delete both Restuarants, plus the related places, plus
  141. # the ItalianRestaurant.
  142. Restaurant.objects.all().delete()
  143. self.assertRaises(
  144. Place.DoesNotExist,
  145. Place.objects.get,
  146. pk=ident)
  147. self.assertRaises(
  148. ItalianRestaurant.DoesNotExist,
  149. ItalianRestaurant.objects.get,
  150. pk=ident)
  151. def test_issue_6755(self):
  152. """
  153. Regression test for #6755
  154. """
  155. r = Restaurant(serves_pizza=False, serves_hot_dogs=False)
  156. r.save()
  157. self.assertEqual(r.id, r.place_ptr_id)
  158. orig_id = r.id
  159. r = Restaurant(place_ptr_id=orig_id, serves_pizza=True, serves_hot_dogs=False)
  160. r.save()
  161. self.assertEqual(r.id, orig_id)
  162. self.assertEqual(r.id, r.place_ptr_id)
  163. def test_issue_7488(self):
  164. # Regression test for #7488. This looks a little crazy, but it's the
  165. # equivalent of what the admin interface has to do for the edit-inline
  166. # case.
  167. suppliers = Supplier.objects.filter(
  168. restaurant=Restaurant(name='xx', address='yy'))
  169. suppliers = list(suppliers)
  170. self.assertEqual(suppliers, [])
  171. def test_issue_11764(self):
  172. """
  173. Regression test for #11764
  174. """
  175. wholesalers = list(Wholesaler.objects.all().select_related())
  176. self.assertEqual(wholesalers, [])
  177. def test_issue_7853(self):
  178. """
  179. Regression test for #7853
  180. If the parent class has a self-referential link, make sure that any
  181. updates to that link via the child update the right table.
  182. """
  183. obj = SelfRefChild.objects.create(child_data=37, parent_data=42)
  184. obj.delete()
  185. def test_get_next_previous_by_date(self):
  186. """
  187. Regression tests for #8076
  188. get_(next/previous)_by_date should work
  189. """
  190. c1 = ArticleWithAuthor(
  191. headline='ArticleWithAuthor 1',
  192. author="Person 1",
  193. pub_date=datetime.datetime(2005, 8, 1, 3, 0))
  194. c1.save()
  195. c2 = ArticleWithAuthor(
  196. headline='ArticleWithAuthor 2',
  197. author="Person 2",
  198. pub_date=datetime.datetime(2005, 8, 1, 10, 0))
  199. c2.save()
  200. c3 = ArticleWithAuthor(
  201. headline='ArticleWithAuthor 3',
  202. author="Person 3",
  203. pub_date=datetime.datetime(2005, 8, 2))
  204. c3.save()
  205. self.assertEqual(c1.get_next_by_pub_date(), c2)
  206. self.assertEqual(c2.get_next_by_pub_date(), c3)
  207. self.assertRaises(
  208. ArticleWithAuthor.DoesNotExist,
  209. c3.get_next_by_pub_date)
  210. self.assertEqual(c3.get_previous_by_pub_date(), c2)
  211. self.assertEqual(c2.get_previous_by_pub_date(), c1)
  212. self.assertRaises(
  213. ArticleWithAuthor.DoesNotExist,
  214. c1.get_previous_by_pub_date)
  215. def test_inherited_fields(self):
  216. """
  217. Regression test for #8825 and #9390
  218. Make sure all inherited fields (esp. m2m fields, in this case) appear
  219. on the child class.
  220. """
  221. m2mchildren = list(M2MChild.objects.filter(articles__isnull=False))
  222. self.assertEqual(m2mchildren, [])
  223. # Ordering should not include any database column more than once (this
  224. # is most likely to ocurr naturally with model inheritance, so we
  225. # check it here). Regression test for #9390. This necessarily pokes at
  226. # the SQL string for the query, since the duplicate problems are only
  227. # apparent at that late stage.
  228. qs = ArticleWithAuthor.objects.order_by('pub_date', 'pk')
  229. sql = qs.query.get_compiler(qs.db).as_sql()[0]
  230. fragment = sql[sql.find('ORDER BY'):]
  231. pos = fragment.find('pub_date')
  232. self.assertEqual(fragment.find('pub_date', pos + 1), -1)
  233. def test_queryset_update_on_parent_model(self):
  234. """
  235. Regression test for #10362
  236. It is possible to call update() and only change a field in
  237. an ancestor model.
  238. """
  239. article = ArticleWithAuthor.objects.create(
  240. author="fred",
  241. headline="Hey there!",
  242. pub_date=datetime.datetime(2009, 3, 1, 8, 0, 0))
  243. update = ArticleWithAuthor.objects.filter(
  244. author="fred").update(headline="Oh, no!")
  245. self.assertEqual(update, 1)
  246. update = ArticleWithAuthor.objects.filter(
  247. pk=article.pk).update(headline="Oh, no!")
  248. self.assertEqual(update, 1)
  249. derivedm1 = DerivedM.objects.create(
  250. customPK=44,
  251. base_name="b1",
  252. derived_name="d1")
  253. self.assertEqual(derivedm1.customPK, 44)
  254. self.assertEqual(derivedm1.base_name, 'b1')
  255. self.assertEqual(derivedm1.derived_name, 'd1')
  256. derivedms = list(DerivedM.objects.all())
  257. self.assertEqual(derivedms, [derivedm1])
  258. def test_use_explicit_o2o_to_parent_as_pk(self):
  259. """
  260. Regression tests for #10406
  261. If there's a one-to-one link between a child model and the parent and
  262. no explicit pk declared, we can use the one-to-one link as the pk on
  263. the child.
  264. """
  265. self.assertEqual(ParkingLot2._meta.pk.name, "parent")
  266. # However, the connector from child to parent need not be the pk on
  267. # the child at all.
  268. self.assertEqual(ParkingLot3._meta.pk.name, "primary_key")
  269. # the child->parent link
  270. self.assertEqual(
  271. ParkingLot3._meta.get_ancestor_link(Place).name,
  272. "parent")
  273. def test_all_fields_from_abstract_base_class(self):
  274. """
  275. Regression tests for #7588
  276. """
  277. # All fields from an ABC, including those inherited non-abstractly
  278. # should be available on child classes (#7588). Creating this instance
  279. # should work without error.
  280. QualityControl.objects.create(
  281. headline="Problems in Django",
  282. pub_date=datetime.datetime.now(),
  283. quality=10,
  284. assignee="adrian")
  285. def test_abstract_base_class_m2m_relation_inheritance(self):
  286. # Check that many-to-many relations defined on an abstract base class
  287. # are correctly inherited (and created) on the child class.
  288. p1 = Person.objects.create(name='Alice')
  289. p2 = Person.objects.create(name='Bob')
  290. p3 = Person.objects.create(name='Carol')
  291. p4 = Person.objects.create(name='Dave')
  292. birthday = BirthdayParty.objects.create(
  293. name='Birthday party for Alice')
  294. birthday.attendees = [p1, p3]
  295. bachelor = BachelorParty.objects.create(name='Bachelor party for Bob')
  296. bachelor.attendees = [p2, p4]
  297. parties = list(p1.birthdayparty_set.all())
  298. self.assertEqual(parties, [birthday])
  299. parties = list(p1.bachelorparty_set.all())
  300. self.assertEqual(parties, [])
  301. parties = list(p2.bachelorparty_set.all())
  302. self.assertEqual(parties, [bachelor])
  303. # Check that a subclass of a subclass of an abstract model doesn't get
  304. # it's own accessor.
  305. self.assertFalse(hasattr(p2, 'messybachelorparty_set'))
  306. # ... but it does inherit the m2m from it's parent
  307. messy = MessyBachelorParty.objects.create(
  308. name='Bachelor party for Dave')
  309. messy.attendees = [p4]
  310. messy_parent = messy.bachelorparty_ptr
  311. parties = list(p4.bachelorparty_set.all())
  312. self.assertEqual(parties, [bachelor, messy_parent])
  313. def test_abstract_verbose_name_plural_inheritance(self):
  314. """
  315. verbose_name_plural correctly inherited from ABC if inheritance chain
  316. includes an abstract model.
  317. """
  318. # Regression test for #11369: verbose_name_plural should be inherited
  319. # from an ABC even when there are one or more intermediate
  320. # abstract models in the inheritance chain, for consistency with
  321. # verbose_name.
  322. self.assertEqual(
  323. InternalCertificationAudit._meta.verbose_name_plural,
  324. 'Audits'
  325. )
  326. def test_inherited_nullable_exclude(self):
  327. obj = SelfRefChild.objects.create(child_data=37, parent_data=42)
  328. self.assertQuerysetEqual(
  329. SelfRefParent.objects.exclude(self_data=72), [
  330. obj.pk
  331. ],
  332. attrgetter("pk")
  333. )
  334. self.assertQuerysetEqual(
  335. SelfRefChild.objects.exclude(self_data=72), [
  336. obj.pk
  337. ],
  338. attrgetter("pk")
  339. )
  340. def test_concrete_abstract_concrete_pk(self):
  341. """
  342. Primary key set correctly with concrete->abstract->concrete inheritance.
  343. """
  344. # Regression test for #13987: Primary key is incorrectly determined
  345. # when more than one model has a concrete->abstract->concrete
  346. # inheritance hierarchy.
  347. self.assertEqual(
  348. len([field for field in BusStation._meta.local_fields
  349. if field.primary_key]),
  350. 1
  351. )
  352. self.assertEqual(
  353. len([field for field in TrainStation._meta.local_fields
  354. if field.primary_key]),
  355. 1
  356. )
  357. self.assertIs(BusStation._meta.pk.model, BusStation)
  358. self.assertIs(TrainStation._meta.pk.model, TrainStation)
  359. def test_inherited_unique_field_with_form(self):
  360. """
  361. Test that a model which has different primary key for the parent model
  362. passes unique field checking correctly. Refs #17615.
  363. """
  364. class ProfileForm(forms.ModelForm):
  365. class Meta:
  366. model = Profile
  367. fields = '__all__'
  368. User.objects.create(username="user_only")
  369. p = Profile.objects.create(username="user_with_profile")
  370. form = ProfileForm({'username': "user_with_profile", 'extra': "hello"},
  371. instance=p)
  372. self.assertTrue(form.is_valid())
  373. def test_inheritance_joins(self):
  374. # Test for #17502 - check that filtering through two levels of
  375. # inheritance chain doesn't generate extra joins.
  376. qs = ItalianRestaurant.objects.all()
  377. self.assertEqual(str(qs.query).count('JOIN'), 2)
  378. qs = ItalianRestaurant.objects.filter(name='foo')
  379. self.assertEqual(str(qs.query).count('JOIN'), 2)
  380. @expectedFailure
  381. def test_inheritance_values_joins(self):
  382. # It would be nice (but not too important) to skip the middle join in
  383. # this case. Skipping is possible as nothing from the middle model is
  384. # used in the qs and top contains direct pointer to the bottom model.
  385. qs = ItalianRestaurant.objects.values_list('serves_gnocchi').filter(name='foo')
  386. self.assertEqual(str(qs.query).count('JOIN'), 1)