PageRenderTime 58ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 0ms

/tests/regressiontests/model_inheritance_regress/tests.py

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