tests.py 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927
  1. # -*- coding: utf-8 -*-
  2. # Unit and doctests for specific database backends.
  3. from __future__ import absolute_import, unicode_literals
  4. import datetime
  5. from decimal import Decimal
  6. import threading
  7. from django.conf import settings
  8. from django.core.management.color import no_style
  9. from django.db import (connection, connections, DEFAULT_DB_ALIAS,
  10. DatabaseError, IntegrityError, transaction)
  11. from django.db.backends.signals import connection_created
  12. from django.db.backends.sqlite3.base import DatabaseOperations
  13. from django.db.backends.postgresql_psycopg2 import version as pg_version
  14. from django.db.backends.util import format_number
  15. from django.db.models import Sum, Avg, Variance, StdDev
  16. from django.db.models.fields import (AutoField, DateField, DateTimeField,
  17. DecimalField, IntegerField, TimeField)
  18. from django.db.utils import ConnectionHandler
  19. from django.test import (TestCase, skipUnlessDBFeature, skipIfDBFeature,
  20. TransactionTestCase)
  21. from django.test.utils import override_settings, str_prefix
  22. from django.utils import six, unittest
  23. from django.utils.six.moves import xrange
  24. from . import models
  25. class DummyBackendTest(TestCase):
  26. def test_no_databases(self):
  27. """
  28. Test that empty DATABASES setting default to the dummy backend.
  29. """
  30. DATABASES = {}
  31. conns = ConnectionHandler(DATABASES)
  32. self.assertEqual(conns[DEFAULT_DB_ALIAS].settings_dict['ENGINE'],
  33. 'django.db.backends.dummy')
  34. class OracleChecks(unittest.TestCase):
  35. @unittest.skipUnless(connection.vendor == 'oracle',
  36. "No need to check Oracle quote_name semantics")
  37. def test_quote_name(self):
  38. # Check that '%' chars are escaped for query execution.
  39. name = '"SOME%NAME"'
  40. quoted_name = connection.ops.quote_name(name)
  41. self.assertEqual(quoted_name % (), name)
  42. @unittest.skipUnless(connection.vendor == 'oracle',
  43. "No need to check Oracle cursor semantics")
  44. def test_dbms_session(self):
  45. # If the backend is Oracle, test that we can call a standard
  46. # stored procedure through our cursor wrapper.
  47. from django.db.backends.oracle.base import convert_unicode
  48. cursor = connection.cursor()
  49. cursor.callproc(convert_unicode('DBMS_SESSION.SET_IDENTIFIER'),
  50. [convert_unicode('_django_testing!')])
  51. @unittest.skipUnless(connection.vendor == 'oracle',
  52. "No need to check Oracle cursor semantics")
  53. def test_cursor_var(self):
  54. # If the backend is Oracle, test that we can pass cursor variables
  55. # as query parameters.
  56. from django.db.backends.oracle.base import Database
  57. cursor = connection.cursor()
  58. var = cursor.var(Database.STRING)
  59. cursor.execute("BEGIN %s := 'X'; END; ", [var])
  60. self.assertEqual(var.getvalue(), 'X')
  61. @unittest.skipUnless(connection.vendor == 'oracle',
  62. "No need to check Oracle cursor semantics")
  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. c = connection.cursor()
  67. c.execute('CREATE TABLE ltext ("TEXT" NCLOB)')
  68. long_str = ''.join([six.text_type(x) for x in xrange(4000)])
  69. c.execute('INSERT INTO ltext VALUES (%s)', [long_str])
  70. c.execute('SELECT text FROM ltext')
  71. row = c.fetchone()
  72. self.assertEqual(long_str, row[0].read())
  73. c.execute('DROP TABLE ltext')
  74. @unittest.skipUnless(connection.vendor == 'oracle',
  75. "No need to check Oracle connection semantics")
  76. def test_client_encoding(self):
  77. # If the backend is Oracle, test that the client encoding is set
  78. # correctly. This was broken under Cygwin prior to r14781.
  79. connection.cursor() # Ensure the connection is initialized.
  80. self.assertEqual(connection.connection.encoding, "UTF-8")
  81. self.assertEqual(connection.connection.nencoding, "UTF-8")
  82. @unittest.skipUnless(connection.vendor == 'oracle',
  83. "No need to check Oracle connection semantics")
  84. def test_order_of_nls_parameters(self):
  85. # an 'almost right' datetime should work with configured
  86. # NLS parameters as per #18465.
  87. c = connection.cursor()
  88. query = "select 1 from dual where '1936-12-29 00:00' < sysdate"
  89. # Test that the query succeeds without errors - pre #18465 this
  90. # wasn't the case.
  91. c.execute(query)
  92. self.assertEqual(c.fetchone()[0], 1)
  93. class MySQLTests(TestCase):
  94. @unittest.skipUnless(connection.vendor == 'mysql',
  95. "Test valid only for MySQL")
  96. def test_autoincrement(self):
  97. """
  98. Check that auto_increment fields are reset correctly by sql_flush().
  99. Before MySQL version 5.0.13 TRUNCATE did not do auto_increment reset.
  100. Refs #16961.
  101. """
  102. statements = connection.ops.sql_flush(no_style(),
  103. tables=['test'],
  104. sequences=[{
  105. 'table': 'test',
  106. 'col': 'somecol',
  107. }])
  108. found_reset = False
  109. for sql in statements:
  110. found_reset = found_reset or 'ALTER TABLE' in sql
  111. if connection.mysql_version < (5, 0, 13):
  112. self.assertTrue(found_reset)
  113. else:
  114. self.assertFalse(found_reset)
  115. class DateQuotingTest(TestCase):
  116. def test_django_date_trunc(self):
  117. """
  118. Test the custom ``django_date_trunc method``, in particular against
  119. fields which clash with strings passed to it (e.g. 'year') - see
  120. #12818__.
  121. __: http://code.djangoproject.com/ticket/12818
  122. """
  123. updated = datetime.datetime(2010, 2, 20)
  124. models.SchoolClass.objects.create(year=2009, last_updated=updated)
  125. years = models.SchoolClass.objects.dates('last_updated', 'year')
  126. self.assertEqual(list(years), [datetime.date(2010, 1, 1)])
  127. def test_django_date_extract(self):
  128. """
  129. Test the custom ``django_date_extract method``, in particular against fields
  130. which clash with strings passed to it (e.g. 'day') - see #12818__.
  131. __: http://code.djangoproject.com/ticket/12818
  132. """
  133. updated = datetime.datetime(2010, 2, 20)
  134. models.SchoolClass.objects.create(year=2009, last_updated=updated)
  135. classes = models.SchoolClass.objects.filter(last_updated__day=20)
  136. self.assertEqual(len(classes), 1)
  137. @override_settings(DEBUG=True)
  138. class LastExecutedQueryTest(TestCase):
  139. def test_debug_sql(self):
  140. list(models.Reporter.objects.filter(first_name="test"))
  141. sql = connection.queries[-1]['sql'].lower()
  142. self.assertIn("select", sql)
  143. self.assertIn(models.Reporter._meta.db_table, sql)
  144. def test_query_encoding(self):
  145. """
  146. Test that last_executed_query() returns an Unicode string
  147. """
  148. persons = models.Reporter.objects.filter(raw_data=b'\x00\x46 \xFE').extra(select={'föö': 1})
  149. sql, params = persons.query.sql_with_params()
  150. cursor = persons.query.get_compiler('default').execute_sql(None)
  151. last_sql = cursor.db.ops.last_executed_query(cursor, sql, params)
  152. self.assertIsInstance(last_sql, six.text_type)
  153. @unittest.skipUnless(connection.vendor == 'sqlite',
  154. "This test is specific to SQLite.")
  155. def test_no_interpolation_on_sqlite(self):
  156. # Regression for #17158
  157. # This shouldn't raise an exception
  158. query = "SELECT strftime('%Y', 'now');"
  159. connection.cursor().execute(query)
  160. self.assertEqual(connection.queries[-1]['sql'],
  161. str_prefix("QUERY = %(_)s\"SELECT strftime('%%Y', 'now');\" - PARAMS = ()"))
  162. class ParameterHandlingTest(TestCase):
  163. def test_bad_parameter_count(self):
  164. "An executemany call with too many/not enough parameters will raise an exception (Refs #12612)"
  165. cursor = connection.cursor()
  166. query = ('INSERT INTO %s (%s, %s) VALUES (%%s, %%s)' % (
  167. connection.introspection.table_name_converter('backends_square'),
  168. connection.ops.quote_name('root'),
  169. connection.ops.quote_name('square')
  170. ))
  171. self.assertRaises(Exception, cursor.executemany, query, [(1, 2, 3)])
  172. self.assertRaises(Exception, cursor.executemany, query, [(1,)])
  173. # Unfortunately, the following tests would be a good test to run on all
  174. # backends, but it breaks MySQL hard. Until #13711 is fixed, it can't be run
  175. # everywhere (although it would be an effective test of #13711).
  176. class LongNameTest(TestCase):
  177. """Long primary keys and model names can result in a sequence name
  178. that exceeds the database limits, which will result in truncation
  179. on certain databases (e.g., Postgres). The backend needs to use
  180. the correct sequence name in last_insert_id and other places, so
  181. check it is. Refs #8901.
  182. """
  183. @skipUnlessDBFeature('supports_long_model_names')
  184. def test_sequence_name_length_limits_create(self):
  185. """Test creation of model with long name and long pk name doesn't error. Ref #8901"""
  186. models.VeryLongModelNameZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ.objects.create()
  187. @skipUnlessDBFeature('supports_long_model_names')
  188. def test_sequence_name_length_limits_m2m(self):
  189. """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"""
  190. obj = models.VeryLongModelNameZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ.objects.create()
  191. rel_obj = models.Person.objects.create(first_name='Django', last_name='Reinhardt')
  192. obj.m2m_also_quite_long_zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz.add(rel_obj)
  193. @skipUnlessDBFeature('supports_long_model_names')
  194. def test_sequence_name_length_limits_flush(self):
  195. """Test that sequence resetting as part of a flush with model with long name and long pk name doesn't error. Ref #8901"""
  196. # A full flush is expensive to the full test, so we dig into the
  197. # internals to generate the likely offending SQL and run it manually
  198. # Some convenience aliases
  199. VLM = models.VeryLongModelNameZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ
  200. VLM_m2m = VLM.m2m_also_quite_long_zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz.through
  201. tables = [
  202. VLM._meta.db_table,
  203. VLM_m2m._meta.db_table,
  204. ]
  205. sequences = [
  206. {
  207. 'column': VLM._meta.pk.column,
  208. 'table': VLM._meta.db_table
  209. },
  210. ]
  211. cursor = connection.cursor()
  212. for statement in connection.ops.sql_flush(no_style(), tables, sequences):
  213. cursor.execute(statement)
  214. class SequenceResetTest(TestCase):
  215. def test_generic_relation(self):
  216. "Sequence names are correct when resetting generic relations (Ref #13941)"
  217. # Create an object with a manually specified PK
  218. models.Post.objects.create(id=10, name='1st post', text='hello world')
  219. # Reset the sequences for the database
  220. cursor = connection.cursor()
  221. commands = connections[DEFAULT_DB_ALIAS].ops.sequence_reset_sql(no_style(), [models.Post])
  222. for sql in commands:
  223. cursor.execute(sql)
  224. # If we create a new object now, it should have a PK greater
  225. # than the PK we specified manually.
  226. obj = models.Post.objects.create(name='New post', text='goodbye world')
  227. self.assertTrue(obj.pk > 10)
  228. class PostgresVersionTest(TestCase):
  229. def assert_parses(self, version_string, version):
  230. self.assertEqual(pg_version._parse_version(version_string), version)
  231. def test_parsing(self):
  232. """Test PostgreSQL version parsing from `SELECT version()` output"""
  233. self.assert_parses("PostgreSQL 8.3 beta4", 80300)
  234. self.assert_parses("PostgreSQL 8.3", 80300)
  235. self.assert_parses("EnterpriseDB 8.3", 80300)
  236. self.assert_parses("PostgreSQL 8.3.6", 80306)
  237. self.assert_parses("PostgreSQL 8.4beta1", 80400)
  238. self.assert_parses("PostgreSQL 8.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)", 80301)
  239. def test_version_detection(self):
  240. """Test PostgreSQL version detection"""
  241. # Helper mocks
  242. class CursorMock(object):
  243. "Very simple mock of DB-API cursor"
  244. def execute(self, arg):
  245. pass
  246. def fetchone(self):
  247. return ["PostgreSQL 8.3"]
  248. class OlderConnectionMock(object):
  249. "Mock of psycopg2 (< 2.0.12) connection"
  250. def cursor(self):
  251. return CursorMock()
  252. # psycopg2 < 2.0.12 code path
  253. conn = OlderConnectionMock()
  254. self.assertEqual(pg_version.get_version(conn), 80300)
  255. class PostgresNewConnectionTest(TestCase):
  256. """
  257. #17062: PostgreSQL shouldn't roll back SET TIME ZONE, even if the first
  258. transaction is rolled back.
  259. """
  260. @unittest.skipUnless(
  261. connection.vendor == 'postgresql',
  262. "This test applies only to PostgreSQL")
  263. def test_connect_and_rollback(self):
  264. new_connections = ConnectionHandler(settings.DATABASES)
  265. new_connection = new_connections[DEFAULT_DB_ALIAS]
  266. try:
  267. # Ensure the database default time zone is different than
  268. # the time zone in new_connection.settings_dict. We can
  269. # get the default time zone by reset & show.
  270. cursor = new_connection.cursor()
  271. cursor.execute("RESET TIMEZONE")
  272. cursor.execute("SHOW TIMEZONE")
  273. db_default_tz = cursor.fetchone()[0]
  274. new_tz = 'Europe/Paris' if db_default_tz == 'UTC' else 'UTC'
  275. new_connection.close()
  276. # Fetch a new connection with the new_tz as default
  277. # time zone, run a query and rollback.
  278. new_connection.settings_dict['TIME_ZONE'] = new_tz
  279. new_connection.enter_transaction_management()
  280. cursor = new_connection.cursor()
  281. new_connection.rollback()
  282. # Now let's see if the rollback rolled back the SET TIME ZONE.
  283. cursor.execute("SHOW TIMEZONE")
  284. tz = cursor.fetchone()[0]
  285. self.assertEqual(new_tz, tz)
  286. finally:
  287. try:
  288. new_connection.close()
  289. except DatabaseError:
  290. pass
  291. # This test needs to run outside of a transaction, otherwise closing the
  292. # connection would implicitly rollback and cause problems during teardown.
  293. class ConnectionCreatedSignalTest(TransactionTestCase):
  294. available_apps = []
  295. # Unfortunately with sqlite3 the in-memory test database cannot be closed,
  296. # and so it cannot be re-opened during testing.
  297. @skipUnlessDBFeature('test_db_allows_multiple_connections')
  298. def test_signal(self):
  299. data = {}
  300. def receiver(sender, connection, **kwargs):
  301. data["connection"] = connection
  302. connection_created.connect(receiver)
  303. connection.close()
  304. connection.cursor()
  305. self.assertTrue(data["connection"].connection is connection.connection)
  306. connection_created.disconnect(receiver)
  307. data.clear()
  308. connection.cursor()
  309. self.assertTrue(data == {})
  310. class EscapingChecks(TestCase):
  311. """
  312. All tests in this test case are also run with settings.DEBUG=True in
  313. EscapingChecksDebug test case, to also test CursorDebugWrapper.
  314. """
  315. # For Oracle, when you want to select a value, you need to specify the
  316. # special pseudo-table 'dual'; a select with no from clause is invalid.
  317. bare_select_suffix = " FROM DUAL" if connection.vendor == 'oracle' else ""
  318. def test_paramless_no_escaping(self):
  319. cursor = connection.cursor()
  320. cursor.execute("SELECT '%s'" + self.bare_select_suffix)
  321. self.assertEqual(cursor.fetchall()[0][0], '%s')
  322. def test_parameter_escaping(self):
  323. cursor = connection.cursor()
  324. cursor.execute("SELECT '%%', %s" + self.bare_select_suffix, ('%d',))
  325. self.assertEqual(cursor.fetchall()[0], ('%', '%d'))
  326. @unittest.skipUnless(connection.vendor == 'sqlite',
  327. "This is a sqlite-specific issue")
  328. def test_sqlite_parameter_escaping(self):
  329. #13648: '%s' escaping support for sqlite3
  330. cursor = connection.cursor()
  331. cursor.execute("select strftime('%s', date('now'))")
  332. response = cursor.fetchall()[0][0]
  333. # response should be an non-zero integer
  334. self.assertTrue(int(response))
  335. @override_settings(DEBUG=True)
  336. class EscapingChecksDebug(EscapingChecks):
  337. pass
  338. class SqliteAggregationTests(TestCase):
  339. """
  340. #19360: Raise NotImplementedError when aggregating on date/time fields.
  341. """
  342. @unittest.skipUnless(connection.vendor == 'sqlite',
  343. "No need to check SQLite aggregation semantics")
  344. def test_aggregation(self):
  345. for aggregate in (Sum, Avg, Variance, StdDev):
  346. self.assertRaises(NotImplementedError,
  347. models.Item.objects.all().aggregate, aggregate('time'))
  348. self.assertRaises(NotImplementedError,
  349. models.Item.objects.all().aggregate, aggregate('date'))
  350. self.assertRaises(NotImplementedError,
  351. models.Item.objects.all().aggregate, aggregate('last_modified'))
  352. class SqliteChecks(TestCase):
  353. @unittest.skipUnless(connection.vendor == 'sqlite',
  354. "No need to do SQLite checks")
  355. def test_convert_values_to_handle_null_value(self):
  356. database_operations = DatabaseOperations(connection)
  357. self.assertEqual(
  358. None,
  359. database_operations.convert_values(None, AutoField(primary_key=True))
  360. )
  361. self.assertEqual(
  362. None,
  363. database_operations.convert_values(None, DateField())
  364. )
  365. self.assertEqual(
  366. None,
  367. database_operations.convert_values(None, DateTimeField())
  368. )
  369. self.assertEqual(
  370. None,
  371. database_operations.convert_values(None, DecimalField())
  372. )
  373. self.assertEqual(
  374. None,
  375. database_operations.convert_values(None, IntegerField())
  376. )
  377. self.assertEqual(
  378. None,
  379. database_operations.convert_values(None, TimeField())
  380. )
  381. class BackendTestCase(TestCase):
  382. def create_squares_with_executemany(self, args):
  383. self.create_squares(args, 'format', True)
  384. def create_squares(self, args, paramstyle, multiple):
  385. cursor = connection.cursor()
  386. opts = models.Square._meta
  387. tbl = connection.introspection.table_name_converter(opts.db_table)
  388. f1 = connection.ops.quote_name(opts.get_field('root').column)
  389. f2 = connection.ops.quote_name(opts.get_field('square').column)
  390. if paramstyle=='format':
  391. query = 'INSERT INTO %s (%s, %s) VALUES (%%s, %%s)' % (tbl, f1, f2)
  392. elif paramstyle=='pyformat':
  393. query = 'INSERT INTO %s (%s, %s) VALUES (%%(root)s, %%(square)s)' % (tbl, f1, f2)
  394. else:
  395. raise ValueError("unsupported paramstyle in test")
  396. if multiple:
  397. cursor.executemany(query, args)
  398. else:
  399. cursor.execute(query, args)
  400. def test_cursor_executemany(self):
  401. #4896: Test cursor.executemany
  402. args = [(i, i**2) for i in range(-5, 6)]
  403. self.create_squares_with_executemany(args)
  404. self.assertEqual(models.Square.objects.count(), 11)
  405. for i in range(-5, 6):
  406. square = models.Square.objects.get(root=i)
  407. self.assertEqual(square.square, i**2)
  408. def test_cursor_executemany_with_empty_params_list(self):
  409. #4765: executemany with params=[] does nothing
  410. args = []
  411. self.create_squares_with_executemany(args)
  412. self.assertEqual(models.Square.objects.count(), 0)
  413. def test_cursor_executemany_with_iterator(self):
  414. #10320: executemany accepts iterators
  415. args = iter((i, i**2) for i in range(-3, 2))
  416. self.create_squares_with_executemany(args)
  417. self.assertEqual(models.Square.objects.count(), 5)
  418. args = iter((i, i**2) for i in range(3, 7))
  419. with override_settings(DEBUG=True):
  420. # same test for DebugCursorWrapper
  421. self.create_squares_with_executemany(args)
  422. self.assertEqual(models.Square.objects.count(), 9)
  423. @skipUnlessDBFeature('supports_paramstyle_pyformat')
  424. def test_cursor_execute_with_pyformat(self):
  425. #10070: Support pyformat style passing of paramters
  426. args = {'root': 3, 'square': 9}
  427. self.create_squares(args, 'pyformat', multiple=False)
  428. self.assertEqual(models.Square.objects.count(), 1)
  429. @skipUnlessDBFeature('supports_paramstyle_pyformat')
  430. def test_cursor_executemany_with_pyformat(self):
  431. #10070: Support pyformat style passing of paramters
  432. args = [{'root': i, 'square': i**2} for i in range(-5, 6)]
  433. self.create_squares(args, 'pyformat', multiple=True)
  434. self.assertEqual(models.Square.objects.count(), 11)
  435. for i in range(-5, 6):
  436. square = models.Square.objects.get(root=i)
  437. self.assertEqual(square.square, i**2)
  438. @skipUnlessDBFeature('supports_paramstyle_pyformat')
  439. def test_cursor_executemany_with_pyformat_iterator(self):
  440. args = iter({'root': i, 'square': i**2} for i in range(-3, 2))
  441. self.create_squares(args, 'pyformat', multiple=True)
  442. self.assertEqual(models.Square.objects.count(), 5)
  443. args = iter({'root': i, 'square': i**2} for i in range(3, 7))
  444. with override_settings(DEBUG=True):
  445. # same test for DebugCursorWrapper
  446. self.create_squares(args, 'pyformat', multiple=True)
  447. self.assertEqual(models.Square.objects.count(), 9)
  448. def test_unicode_fetches(self):
  449. #6254: fetchone, fetchmany, fetchall return strings as unicode objects
  450. qn = connection.ops.quote_name
  451. models.Person(first_name="John", last_name="Doe").save()
  452. models.Person(first_name="Jane", last_name="Doe").save()
  453. models.Person(first_name="Mary", last_name="Agnelline").save()
  454. models.Person(first_name="Peter", last_name="Parker").save()
  455. models.Person(first_name="Clark", last_name="Kent").save()
  456. opts2 = models.Person._meta
  457. f3, f4 = opts2.get_field('first_name'), opts2.get_field('last_name')
  458. query2 = ('SELECT %s, %s FROM %s ORDER BY %s'
  459. % (qn(f3.column), qn(f4.column), connection.introspection.table_name_converter(opts2.db_table),
  460. qn(f3.column)))
  461. cursor = connection.cursor()
  462. cursor.execute(query2)
  463. self.assertEqual(cursor.fetchone(), ('Clark', 'Kent'))
  464. self.assertEqual(list(cursor.fetchmany(2)), [('Jane', 'Doe'), ('John', 'Doe')])
  465. self.assertEqual(list(cursor.fetchall()), [('Mary', 'Agnelline'), ('Peter', 'Parker')])
  466. def test_unicode_password(self):
  467. old_password = connection.settings_dict['PASSWORD']
  468. connection.settings_dict['PASSWORD'] = "françois"
  469. try:
  470. connection.cursor()
  471. except DatabaseError:
  472. # As password is probably wrong, a database exception is expected
  473. pass
  474. except Exception as e:
  475. self.fail("Unexpected error raised with unicode password: %s" % e)
  476. finally:
  477. connection.settings_dict['PASSWORD'] = old_password
  478. def test_database_operations_helper_class(self):
  479. # Ticket #13630
  480. self.assertTrue(hasattr(connection, 'ops'))
  481. self.assertTrue(hasattr(connection.ops, 'connection'))
  482. self.assertEqual(connection, connection.ops.connection)
  483. def test_cached_db_features(self):
  484. self.assertIn(connection.features.supports_transactions, (True, False))
  485. self.assertIn(connection.features.supports_stddev, (True, False))
  486. self.assertIn(connection.features.can_introspect_foreign_keys, (True, False))
  487. def test_duplicate_table_error(self):
  488. """ Test that creating an existing table returns a DatabaseError """
  489. cursor = connection.cursor()
  490. query = 'CREATE TABLE %s (id INTEGER);' % models.Article._meta.db_table
  491. with self.assertRaises(DatabaseError):
  492. cursor.execute(query)
  493. # We don't make these tests conditional because that means we would need to
  494. # check and differentiate between:
  495. # * MySQL+InnoDB, MySQL+MYISAM (something we currently can't do).
  496. # * if sqlite3 (if/once we get #14204 fixed) has referential integrity turned
  497. # on or not, something that would be controlled by runtime support and user
  498. # preference.
  499. # verify if its type is django.database.db.IntegrityError.
  500. class FkConstraintsTests(TransactionTestCase):
  501. available_apps = ['backends']
  502. def setUp(self):
  503. # Create a Reporter.
  504. self.r = models.Reporter.objects.create(first_name='John', last_name='Smith')
  505. def test_integrity_checks_on_creation(self):
  506. """
  507. Try to create a model instance that violates a FK constraint. If it
  508. fails it should fail with IntegrityError.
  509. """
  510. a = models.Article(headline="This is a test", pub_date=datetime.datetime(2005, 7, 27), reporter_id=30)
  511. try:
  512. a.save()
  513. except IntegrityError:
  514. return
  515. self.skipTest("This backend does not support integrity checks.")
  516. def test_integrity_checks_on_update(self):
  517. """
  518. Try to update a model instance introducing a FK constraint violation.
  519. If it fails it should fail with IntegrityError.
  520. """
  521. # Create an Article.
  522. models.Article.objects.create(headline="Test article", pub_date=datetime.datetime(2010, 9, 4), reporter=self.r)
  523. # Retrive it from the DB
  524. a = models.Article.objects.get(headline="Test article")
  525. a.reporter_id = 30
  526. try:
  527. a.save()
  528. except IntegrityError:
  529. return
  530. self.skipTest("This backend does not support integrity checks.")
  531. def test_disable_constraint_checks_manually(self):
  532. """
  533. When constraint checks are disabled, should be able to write bad data without IntegrityErrors.
  534. """
  535. transaction.set_autocommit(False)
  536. try:
  537. # Create an Article.
  538. models.Article.objects.create(headline="Test article", pub_date=datetime.datetime(2010, 9, 4), reporter=self.r)
  539. # Retrive it from the DB
  540. a = models.Article.objects.get(headline="Test article")
  541. a.reporter_id = 30
  542. try:
  543. connection.disable_constraint_checking()
  544. a.save()
  545. connection.enable_constraint_checking()
  546. except IntegrityError:
  547. self.fail("IntegrityError should not have occurred.")
  548. finally:
  549. transaction.rollback()
  550. finally:
  551. transaction.set_autocommit(True)
  552. def test_disable_constraint_checks_context_manager(self):
  553. """
  554. When constraint checks are disabled (using context manager), should be able to write bad data without IntegrityErrors.
  555. """
  556. transaction.set_autocommit(False)
  557. try:
  558. # Create an Article.
  559. models.Article.objects.create(headline="Test article", pub_date=datetime.datetime(2010, 9, 4), reporter=self.r)
  560. # Retrive it from the DB
  561. a = models.Article.objects.get(headline="Test article")
  562. a.reporter_id = 30
  563. try:
  564. with connection.constraint_checks_disabled():
  565. a.save()
  566. except IntegrityError:
  567. self.fail("IntegrityError should not have occurred.")
  568. finally:
  569. transaction.rollback()
  570. finally:
  571. transaction.set_autocommit(True)
  572. def test_check_constraints(self):
  573. """
  574. Constraint checks should raise an IntegrityError when bad data is in the DB.
  575. """
  576. try:
  577. transaction.set_autocommit(False)
  578. # Create an Article.
  579. models.Article.objects.create(headline="Test article", pub_date=datetime.datetime(2010, 9, 4), reporter=self.r)
  580. # Retrive it from the DB
  581. a = models.Article.objects.get(headline="Test article")
  582. a.reporter_id = 30
  583. try:
  584. with connection.constraint_checks_disabled():
  585. a.save()
  586. with self.assertRaises(IntegrityError):
  587. connection.check_constraints()
  588. finally:
  589. transaction.rollback()
  590. finally:
  591. transaction.set_autocommit(True)
  592. class ThreadTests(TestCase):
  593. def test_default_connection_thread_local(self):
  594. """
  595. Ensure that the default connection (i.e. django.db.connection) is
  596. different for each thread.
  597. Refs #17258.
  598. """
  599. # Map connections by id because connections with identical aliases
  600. # have the same hash.
  601. connections_dict = {}
  602. connection.cursor()
  603. connections_dict[id(connection)] = connection
  604. def runner():
  605. # Passing django.db.connection between threads doesn't work while
  606. # connections[DEFAULT_DB_ALIAS] does.
  607. from django.db import connections
  608. connection = connections[DEFAULT_DB_ALIAS]
  609. # Allow thread sharing so the connection can be closed by the
  610. # main thread.
  611. connection.allow_thread_sharing = True
  612. connection.cursor()
  613. connections_dict[id(connection)] = connection
  614. for x in range(2):
  615. t = threading.Thread(target=runner)
  616. t.start()
  617. t.join()
  618. # Check that each created connection got different inner connection.
  619. self.assertEqual(
  620. len(set(conn.connection for conn in connections_dict.values())),
  621. 3)
  622. # Finish by closing the connections opened by the other threads (the
  623. # connection opened in the main thread will automatically be closed on
  624. # teardown).
  625. for conn in connections_dict.values():
  626. if conn is not connection:
  627. conn.close()
  628. def test_connections_thread_local(self):
  629. """
  630. Ensure that the connections are different for each thread.
  631. Refs #17258.
  632. """
  633. # Map connections by id because connections with identical aliases
  634. # have the same hash.
  635. connections_dict = {}
  636. for conn in connections.all():
  637. connections_dict[id(conn)] = conn
  638. def runner():
  639. from django.db import connections
  640. for conn in connections.all():
  641. # Allow thread sharing so the connection can be closed by the
  642. # main thread.
  643. conn.allow_thread_sharing = True
  644. connections_dict[id(conn)] = conn
  645. for x in range(2):
  646. t = threading.Thread(target=runner)
  647. t.start()
  648. t.join()
  649. self.assertEqual(len(connections_dict), 6)
  650. # Finish by closing the connections opened by the other threads (the
  651. # connection opened in the main thread will automatically be closed on
  652. # teardown).
  653. for conn in connections_dict.values():
  654. if conn is not connection:
  655. conn.close()
  656. def test_pass_connection_between_threads(self):
  657. """
  658. Ensure that a connection can be passed from one thread to the other.
  659. Refs #17258.
  660. """
  661. models.Person.objects.create(first_name="John", last_name="Doe")
  662. def do_thread():
  663. def runner(main_thread_connection):
  664. from django.db import connections
  665. connections['default'] = main_thread_connection
  666. try:
  667. models.Person.objects.get(first_name="John", last_name="Doe")
  668. except Exception as e:
  669. exceptions.append(e)
  670. t = threading.Thread(target=runner, args=[connections['default']])
  671. t.start()
  672. t.join()
  673. # Without touching allow_thread_sharing, which should be False by default.
  674. exceptions = []
  675. do_thread()
  676. # Forbidden!
  677. self.assertIsInstance(exceptions[0], DatabaseError)
  678. # If explicitly setting allow_thread_sharing to False
  679. connections['default'].allow_thread_sharing = False
  680. exceptions = []
  681. do_thread()
  682. # Forbidden!
  683. self.assertIsInstance(exceptions[0], DatabaseError)
  684. # If explicitly setting allow_thread_sharing to True
  685. connections['default'].allow_thread_sharing = True
  686. exceptions = []
  687. do_thread()
  688. # All good
  689. self.assertEqual(exceptions, [])
  690. def test_closing_non_shared_connections(self):
  691. """
  692. Ensure that a connection that is not explicitly shareable cannot be
  693. closed by another thread.
  694. Refs #17258.
  695. """
  696. # First, without explicitly enabling the connection for sharing.
  697. exceptions = set()
  698. def runner1():
  699. def runner2(other_thread_connection):
  700. try:
  701. other_thread_connection.close()
  702. except DatabaseError as e:
  703. exceptions.add(e)
  704. t2 = threading.Thread(target=runner2, args=[connections['default']])
  705. t2.start()
  706. t2.join()
  707. t1 = threading.Thread(target=runner1)
  708. t1.start()
  709. t1.join()
  710. # The exception was raised
  711. self.assertEqual(len(exceptions), 1)
  712. # Then, with explicitly enabling the connection for sharing.
  713. exceptions = set()
  714. def runner1():
  715. def runner2(other_thread_connection):
  716. try:
  717. other_thread_connection.close()
  718. except DatabaseError as e:
  719. exceptions.add(e)
  720. # Enable thread sharing
  721. connections['default'].allow_thread_sharing = True
  722. t2 = threading.Thread(target=runner2, args=[connections['default']])
  723. t2.start()
  724. t2.join()
  725. t1 = threading.Thread(target=runner1)
  726. t1.start()
  727. t1.join()
  728. # No exception was raised
  729. self.assertEqual(len(exceptions), 0)
  730. class MySQLPKZeroTests(TestCase):
  731. """
  732. Zero as id for AutoField should raise exception in MySQL, because MySQL
  733. does not allow zero for automatic primary key.
  734. """
  735. @skipIfDBFeature('allows_primary_key_0')
  736. def test_zero_as_autoval(self):
  737. with self.assertRaises(ValueError):
  738. models.Square.objects.create(id=0, root=0, square=1)
  739. class DBConstraintTestCase(TransactionTestCase):
  740. available_apps = ['backends']
  741. def test_can_reference_existant(self):
  742. obj = models.Object.objects.create()
  743. ref = models.ObjectReference.objects.create(obj=obj)
  744. self.assertEqual(ref.obj, obj)
  745. ref = models.ObjectReference.objects.get(obj=obj)
  746. self.assertEqual(ref.obj, obj)
  747. def test_can_reference_non_existant(self):
  748. self.assertFalse(models.Object.objects.filter(id=12345).exists())
  749. ref = models.ObjectReference.objects.create(obj_id=12345)
  750. ref_new = models.ObjectReference.objects.get(obj_id=12345)
  751. self.assertEqual(ref, ref_new)
  752. with self.assertRaises(models.Object.DoesNotExist):
  753. ref.obj
  754. def test_many_to_many(self):
  755. obj = models.Object.objects.create()
  756. obj.related_objects.create()
  757. self.assertEqual(models.Object.objects.count(), 2)
  758. self.assertEqual(obj.related_objects.count(), 1)
  759. intermediary_model = models.Object._meta.get_field_by_name("related_objects")[0].rel.through
  760. intermediary_model.objects.create(from_object_id=obj.id, to_object_id=12345)
  761. self.assertEqual(obj.related_objects.count(), 1)
  762. self.assertEqual(intermediary_model.objects.count(), 2)
  763. class BackendUtilTests(TestCase):
  764. def test_format_number(self):
  765. """
  766. Test the format_number converter utility
  767. """
  768. def equal(value, max_d, places, result):
  769. self.assertEqual(format_number(Decimal(value), max_d, places), result)
  770. equal('0', 12, 3,
  771. '0.000')
  772. equal('0', 12, 8,
  773. '0.00000000')
  774. equal('1', 12, 9,
  775. '1.000000000')
  776. equal('0.00000000', 12, 8,
  777. '0.00000000')
  778. equal('0.000000004', 12, 8,
  779. '0.00000000')
  780. equal('0.000000008', 12, 8,
  781. '0.00000001')
  782. equal('0.000000000000000000999', 10, 8,
  783. '0.00000000')
  784. equal('0.1234567890', 12, 10,
  785. '0.1234567890')
  786. equal('0.1234567890', 12, 9,
  787. '0.123456789')
  788. equal('0.1234567890', 12, 8,
  789. '0.12345679')
  790. equal('0.1234567890', 12, 5,
  791. '0.12346')
  792. equal('0.1234567890', 12, 3,
  793. '0.123')
  794. equal('0.1234567890', 12, 1,
  795. '0.1')
  796. equal('0.1234567890', 12, 0,
  797. '0')