tests.py 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  1. import re
  2. import threading
  3. import unittest
  4. from django.db import connection, transaction
  5. from django.db.models import Avg, StdDev, Sum, Variance
  6. from django.db.models.aggregates import Aggregate
  7. from django.db.models.fields import CharField
  8. from django.db.utils import NotSupportedError
  9. from django.test import (
  10. TestCase, TransactionTestCase, override_settings, skipIfDBFeature,
  11. )
  12. from django.test.utils import isolate_apps
  13. from ..models import Author, Item, Object, Square
  14. @unittest.skipUnless(connection.vendor == 'sqlite', 'SQLite tests')
  15. class Tests(TestCase):
  16. longMessage = True
  17. def test_aggregation(self):
  18. """
  19. Raise NotImplementedError when aggregating on date/time fields (#19360).
  20. """
  21. for aggregate in (Sum, Avg, Variance, StdDev):
  22. with self.assertRaises(NotSupportedError):
  23. Item.objects.all().aggregate(aggregate('time'))
  24. with self.assertRaises(NotSupportedError):
  25. Item.objects.all().aggregate(aggregate('date'))
  26. with self.assertRaises(NotSupportedError):
  27. Item.objects.all().aggregate(aggregate('last_modified'))
  28. with self.assertRaises(NotSupportedError):
  29. Item.objects.all().aggregate(
  30. **{'complex': aggregate('last_modified') + aggregate('last_modified')}
  31. )
  32. def test_distinct_aggregation(self):
  33. class DistinctAggregate(Aggregate):
  34. allow_distinct = True
  35. aggregate = DistinctAggregate('first', 'second', distinct=True)
  36. msg = (
  37. "SQLite doesn't support DISTINCT on aggregate functions accepting "
  38. "multiple arguments."
  39. )
  40. with self.assertRaisesMessage(NotSupportedError, msg):
  41. connection.ops.check_expression_support(aggregate)
  42. def test_memory_db_test_name(self):
  43. """A named in-memory db should be allowed where supported."""
  44. from django.db.backends.sqlite3.base import DatabaseWrapper
  45. settings_dict = {
  46. 'TEST': {
  47. 'NAME': 'file:memorydb_test?mode=memory&cache=shared',
  48. }
  49. }
  50. creation = DatabaseWrapper(settings_dict).creation
  51. self.assertEqual(creation._get_test_db_name(), creation.connection.settings_dict['TEST']['NAME'])
  52. def test_regexp_function(self):
  53. tests = (
  54. ('test', r'[0-9]+', False),
  55. ('test', r'[a-z]+', True),
  56. ('test', None, None),
  57. (None, r'[a-z]+', None),
  58. (None, None, None),
  59. )
  60. for string, pattern, expected in tests:
  61. with self.subTest((string, pattern)):
  62. with connection.cursor() as cursor:
  63. cursor.execute('SELECT %s REGEXP %s', [string, pattern])
  64. value = cursor.fetchone()[0]
  65. value = bool(value) if value in {0, 1} else value
  66. self.assertIs(value, expected)
  67. @unittest.skipUnless(connection.vendor == 'sqlite', 'SQLite tests')
  68. @isolate_apps('backends')
  69. class SchemaTests(TransactionTestCase):
  70. available_apps = ['backends']
  71. def test_autoincrement(self):
  72. """
  73. auto_increment fields are created with the AUTOINCREMENT keyword
  74. in order to be monotonically increasing (#10164).
  75. """
  76. with connection.schema_editor(collect_sql=True) as editor:
  77. editor.create_model(Square)
  78. statements = editor.collected_sql
  79. match = re.search('"id" ([^,]+),', statements[0])
  80. self.assertIsNotNone(match)
  81. self.assertEqual(
  82. 'integer NOT NULL PRIMARY KEY AUTOINCREMENT',
  83. match.group(1),
  84. 'Wrong SQL used to create an auto-increment column on SQLite'
  85. )
  86. def test_disable_constraint_checking_failure_disallowed(self):
  87. """
  88. SQLite schema editor is not usable within an outer transaction if
  89. foreign key constraint checks are not disabled beforehand.
  90. """
  91. msg = (
  92. 'SQLite schema editor cannot be used while foreign key '
  93. 'constraint checks are enabled. Make sure to disable them '
  94. 'before entering a transaction.atomic() context because '
  95. 'SQLite does not support disabling them in the middle of '
  96. 'a multi-statement transaction.'
  97. )
  98. with self.assertRaisesMessage(NotSupportedError, msg):
  99. with transaction.atomic(), connection.schema_editor(atomic=True):
  100. pass
  101. def test_constraint_checks_disabled_atomic_allowed(self):
  102. """
  103. SQLite schema editor is usable within an outer transaction as long as
  104. foreign key constraints checks are disabled beforehand.
  105. """
  106. def constraint_checks_enabled():
  107. with connection.cursor() as cursor:
  108. return bool(cursor.execute('PRAGMA foreign_keys').fetchone()[0])
  109. with connection.constraint_checks_disabled(), transaction.atomic():
  110. with connection.schema_editor(atomic=True):
  111. self.assertFalse(constraint_checks_enabled())
  112. self.assertFalse(constraint_checks_enabled())
  113. self.assertTrue(constraint_checks_enabled())
  114. @skipIfDBFeature('supports_atomic_references_rename')
  115. def test_field_rename_inside_atomic_block(self):
  116. """
  117. NotImplementedError is raised when a model field rename is attempted
  118. inside an atomic block.
  119. """
  120. new_field = CharField(max_length=255, unique=True)
  121. new_field.set_attributes_from_name('renamed')
  122. msg = (
  123. "Renaming the 'backends_author'.'name' column while in a "
  124. "transaction is not supported on SQLite < 3.26 because it would "
  125. "break referential integrity. Try adding `atomic = False` to the "
  126. "Migration class."
  127. )
  128. with self.assertRaisesMessage(NotSupportedError, msg):
  129. with connection.schema_editor(atomic=True) as editor:
  130. editor.alter_field(Author, Author._meta.get_field('name'), new_field)
  131. @skipIfDBFeature('supports_atomic_references_rename')
  132. def test_table_rename_inside_atomic_block(self):
  133. """
  134. NotImplementedError is raised when a table rename is attempted inside
  135. an atomic block.
  136. """
  137. msg = (
  138. "Renaming the 'backends_author' table while in a transaction is "
  139. "not supported on SQLite < 3.26 because it would break referential "
  140. "integrity. Try adding `atomic = False` to the Migration class."
  141. )
  142. with self.assertRaisesMessage(NotSupportedError, msg):
  143. with connection.schema_editor(atomic=True) as editor:
  144. editor.alter_db_table(Author, "backends_author", "renamed_table")
  145. @unittest.skipUnless(connection.vendor == 'sqlite', 'Test only for SQLite')
  146. @override_settings(DEBUG=True)
  147. class LastExecutedQueryTest(TestCase):
  148. def test_no_interpolation(self):
  149. # This shouldn't raise an exception (#17158)
  150. query = "SELECT strftime('%Y', 'now');"
  151. connection.cursor().execute(query)
  152. self.assertEqual(connection.queries[-1]['sql'], query)
  153. def test_parameter_quoting(self):
  154. # The implementation of last_executed_queries isn't optimal. It's
  155. # worth testing that parameters are quoted (#14091).
  156. query = "SELECT %s"
  157. params = ["\"'\\"]
  158. connection.cursor().execute(query, params)
  159. # Note that the single quote is repeated
  160. substituted = "SELECT '\"''\\'"
  161. self.assertEqual(connection.queries[-1]['sql'], substituted)
  162. def test_large_number_of_parameters(self):
  163. # If SQLITE_MAX_VARIABLE_NUMBER (default = 999) has been changed to be
  164. # greater than SQLITE_MAX_COLUMN (default = 2000), last_executed_query
  165. # can hit the SQLITE_MAX_COLUMN limit (#26063).
  166. with connection.cursor() as cursor:
  167. sql = "SELECT MAX(%s)" % ", ".join(["%s"] * 2001)
  168. params = list(range(2001))
  169. # This should not raise an exception.
  170. cursor.db.ops.last_executed_query(cursor.cursor, sql, params)
  171. @unittest.skipUnless(connection.vendor == 'sqlite', 'SQLite tests')
  172. class EscapingChecks(TestCase):
  173. """
  174. All tests in this test case are also run with settings.DEBUG=True in
  175. EscapingChecksDebug test case, to also test CursorDebugWrapper.
  176. """
  177. def test_parameter_escaping(self):
  178. # '%s' escaping support for sqlite3 (#13648).
  179. with connection.cursor() as cursor:
  180. cursor.execute("select strftime('%s', date('now'))")
  181. response = cursor.fetchall()[0][0]
  182. # response should be an non-zero integer
  183. self.assertTrue(int(response))
  184. @unittest.skipUnless(connection.vendor == 'sqlite', 'SQLite tests')
  185. @override_settings(DEBUG=True)
  186. class EscapingChecksDebug(EscapingChecks):
  187. pass
  188. @unittest.skipUnless(connection.vendor == 'sqlite', 'SQLite tests')
  189. class ThreadSharing(TransactionTestCase):
  190. available_apps = ['backends']
  191. def test_database_sharing_in_threads(self):
  192. def create_object():
  193. Object.objects.create()
  194. create_object()
  195. thread = threading.Thread(target=create_object)
  196. thread.start()
  197. thread.join()
  198. self.assertEqual(Object.objects.count(), 2)