tests.py 48 KB

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