2
0

tests.py 46 KB

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