tests.py 30 KB

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