tests.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  1. from __future__ import unicode_literals
  2. import datetime
  3. from django.conf import settings
  4. from django.db import DEFAULT_DB_ALIAS, models, transaction
  5. from django.db.utils import ConnectionHandler
  6. from django.test import TestCase, TransactionTestCase, skipUnlessDBFeature
  7. from .models import (
  8. Award, AwardNote, Book, Child, Eaten, Email, File, Food, FooFile,
  9. FooFileProxy, FooImage, FooPhoto, House, Image, Item, Location, Login,
  10. OrderedPerson, OrgUnit, Person, Photo, PlayedWith, PlayedWithNote, Policy,
  11. Researcher, Toy, Version,
  12. )
  13. # Can't run this test under SQLite, because you can't
  14. # get two connections to an in-memory database.
  15. @skipUnlessDBFeature('test_db_allows_multiple_connections')
  16. class DeleteLockingTest(TransactionTestCase):
  17. available_apps = ['delete_regress']
  18. def setUp(self):
  19. # Create a second connection to the default database
  20. new_connections = ConnectionHandler(settings.DATABASES)
  21. self.conn2 = new_connections[DEFAULT_DB_ALIAS]
  22. self.conn2.set_autocommit(False)
  23. def tearDown(self):
  24. # Close down the second connection.
  25. self.conn2.rollback()
  26. self.conn2.close()
  27. def test_concurrent_delete(self):
  28. """Concurrent deletes don't collide and lock the database (#9479)."""
  29. with transaction.atomic():
  30. Book.objects.create(id=1, pagecount=100)
  31. Book.objects.create(id=2, pagecount=200)
  32. Book.objects.create(id=3, pagecount=300)
  33. with transaction.atomic():
  34. # Start a transaction on the main connection.
  35. self.assertEqual(3, Book.objects.count())
  36. # Delete something using another database connection.
  37. with self.conn2.cursor() as cursor2:
  38. cursor2.execute("DELETE from delete_regress_book WHERE id = 1")
  39. self.conn2.commit()
  40. # In the same transaction on the main connection, perform a
  41. # queryset delete that covers the object deleted with the other
  42. # connection. This causes an infinite loop under MySQL InnoDB
  43. # unless we keep track of already deleted objects.
  44. Book.objects.filter(pagecount__lt=250).delete()
  45. self.assertEqual(1, Book.objects.count())
  46. class DeleteCascadeTests(TestCase):
  47. def test_generic_relation_cascade(self):
  48. """
  49. Django cascades deletes through generic-related objects to their
  50. reverse relations.
  51. """
  52. person = Person.objects.create(name='Nelson Mandela')
  53. award = Award.objects.create(name='Nobel', content_object=person)
  54. AwardNote.objects.create(note='a peace prize',
  55. award=award)
  56. self.assertEqual(AwardNote.objects.count(), 1)
  57. person.delete()
  58. self.assertEqual(Award.objects.count(), 0)
  59. # first two asserts are just sanity checks, this is the kicker:
  60. self.assertEqual(AwardNote.objects.count(), 0)
  61. def test_fk_to_m2m_through(self):
  62. """
  63. If an M2M relationship has an explicitly-specified through model, and
  64. some other model has an FK to that through model, deletion is cascaded
  65. from one of the participants in the M2M, to the through model, to its
  66. related model.
  67. """
  68. juan = Child.objects.create(name='Juan')
  69. paints = Toy.objects.create(name='Paints')
  70. played = PlayedWith.objects.create(child=juan, toy=paints,
  71. date=datetime.date.today())
  72. PlayedWithNote.objects.create(played=played,
  73. note='the next Jackson Pollock')
  74. self.assertEqual(PlayedWithNote.objects.count(), 1)
  75. paints.delete()
  76. self.assertEqual(PlayedWith.objects.count(), 0)
  77. # first two asserts just sanity checks, this is the kicker:
  78. self.assertEqual(PlayedWithNote.objects.count(), 0)
  79. def test_15776(self):
  80. policy = Policy.objects.create(pk=1, policy_number="1234")
  81. version = Version.objects.create(policy=policy)
  82. location = Location.objects.create(version=version)
  83. Item.objects.create(version=version, location=location)
  84. policy.delete()
  85. class DeleteCascadeTransactionTests(TransactionTestCase):
  86. available_apps = ['delete_regress']
  87. def test_inheritance(self):
  88. """
  89. Auto-created many-to-many through tables referencing a parent model are
  90. correctly found by the delete cascade when a child of that parent is
  91. deleted.
  92. Refs #14896.
  93. """
  94. r = Researcher.objects.create()
  95. email = Email.objects.create(
  96. label="office-email", email_address="carl@science.edu"
  97. )
  98. r.contacts.add(email)
  99. email.delete()
  100. def test_to_field(self):
  101. """
  102. Cascade deletion works with ForeignKey.to_field set to non-PK.
  103. """
  104. apple = Food.objects.create(name="apple")
  105. Eaten.objects.create(food=apple, meal="lunch")
  106. apple.delete()
  107. self.assertFalse(Food.objects.exists())
  108. self.assertFalse(Eaten.objects.exists())
  109. class LargeDeleteTests(TestCase):
  110. def test_large_deletes(self):
  111. "Regression for #13309 -- if the number of objects > chunk size, deletion still occurs"
  112. for x in range(300):
  113. Book.objects.create(pagecount=x + 100)
  114. # attach a signal to make sure we will not fast-delete
  115. def noop(*args, **kwargs):
  116. pass
  117. models.signals.post_delete.connect(noop, sender=Book)
  118. Book.objects.all().delete()
  119. models.signals.post_delete.disconnect(noop, sender=Book)
  120. self.assertEqual(Book.objects.count(), 0)
  121. class ProxyDeleteTest(TestCase):
  122. """
  123. Tests on_delete behavior for proxy models.
  124. See #16128.
  125. """
  126. def create_image(self):
  127. """Return an Image referenced by both a FooImage and a FooFile."""
  128. # Create an Image
  129. test_image = Image()
  130. test_image.save()
  131. foo_image = FooImage(my_image=test_image)
  132. foo_image.save()
  133. # Get the Image instance as a File
  134. test_file = File.objects.get(pk=test_image.pk)
  135. foo_file = FooFile(my_file=test_file)
  136. foo_file.save()
  137. return test_image
  138. def test_delete_proxy(self):
  139. """
  140. Deleting the *proxy* instance bubbles through to its non-proxy and
  141. *all* referring objects are deleted.
  142. """
  143. self.create_image()
  144. Image.objects.all().delete()
  145. # An Image deletion == File deletion
  146. self.assertEqual(len(Image.objects.all()), 0)
  147. self.assertEqual(len(File.objects.all()), 0)
  148. # The Image deletion cascaded and *all* references to it are deleted.
  149. self.assertEqual(len(FooImage.objects.all()), 0)
  150. self.assertEqual(len(FooFile.objects.all()), 0)
  151. def test_delete_proxy_of_proxy(self):
  152. """
  153. Deleting a proxy-of-proxy instance should bubble through to its proxy
  154. and non-proxy parents, deleting *all* referring objects.
  155. """
  156. test_image = self.create_image()
  157. # Get the Image as a Photo
  158. test_photo = Photo.objects.get(pk=test_image.pk)
  159. foo_photo = FooPhoto(my_photo=test_photo)
  160. foo_photo.save()
  161. Photo.objects.all().delete()
  162. # A Photo deletion == Image deletion == File deletion
  163. self.assertEqual(len(Photo.objects.all()), 0)
  164. self.assertEqual(len(Image.objects.all()), 0)
  165. self.assertEqual(len(File.objects.all()), 0)
  166. # The Photo deletion should have cascaded and deleted *all*
  167. # references to it.
  168. self.assertEqual(len(FooPhoto.objects.all()), 0)
  169. self.assertEqual(len(FooFile.objects.all()), 0)
  170. self.assertEqual(len(FooImage.objects.all()), 0)
  171. def test_delete_concrete_parent(self):
  172. """
  173. Deleting an instance of a concrete model should also delete objects
  174. referencing its proxy subclass.
  175. """
  176. self.create_image()
  177. File.objects.all().delete()
  178. # A File deletion == Image deletion
  179. self.assertEqual(len(File.objects.all()), 0)
  180. self.assertEqual(len(Image.objects.all()), 0)
  181. # The File deletion should have cascaded and deleted *all* references
  182. # to it.
  183. self.assertEqual(len(FooFile.objects.all()), 0)
  184. self.assertEqual(len(FooImage.objects.all()), 0)
  185. def test_delete_proxy_pair(self):
  186. """
  187. If a pair of proxy models are linked by an FK from one concrete parent
  188. to the other, deleting one proxy model cascade-deletes the other, and
  189. the deletion happens in the right order (not triggering an
  190. IntegrityError on databases unable to defer integrity checks).
  191. Refs #17918.
  192. """
  193. # Create an Image (proxy of File) and FooFileProxy (proxy of FooFile,
  194. # which has an FK to File)
  195. image = Image.objects.create()
  196. as_file = File.objects.get(pk=image.pk)
  197. FooFileProxy.objects.create(my_file=as_file)
  198. Image.objects.all().delete()
  199. self.assertEqual(len(FooFileProxy.objects.all()), 0)
  200. def test_19187_values(self):
  201. with self.assertRaises(TypeError):
  202. Image.objects.values().delete()
  203. with self.assertRaises(TypeError):
  204. Image.objects.values_list().delete()
  205. class Ticket19102Tests(TestCase):
  206. """
  207. Test different queries which alter the SELECT clause of the query. We
  208. also must be using a subquery for the deletion (that is, the original
  209. query has a join in it). The deletion should be done as "fast-path"
  210. deletion (that is, just one query for the .delete() call).
  211. Note that .values() is not tested here on purpose. .values().delete()
  212. doesn't work for non fast-path deletes at all.
  213. """
  214. def setUp(self):
  215. self.o1 = OrgUnit.objects.create(name='o1')
  216. self.o2 = OrgUnit.objects.create(name='o2')
  217. self.l1 = Login.objects.create(description='l1', orgunit=self.o1)
  218. self.l2 = Login.objects.create(description='l2', orgunit=self.o2)
  219. @skipUnlessDBFeature("update_can_self_select")
  220. def test_ticket_19102_annotate(self):
  221. with self.assertNumQueries(1):
  222. Login.objects.order_by('description').filter(
  223. orgunit__name__isnull=False
  224. ).annotate(
  225. n=models.Count('description')
  226. ).filter(
  227. n=1, pk=self.l1.pk
  228. ).delete()
  229. self.assertFalse(Login.objects.filter(pk=self.l1.pk).exists())
  230. self.assertTrue(Login.objects.filter(pk=self.l2.pk).exists())
  231. @skipUnlessDBFeature("update_can_self_select")
  232. def test_ticket_19102_extra(self):
  233. with self.assertNumQueries(1):
  234. Login.objects.order_by('description').filter(
  235. orgunit__name__isnull=False
  236. ).extra(
  237. select={'extraf': '1'}
  238. ).filter(
  239. pk=self.l1.pk
  240. ).delete()
  241. self.assertFalse(Login.objects.filter(pk=self.l1.pk).exists())
  242. self.assertTrue(Login.objects.filter(pk=self.l2.pk).exists())
  243. @skipUnlessDBFeature("update_can_self_select")
  244. @skipUnlessDBFeature('can_distinct_on_fields')
  245. def test_ticket_19102_distinct_on(self):
  246. # Both Login objs should have same description so that only the one
  247. # having smaller PK will be deleted.
  248. Login.objects.update(description='description')
  249. with self.assertNumQueries(1):
  250. Login.objects.distinct('description').order_by('pk').filter(
  251. orgunit__name__isnull=False
  252. ).delete()
  253. # Assumed that l1 which is created first has smaller PK.
  254. self.assertFalse(Login.objects.filter(pk=self.l1.pk).exists())
  255. self.assertTrue(Login.objects.filter(pk=self.l2.pk).exists())
  256. @skipUnlessDBFeature("update_can_self_select")
  257. def test_ticket_19102_select_related(self):
  258. with self.assertNumQueries(1):
  259. Login.objects.filter(
  260. pk=self.l1.pk
  261. ).filter(
  262. orgunit__name__isnull=False
  263. ).order_by(
  264. 'description'
  265. ).select_related('orgunit').delete()
  266. self.assertFalse(Login.objects.filter(pk=self.l1.pk).exists())
  267. self.assertTrue(Login.objects.filter(pk=self.l2.pk).exists())
  268. @skipUnlessDBFeature("update_can_self_select")
  269. def test_ticket_19102_defer(self):
  270. with self.assertNumQueries(1):
  271. Login.objects.filter(
  272. pk=self.l1.pk
  273. ).filter(
  274. orgunit__name__isnull=False
  275. ).order_by(
  276. 'description'
  277. ).only('id').delete()
  278. self.assertFalse(Login.objects.filter(pk=self.l1.pk).exists())
  279. self.assertTrue(Login.objects.filter(pk=self.l2.pk).exists())
  280. class OrderedDeleteTests(TestCase):
  281. def test_meta_ordered_delete(self):
  282. # When a subquery is performed by deletion code, the subquery must be
  283. # cleared of all ordering. There was a but that caused _meta ordering
  284. # to be used. Refs #19720.
  285. h = House.objects.create(address='Foo')
  286. OrderedPerson.objects.create(name='Jack', lives_in=h)
  287. OrderedPerson.objects.create(name='Bob', lives_in=h)
  288. OrderedPerson.objects.filter(lives_in__address='Foo').delete()
  289. self.assertEqual(OrderedPerson.objects.count(), 0)