2
0

tests.py 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166
  1. # -*- coding: utf-8 -*-
  2. # Unit and doctests for specific database backends.
  3. from __future__ import unicode_literals
  4. import copy
  5. import datetime
  6. import re
  7. import threading
  8. import unittest
  9. import warnings
  10. from decimal import Decimal, Rounded
  11. from django.conf import settings
  12. from django.core.exceptions import ImproperlyConfigured
  13. from django.core.management.color import no_style
  14. from django.db import (
  15. DEFAULT_DB_ALIAS, DatabaseError, IntegrityError, connection, connections,
  16. reset_queries, transaction,
  17. )
  18. from django.db.backends.base.base import BaseDatabaseWrapper
  19. from django.db.backends.postgresql import version as pg_version
  20. from django.db.backends.signals import connection_created
  21. from django.db.backends.utils import CursorWrapper, format_number
  22. from django.db.models import Avg, StdDev, Sum, Variance
  23. from django.db.models.sql.constants import CURSOR
  24. from django.db.utils import ConnectionHandler
  25. from django.test import (
  26. SimpleTestCase, TestCase, TransactionTestCase, mock, override_settings,
  27. skipIfDBFeature, skipUnlessDBFeature,
  28. )
  29. from django.test.utils import str_prefix
  30. from django.utils import six
  31. from django.utils.six.moves import range
  32. from . import models
  33. class DummyBackendTest(SimpleTestCase):
  34. def test_no_databases(self):
  35. """
  36. Test that empty DATABASES setting default to the dummy backend.
  37. """
  38. DATABASES = {}
  39. conns = ConnectionHandler(DATABASES)
  40. self.assertEqual(conns[DEFAULT_DB_ALIAS].settings_dict['ENGINE'],
  41. 'django.db.backends.dummy')
  42. with self.assertRaises(ImproperlyConfigured):
  43. conns[DEFAULT_DB_ALIAS].ensure_connection()
  44. @unittest.skipUnless(connection.vendor == 'oracle', "Test only for Oracle")
  45. class OracleTests(unittest.TestCase):
  46. def test_quote_name(self):
  47. # Check that '%' chars are escaped for query execution.
  48. name = '"SOME%NAME"'
  49. quoted_name = connection.ops.quote_name(name)
  50. self.assertEqual(quoted_name % (), name)
  51. def test_dbms_session(self):
  52. # If the backend is Oracle, test that we can call a standard
  53. # stored procedure through our cursor wrapper.
  54. from django.db.backends.oracle.base import convert_unicode
  55. with connection.cursor() as cursor:
  56. cursor.callproc(convert_unicode('DBMS_SESSION.SET_IDENTIFIER'),
  57. [convert_unicode('_django_testing!')])
  58. def test_cursor_var(self):
  59. # If the backend is Oracle, test that we can pass cursor variables
  60. # as query parameters.
  61. from django.db.backends.oracle.base import Database
  62. with connection.cursor() as cursor:
  63. var = cursor.var(Database.STRING)
  64. cursor.execute("BEGIN %s := 'X'; END; ", [var])
  65. self.assertEqual(var.getvalue(), 'X')
  66. def test_long_string(self):
  67. # If the backend is Oracle, test that we can save a text longer
  68. # than 4000 chars and read it properly
  69. with connection.cursor() as cursor:
  70. cursor.execute('CREATE TABLE ltext ("TEXT" NCLOB)')
  71. long_str = ''.join(six.text_type(x) for x in range(4000))
  72. cursor.execute('INSERT INTO ltext VALUES (%s)', [long_str])
  73. cursor.execute('SELECT text FROM ltext')
  74. row = cursor.fetchone()
  75. self.assertEqual(long_str, row[0].read())
  76. cursor.execute('DROP TABLE ltext')
  77. def test_client_encoding(self):
  78. # If the backend is Oracle, test that the client encoding is set
  79. # correctly. This was broken under Cygwin prior to r14781.
  80. connection.ensure_connection()
  81. self.assertEqual(connection.connection.encoding, "UTF-8")
  82. self.assertEqual(connection.connection.nencoding, "UTF-8")
  83. def test_order_of_nls_parameters(self):
  84. # an 'almost right' datetime should work with configured
  85. # NLS parameters as per #18465.
  86. with connection.cursor() as cursor:
  87. query = "select 1 from dual where '1936-12-29 00:00' < sysdate"
  88. # Test that the query succeeds without errors - pre #18465 this
  89. # wasn't the case.
  90. cursor.execute(query)
  91. self.assertEqual(cursor.fetchone()[0], 1)
  92. @unittest.skipUnless(connection.vendor == 'sqlite', "Test only for SQLite")
  93. class SQLiteTests(TestCase):
  94. longMessage = True
  95. def test_autoincrement(self):
  96. """
  97. Check that auto_increment fields are created with the AUTOINCREMENT
  98. keyword in order to be monotonically increasing. Refs #10164.
  99. """
  100. with connection.schema_editor(collect_sql=True) as editor:
  101. editor.create_model(models.Square)
  102. statements = editor.collected_sql
  103. match = re.search('"id" ([^,]+),', statements[0])
  104. self.assertIsNotNone(match)
  105. self.assertEqual('integer NOT NULL PRIMARY KEY AUTOINCREMENT',
  106. match.group(1), "Wrong SQL used to create an auto-increment "
  107. "column on SQLite")
  108. def test_aggregation(self):
  109. """
  110. #19360: Raise NotImplementedError when aggregating on date/time fields.
  111. """
  112. for aggregate in (Sum, Avg, Variance, StdDev):
  113. self.assertRaises(
  114. NotImplementedError,
  115. models.Item.objects.all().aggregate, aggregate('time'))
  116. self.assertRaises(
  117. NotImplementedError,
  118. models.Item.objects.all().aggregate, aggregate('date'))
  119. self.assertRaises(
  120. NotImplementedError,
  121. models.Item.objects.all().aggregate, aggregate('last_modified'))
  122. self.assertRaises(
  123. NotImplementedError,
  124. models.Item.objects.all().aggregate,
  125. **{'complex': aggregate('last_modified') + aggregate('last_modified')})
  126. @unittest.skipUnless(connection.vendor == 'postgresql', "Test only for PostgreSQL")
  127. class PostgreSQLTests(TestCase):
  128. def assert_parses(self, version_string, version):
  129. self.assertEqual(pg_version._parse_version(version_string), version)
  130. def test_parsing(self):
  131. """Test PostgreSQL version parsing from `SELECT version()` output"""
  132. self.assert_parses("PostgreSQL 9.3 beta4", 90300)
  133. self.assert_parses("PostgreSQL 9.3", 90300)
  134. self.assert_parses("EnterpriseDB 9.3", 90300)
  135. self.assert_parses("PostgreSQL 9.3.6", 90306)
  136. self.assert_parses("PostgreSQL 9.4beta1", 90400)
  137. self.assert_parses("PostgreSQL 9.3.1 on i386-apple-darwin9.2.2, compiled by GCC i686-apple-darwin9-gcc-4.0.1 (GCC) 4.0.1 (Apple Inc. build 5478)", 90301)
  138. def test_nodb_connection(self):
  139. """
  140. Test that the _nodb_connection property fallbacks to the default connection
  141. database when access to the 'postgres' database is not granted.
  142. """
  143. def mocked_connect(self):
  144. if self.settings_dict['NAME'] is None:
  145. raise DatabaseError()
  146. return ''
  147. nodb_conn = connection._nodb_connection
  148. self.assertIsNone(nodb_conn.settings_dict['NAME'])
  149. # Now assume the 'postgres' db isn't available
  150. del connection._nodb_connection
  151. with warnings.catch_warnings(record=True) as w:
  152. with mock.patch('django.db.backends.base.base.BaseDatabaseWrapper.connect',
  153. side_effect=mocked_connect, autospec=True):
  154. nodb_conn = connection._nodb_connection
  155. del connection._nodb_connection
  156. self.assertIsNotNone(nodb_conn.settings_dict['NAME'])
  157. self.assertEqual(nodb_conn.settings_dict['NAME'], settings.DATABASES[DEFAULT_DB_ALIAS]['NAME'])
  158. # Check a RuntimeWarning nas been emitted
  159. self.assertEqual(len(w), 1)
  160. self.assertEqual(w[0].message.__class__, RuntimeWarning)
  161. def test_version_detection(self):
  162. """Test PostgreSQL version detection"""
  163. # Helper mocks
  164. class CursorMock(object):
  165. "Very simple mock of DB-API cursor"
  166. def execute(self, arg):
  167. pass
  168. def fetchone(self):
  169. return ["PostgreSQL 9.3"]
  170. def __enter__(self):
  171. return self
  172. def __exit__(self, type, value, traceback):
  173. pass
  174. class OlderConnectionMock(object):
  175. "Mock of psycopg2 (< 2.0.12) connection"
  176. def cursor(self):
  177. return CursorMock()
  178. # psycopg2 < 2.0.12 code path
  179. conn = OlderConnectionMock()
  180. self.assertEqual(pg_version.get_version(conn), 90300)
  181. def test_connect_and_rollback(self):
  182. """
  183. PostgreSQL shouldn't roll back SET TIME ZONE, even if the first
  184. transaction is rolled back (#17062).
  185. """
  186. databases = copy.deepcopy(settings.DATABASES)
  187. new_connections = ConnectionHandler(databases)
  188. new_connection = new_connections[DEFAULT_DB_ALIAS]
  189. try:
  190. # Ensure the database default time zone is different than
  191. # the time zone in new_connection.settings_dict. We can
  192. # get the default time zone by reset & show.
  193. cursor = new_connection.cursor()
  194. cursor.execute("RESET TIMEZONE")
  195. cursor.execute("SHOW TIMEZONE")
  196. db_default_tz = cursor.fetchone()[0]
  197. new_tz = 'Europe/Paris' if db_default_tz == 'UTC' else 'UTC'
  198. new_connection.close()
  199. # Invalidate timezone name cache, because the setting_changed
  200. # handler cannot know about new_connection.
  201. del new_connection.timezone_name
  202. # Fetch a new connection with the new_tz as default
  203. # time zone, run a query and rollback.
  204. with self.settings(TIME_ZONE=new_tz):
  205. new_connection.set_autocommit(False)
  206. cursor = new_connection.cursor()
  207. new_connection.rollback()
  208. # Now let's see if the rollback rolled back the SET TIME ZONE.
  209. cursor.execute("SHOW TIMEZONE")
  210. tz = cursor.fetchone()[0]
  211. self.assertEqual(new_tz, tz)
  212. finally:
  213. new_connection.close()
  214. def test_connect_non_autocommit(self):
  215. """
  216. The connection wrapper shouldn't believe that autocommit is enabled
  217. after setting the time zone when AUTOCOMMIT is False (#21452).
  218. """
  219. databases = copy.deepcopy(settings.DATABASES)
  220. databases[DEFAULT_DB_ALIAS]['AUTOCOMMIT'] = False
  221. new_connections = ConnectionHandler(databases)
  222. new_connection = new_connections[DEFAULT_DB_ALIAS]
  223. try:
  224. # Open a database connection.
  225. new_connection.cursor()
  226. self.assertFalse(new_connection.get_autocommit())
  227. finally:
  228. new_connection.close()
  229. def test_connect_isolation_level(self):
  230. """
  231. Regression test for #18130 and #24318.
  232. """
  233. from psycopg2.extensions import (
  234. ISOLATION_LEVEL_READ_COMMITTED as read_committed,
  235. ISOLATION_LEVEL_SERIALIZABLE as serializable,
  236. )
  237. # Since this is a django.test.TestCase, a transaction is in progress
  238. # and the isolation level isn't reported as 0. This test assumes that
  239. # PostgreSQL is configured with the default isolation level.
  240. # Check the level on the psycopg2 connection, not the Django wrapper.
  241. self.assertEqual(connection.connection.isolation_level, read_committed)
  242. databases = copy.deepcopy(settings.DATABASES)
  243. databases[DEFAULT_DB_ALIAS]['OPTIONS']['isolation_level'] = serializable
  244. new_connections = ConnectionHandler(databases)
  245. new_connection = new_connections[DEFAULT_DB_ALIAS]
  246. try:
  247. # Start a transaction so the isolation level isn't reported as 0.
  248. new_connection.set_autocommit(False)
  249. # Check the level on the psycopg2 connection, not the Django wrapper.
  250. self.assertEqual(new_connection.connection.isolation_level, serializable)
  251. finally:
  252. new_connection.close()
  253. def _select(self, val):
  254. with connection.cursor() as cursor:
  255. cursor.execute("SELECT %s", (val,))
  256. return cursor.fetchone()[0]
  257. def test_select_ascii_array(self):
  258. a = ["awef"]
  259. b = self._select(a)
  260. self.assertEqual(a[0], b[0])
  261. def test_select_unicode_array(self):
  262. a = ["ᄲawef"]
  263. b = self._select(a)
  264. self.assertEqual(a[0], b[0])
  265. def test_lookup_cast(self):
  266. from django.db.backends.postgresql.operations import DatabaseOperations
  267. do = DatabaseOperations(connection=None)
  268. for lookup in ('iexact', 'contains', 'icontains', 'startswith',
  269. 'istartswith', 'endswith', 'iendswith', 'regex', 'iregex'):
  270. self.assertIn('::text', do.lookup_cast(lookup))
  271. def test_correct_extraction_psycopg2_version(self):
  272. from django.db.backends.postgresql.base import psycopg2_version
  273. version_path = 'django.db.backends.postgresql.base.Database.__version__'
  274. with mock.patch(version_path, '2.6.9'):
  275. self.assertEqual(psycopg2_version(), (2, 6, 9))
  276. with mock.patch(version_path, '2.5.dev0'):
  277. self.assertEqual(psycopg2_version(), (2, 5))
  278. class DateQuotingTest(TestCase):
  279. def test_django_date_trunc(self):
  280. """
  281. Test the custom ``django_date_trunc method``, in particular against
  282. fields which clash with strings passed to it (e.g. 'year') - see
  283. #12818__.
  284. __: http://code.djangoproject.com/ticket/12818
  285. """
  286. updated = datetime.datetime(2010, 2, 20)
  287. models.SchoolClass.objects.create(year=2009, last_updated=updated)
  288. years = models.SchoolClass.objects.dates('last_updated', 'year')
  289. self.assertEqual(list(years), [datetime.date(2010, 1, 1)])
  290. def test_django_date_extract(self):
  291. """
  292. Test the custom ``django_date_extract method``, in particular against fields
  293. which clash with strings passed to it (e.g. 'day') - see #12818__.
  294. __: http://code.djangoproject.com/ticket/12818
  295. """
  296. updated = datetime.datetime(2010, 2, 20)
  297. models.SchoolClass.objects.create(year=2009, last_updated=updated)
  298. classes = models.SchoolClass.objects.filter(last_updated__day=20)
  299. self.assertEqual(len(classes), 1)
  300. @override_settings(DEBUG=True)
  301. class LastExecutedQueryTest(TestCase):
  302. def test_last_executed_query(self):
  303. """
  304. last_executed_query should not raise an exception even if no previous
  305. query has been run.
  306. """
  307. cursor = connection.cursor()
  308. connection.ops.last_executed_query(cursor, '', ())
  309. def test_debug_sql(self):
  310. list(models.Reporter.objects.filter(first_name="test"))
  311. sql = connection.queries[-1]['sql'].lower()
  312. self.assertIn("select", sql)
  313. self.assertIn(models.Reporter._meta.db_table, sql)
  314. def test_query_encoding(self):
  315. """
  316. Test that last_executed_query() returns an Unicode string
  317. """
  318. data = models.RawData.objects.filter(raw_data=b'\x00\x46 \xFE').extra(select={'föö': 1})
  319. sql, params = data.query.sql_with_params()
  320. cursor = data.query.get_compiler('default').execute_sql(CURSOR)
  321. last_sql = cursor.db.ops.last_executed_query(cursor, sql, params)
  322. self.assertIsInstance(last_sql, six.text_type)
  323. @unittest.skipUnless(connection.vendor == 'sqlite',
  324. "This test is specific to SQLite.")
  325. def test_no_interpolation_on_sqlite(self):
  326. # Regression for #17158
  327. # This shouldn't raise an exception
  328. query = "SELECT strftime('%Y', 'now');"
  329. connection.cursor().execute(query)
  330. self.assertEqual(connection.queries[-1]['sql'],
  331. str_prefix("QUERY = %(_)s\"SELECT strftime('%%Y', 'now');\" - PARAMS = ()"))
  332. class ParameterHandlingTest(TestCase):
  333. def test_bad_parameter_count(self):
  334. "An executemany call with too many/not enough parameters will raise an exception (Refs #12612)"
  335. cursor = connection.cursor()
  336. query = ('INSERT INTO %s (%s, %s) VALUES (%%s, %%s)' % (
  337. connection.introspection.table_name_converter('backends_square'),
  338. connection.ops.quote_name('root'),
  339. connection.ops.quote_name('square')
  340. ))
  341. self.assertRaises(Exception, cursor.executemany, query, [(1, 2, 3)])
  342. self.assertRaises(Exception, cursor.executemany, query, [(1,)])
  343. # Unfortunately, the following tests would be a good test to run on all
  344. # backends, but it breaks MySQL hard. Until #13711 is fixed, it can't be run
  345. # everywhere (although it would be an effective test of #13711).
  346. class LongNameTest(TransactionTestCase):
  347. """Long primary keys and model names can result in a sequence name
  348. that exceeds the database limits, which will result in truncation
  349. on certain databases (e.g., Postgres). The backend needs to use
  350. the correct sequence name in last_insert_id and other places, so
  351. check it is. Refs #8901.
  352. """
  353. available_apps = ['backends']
  354. def test_sequence_name_length_limits_create(self):
  355. """Test creation of model with long name and long pk name doesn't error. Ref #8901"""
  356. models.VeryLongModelNameZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ.objects.create()
  357. def test_sequence_name_length_limits_m2m(self):
  358. """Test an m2m save of a model with a long name and a long m2m field name doesn't error as on Django >=1.2 this now uses object saves. Ref #8901"""
  359. obj = models.VeryLongModelNameZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ.objects.create()
  360. rel_obj = models.Person.objects.create(first_name='Django', last_name='Reinhardt')
  361. obj.m2m_also_quite_long_zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz.add(rel_obj)
  362. def test_sequence_name_length_limits_flush(self):
  363. """Test that sequence resetting as part of a flush with model with long name and long pk name doesn't error. Ref #8901"""
  364. # A full flush is expensive to the full test, so we dig into the
  365. # internals to generate the likely offending SQL and run it manually
  366. # Some convenience aliases
  367. VLM = models.VeryLongModelNameZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ
  368. VLM_m2m = VLM.m2m_also_quite_long_zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz.through
  369. tables = [
  370. VLM._meta.db_table,
  371. VLM_m2m._meta.db_table,
  372. ]
  373. sequences = [
  374. {
  375. 'column': VLM._meta.pk.column,
  376. 'table': VLM._meta.db_table
  377. },
  378. ]
  379. cursor = connection.cursor()
  380. for statement in connection.ops.sql_flush(no_style(), tables, sequences):
  381. cursor.execute(statement)
  382. class SequenceResetTest(TestCase):
  383. def test_generic_relation(self):
  384. "Sequence names are correct when resetting generic relations (Ref #13941)"
  385. # Create an object with a manually specified PK
  386. models.Post.objects.create(id=10, name='1st post', text='hello world')
  387. # Reset the sequences for the database
  388. cursor = connection.cursor()
  389. commands = connections[DEFAULT_DB_ALIAS].ops.sequence_reset_sql(no_style(), [models.Post])
  390. for sql in commands:
  391. cursor.execute(sql)
  392. # If we create a new object now, it should have a PK greater
  393. # than the PK we specified manually.
  394. obj = models.Post.objects.create(name='New post', text='goodbye world')
  395. self.assertGreater(obj.pk, 10)
  396. # This test needs to run outside of a transaction, otherwise closing the
  397. # connection would implicitly rollback and cause problems during teardown.
  398. class ConnectionCreatedSignalTest(TransactionTestCase):
  399. available_apps = []
  400. # Unfortunately with sqlite3 the in-memory test database cannot be closed,
  401. # and so it cannot be re-opened during testing.
  402. @skipUnlessDBFeature('test_db_allows_multiple_connections')
  403. def test_signal(self):
  404. data = {}
  405. def receiver(sender, connection, **kwargs):
  406. data["connection"] = connection
  407. connection_created.connect(receiver)
  408. connection.close()
  409. connection.cursor()
  410. self.assertIs(data["connection"].connection, connection.connection)
  411. connection_created.disconnect(receiver)
  412. data.clear()
  413. connection.cursor()
  414. self.assertEqual(data, {})
  415. class EscapingChecks(TestCase):
  416. """
  417. All tests in this test case are also run with settings.DEBUG=True in
  418. EscapingChecksDebug test case, to also test CursorDebugWrapper.
  419. """
  420. bare_select_suffix = connection.features.bare_select_suffix
  421. def test_paramless_no_escaping(self):
  422. cursor = connection.cursor()
  423. cursor.execute("SELECT '%s'" + self.bare_select_suffix)
  424. self.assertEqual(cursor.fetchall()[0][0], '%s')
  425. def test_parameter_escaping(self):
  426. cursor = connection.cursor()
  427. cursor.execute("SELECT '%%', %s" + self.bare_select_suffix, ('%d',))
  428. self.assertEqual(cursor.fetchall()[0], ('%', '%d'))
  429. @unittest.skipUnless(connection.vendor == 'sqlite',
  430. "This is an sqlite-specific issue")
  431. def test_sqlite_parameter_escaping(self):
  432. # '%s' escaping support for sqlite3 #13648
  433. cursor = connection.cursor()
  434. cursor.execute("select strftime('%s', date('now'))")
  435. response = cursor.fetchall()[0][0]
  436. # response should be an non-zero integer
  437. self.assertTrue(int(response))
  438. @override_settings(DEBUG=True)
  439. class EscapingChecksDebug(EscapingChecks):
  440. pass
  441. class BackendTestCase(TransactionTestCase):
  442. available_apps = ['backends']
  443. def create_squares_with_executemany(self, args):
  444. self.create_squares(args, 'format', True)
  445. def create_squares(self, args, paramstyle, multiple):
  446. cursor = connection.cursor()
  447. opts = models.Square._meta
  448. tbl = connection.introspection.table_name_converter(opts.db_table)
  449. f1 = connection.ops.quote_name(opts.get_field('root').column)
  450. f2 = connection.ops.quote_name(opts.get_field('square').column)
  451. if paramstyle == 'format':
  452. query = 'INSERT INTO %s (%s, %s) VALUES (%%s, %%s)' % (tbl, f1, f2)
  453. elif paramstyle == 'pyformat':
  454. query = 'INSERT INTO %s (%s, %s) VALUES (%%(root)s, %%(square)s)' % (tbl, f1, f2)
  455. else:
  456. raise ValueError("unsupported paramstyle in test")
  457. if multiple:
  458. cursor.executemany(query, args)
  459. else:
  460. cursor.execute(query, args)
  461. def test_cursor_executemany(self):
  462. # Test cursor.executemany #4896
  463. args = [(i, i ** 2) for i in range(-5, 6)]
  464. self.create_squares_with_executemany(args)
  465. self.assertEqual(models.Square.objects.count(), 11)
  466. for i in range(-5, 6):
  467. square = models.Square.objects.get(root=i)
  468. self.assertEqual(square.square, i ** 2)
  469. def test_cursor_executemany_with_empty_params_list(self):
  470. # Test executemany with params=[] does nothing #4765
  471. args = []
  472. self.create_squares_with_executemany(args)
  473. self.assertEqual(models.Square.objects.count(), 0)
  474. def test_cursor_executemany_with_iterator(self):
  475. # Test executemany accepts iterators #10320
  476. args = iter((i, i ** 2) for i in range(-3, 2))
  477. self.create_squares_with_executemany(args)
  478. self.assertEqual(models.Square.objects.count(), 5)
  479. args = iter((i, i ** 2) for i in range(3, 7))
  480. with override_settings(DEBUG=True):
  481. # same test for DebugCursorWrapper
  482. self.create_squares_with_executemany(args)
  483. self.assertEqual(models.Square.objects.count(), 9)
  484. @skipUnlessDBFeature('supports_paramstyle_pyformat')
  485. def test_cursor_execute_with_pyformat(self):
  486. # Support pyformat style passing of parameters #10070
  487. args = {'root': 3, 'square': 9}
  488. self.create_squares(args, 'pyformat', multiple=False)
  489. self.assertEqual(models.Square.objects.count(), 1)
  490. @skipUnlessDBFeature('supports_paramstyle_pyformat')
  491. def test_cursor_executemany_with_pyformat(self):
  492. # Support pyformat style passing of parameters #10070
  493. args = [{'root': i, 'square': i ** 2} for i in range(-5, 6)]
  494. self.create_squares(args, 'pyformat', multiple=True)
  495. self.assertEqual(models.Square.objects.count(), 11)
  496. for i in range(-5, 6):
  497. square = models.Square.objects.get(root=i)
  498. self.assertEqual(square.square, i ** 2)
  499. @skipUnlessDBFeature('supports_paramstyle_pyformat')
  500. def test_cursor_executemany_with_pyformat_iterator(self):
  501. args = iter({'root': i, 'square': i ** 2} for i in range(-3, 2))
  502. self.create_squares(args, 'pyformat', multiple=True)
  503. self.assertEqual(models.Square.objects.count(), 5)
  504. args = iter({'root': i, 'square': i ** 2} for i in range(3, 7))
  505. with override_settings(DEBUG=True):
  506. # same test for DebugCursorWrapper
  507. self.create_squares(args, 'pyformat', multiple=True)
  508. self.assertEqual(models.Square.objects.count(), 9)
  509. def test_unicode_fetches(self):
  510. # fetchone, fetchmany, fetchall return strings as unicode objects #6254
  511. qn = connection.ops.quote_name
  512. models.Person(first_name="John", last_name="Doe").save()
  513. models.Person(first_name="Jane", last_name="Doe").save()
  514. models.Person(first_name="Mary", last_name="Agnelline").save()
  515. models.Person(first_name="Peter", last_name="Parker").save()
  516. models.Person(first_name="Clark", last_name="Kent").save()
  517. opts2 = models.Person._meta
  518. f3, f4 = opts2.get_field('first_name'), opts2.get_field('last_name')
  519. query2 = ('SELECT %s, %s FROM %s ORDER BY %s'
  520. % (qn(f3.column), qn(f4.column), connection.introspection.table_name_converter(opts2.db_table),
  521. qn(f3.column)))
  522. cursor = connection.cursor()
  523. cursor.execute(query2)
  524. self.assertEqual(cursor.fetchone(), ('Clark', 'Kent'))
  525. self.assertEqual(list(cursor.fetchmany(2)), [('Jane', 'Doe'), ('John', 'Doe')])
  526. self.assertEqual(list(cursor.fetchall()), [('Mary', 'Agnelline'), ('Peter', 'Parker')])
  527. def test_unicode_password(self):
  528. old_password = connection.settings_dict['PASSWORD']
  529. connection.settings_dict['PASSWORD'] = "françois"
  530. try:
  531. connection.cursor()
  532. except DatabaseError:
  533. # As password is probably wrong, a database exception is expected
  534. pass
  535. except Exception as e:
  536. self.fail("Unexpected error raised with unicode password: %s" % e)
  537. finally:
  538. connection.settings_dict['PASSWORD'] = old_password
  539. def test_database_operations_helper_class(self):
  540. # Ticket #13630
  541. self.assertTrue(hasattr(connection, 'ops'))
  542. self.assertTrue(hasattr(connection.ops, 'connection'))
  543. self.assertEqual(connection, connection.ops.connection)
  544. def test_database_operations_init(self):
  545. """
  546. Test that DatabaseOperations initialization doesn't query the database.
  547. See #17656.
  548. """
  549. with self.assertNumQueries(0):
  550. connection.ops.__class__(connection)
  551. def test_cached_db_features(self):
  552. self.assertIn(connection.features.supports_transactions, (True, False))
  553. self.assertIn(connection.features.supports_stddev, (True, False))
  554. self.assertIn(connection.features.can_introspect_foreign_keys, (True, False))
  555. def test_duplicate_table_error(self):
  556. """ Test that creating an existing table returns a DatabaseError """
  557. cursor = connection.cursor()
  558. query = 'CREATE TABLE %s (id INTEGER);' % models.Article._meta.db_table
  559. with self.assertRaises(DatabaseError):
  560. cursor.execute(query)
  561. def test_cursor_contextmanager(self):
  562. """
  563. Test that cursors can be used as a context manager
  564. """
  565. with connection.cursor() as cursor:
  566. self.assertIsInstance(cursor, CursorWrapper)
  567. # Both InterfaceError and ProgrammingError seem to be used when
  568. # accessing closed cursor (psycopg2 has InterfaceError, rest seem
  569. # to use ProgrammingError).
  570. with self.assertRaises(connection.features.closed_cursor_error_class):
  571. # cursor should be closed, so no queries should be possible.
  572. cursor.execute("SELECT 1" + connection.features.bare_select_suffix)
  573. @unittest.skipUnless(connection.vendor == 'postgresql',
  574. "Psycopg2 specific cursor.closed attribute needed")
  575. def test_cursor_contextmanager_closing(self):
  576. # There isn't a generic way to test that cursors are closed, but
  577. # psycopg2 offers us a way to check that by closed attribute.
  578. # So, run only on psycopg2 for that reason.
  579. with connection.cursor() as cursor:
  580. self.assertIsInstance(cursor, CursorWrapper)
  581. self.assertTrue(cursor.closed)
  582. # Unfortunately with sqlite3 the in-memory test database cannot be closed.
  583. @skipUnlessDBFeature('test_db_allows_multiple_connections')
  584. def test_is_usable_after_database_disconnects(self):
  585. """
  586. Test that is_usable() doesn't crash when the database disconnects.
  587. Regression for #21553.
  588. """
  589. # Open a connection to the database.
  590. with connection.cursor():
  591. pass
  592. # Emulate a connection close by the database.
  593. connection._close()
  594. # Even then is_usable() should not raise an exception.
  595. try:
  596. self.assertFalse(connection.is_usable())
  597. finally:
  598. # Clean up the mess created by connection._close(). Since the
  599. # connection is already closed, this crashes on some backends.
  600. try:
  601. connection.close()
  602. except Exception:
  603. pass
  604. @override_settings(DEBUG=True)
  605. def test_queries(self):
  606. """
  607. Test the documented API of connection.queries.
  608. """
  609. with connection.cursor() as cursor:
  610. reset_queries()
  611. cursor.execute("SELECT 1" + connection.features.bare_select_suffix)
  612. self.assertEqual(1, len(connection.queries))
  613. self.assertIsInstance(connection.queries, list)
  614. self.assertIsInstance(connection.queries[0], dict)
  615. six.assertCountEqual(self, connection.queries[0].keys(), ['sql', 'time'])
  616. reset_queries()
  617. self.assertEqual(0, len(connection.queries))
  618. # Unfortunately with sqlite3 the in-memory test database cannot be closed.
  619. @skipUnlessDBFeature('test_db_allows_multiple_connections')
  620. @override_settings(DEBUG=True)
  621. def test_queries_limit(self):
  622. """
  623. Test that the backend doesn't store an unlimited number of queries.
  624. Regression for #12581.
  625. """
  626. old_queries_limit = BaseDatabaseWrapper.queries_limit
  627. BaseDatabaseWrapper.queries_limit = 3
  628. new_connections = ConnectionHandler(settings.DATABASES)
  629. new_connection = new_connections[DEFAULT_DB_ALIAS]
  630. # Initialize the connection and clear initialization statements.
  631. with new_connection.cursor():
  632. pass
  633. new_connection.queries_log.clear()
  634. try:
  635. with new_connection.cursor() as cursor:
  636. cursor.execute("SELECT 1" + new_connection.features.bare_select_suffix)
  637. cursor.execute("SELECT 2" + new_connection.features.bare_select_suffix)
  638. with warnings.catch_warnings(record=True) as w:
  639. self.assertEqual(2, len(new_connection.queries))
  640. self.assertEqual(0, len(w))
  641. with new_connection.cursor() as cursor:
  642. cursor.execute("SELECT 3" + new_connection.features.bare_select_suffix)
  643. cursor.execute("SELECT 4" + new_connection.features.bare_select_suffix)
  644. with warnings.catch_warnings(record=True) as w:
  645. self.assertEqual(3, len(new_connection.queries))
  646. self.assertEqual(1, len(w))
  647. self.assertEqual(str(w[0].message), "Limit for query logging "
  648. "exceeded, only the last 3 queries will be returned.")
  649. finally:
  650. BaseDatabaseWrapper.queries_limit = old_queries_limit
  651. new_connection.close()
  652. # We don't make these tests conditional because that means we would need to
  653. # check and differentiate between:
  654. # * MySQL+InnoDB, MySQL+MYISAM (something we currently can't do).
  655. # * if sqlite3 (if/once we get #14204 fixed) has referential integrity turned
  656. # on or not, something that would be controlled by runtime support and user
  657. # preference.
  658. # verify if its type is django.database.db.IntegrityError.
  659. class FkConstraintsTests(TransactionTestCase):
  660. available_apps = ['backends']
  661. def setUp(self):
  662. # Create a Reporter.
  663. self.r = models.Reporter.objects.create(first_name='John', last_name='Smith')
  664. def test_integrity_checks_on_creation(self):
  665. """
  666. Try to create a model instance that violates a FK constraint. If it
  667. fails it should fail with IntegrityError.
  668. """
  669. a1 = models.Article(headline="This is a test", pub_date=datetime.datetime(2005, 7, 27), reporter_id=30)
  670. try:
  671. a1.save()
  672. except IntegrityError:
  673. pass
  674. else:
  675. self.skipTest("This backend does not support integrity checks.")
  676. # Now that we know this backend supports integrity checks we make sure
  677. # constraints are also enforced for proxy models. Refs #17519
  678. a2 = models.Article(headline='This is another test', reporter=self.r,
  679. pub_date=datetime.datetime(2012, 8, 3),
  680. reporter_proxy_id=30)
  681. self.assertRaises(IntegrityError, a2.save)
  682. def test_integrity_checks_on_update(self):
  683. """
  684. Try to update a model instance introducing a FK constraint violation.
  685. If it fails it should fail with IntegrityError.
  686. """
  687. # Create an Article.
  688. models.Article.objects.create(headline="Test article", pub_date=datetime.datetime(2010, 9, 4), reporter=self.r)
  689. # Retrieve it from the DB
  690. a1 = models.Article.objects.get(headline="Test article")
  691. a1.reporter_id = 30
  692. try:
  693. a1.save()
  694. except IntegrityError:
  695. pass
  696. else:
  697. self.skipTest("This backend does not support integrity checks.")
  698. # Now that we know this backend supports integrity checks we make sure
  699. # constraints are also enforced for proxy models. Refs #17519
  700. # Create another article
  701. r_proxy = models.ReporterProxy.objects.get(pk=self.r.pk)
  702. models.Article.objects.create(headline='Another article',
  703. pub_date=datetime.datetime(1988, 5, 15),
  704. reporter=self.r, reporter_proxy=r_proxy)
  705. # Retrieve the second article from the DB
  706. a2 = models.Article.objects.get(headline='Another article')
  707. a2.reporter_proxy_id = 30
  708. self.assertRaises(IntegrityError, a2.save)
  709. def test_disable_constraint_checks_manually(self):
  710. """
  711. When constraint checks are disabled, should be able to write bad data without IntegrityErrors.
  712. """
  713. with transaction.atomic():
  714. # Create an Article.
  715. models.Article.objects.create(headline="Test article", pub_date=datetime.datetime(2010, 9, 4), reporter=self.r)
  716. # Retrieve it from the DB
  717. a = models.Article.objects.get(headline="Test article")
  718. a.reporter_id = 30
  719. try:
  720. connection.disable_constraint_checking()
  721. a.save()
  722. connection.enable_constraint_checking()
  723. except IntegrityError:
  724. self.fail("IntegrityError should not have occurred.")
  725. transaction.set_rollback(True)
  726. def test_disable_constraint_checks_context_manager(self):
  727. """
  728. When constraint checks are disabled (using context manager), should be able to write bad data without IntegrityErrors.
  729. """
  730. with transaction.atomic():
  731. # Create an Article.
  732. models.Article.objects.create(headline="Test article", pub_date=datetime.datetime(2010, 9, 4), reporter=self.r)
  733. # Retrieve it from the DB
  734. a = models.Article.objects.get(headline="Test article")
  735. a.reporter_id = 30
  736. try:
  737. with connection.constraint_checks_disabled():
  738. a.save()
  739. except IntegrityError:
  740. self.fail("IntegrityError should not have occurred.")
  741. transaction.set_rollback(True)
  742. def test_check_constraints(self):
  743. """
  744. Constraint checks should raise an IntegrityError when bad data is in the DB.
  745. """
  746. with transaction.atomic():
  747. # Create an Article.
  748. models.Article.objects.create(headline="Test article", pub_date=datetime.datetime(2010, 9, 4), reporter=self.r)
  749. # Retrieve it from the DB
  750. a = models.Article.objects.get(headline="Test article")
  751. a.reporter_id = 30
  752. with connection.constraint_checks_disabled():
  753. a.save()
  754. with self.assertRaises(IntegrityError):
  755. connection.check_constraints()
  756. transaction.set_rollback(True)
  757. class ThreadTests(TransactionTestCase):
  758. available_apps = ['backends']
  759. def test_default_connection_thread_local(self):
  760. """
  761. Ensure that the default connection (i.e. django.db.connection) is
  762. different for each thread.
  763. Refs #17258.
  764. """
  765. # Map connections by id because connections with identical aliases
  766. # have the same hash.
  767. connections_dict = {}
  768. connection.cursor()
  769. connections_dict[id(connection)] = connection
  770. def runner():
  771. # Passing django.db.connection between threads doesn't work while
  772. # connections[DEFAULT_DB_ALIAS] does.
  773. from django.db import connections
  774. connection = connections[DEFAULT_DB_ALIAS]
  775. # Allow thread sharing so the connection can be closed by the
  776. # main thread.
  777. connection.allow_thread_sharing = True
  778. connection.cursor()
  779. connections_dict[id(connection)] = connection
  780. for x in range(2):
  781. t = threading.Thread(target=runner)
  782. t.start()
  783. t.join()
  784. # Check that each created connection got different inner connection.
  785. self.assertEqual(
  786. len(set(conn.connection for conn in connections_dict.values())),
  787. 3)
  788. # Finish by closing the connections opened by the other threads (the
  789. # connection opened in the main thread will automatically be closed on
  790. # teardown).
  791. for conn in connections_dict.values():
  792. if conn is not connection:
  793. conn.close()
  794. def test_connections_thread_local(self):
  795. """
  796. Ensure that the connections are different for each thread.
  797. Refs #17258.
  798. """
  799. # Map connections by id because connections with identical aliases
  800. # have the same hash.
  801. connections_dict = {}
  802. for conn in connections.all():
  803. connections_dict[id(conn)] = conn
  804. def runner():
  805. from django.db import connections
  806. for conn in connections.all():
  807. # Allow thread sharing so the connection can be closed by the
  808. # main thread.
  809. conn.allow_thread_sharing = True
  810. connections_dict[id(conn)] = conn
  811. for x in range(2):
  812. t = threading.Thread(target=runner)
  813. t.start()
  814. t.join()
  815. self.assertEqual(len(connections_dict), 6)
  816. # Finish by closing the connections opened by the other threads (the
  817. # connection opened in the main thread will automatically be closed on
  818. # teardown).
  819. for conn in connections_dict.values():
  820. if conn is not connection:
  821. conn.close()
  822. def test_pass_connection_between_threads(self):
  823. """
  824. Ensure that a connection can be passed from one thread to the other.
  825. Refs #17258.
  826. """
  827. models.Person.objects.create(first_name="John", last_name="Doe")
  828. def do_thread():
  829. def runner(main_thread_connection):
  830. from django.db import connections
  831. connections['default'] = main_thread_connection
  832. try:
  833. models.Person.objects.get(first_name="John", last_name="Doe")
  834. except Exception as e:
  835. exceptions.append(e)
  836. t = threading.Thread(target=runner, args=[connections['default']])
  837. t.start()
  838. t.join()
  839. # Without touching allow_thread_sharing, which should be False by default.
  840. exceptions = []
  841. do_thread()
  842. # Forbidden!
  843. self.assertIsInstance(exceptions[0], DatabaseError)
  844. # If explicitly setting allow_thread_sharing to False
  845. connections['default'].allow_thread_sharing = False
  846. exceptions = []
  847. do_thread()
  848. # Forbidden!
  849. self.assertIsInstance(exceptions[0], DatabaseError)
  850. # If explicitly setting allow_thread_sharing to True
  851. connections['default'].allow_thread_sharing = True
  852. exceptions = []
  853. do_thread()
  854. # All good
  855. self.assertEqual(exceptions, [])
  856. def test_closing_non_shared_connections(self):
  857. """
  858. Ensure that a connection that is not explicitly shareable cannot be
  859. closed by another thread.
  860. Refs #17258.
  861. """
  862. # First, without explicitly enabling the connection for sharing.
  863. exceptions = set()
  864. def runner1():
  865. def runner2(other_thread_connection):
  866. try:
  867. other_thread_connection.close()
  868. except DatabaseError as e:
  869. exceptions.add(e)
  870. t2 = threading.Thread(target=runner2, args=[connections['default']])
  871. t2.start()
  872. t2.join()
  873. t1 = threading.Thread(target=runner1)
  874. t1.start()
  875. t1.join()
  876. # The exception was raised
  877. self.assertEqual(len(exceptions), 1)
  878. # Then, with explicitly enabling the connection for sharing.
  879. exceptions = set()
  880. def runner1():
  881. def runner2(other_thread_connection):
  882. try:
  883. other_thread_connection.close()
  884. except DatabaseError as e:
  885. exceptions.add(e)
  886. # Enable thread sharing
  887. connections['default'].allow_thread_sharing = True
  888. t2 = threading.Thread(target=runner2, args=[connections['default']])
  889. t2.start()
  890. t2.join()
  891. t1 = threading.Thread(target=runner1)
  892. t1.start()
  893. t1.join()
  894. # No exception was raised
  895. self.assertEqual(len(exceptions), 0)
  896. class MySQLPKZeroTests(TestCase):
  897. """
  898. Zero as id for AutoField should raise exception in MySQL, because MySQL
  899. does not allow zero for autoincrement primary key.
  900. """
  901. @skipIfDBFeature('allows_auto_pk_0')
  902. def test_zero_as_autoval(self):
  903. with self.assertRaises(ValueError):
  904. models.Square.objects.create(id=0, root=0, square=1)
  905. class DBConstraintTestCase(TestCase):
  906. def test_can_reference_existent(self):
  907. obj = models.Object.objects.create()
  908. ref = models.ObjectReference.objects.create(obj=obj)
  909. self.assertEqual(ref.obj, obj)
  910. ref = models.ObjectReference.objects.get(obj=obj)
  911. self.assertEqual(ref.obj, obj)
  912. def test_can_reference_non_existent(self):
  913. self.assertFalse(models.Object.objects.filter(id=12345).exists())
  914. ref = models.ObjectReference.objects.create(obj_id=12345)
  915. ref_new = models.ObjectReference.objects.get(obj_id=12345)
  916. self.assertEqual(ref, ref_new)
  917. with self.assertRaises(models.Object.DoesNotExist):
  918. ref.obj
  919. def test_many_to_many(self):
  920. obj = models.Object.objects.create()
  921. obj.related_objects.create()
  922. self.assertEqual(models.Object.objects.count(), 2)
  923. self.assertEqual(obj.related_objects.count(), 1)
  924. intermediary_model = models.Object._meta.get_field("related_objects").remote_field.through
  925. intermediary_model.objects.create(from_object_id=obj.id, to_object_id=12345)
  926. self.assertEqual(obj.related_objects.count(), 1)
  927. self.assertEqual(intermediary_model.objects.count(), 2)
  928. class BackendUtilTests(SimpleTestCase):
  929. def test_format_number(self):
  930. """
  931. Test the format_number converter utility
  932. """
  933. def equal(value, max_d, places, result):
  934. self.assertEqual(format_number(Decimal(value), max_d, places), result)
  935. equal('0', 12, 3,
  936. '0.000')
  937. equal('0', 12, 8,
  938. '0.00000000')
  939. equal('1', 12, 9,
  940. '1.000000000')
  941. equal('0.00000000', 12, 8,
  942. '0.00000000')
  943. equal('0.000000004', 12, 8,
  944. '0.00000000')
  945. equal('0.000000008', 12, 8,
  946. '0.00000001')
  947. equal('0.000000000000000000999', 10, 8,
  948. '0.00000000')
  949. equal('0.1234567890', 12, 10,
  950. '0.1234567890')
  951. equal('0.1234567890', 12, 9,
  952. '0.123456789')
  953. equal('0.1234567890', 12, 8,
  954. '0.12345679')
  955. equal('0.1234567890', 12, 5,
  956. '0.12346')
  957. equal('0.1234567890', 12, 3,
  958. '0.123')
  959. equal('0.1234567890', 12, 1,
  960. '0.1')
  961. equal('0.1234567890', 12, 0,
  962. '0')
  963. equal('0.1234567890', None, 0,
  964. '0')
  965. equal('1234567890.1234567890', None, 0,
  966. '1234567890')
  967. equal('1234567890.1234567890', None, 2,
  968. '1234567890.12')
  969. equal('0.1234', 5, None,
  970. '0.1234')
  971. equal('123.12', 5, None,
  972. '123.12')
  973. with self.assertRaises(Rounded):
  974. equal('0.1234567890', 5, None,
  975. '0.12346')
  976. with self.assertRaises(Rounded):
  977. equal('1234567890.1234', 5, None,
  978. '1234600000')
  979. @unittest.skipUnless(connection.vendor == 'sqlite', 'SQLite specific test.')
  980. @skipUnlessDBFeature('can_share_in_memory_db')
  981. class TestSqliteThreadSharing(TransactionTestCase):
  982. available_apps = ['backends']
  983. def test_database_sharing_in_threads(self):
  984. def create_object():
  985. models.Object.objects.create()
  986. create_object()
  987. thread = threading.Thread(target=create_object)
  988. thread.start()
  989. thread.join()
  990. self.assertEqual(models.Object.objects.count(), 2)