tests.py 38 KB

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