tests.py 27 KB

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