tests.py 11 KB

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