tests.py 40 KB

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