2
0

tests.py 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  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, 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=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_name_auto_generation(self):
  52. index = models.Index(fields=['author'])
  53. index.set_name_with_model(Book)
  54. self.assertEqual(index.name, 'model_index_author_0f5565_idx')
  55. # '-' for DESC columns should be accounted for in the index name.
  56. index = models.Index(fields=['-author'])
  57. index.set_name_with_model(Book)
  58. self.assertEqual(index.name, 'model_index_author_708765_idx')
  59. # fields may be truncated in the name. db_column is used for naming.
  60. long_field_index = models.Index(fields=['pages'])
  61. long_field_index.set_name_with_model(Book)
  62. self.assertEqual(long_field_index.name, 'model_index_page_co_69235a_idx')
  63. # suffix can't be longer than 3 characters.
  64. long_field_index.suffix = 'suff'
  65. msg = 'Index too long for multiple database support. Is self.suffix longer than 3 characters?'
  66. with self.assertRaisesMessage(AssertionError, msg):
  67. long_field_index.set_name_with_model(Book)
  68. @isolate_apps('model_indexes')
  69. def test_name_auto_generation_with_quoted_db_table(self):
  70. class QuotedDbTable(models.Model):
  71. name = models.CharField(max_length=50)
  72. class Meta:
  73. db_table = '"t_quoted"'
  74. index = models.Index(fields=['name'])
  75. index.set_name_with_model(QuotedDbTable)
  76. self.assertEqual(index.name, 't_quoted_name_e4ed1b_idx')
  77. def test_deconstruction(self):
  78. index = models.Index(fields=['title'], db_tablespace='idx_tbls')
  79. index.set_name_with_model(Book)
  80. path, args, kwargs = index.deconstruct()
  81. self.assertEqual(path, 'django.db.models.Index')
  82. self.assertEqual(args, ())
  83. self.assertEqual(
  84. kwargs,
  85. {'fields': ['title'], 'name': 'model_index_title_196f42_idx', 'db_tablespace': 'idx_tbls'}
  86. )
  87. def test_deconstruct_with_condition(self):
  88. index = models.Index(
  89. name='big_book_index',
  90. fields=['title'],
  91. condition=Q(pages__gt=400),
  92. )
  93. index.set_name_with_model(Book)
  94. path, args, kwargs = index.deconstruct()
  95. self.assertEqual(path, 'django.db.models.Index')
  96. self.assertEqual(args, ())
  97. self.assertEqual(
  98. kwargs,
  99. {
  100. 'fields': ['title'],
  101. 'name': 'model_index_title_196f42_idx',
  102. 'condition': Q(pages__gt=400),
  103. }
  104. )
  105. def test_clone(self):
  106. index = models.Index(fields=['title'])
  107. new_index = index.clone()
  108. self.assertIsNot(index, new_index)
  109. self.assertEqual(index.fields, new_index.fields)
  110. def test_name_set(self):
  111. index_names = [index.name for index in Book._meta.indexes]
  112. self.assertCountEqual(
  113. index_names,
  114. [
  115. 'model_index_title_196f42_idx',
  116. 'model_index_isbn_34f975_idx',
  117. 'model_indexes_book_barcode_idx',
  118. ],
  119. )
  120. def test_abstract_children(self):
  121. index_names = [index.name for index in ChildModel1._meta.indexes]
  122. self.assertEqual(
  123. index_names,
  124. ['model_index_name_440998_idx', 'model_indexes_childmodel1_idx'],
  125. )
  126. index_names = [index.name for index in ChildModel2._meta.indexes]
  127. self.assertEqual(
  128. index_names,
  129. ['model_index_name_b6c374_idx', 'model_indexes_childmodel2_idx'],
  130. )
  131. class IndexesTests(TestCase):
  132. @skipUnlessDBFeature('supports_tablespaces')
  133. def test_db_tablespace(self):
  134. editor = connection.schema_editor()
  135. # Index with db_tablespace attribute.
  136. for fields in [
  137. # Field with db_tablespace specified on model.
  138. ['shortcut'],
  139. # Field without db_tablespace specified on model.
  140. ['author'],
  141. # Multi-column with db_tablespaces specified on model.
  142. ['shortcut', 'isbn'],
  143. # Multi-column without db_tablespace specified on model.
  144. ['title', 'author'],
  145. ]:
  146. with self.subTest(fields=fields):
  147. index = models.Index(fields=fields, db_tablespace='idx_tbls2')
  148. self.assertIn('"idx_tbls2"', str(index.create_sql(Book, editor)).lower())
  149. # Indexes without db_tablespace attribute.
  150. for fields in [['author'], ['shortcut', 'isbn'], ['title', 'author']]:
  151. with self.subTest(fields=fields):
  152. index = models.Index(fields=fields)
  153. # The DEFAULT_INDEX_TABLESPACE setting can't be tested because
  154. # it's evaluated when the model class is defined. As a
  155. # consequence, @override_settings doesn't work.
  156. if settings.DEFAULT_INDEX_TABLESPACE:
  157. self.assertIn(
  158. '"%s"' % settings.DEFAULT_INDEX_TABLESPACE,
  159. str(index.create_sql(Book, editor)).lower()
  160. )
  161. else:
  162. self.assertNotIn('TABLESPACE', str(index.create_sql(Book, editor)))
  163. # Field with db_tablespace specified on the model and an index without
  164. # db_tablespace.
  165. index = models.Index(fields=['shortcut'])
  166. self.assertIn('"idx_tbls"', str(index.create_sql(Book, editor)).lower())