tests.py 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  1. from __future__ import unicode_literals
  2. from unittest import skipUnless
  3. from django.db import connection
  4. from django.db.utils import DatabaseError
  5. from django.test import TransactionTestCase, mock, skipUnlessDBFeature
  6. from .models import Article, Reporter
  7. class IntrospectionTests(TransactionTestCase):
  8. available_apps = ['introspection']
  9. def test_table_names(self):
  10. tl = connection.introspection.table_names()
  11. self.assertEqual(tl, sorted(tl))
  12. self.assertIn(Reporter._meta.db_table, tl,
  13. "'%s' isn't in table_list()." % Reporter._meta.db_table)
  14. self.assertIn(Article._meta.db_table, tl,
  15. "'%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',
  41. connection.introspection.table_names(include_views=True))
  42. self.assertNotIn('introspection_article_view',
  43. connection.introspection.table_names())
  44. def test_installed_models(self):
  45. tables = [Article._meta.db_table, Reporter._meta.db_table]
  46. models = connection.introspection.installed_models(tables)
  47. self.assertEqual(models, {Article, Reporter})
  48. def test_sequence_list(self):
  49. sequences = connection.introspection.sequence_list()
  50. expected = {'table': Reporter._meta.db_table, 'column': 'id'}
  51. self.assertIn(expected, sequences,
  52. '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. # The following test fails on Oracle due to #17202 (can't correctly
  70. # inspect the length of character columns).
  71. @skipUnlessDBFeature('can_introspect_max_length')
  72. def test_get_table_description_col_lengths(self):
  73. with connection.cursor() as cursor:
  74. desc = connection.introspection.get_table_description(cursor, Reporter._meta.db_table)
  75. self.assertEqual(
  76. [r[3] for r in desc if datatype(r[1], r) == 'CharField'],
  77. [30, 30, 254]
  78. )
  79. @skipUnlessDBFeature('can_introspect_null')
  80. def test_get_table_description_nullable(self):
  81. with connection.cursor() as cursor:
  82. desc = connection.introspection.get_table_description(cursor, Reporter._meta.db_table)
  83. nullable_by_backend = connection.features.interprets_empty_strings_as_nulls
  84. self.assertEqual(
  85. [r[6] for r in desc],
  86. [False, nullable_by_backend, nullable_by_backend, nullable_by_backend, True, True, False]
  87. )
  88. # Regression test for #9991 - 'real' types in postgres
  89. @skipUnlessDBFeature('has_real_datatype')
  90. def test_postgresql_real_type(self):
  91. with connection.cursor() as cursor:
  92. cursor.execute("CREATE TABLE django_ixn_real_test_table (number REAL);")
  93. desc = connection.introspection.get_table_description(cursor, 'django_ixn_real_test_table')
  94. cursor.execute('DROP TABLE django_ixn_real_test_table;')
  95. self.assertEqual(datatype(desc[0][1], desc[0]), 'FloatField')
  96. @skipUnlessDBFeature('can_introspect_foreign_keys')
  97. def test_get_relations(self):
  98. with connection.cursor() as cursor:
  99. relations = connection.introspection.get_relations(cursor, Article._meta.db_table)
  100. # That's {field_name: (field_name_other_table, other_table)}
  101. expected_relations = {
  102. 'reporter_id': ('id', Reporter._meta.db_table),
  103. 'response_to_id': ('id', Article._meta.db_table),
  104. }
  105. self.assertEqual(relations, expected_relations)
  106. # Removing a field shouldn't disturb get_relations (#17785)
  107. body = Article._meta.get_field('body')
  108. with connection.schema_editor() as editor:
  109. editor.remove_field(Article, body)
  110. with connection.cursor() as cursor:
  111. relations = connection.introspection.get_relations(cursor, Article._meta.db_table)
  112. with connection.schema_editor() as editor:
  113. editor.add_field(Article, body)
  114. self.assertEqual(relations, expected_relations)
  115. @skipUnless(connection.vendor == 'sqlite', "This is an sqlite-specific issue")
  116. def test_get_relations_alt_format(self):
  117. """With SQLite, foreign keys can be added with different syntaxes."""
  118. with connection.cursor() as cursor:
  119. cursor.fetchone = mock.Mock(return_value=[
  120. "CREATE TABLE track(id, art_id INTEGER, FOREIGN KEY(art_id) REFERENCES %s(id));" % Article._meta.db_table
  121. ])
  122. relations = connection.introspection.get_relations(cursor, 'mocked_table')
  123. self.assertEqual(relations, {'art_id': ('id', Article._meta.db_table)})
  124. @skipUnlessDBFeature('can_introspect_foreign_keys')
  125. def test_get_key_columns(self):
  126. with connection.cursor() as cursor:
  127. key_columns = connection.introspection.get_key_columns(cursor, Article._meta.db_table)
  128. self.assertEqual(
  129. set(key_columns),
  130. {('reporter_id', Reporter._meta.db_table, 'id'),
  131. ('response_to_id', Article._meta.db_table, 'id')})
  132. def test_get_primary_key_column(self):
  133. with connection.cursor() as cursor:
  134. primary_key_column = connection.introspection.get_primary_key_column(cursor, Article._meta.db_table)
  135. self.assertEqual(primary_key_column, 'id')
  136. def test_get_indexes(self):
  137. with connection.cursor() as cursor:
  138. indexes = connection.introspection.get_indexes(cursor, Article._meta.db_table)
  139. self.assertEqual(indexes['reporter_id'], {'unique': False, 'primary_key': False})
  140. def test_get_indexes_multicol(self):
  141. """
  142. Test that multicolumn indexes are not included in the introspection
  143. results.
  144. """
  145. with connection.cursor() as cursor:
  146. indexes = connection.introspection.get_indexes(cursor, Reporter._meta.db_table)
  147. self.assertNotIn('first_name', indexes)
  148. self.assertIn('id', indexes)
  149. def datatype(dbtype, description):
  150. """Helper to convert a data type into a string."""
  151. dt = connection.introspection.get_field_type(dbtype, description)
  152. if type(dt) is tuple:
  153. return dt[0]
  154. else:
  155. return dt