tests.py 8.6 KB

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