tests.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786
  1. from __future__ import unicode_literals
  2. import threading
  3. import warnings
  4. from datetime import datetime, timedelta
  5. from django.core.exceptions import MultipleObjectsReturned, ObjectDoesNotExist
  6. from django.db import DEFAULT_DB_ALIAS, DatabaseError, connections
  7. from django.db.models.fields import Field
  8. from django.db.models.fields.related import ForeignObjectRel
  9. from django.db.models.manager import BaseManager
  10. from django.db.models.query import EmptyQuerySet, QuerySet
  11. from django.test import (
  12. SimpleTestCase, TestCase, TransactionTestCase, skipIfDBFeature,
  13. skipUnlessDBFeature,
  14. )
  15. from django.utils import six
  16. from django.utils.translation import ugettext_lazy
  17. from .models import Article, ArticleSelectOnSave, SelfRef
  18. class ModelInstanceCreationTests(TestCase):
  19. def test_object_is_not_written_to_database_until_save_was_called(self):
  20. a = Article(
  21. id=None,
  22. headline='Parrot programs in Python',
  23. pub_date=datetime(2005, 7, 28),
  24. )
  25. self.assertIsNone(a.id)
  26. self.assertEqual(Article.objects.all().count(), 0)
  27. # Save it into the database. You have to call save() explicitly.
  28. a.save()
  29. self.assertIsNotNone(a.id)
  30. self.assertEqual(Article.objects.all().count(), 1)
  31. def test_can_initialize_model_instance_using_positional_arguments(self):
  32. """
  33. You can initialize a model instance using positional arguments,
  34. which should match the field order as defined in the model.
  35. """
  36. a = Article(None, 'Second article', datetime(2005, 7, 29))
  37. a.save()
  38. self.assertEqual(a.headline, 'Second article')
  39. self.assertEqual(a.pub_date, datetime(2005, 7, 29, 0, 0))
  40. def test_can_create_instance_using_kwargs(self):
  41. a = Article(
  42. id=None,
  43. headline='Third article',
  44. pub_date=datetime(2005, 7, 30),
  45. )
  46. a.save()
  47. self.assertEqual(a.headline, 'Third article')
  48. self.assertEqual(a.pub_date, datetime(2005, 7, 30, 0, 0))
  49. def test_autofields_generate_different_values_for_each_instance(self):
  50. a1 = Article.objects.create(headline='First', pub_date=datetime(2005, 7, 30, 0, 0))
  51. a2 = Article.objects.create(headline='First', pub_date=datetime(2005, 7, 30, 0, 0))
  52. a3 = Article.objects.create(headline='First', pub_date=datetime(2005, 7, 30, 0, 0))
  53. self.assertNotEqual(a3.id, a1.id)
  54. self.assertNotEqual(a3.id, a2.id)
  55. def test_can_mix_and_match_position_and_kwargs(self):
  56. # You can also mix and match position and keyword arguments, but
  57. # be sure not to duplicate field information.
  58. a = Article(None, 'Fourth article', pub_date=datetime(2005, 7, 31))
  59. a.save()
  60. self.assertEqual(a.headline, 'Fourth article')
  61. def test_cannot_create_instance_with_invalid_kwargs(self):
  62. six.assertRaisesRegex(
  63. self,
  64. TypeError,
  65. "'foo' is an invalid keyword argument for this function",
  66. Article,
  67. id=None,
  68. headline='Some headline',
  69. pub_date=datetime(2005, 7, 31),
  70. foo='bar',
  71. )
  72. def test_can_leave_off_value_for_autofield_and_it_gets_value_on_save(self):
  73. """
  74. You can leave off the value for an AutoField when creating an
  75. object, because it'll get filled in automatically when you save().
  76. """
  77. a = Article(headline='Article 5', pub_date=datetime(2005, 7, 31))
  78. a.save()
  79. self.assertEqual(a.headline, 'Article 5')
  80. self.assertNotEqual(a.id, None)
  81. def test_leaving_off_a_field_with_default_set_the_default_will_be_saved(self):
  82. a = Article(pub_date=datetime(2005, 7, 31))
  83. a.save()
  84. self.assertEqual(a.headline, 'Default headline')
  85. def test_for_datetimefields_saves_as_much_precision_as_was_given(self):
  86. """as much precision in *seconds*"""
  87. a1 = Article(
  88. headline='Article 7',
  89. pub_date=datetime(2005, 7, 31, 12, 30),
  90. )
  91. a1.save()
  92. self.assertEqual(Article.objects.get(id__exact=a1.id).pub_date,
  93. datetime(2005, 7, 31, 12, 30))
  94. a2 = Article(
  95. headline='Article 8',
  96. pub_date=datetime(2005, 7, 31, 12, 30, 45),
  97. )
  98. a2.save()
  99. self.assertEqual(Article.objects.get(id__exact=a2.id).pub_date,
  100. datetime(2005, 7, 31, 12, 30, 45))
  101. def test_saving_an_object_again_does_not_create_a_new_object(self):
  102. a = Article(headline='original', pub_date=datetime(2014, 5, 16))
  103. a.save()
  104. current_id = a.id
  105. a.save()
  106. self.assertEqual(a.id, current_id)
  107. a.headline = 'Updated headline'
  108. a.save()
  109. self.assertEqual(a.id, current_id)
  110. def test_querysets_checking_for_membership(self):
  111. headlines = [
  112. 'Parrot programs in Python', 'Second article', 'Third article']
  113. some_pub_date = datetime(2014, 5, 16, 12, 1)
  114. for headline in headlines:
  115. Article(headline=headline, pub_date=some_pub_date).save()
  116. a = Article(headline='Some headline', pub_date=some_pub_date)
  117. a.save()
  118. # You can use 'in' to test for membership...
  119. self.assertIn(a, Article.objects.all())
  120. # ... but there will often be more efficient ways if that is all you need:
  121. self.assertTrue(Article.objects.filter(id=a.id).exists())
  122. class ModelTest(TestCase):
  123. def test_objects_attribute_is_only_available_on_the_class_itself(self):
  124. six.assertRaisesRegex(
  125. self,
  126. AttributeError,
  127. "Manager isn't accessible via Article instances",
  128. getattr,
  129. Article(),
  130. "objects",
  131. )
  132. self.assertFalse(hasattr(Article(), 'objects'))
  133. self.assertTrue(hasattr(Article, 'objects'))
  134. def test_queryset_delete_removes_all_items_in_that_queryset(self):
  135. headlines = [
  136. 'An article', 'Article One', 'Amazing article', 'Boring article']
  137. some_pub_date = datetime(2014, 5, 16, 12, 1)
  138. for headline in headlines:
  139. Article(headline=headline, pub_date=some_pub_date).save()
  140. self.assertQuerysetEqual(Article.objects.all().order_by('headline'),
  141. ["<Article: Amazing article>",
  142. "<Article: An article>",
  143. "<Article: Article One>",
  144. "<Article: Boring article>"])
  145. Article.objects.filter(headline__startswith='A').delete()
  146. self.assertQuerysetEqual(Article.objects.all().order_by('headline'),
  147. ["<Article: Boring article>"])
  148. def test_not_equal_and_equal_operators_behave_as_expected_on_instances(self):
  149. some_pub_date = datetime(2014, 5, 16, 12, 1)
  150. a1 = Article.objects.create(headline='First', pub_date=some_pub_date)
  151. a2 = Article.objects.create(headline='Second', pub_date=some_pub_date)
  152. self.assertNotEqual(a1, a2)
  153. self.assertEqual(a1, Article.objects.get(id__exact=a1.id))
  154. self.assertNotEqual(Article.objects.get(id__exact=a1.id), Article.objects.get(id__exact=a2.id))
  155. @skipUnlessDBFeature('supports_microsecond_precision')
  156. def test_microsecond_precision(self):
  157. # In PostgreSQL, microsecond-level precision is available.
  158. a9 = Article(
  159. headline='Article 9',
  160. pub_date=datetime(2005, 7, 31, 12, 30, 45, 180),
  161. )
  162. a9.save()
  163. self.assertEqual(Article.objects.get(pk=a9.pk).pub_date,
  164. datetime(2005, 7, 31, 12, 30, 45, 180))
  165. @skipIfDBFeature('supports_microsecond_precision')
  166. def test_microsecond_precision_not_supported(self):
  167. # In MySQL, microsecond-level precision isn't always available. You'll
  168. # lose microsecond-level precision once the data is saved.
  169. a9 = Article(
  170. headline='Article 9',
  171. pub_date=datetime(2005, 7, 31, 12, 30, 45, 180),
  172. )
  173. a9.save()
  174. self.assertEqual(
  175. Article.objects.get(id__exact=a9.id).pub_date,
  176. datetime(2005, 7, 31, 12, 30, 45),
  177. )
  178. @skipIfDBFeature('supports_microsecond_precision')
  179. def test_microsecond_precision_not_supported_edge_case(self):
  180. # In MySQL, microsecond-level precision isn't always available. You'll
  181. # lose microsecond-level precision once the data is saved.
  182. a = Article.objects.create(
  183. headline='Article',
  184. pub_date=datetime(2008, 12, 31, 23, 59, 59, 999999),
  185. )
  186. self.assertEqual(
  187. Article.objects.get(pk=a.pk).pub_date,
  188. datetime(2008, 12, 31, 23, 59, 59),
  189. )
  190. def test_manually_specify_primary_key(self):
  191. # You can manually specify the primary key when creating a new object.
  192. a101 = Article(
  193. id=101,
  194. headline='Article 101',
  195. pub_date=datetime(2005, 7, 31, 12, 30, 45),
  196. )
  197. a101.save()
  198. a101 = Article.objects.get(pk=101)
  199. self.assertEqual(a101.headline, 'Article 101')
  200. def test_create_method(self):
  201. # You can create saved objects in a single step
  202. a10 = Article.objects.create(
  203. headline="Article 10",
  204. pub_date=datetime(2005, 7, 31, 12, 30, 45),
  205. )
  206. self.assertEqual(Article.objects.get(headline="Article 10"), a10)
  207. def test_year_lookup_edge_case(self):
  208. # Edge-case test: A year lookup should retrieve all objects in
  209. # the given year, including Jan. 1 and Dec. 31.
  210. Article.objects.create(
  211. headline='Article 11',
  212. pub_date=datetime(2008, 1, 1),
  213. )
  214. Article.objects.create(
  215. headline='Article 12',
  216. pub_date=datetime(2008, 12, 31, 23, 59, 59, 999999),
  217. )
  218. self.assertQuerysetEqual(Article.objects.filter(pub_date__year=2008),
  219. ["<Article: Article 11>", "<Article: Article 12>"])
  220. def test_unicode_data(self):
  221. # Unicode data works, too.
  222. a = Article(
  223. headline='\u6797\u539f \u3081\u3050\u307f',
  224. pub_date=datetime(2005, 7, 28),
  225. )
  226. a.save()
  227. self.assertEqual(Article.objects.get(pk=a.id).headline,
  228. '\u6797\u539f \u3081\u3050\u307f')
  229. def test_hash_function(self):
  230. # Model instances have a hash function, so they can be used in sets
  231. # or as dictionary keys. Two models compare as equal if their primary
  232. # keys are equal.
  233. a10 = Article.objects.create(
  234. headline="Article 10",
  235. pub_date=datetime(2005, 7, 31, 12, 30, 45),
  236. )
  237. a11 = Article.objects.create(
  238. headline='Article 11',
  239. pub_date=datetime(2008, 1, 1),
  240. )
  241. a12 = Article.objects.create(
  242. headline='Article 12',
  243. pub_date=datetime(2008, 12, 31, 23, 59, 59, 999999),
  244. )
  245. s = {a10, a11, a12}
  246. self.assertIn(Article.objects.get(headline='Article 11'), s)
  247. def test_field_ordering(self):
  248. """
  249. Field instances have a `__lt__` comparison function to define an
  250. ordering based on their creation. Prior to #17851 this ordering
  251. comparison relied on the now unsupported `__cmp__` and was assuming
  252. compared objects were both Field instances raising `AttributeError`
  253. when it should have returned `NotImplemented`.
  254. """
  255. f1 = Field()
  256. f2 = Field(auto_created=True)
  257. f3 = Field()
  258. self.assertLess(f2, f1)
  259. self.assertGreater(f3, f1)
  260. self.assertIsNotNone(f1)
  261. self.assertNotIn(f2, (None, 1, ''))
  262. def test_extra_method_select_argument_with_dashes_and_values(self):
  263. # The 'select' argument to extra() supports names with dashes in
  264. # them, as long as you use values().
  265. Article.objects.create(
  266. headline="Article 10",
  267. pub_date=datetime(2005, 7, 31, 12, 30, 45),
  268. )
  269. Article.objects.create(
  270. headline='Article 11',
  271. pub_date=datetime(2008, 1, 1),
  272. )
  273. Article.objects.create(
  274. headline='Article 12',
  275. pub_date=datetime(2008, 12, 31, 23, 59, 59, 999999),
  276. )
  277. dicts = Article.objects.filter(
  278. pub_date__year=2008).extra(
  279. select={'dashed-value': '1'}).values('headline', 'dashed-value')
  280. self.assertEqual([sorted(d.items()) for d in dicts],
  281. [[('dashed-value', 1), ('headline', 'Article 11')], [('dashed-value', 1), ('headline', 'Article 12')]])
  282. def test_extra_method_select_argument_with_dashes(self):
  283. # If you use 'select' with extra() and names containing dashes on a
  284. # query that's *not* a values() query, those extra 'select' values
  285. # will silently be ignored.
  286. Article.objects.create(
  287. headline="Article 10",
  288. pub_date=datetime(2005, 7, 31, 12, 30, 45),
  289. )
  290. Article.objects.create(
  291. headline='Article 11',
  292. pub_date=datetime(2008, 1, 1),
  293. )
  294. Article.objects.create(
  295. headline='Article 12',
  296. pub_date=datetime(2008, 12, 31, 23, 59, 59, 999999),
  297. )
  298. articles = Article.objects.filter(
  299. pub_date__year=2008).extra(select={'dashed-value': '1', 'undashedvalue': '2'})
  300. self.assertEqual(articles[0].undashedvalue, 2)
  301. def test_create_relation_with_ugettext_lazy(self):
  302. """
  303. Test that ugettext_lazy objects work when saving model instances
  304. through various methods. Refs #10498.
  305. """
  306. notlazy = 'test'
  307. lazy = ugettext_lazy(notlazy)
  308. Article.objects.create(headline=lazy, pub_date=datetime.now())
  309. article = Article.objects.get()
  310. self.assertEqual(article.headline, notlazy)
  311. # test that assign + save works with Promise objects
  312. article.headline = lazy
  313. article.save()
  314. self.assertEqual(article.headline, notlazy)
  315. # test .update()
  316. Article.objects.update(headline=lazy)
  317. article = Article.objects.get()
  318. self.assertEqual(article.headline, notlazy)
  319. # still test bulk_create()
  320. Article.objects.all().delete()
  321. Article.objects.bulk_create([Article(headline=lazy, pub_date=datetime.now())])
  322. article = Article.objects.get()
  323. self.assertEqual(article.headline, notlazy)
  324. def test_emptyqs(self):
  325. # Can't be instantiated
  326. with self.assertRaises(TypeError):
  327. EmptyQuerySet()
  328. self.assertIsInstance(Article.objects.none(), EmptyQuerySet)
  329. def test_emptyqs_values(self):
  330. # test for #15959
  331. Article.objects.create(headline='foo', pub_date=datetime.now())
  332. with self.assertNumQueries(0):
  333. qs = Article.objects.none().values_list('pk')
  334. self.assertIsInstance(qs, EmptyQuerySet)
  335. self.assertEqual(len(qs), 0)
  336. def test_emptyqs_customqs(self):
  337. # A hacky test for custom QuerySet subclass - refs #17271
  338. Article.objects.create(headline='foo', pub_date=datetime.now())
  339. class CustomQuerySet(QuerySet):
  340. def do_something(self):
  341. return 'did something'
  342. qs = Article.objects.all()
  343. qs.__class__ = CustomQuerySet
  344. qs = qs.none()
  345. with self.assertNumQueries(0):
  346. self.assertEqual(len(qs), 0)
  347. self.assertIsInstance(qs, EmptyQuerySet)
  348. self.assertEqual(qs.do_something(), 'did something')
  349. def test_emptyqs_values_order(self):
  350. # Tests for ticket #17712
  351. Article.objects.create(headline='foo', pub_date=datetime.now())
  352. with self.assertNumQueries(0):
  353. self.assertEqual(len(Article.objects.none().values_list('id').order_by('id')), 0)
  354. with self.assertNumQueries(0):
  355. self.assertEqual(len(Article.objects.none().filter(
  356. id__in=Article.objects.values_list('id', flat=True))), 0)
  357. @skipUnlessDBFeature('can_distinct_on_fields')
  358. def test_emptyqs_distinct(self):
  359. # Tests for #19426
  360. Article.objects.create(headline='foo', pub_date=datetime.now())
  361. with self.assertNumQueries(0):
  362. self.assertEqual(len(Article.objects.none().distinct('headline', 'pub_date')), 0)
  363. def test_ticket_20278(self):
  364. sr = SelfRef.objects.create()
  365. with self.assertRaises(ObjectDoesNotExist):
  366. SelfRef.objects.get(selfref=sr)
  367. def test_eq(self):
  368. self.assertEqual(Article(id=1), Article(id=1))
  369. self.assertNotEqual(Article(id=1), object())
  370. self.assertNotEqual(object(), Article(id=1))
  371. a = Article()
  372. self.assertEqual(a, a)
  373. self.assertNotEqual(Article(), a)
  374. def test_hash(self):
  375. # Value based on PK
  376. self.assertEqual(hash(Article(id=1)), hash(1))
  377. with self.assertRaises(TypeError):
  378. # No PK value -> unhashable (because save() would then change
  379. # hash)
  380. hash(Article())
  381. class ModelLookupTest(TestCase):
  382. def setUp(self):
  383. # Create an Article.
  384. self.a = Article(
  385. id=None,
  386. headline='Swallow programs in Python',
  387. pub_date=datetime(2005, 7, 28),
  388. )
  389. # Save it into the database. You have to call save() explicitly.
  390. self.a.save()
  391. def test_all_lookup(self):
  392. # Change values by changing the attributes, then calling save().
  393. self.a.headline = 'Parrot programs in Python'
  394. self.a.save()
  395. # Article.objects.all() returns all the articles in the database.
  396. self.assertQuerysetEqual(Article.objects.all(),
  397. ['<Article: Parrot programs in Python>'])
  398. def test_rich_lookup(self):
  399. # Django provides a rich database lookup API.
  400. self.assertEqual(Article.objects.get(id__exact=self.a.id), self.a)
  401. self.assertEqual(Article.objects.get(headline__startswith='Swallow'), self.a)
  402. self.assertEqual(Article.objects.get(pub_date__year=2005), self.a)
  403. self.assertEqual(Article.objects.get(pub_date__year=2005, pub_date__month=7), self.a)
  404. self.assertEqual(Article.objects.get(pub_date__year=2005, pub_date__month=7, pub_date__day=28), self.a)
  405. self.assertEqual(Article.objects.get(pub_date__week_day=5), self.a)
  406. def test_equal_lookup(self):
  407. # The "__exact" lookup type can be omitted, as a shortcut.
  408. self.assertEqual(Article.objects.get(id=self.a.id), self.a)
  409. self.assertEqual(Article.objects.get(headline='Swallow programs in Python'), self.a)
  410. self.assertQuerysetEqual(
  411. Article.objects.filter(pub_date__year=2005),
  412. ['<Article: Swallow programs in Python>'],
  413. )
  414. self.assertQuerysetEqual(
  415. Article.objects.filter(pub_date__year=2004),
  416. [],
  417. )
  418. self.assertQuerysetEqual(
  419. Article.objects.filter(pub_date__year=2005, pub_date__month=7),
  420. ['<Article: Swallow programs in Python>'],
  421. )
  422. self.assertQuerysetEqual(
  423. Article.objects.filter(pub_date__week_day=5),
  424. ['<Article: Swallow programs in Python>'],
  425. )
  426. self.assertQuerysetEqual(
  427. Article.objects.filter(pub_date__week_day=6),
  428. [],
  429. )
  430. def test_does_not_exist(self):
  431. # Django raises an Article.DoesNotExist exception for get() if the
  432. # parameters don't match any object.
  433. six.assertRaisesRegex(
  434. self,
  435. ObjectDoesNotExist,
  436. "Article matching query does not exist.",
  437. Article.objects.get,
  438. id__exact=2000,
  439. )
  440. # To avoid dict-ordering related errors check only one lookup
  441. # in single assert.
  442. self.assertRaises(
  443. ObjectDoesNotExist,
  444. Article.objects.get,
  445. pub_date__year=2005,
  446. pub_date__month=8,
  447. )
  448. six.assertRaisesRegex(
  449. self,
  450. ObjectDoesNotExist,
  451. "Article matching query does not exist.",
  452. Article.objects.get,
  453. pub_date__week_day=6,
  454. )
  455. def test_lookup_by_primary_key(self):
  456. # Lookup by a primary key is the most common case, so Django
  457. # provides a shortcut for primary-key exact lookups.
  458. # The following is identical to articles.get(id=a.id).
  459. self.assertEqual(Article.objects.get(pk=self.a.id), self.a)
  460. # pk can be used as a shortcut for the primary key name in any query.
  461. self.assertQuerysetEqual(Article.objects.filter(pk__in=[self.a.id]),
  462. ["<Article: Swallow programs in Python>"])
  463. # Model instances of the same type and same ID are considered equal.
  464. a = Article.objects.get(pk=self.a.id)
  465. b = Article.objects.get(pk=self.a.id)
  466. self.assertEqual(a, b)
  467. def test_too_many(self):
  468. # Create a very similar object
  469. a = Article(
  470. id=None,
  471. headline='Swallow bites Python',
  472. pub_date=datetime(2005, 7, 28),
  473. )
  474. a.save()
  475. self.assertEqual(Article.objects.count(), 2)
  476. # Django raises an Article.MultipleObjectsReturned exception if the
  477. # lookup matches more than one object
  478. six.assertRaisesRegex(
  479. self,
  480. MultipleObjectsReturned,
  481. "get\(\) returned more than one Article -- it returned 2!",
  482. Article.objects.get,
  483. headline__startswith='Swallow',
  484. )
  485. six.assertRaisesRegex(
  486. self,
  487. MultipleObjectsReturned,
  488. "get\(\) returned more than one Article -- it returned 2!",
  489. Article.objects.get,
  490. pub_date__year=2005,
  491. )
  492. six.assertRaisesRegex(
  493. self,
  494. MultipleObjectsReturned,
  495. "get\(\) returned more than one Article -- it returned 2!",
  496. Article.objects.get,
  497. pub_date__year=2005,
  498. pub_date__month=7,
  499. )
  500. class ConcurrentSaveTests(TransactionTestCase):
  501. available_apps = ['basic']
  502. @skipUnlessDBFeature('test_db_allows_multiple_connections')
  503. def test_concurrent_delete_with_save(self):
  504. """
  505. Test fetching, deleting and finally saving an object - we should get
  506. an insert in this case.
  507. """
  508. a = Article.objects.create(headline='foo', pub_date=datetime.now())
  509. exceptions = []
  510. def deleter():
  511. try:
  512. # Do not delete a directly - doing so alters its state.
  513. Article.objects.filter(pk=a.pk).delete()
  514. except Exception as e:
  515. exceptions.append(e)
  516. finally:
  517. connections[DEFAULT_DB_ALIAS].close()
  518. self.assertEqual(len(exceptions), 0)
  519. t = threading.Thread(target=deleter)
  520. t.start()
  521. t.join()
  522. a.save()
  523. self.assertEqual(Article.objects.get(pk=a.pk).headline, 'foo')
  524. class ManagerTest(SimpleTestCase):
  525. QUERYSET_PROXY_METHODS = [
  526. 'none',
  527. 'count',
  528. 'dates',
  529. 'datetimes',
  530. 'distinct',
  531. 'extra',
  532. 'get',
  533. 'get_or_create',
  534. 'update_or_create',
  535. 'create',
  536. 'bulk_create',
  537. 'filter',
  538. 'aggregate',
  539. 'annotate',
  540. 'complex_filter',
  541. 'exclude',
  542. 'in_bulk',
  543. 'iterator',
  544. 'earliest',
  545. 'latest',
  546. 'first',
  547. 'last',
  548. 'order_by',
  549. 'select_for_update',
  550. 'select_related',
  551. 'prefetch_related',
  552. 'values',
  553. 'values_list',
  554. 'update',
  555. 'reverse',
  556. 'defer',
  557. 'only',
  558. 'using',
  559. 'exists',
  560. '_insert',
  561. '_update',
  562. 'raw',
  563. ]
  564. def test_manager_methods(self):
  565. """
  566. This test ensures that the correct set of methods from `QuerySet`
  567. are copied onto `Manager`.
  568. It's particularly useful to prevent accidentally leaking new methods
  569. into `Manager`. New `QuerySet` methods that should also be copied onto
  570. `Manager` will need to be added to `ManagerTest.QUERYSET_PROXY_METHODS`.
  571. """
  572. self.assertEqual(
  573. sorted(BaseManager._get_queryset_methods(QuerySet).keys()),
  574. sorted(self.QUERYSET_PROXY_METHODS),
  575. )
  576. class SelectOnSaveTests(TestCase):
  577. def test_select_on_save(self):
  578. a1 = Article.objects.create(pub_date=datetime.now())
  579. with self.assertNumQueries(1):
  580. a1.save()
  581. asos = ArticleSelectOnSave.objects.create(pub_date=datetime.now())
  582. with self.assertNumQueries(2):
  583. asos.save()
  584. with self.assertNumQueries(1):
  585. asos.save(force_update=True)
  586. Article.objects.all().delete()
  587. with self.assertRaises(DatabaseError):
  588. with self.assertNumQueries(1):
  589. asos.save(force_update=True)
  590. def test_select_on_save_lying_update(self):
  591. """
  592. Test that select_on_save works correctly if the database
  593. doesn't return correct information about matched rows from
  594. UPDATE.
  595. """
  596. # Change the manager to not return "row matched" for update().
  597. # We are going to change the Article's _base_manager class
  598. # dynamically. This is a bit of a hack, but it seems hard to
  599. # test this properly otherwise. Article's manager, because
  600. # proxy models use their parent model's _base_manager.
  601. orig_class = Article._base_manager.__class__
  602. class FakeQuerySet(QuerySet):
  603. # Make sure the _update method below is in fact called.
  604. called = False
  605. def _update(self, *args, **kwargs):
  606. FakeQuerySet.called = True
  607. super(FakeQuerySet, self)._update(*args, **kwargs)
  608. return 0
  609. class FakeManager(orig_class):
  610. def get_queryset(self):
  611. return FakeQuerySet(self.model)
  612. try:
  613. Article._base_manager.__class__ = FakeManager
  614. asos = ArticleSelectOnSave.objects.create(pub_date=datetime.now())
  615. with self.assertNumQueries(3):
  616. asos.save()
  617. self.assertTrue(FakeQuerySet.called)
  618. # This is not wanted behavior, but this is how Django has always
  619. # behaved for databases that do not return correct information
  620. # about matched rows for UPDATE.
  621. with self.assertRaises(DatabaseError):
  622. asos.save(force_update=True)
  623. with self.assertRaises(DatabaseError):
  624. asos.save(update_fields=['pub_date'])
  625. finally:
  626. Article._base_manager.__class__ = orig_class
  627. class ModelRefreshTests(TestCase):
  628. def _truncate_ms(self, val):
  629. # MySQL < 5.6.4 removes microseconds from the datetimes which can cause
  630. # problems when comparing the original value to that loaded from DB
  631. return val - timedelta(microseconds=val.microsecond)
  632. def test_refresh(self):
  633. a = Article.objects.create(pub_date=self._truncate_ms(datetime.now()))
  634. Article.objects.create(pub_date=self._truncate_ms(datetime.now()))
  635. Article.objects.filter(pk=a.pk).update(headline='new headline')
  636. with self.assertNumQueries(1):
  637. a.refresh_from_db()
  638. self.assertEqual(a.headline, 'new headline')
  639. orig_pub_date = a.pub_date
  640. new_pub_date = a.pub_date + timedelta(10)
  641. Article.objects.update(headline='new headline 2', pub_date=new_pub_date)
  642. with self.assertNumQueries(1):
  643. a.refresh_from_db(fields=['headline'])
  644. self.assertEqual(a.headline, 'new headline 2')
  645. self.assertEqual(a.pub_date, orig_pub_date)
  646. with self.assertNumQueries(1):
  647. a.refresh_from_db()
  648. self.assertEqual(a.pub_date, new_pub_date)
  649. def test_refresh_fk(self):
  650. s1 = SelfRef.objects.create()
  651. s2 = SelfRef.objects.create()
  652. s3 = SelfRef.objects.create(selfref=s1)
  653. s3_copy = SelfRef.objects.get(pk=s3.pk)
  654. s3_copy.selfref.touched = True
  655. s3.selfref = s2
  656. s3.save()
  657. with self.assertNumQueries(1):
  658. s3_copy.refresh_from_db()
  659. with self.assertNumQueries(1):
  660. # The old related instance was thrown away (the selfref_id has
  661. # changed). It needs to be reloaded on access, so one query
  662. # executed.
  663. self.assertFalse(hasattr(s3_copy.selfref, 'touched'))
  664. self.assertEqual(s3_copy.selfref, s2)
  665. def test_refresh_null_fk(self):
  666. s1 = SelfRef.objects.create()
  667. s2 = SelfRef.objects.create(selfref=s1)
  668. s2.selfref = None
  669. s2.refresh_from_db()
  670. self.assertEqual(s2.selfref, s1)
  671. def test_refresh_unsaved(self):
  672. pub_date = self._truncate_ms(datetime.now())
  673. a = Article.objects.create(pub_date=pub_date)
  674. a2 = Article(id=a.pk)
  675. with self.assertNumQueries(1):
  676. a2.refresh_from_db()
  677. self.assertEqual(a2.pub_date, pub_date)
  678. self.assertEqual(a2._state.db, "default")
  679. def test_refresh_no_fields(self):
  680. a = Article.objects.create(pub_date=self._truncate_ms(datetime.now()))
  681. with self.assertNumQueries(0):
  682. a.refresh_from_db(fields=[])
  683. class TestRelatedObjectDeprecation(SimpleTestCase):
  684. def test_field_related_deprecation(self):
  685. field = SelfRef._meta.get_field('selfref')
  686. with warnings.catch_warnings(record=True) as warns:
  687. warnings.simplefilter('always')
  688. self.assertIsInstance(field.related, ForeignObjectRel)
  689. self.assertEqual(len(warns), 1)
  690. self.assertEqual(
  691. str(warns.pop().message),
  692. 'Usage of field.related has been deprecated. Use field.remote_field instead.'
  693. )