tests.py 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  1. from unittest import mock
  2. from django.conf import settings
  3. from django.db import connection, models
  4. from django.test import SimpleTestCase, TestCase, skipUnlessDBFeature
  5. from django.test.utils import isolate_apps
  6. from .models import Book, ChildModel1, ChildModel2
  7. class SimpleIndexesTests(SimpleTestCase):
  8. def test_suffix(self):
  9. self.assertEqual(models.Index.suffix, 'idx')
  10. def test_repr(self):
  11. index = models.Index(fields=['title'])
  12. multi_col_index = models.Index(fields=['title', 'author'])
  13. partial_index = models.Index(fields=['title'], name='long_books_idx', condition=models.Q(pages__gt=400))
  14. covering_index = models.Index(
  15. fields=['title'],
  16. name='include_idx',
  17. include=['author', 'pages'],
  18. )
  19. self.assertEqual(repr(index), "<Index: fields='title'>")
  20. self.assertEqual(repr(multi_col_index), "<Index: fields='title, author'>")
  21. self.assertEqual(repr(partial_index), "<Index: fields='title', condition=(AND: ('pages__gt', 400))>")
  22. self.assertEqual(
  23. repr(covering_index),
  24. "<Index: fields='title', include='author, pages'>",
  25. )
  26. def test_eq(self):
  27. index = models.Index(fields=['title'])
  28. same_index = models.Index(fields=['title'])
  29. another_index = models.Index(fields=['title', 'author'])
  30. index.model = Book
  31. same_index.model = Book
  32. another_index.model = Book
  33. self.assertEqual(index, same_index)
  34. self.assertEqual(index, mock.ANY)
  35. self.assertNotEqual(index, another_index)
  36. def test_index_fields_type(self):
  37. with self.assertRaisesMessage(ValueError, 'Index.fields must be a list or tuple.'):
  38. models.Index(fields='title')
  39. def test_fields_tuple(self):
  40. self.assertEqual(models.Index(fields=('title',)).fields, ['title'])
  41. def test_raises_error_without_field(self):
  42. msg = 'At least one field is required to define an index.'
  43. with self.assertRaisesMessage(ValueError, msg):
  44. models.Index()
  45. def test_opclasses_requires_index_name(self):
  46. with self.assertRaisesMessage(ValueError, 'An index must be named to use opclasses.'):
  47. models.Index(opclasses=['jsonb_path_ops'])
  48. def test_opclasses_requires_list_or_tuple(self):
  49. with self.assertRaisesMessage(ValueError, 'Index.opclasses must be a list or tuple.'):
  50. models.Index(name='test_opclass', fields=['field'], opclasses='jsonb_path_ops')
  51. def test_opclasses_and_fields_same_length(self):
  52. msg = 'Index.fields and Index.opclasses must have the same number of elements.'
  53. with self.assertRaisesMessage(ValueError, msg):
  54. models.Index(name='test_opclass', fields=['field', 'other'], opclasses=['jsonb_path_ops'])
  55. def test_condition_requires_index_name(self):
  56. with self.assertRaisesMessage(ValueError, 'An index must be named to use condition.'):
  57. models.Index(condition=models.Q(pages__gt=400))
  58. def test_condition_must_be_q(self):
  59. with self.assertRaisesMessage(ValueError, 'Index.condition must be a Q instance.'):
  60. models.Index(condition='invalid', name='long_book_idx')
  61. def test_include_requires_list_or_tuple(self):
  62. msg = 'Index.include must be a list or tuple.'
  63. with self.assertRaisesMessage(ValueError, msg):
  64. models.Index(name='test_include', fields=['field'], include='other')
  65. def test_include_requires_index_name(self):
  66. msg = 'A covering index must be named.'
  67. with self.assertRaisesMessage(ValueError, msg):
  68. models.Index(fields=['field'], include=['other'])
  69. def test_name_auto_generation(self):
  70. index = models.Index(fields=['author'])
  71. index.set_name_with_model(Book)
  72. self.assertEqual(index.name, 'model_index_author_0f5565_idx')
  73. # '-' for DESC columns should be accounted for in the index name.
  74. index = models.Index(fields=['-author'])
  75. index.set_name_with_model(Book)
  76. self.assertEqual(index.name, 'model_index_author_708765_idx')
  77. # fields may be truncated in the name. db_column is used for naming.
  78. long_field_index = models.Index(fields=['pages'])
  79. long_field_index.set_name_with_model(Book)
  80. self.assertEqual(long_field_index.name, 'model_index_page_co_69235a_idx')
  81. # suffix can't be longer than 3 characters.
  82. long_field_index.suffix = 'suff'
  83. msg = 'Index too long for multiple database support. Is self.suffix longer than 3 characters?'
  84. with self.assertRaisesMessage(AssertionError, msg):
  85. long_field_index.set_name_with_model(Book)
  86. @isolate_apps('model_indexes')
  87. def test_name_auto_generation_with_quoted_db_table(self):
  88. class QuotedDbTable(models.Model):
  89. name = models.CharField(max_length=50)
  90. class Meta:
  91. db_table = '"t_quoted"'
  92. index = models.Index(fields=['name'])
  93. index.set_name_with_model(QuotedDbTable)
  94. self.assertEqual(index.name, 't_quoted_name_e4ed1b_idx')
  95. def test_deconstruction(self):
  96. index = models.Index(fields=['title'], db_tablespace='idx_tbls')
  97. index.set_name_with_model(Book)
  98. path, args, kwargs = index.deconstruct()
  99. self.assertEqual(path, 'django.db.models.Index')
  100. self.assertEqual(args, ())
  101. self.assertEqual(
  102. kwargs,
  103. {'fields': ['title'], 'name': 'model_index_title_196f42_idx', 'db_tablespace': 'idx_tbls'}
  104. )
  105. def test_deconstruct_with_condition(self):
  106. index = models.Index(
  107. name='big_book_index',
  108. fields=['title'],
  109. condition=models.Q(pages__gt=400),
  110. )
  111. index.set_name_with_model(Book)
  112. path, args, kwargs = index.deconstruct()
  113. self.assertEqual(path, 'django.db.models.Index')
  114. self.assertEqual(args, ())
  115. self.assertEqual(
  116. kwargs,
  117. {
  118. 'fields': ['title'],
  119. 'name': 'model_index_title_196f42_idx',
  120. 'condition': models.Q(pages__gt=400),
  121. }
  122. )
  123. def test_deconstruct_with_include(self):
  124. index = models.Index(
  125. name='book_include_idx',
  126. fields=['title'],
  127. include=['author'],
  128. )
  129. index.set_name_with_model(Book)
  130. path, args, kwargs = index.deconstruct()
  131. self.assertEqual(path, 'django.db.models.Index')
  132. self.assertEqual(args, ())
  133. self.assertEqual(
  134. kwargs,
  135. {
  136. 'fields': ['title'],
  137. 'name': 'model_index_title_196f42_idx',
  138. 'include': ('author',),
  139. },
  140. )
  141. def test_clone(self):
  142. index = models.Index(fields=['title'])
  143. new_index = index.clone()
  144. self.assertIsNot(index, new_index)
  145. self.assertEqual(index.fields, new_index.fields)
  146. def test_name_set(self):
  147. index_names = [index.name for index in Book._meta.indexes]
  148. self.assertCountEqual(
  149. index_names,
  150. [
  151. 'model_index_title_196f42_idx',
  152. 'model_index_isbn_34f975_idx',
  153. 'model_indexes_book_barcode_idx',
  154. ],
  155. )
  156. def test_abstract_children(self):
  157. index_names = [index.name for index in ChildModel1._meta.indexes]
  158. self.assertEqual(
  159. index_names,
  160. ['model_index_name_440998_idx', 'model_indexes_childmodel1_idx'],
  161. )
  162. index_names = [index.name for index in ChildModel2._meta.indexes]
  163. self.assertEqual(
  164. index_names,
  165. ['model_index_name_b6c374_idx', 'model_indexes_childmodel2_idx'],
  166. )
  167. class IndexesTests(TestCase):
  168. @skipUnlessDBFeature('supports_tablespaces')
  169. def test_db_tablespace(self):
  170. editor = connection.schema_editor()
  171. # Index with db_tablespace attribute.
  172. for fields in [
  173. # Field with db_tablespace specified on model.
  174. ['shortcut'],
  175. # Field without db_tablespace specified on model.
  176. ['author'],
  177. # Multi-column with db_tablespaces specified on model.
  178. ['shortcut', 'isbn'],
  179. # Multi-column without db_tablespace specified on model.
  180. ['title', 'author'],
  181. ]:
  182. with self.subTest(fields=fields):
  183. index = models.Index(fields=fields, db_tablespace='idx_tbls2')
  184. self.assertIn('"idx_tbls2"', str(index.create_sql(Book, editor)).lower())
  185. # Indexes without db_tablespace attribute.
  186. for fields in [['author'], ['shortcut', 'isbn'], ['title', 'author']]:
  187. with self.subTest(fields=fields):
  188. index = models.Index(fields=fields)
  189. # The DEFAULT_INDEX_TABLESPACE setting can't be tested because
  190. # it's evaluated when the model class is defined. As a
  191. # consequence, @override_settings doesn't work.
  192. if settings.DEFAULT_INDEX_TABLESPACE:
  193. self.assertIn(
  194. '"%s"' % settings.DEFAULT_INDEX_TABLESPACE,
  195. str(index.create_sql(Book, editor)).lower()
  196. )
  197. else:
  198. self.assertNotIn('TABLESPACE', str(index.create_sql(Book, editor)))
  199. # Field with db_tablespace specified on the model and an index without
  200. # db_tablespace.
  201. index = models.Index(fields=['shortcut'])
  202. self.assertIn('"idx_tbls"', str(index.create_sql(Book, editor)).lower())