tests.py 17 KB

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