tests.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. from unittest import mock, skipUnless
  2. from django.db import connection
  3. from django.db.models import Index
  4. from django.db.utils import DatabaseError
  5. from django.test import TransactionTestCase, skipUnlessDBFeature
  6. from django.test.utils import ignore_warnings
  7. from django.utils.deprecation import RemovedInDjango21Warning
  8. from .models import Article, ArticleReporter, City, District, Reporter
  9. class IntrospectionTests(TransactionTestCase):
  10. available_apps = ['introspection']
  11. def test_table_names(self):
  12. tl = connection.introspection.table_names()
  13. self.assertEqual(tl, sorted(tl))
  14. self.assertIn(Reporter._meta.db_table, tl, "'%s' isn't in table_list()." % Reporter._meta.db_table)
  15. self.assertIn(Article._meta.db_table, tl, "'%s' isn't in table_list()." % Article._meta.db_table)
  16. def test_django_table_names(self):
  17. with connection.cursor() as cursor:
  18. cursor.execute('CREATE TABLE django_ixn_test_table (id INTEGER);')
  19. tl = connection.introspection.django_table_names()
  20. cursor.execute("DROP TABLE django_ixn_test_table;")
  21. self.assertNotIn('django_ixn_test_table', tl,
  22. "django_table_names() returned a non-Django table")
  23. def test_django_table_names_retval_type(self):
  24. # Table name is a list #15216
  25. tl = connection.introspection.django_table_names(only_existing=True)
  26. self.assertIs(type(tl), list)
  27. tl = connection.introspection.django_table_names(only_existing=False)
  28. self.assertIs(type(tl), list)
  29. def test_table_names_with_views(self):
  30. with connection.cursor() as cursor:
  31. try:
  32. cursor.execute(
  33. 'CREATE VIEW introspection_article_view AS SELECT headline '
  34. 'from introspection_article;')
  35. except DatabaseError as e:
  36. if 'insufficient privileges' in str(e):
  37. self.fail("The test user has no CREATE VIEW privileges")
  38. else:
  39. raise
  40. self.assertIn('introspection_article_view', connection.introspection.table_names(include_views=True))
  41. self.assertNotIn('introspection_article_view', connection.introspection.table_names())
  42. def test_unmanaged_through_model(self):
  43. tables = connection.introspection.django_table_names()
  44. self.assertNotIn(ArticleReporter._meta.db_table, tables)
  45. def test_installed_models(self):
  46. tables = [Article._meta.db_table, Reporter._meta.db_table]
  47. models = connection.introspection.installed_models(tables)
  48. self.assertEqual(models, {Article, Reporter})
  49. def test_sequence_list(self):
  50. sequences = connection.introspection.sequence_list()
  51. expected = {'table': Reporter._meta.db_table, 'column': 'id'}
  52. self.assertIn(expected, sequences, 'Reporter sequence not found in sequence_list()')
  53. def test_get_table_description_names(self):
  54. with connection.cursor() as cursor:
  55. desc = connection.introspection.get_table_description(cursor, Reporter._meta.db_table)
  56. self.assertEqual([r[0] for r in desc],
  57. [f.column for f in Reporter._meta.fields])
  58. def test_get_table_description_types(self):
  59. with connection.cursor() as cursor:
  60. desc = connection.introspection.get_table_description(cursor, Reporter._meta.db_table)
  61. self.assertEqual(
  62. [datatype(r[1], r) for r in desc],
  63. ['AutoField' if connection.features.can_introspect_autofield else 'IntegerField',
  64. 'CharField', 'CharField', 'CharField',
  65. 'BigIntegerField' if connection.features.can_introspect_big_integer_field else 'IntegerField',
  66. 'BinaryField' if connection.features.can_introspect_binary_field else 'TextField',
  67. 'SmallIntegerField' if connection.features.can_introspect_small_integer_field else 'IntegerField']
  68. )
  69. def test_get_table_description_col_lengths(self):
  70. with connection.cursor() as cursor:
  71. desc = connection.introspection.get_table_description(cursor, Reporter._meta.db_table)
  72. self.assertEqual(
  73. [r[3] for r in desc if datatype(r[1], r) == 'CharField'],
  74. [30, 30, 254]
  75. )
  76. @skipUnlessDBFeature('can_introspect_null')
  77. def test_get_table_description_nullable(self):
  78. with connection.cursor() as cursor:
  79. desc = connection.introspection.get_table_description(cursor, Reporter._meta.db_table)
  80. nullable_by_backend = connection.features.interprets_empty_strings_as_nulls
  81. self.assertEqual(
  82. [r[6] for r in desc],
  83. [False, nullable_by_backend, nullable_by_backend, nullable_by_backend, True, True, False]
  84. )
  85. @skipUnlessDBFeature('can_introspect_autofield')
  86. def test_bigautofield(self):
  87. with connection.cursor() as cursor:
  88. desc = connection.introspection.get_table_description(cursor, City._meta.db_table)
  89. self.assertIn('BigAutoField', [datatype(r[1], r) for r in desc])
  90. # Regression test for #9991 - 'real' types in postgres
  91. @skipUnlessDBFeature('has_real_datatype')
  92. def test_postgresql_real_type(self):
  93. with connection.cursor() as cursor:
  94. cursor.execute("CREATE TABLE django_ixn_real_test_table (number REAL);")
  95. desc = connection.introspection.get_table_description(cursor, 'django_ixn_real_test_table')
  96. cursor.execute('DROP TABLE django_ixn_real_test_table;')
  97. self.assertEqual(datatype(desc[0][1], desc[0]), 'FloatField')
  98. @skipUnlessDBFeature('can_introspect_foreign_keys')
  99. def test_get_relations(self):
  100. with connection.cursor() as cursor:
  101. relations = connection.introspection.get_relations(cursor, Article._meta.db_table)
  102. # That's {field_name: (field_name_other_table, other_table)}
  103. expected_relations = {
  104. 'reporter_id': ('id', Reporter._meta.db_table),
  105. 'response_to_id': ('id', Article._meta.db_table),
  106. }
  107. self.assertEqual(relations, expected_relations)
  108. # Removing a field shouldn't disturb get_relations (#17785)
  109. body = Article._meta.get_field('body')
  110. with connection.schema_editor() as editor:
  111. editor.remove_field(Article, body)
  112. with connection.cursor() as cursor:
  113. relations = connection.introspection.get_relations(cursor, Article._meta.db_table)
  114. with connection.schema_editor() as editor:
  115. editor.add_field(Article, body)
  116. self.assertEqual(relations, expected_relations)
  117. @skipUnless(connection.vendor == 'sqlite', "This is an sqlite-specific issue")
  118. def test_get_relations_alt_format(self):
  119. """
  120. With SQLite, foreign keys can be added with different syntaxes and
  121. formatting.
  122. """
  123. create_table_statements = [
  124. "CREATE TABLE track(id, art_id INTEGER, FOREIGN KEY(art_id) REFERENCES {}(id));",
  125. "CREATE TABLE track(id, art_id INTEGER, FOREIGN KEY (art_id) REFERENCES {}(id));"
  126. ]
  127. for statement in create_table_statements:
  128. with connection.cursor() as cursor:
  129. cursor.fetchone = mock.Mock(return_value=[statement.format(Article._meta.db_table)])
  130. relations = connection.introspection.get_relations(cursor, 'mocked_table')
  131. self.assertEqual(relations, {'art_id': ('id', Article._meta.db_table)})
  132. @skipUnlessDBFeature('can_introspect_foreign_keys')
  133. def test_get_key_columns(self):
  134. with connection.cursor() as cursor:
  135. key_columns = connection.introspection.get_key_columns(cursor, Article._meta.db_table)
  136. self.assertEqual(
  137. set(key_columns),
  138. {('reporter_id', Reporter._meta.db_table, 'id'),
  139. ('response_to_id', Article._meta.db_table, 'id')})
  140. def test_get_primary_key_column(self):
  141. with connection.cursor() as cursor:
  142. primary_key_column = connection.introspection.get_primary_key_column(cursor, Article._meta.db_table)
  143. pk_fk_column = connection.introspection.get_primary_key_column(cursor, District._meta.db_table)
  144. self.assertEqual(primary_key_column, 'id')
  145. self.assertEqual(pk_fk_column, 'city_id')
  146. @ignore_warnings(category=RemovedInDjango21Warning)
  147. def test_get_indexes(self):
  148. with connection.cursor() as cursor:
  149. indexes = connection.introspection.get_indexes(cursor, Article._meta.db_table)
  150. self.assertEqual(indexes['reporter_id'], {'unique': False, 'primary_key': False})
  151. @ignore_warnings(category=RemovedInDjango21Warning)
  152. def test_get_indexes_multicol(self):
  153. """
  154. Multicolumn indexes are not included in the introspection results.
  155. """
  156. with connection.cursor() as cursor:
  157. indexes = connection.introspection.get_indexes(cursor, Reporter._meta.db_table)
  158. self.assertNotIn('first_name', indexes)
  159. self.assertIn('id', indexes)
  160. def test_get_constraints_index_types(self):
  161. with connection.cursor() as cursor:
  162. constraints = connection.introspection.get_constraints(cursor, Article._meta.db_table)
  163. index = {}
  164. index2 = {}
  165. for key, val in constraints.items():
  166. if val['columns'] == ['headline', 'pub_date']:
  167. index = val
  168. if val['columns'] == ['headline', 'response_to_id', 'pub_date', 'reporter_id']:
  169. index2 = val
  170. self.assertEqual(index['type'], Index.suffix)
  171. self.assertEqual(index2['type'], Index.suffix)
  172. @skipUnlessDBFeature('supports_index_column_ordering')
  173. def test_get_constraints_indexes_orders(self):
  174. """
  175. Indexes have the 'orders' key with a list of 'ASC'/'DESC' values.
  176. """
  177. with connection.cursor() as cursor:
  178. constraints = connection.introspection.get_constraints(cursor, Article._meta.db_table)
  179. indexes_verified = 0
  180. expected_columns = [
  181. ['reporter_id'],
  182. ['headline', 'pub_date'],
  183. ['response_to_id'],
  184. ['headline', 'response_to_id', 'pub_date', 'reporter_id'],
  185. ]
  186. for key, val in constraints.items():
  187. if val['index'] and not (val['primary_key'] or val['unique']):
  188. self.assertIn(val['columns'], expected_columns)
  189. self.assertEqual(val['orders'], ['ASC'] * len(val['columns']))
  190. indexes_verified += 1
  191. self.assertEqual(indexes_verified, 4)
  192. def datatype(dbtype, description):
  193. """Helper to convert a data type into a string."""
  194. dt = connection.introspection.get_field_type(dbtype, description)
  195. if type(dt) is tuple:
  196. return dt[0]
  197. else:
  198. return dt