tests.py 32 KB

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