tests.py 41 KB

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