2
0

tests.py 47 KB

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