tests.py 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  1. from __future__ import absolute_import, unicode_literals
  2. from functools import update_wrapper
  3. from django.db import connection
  4. from django.test import TestCase, skipUnlessDBFeature, skipIfDBFeature
  5. from django.utils import six, unittest
  6. from .models import Reporter, Article
  7. if connection.vendor == 'oracle':
  8. expectedFailureOnOracle = unittest.expectedFailure
  9. else:
  10. expectedFailureOnOracle = lambda f: f
  11. # The introspection module is optional, so methods tested here might raise
  12. # NotImplementedError. This is perfectly acceptable behavior for the backend
  13. # in question, but the tests need to handle this without failing. Ideally we'd
  14. # skip these tests, but until #4788 is done we'll just ignore them.
  15. #
  16. # The easiest way to accomplish this is to decorate every test case with a
  17. # wrapper that ignores the exception.
  18. #
  19. # The metaclass is just for fun.
  20. def ignore_not_implemented(func):
  21. def _inner(*args, **kwargs):
  22. try:
  23. return func(*args, **kwargs)
  24. except NotImplementedError:
  25. return None
  26. update_wrapper(_inner, func)
  27. return _inner
  28. class IgnoreNotimplementedError(type):
  29. def __new__(cls, name, bases, attrs):
  30. for k, v in attrs.items():
  31. if k.startswith('test'):
  32. attrs[k] = ignore_not_implemented(v)
  33. return type.__new__(cls, name, bases, attrs)
  34. class IntrospectionTests(six.with_metaclass(IgnoreNotimplementedError, TestCase)):
  35. def test_table_names(self):
  36. tl = connection.introspection.table_names()
  37. self.assertEqual(tl, sorted(tl))
  38. self.assertTrue(Reporter._meta.db_table in tl,
  39. "'%s' isn't in table_list()." % Reporter._meta.db_table)
  40. self.assertTrue(Article._meta.db_table in tl,
  41. "'%s' isn't in table_list()." % Article._meta.db_table)
  42. def test_django_table_names(self):
  43. cursor = connection.cursor()
  44. cursor.execute('CREATE TABLE django_ixn_test_table (id INTEGER);')
  45. tl = connection.introspection.django_table_names()
  46. cursor.execute("DROP TABLE django_ixn_test_table;")
  47. self.assertTrue('django_ixn_testcase_table' not in tl,
  48. "django_table_names() returned a non-Django table")
  49. def test_django_table_names_retval_type(self):
  50. # Ticket #15216
  51. cursor = connection.cursor()
  52. cursor.execute('CREATE TABLE django_ixn_test_table (id INTEGER);')
  53. tl = connection.introspection.django_table_names(only_existing=True)
  54. self.assertIs(type(tl), list)
  55. tl = connection.introspection.django_table_names(only_existing=False)
  56. self.assertIs(type(tl), list)
  57. def test_installed_models(self):
  58. tables = [Article._meta.db_table, Reporter._meta.db_table]
  59. models = connection.introspection.installed_models(tables)
  60. self.assertEqual(models, set([Article, Reporter]))
  61. def test_sequence_list(self):
  62. sequences = connection.introspection.sequence_list()
  63. expected = {'table': Reporter._meta.db_table, 'column': 'id'}
  64. self.assertTrue(expected in sequences,
  65. 'Reporter sequence not found in sequence_list()')
  66. def test_get_table_description_names(self):
  67. cursor = connection.cursor()
  68. desc = connection.introspection.get_table_description(cursor, Reporter._meta.db_table)
  69. self.assertEqual([r[0] for r in desc],
  70. [f.column for f in Reporter._meta.fields])
  71. def test_get_table_description_types(self):
  72. cursor = connection.cursor()
  73. desc = connection.introspection.get_table_description(cursor, Reporter._meta.db_table)
  74. self.assertEqual(
  75. [datatype(r[1], r) for r in desc],
  76. ['IntegerField', 'CharField', 'CharField', 'CharField', 'BigIntegerField']
  77. )
  78. # The following test fails on Oracle due to #17202 (can't correctly
  79. # inspect the length of character columns).
  80. @expectedFailureOnOracle
  81. def test_get_table_description_col_lengths(self):
  82. cursor = connection.cursor()
  83. desc = connection.introspection.get_table_description(cursor, Reporter._meta.db_table)
  84. self.assertEqual(
  85. [r[3] for r in desc if datatype(r[1], r) == 'CharField'],
  86. [30, 30, 75]
  87. )
  88. # Oracle forces null=True under the hood in some cases (see
  89. # https://docs.djangoproject.com/en/dev/ref/databases/#null-and-empty-strings)
  90. # so its idea about null_ok in cursor.description is different from ours.
  91. @skipIfDBFeature('interprets_empty_strings_as_nulls')
  92. def test_get_table_description_nullable(self):
  93. cursor = connection.cursor()
  94. desc = connection.introspection.get_table_description(cursor, Reporter._meta.db_table)
  95. self.assertEqual(
  96. [r[6] for r in desc],
  97. [False, False, False, False, True]
  98. )
  99. # Regression test for #9991 - 'real' types in postgres
  100. @skipUnlessDBFeature('has_real_datatype')
  101. def test_postgresql_real_type(self):
  102. cursor = connection.cursor()
  103. cursor.execute("CREATE TABLE django_ixn_real_test_table (number REAL);")
  104. desc = connection.introspection.get_table_description(cursor, 'django_ixn_real_test_table')
  105. cursor.execute('DROP TABLE django_ixn_real_test_table;')
  106. self.assertEqual(datatype(desc[0][1], desc[0]), 'FloatField')
  107. def test_get_relations(self):
  108. cursor = connection.cursor()
  109. relations = connection.introspection.get_relations(cursor, Article._meta.db_table)
  110. # Older versions of MySQL don't have the chops to report on this stuff,
  111. # so just skip it if no relations come back. If they do, though, we
  112. # should test that the response is correct.
  113. if relations:
  114. # That's {field_index: (field_index_other_table, other_table)}
  115. self.assertEqual(relations, {3: (0, Reporter._meta.db_table)})
  116. def test_get_key_columns(self):
  117. cursor = connection.cursor()
  118. key_columns = connection.introspection.get_key_columns(cursor, Article._meta.db_table)
  119. self.assertEqual(key_columns, [('reporter_id', Reporter._meta.db_table, 'id')])
  120. def test_get_primary_key_column(self):
  121. cursor = connection.cursor()
  122. primary_key_column = connection.introspection.get_primary_key_column(cursor, Article._meta.db_table)
  123. self.assertEqual(primary_key_column, 'id')
  124. def test_get_indexes(self):
  125. cursor = connection.cursor()
  126. indexes = connection.introspection.get_indexes(cursor, Article._meta.db_table)
  127. self.assertEqual(indexes['reporter_id'], {'unique': False, 'primary_key': False})
  128. def test_get_indexes_multicol(self):
  129. """
  130. Test that multicolumn indexes are not included in the introspection
  131. results.
  132. """
  133. cursor = connection.cursor()
  134. indexes = connection.introspection.get_indexes(cursor, Reporter._meta.db_table)
  135. self.assertNotIn('first_name', indexes)
  136. self.assertIn('id', indexes)
  137. def datatype(dbtype, description):
  138. """Helper to convert a data type into a string."""
  139. dt = connection.introspection.get_field_type(dbtype, description)
  140. if type(dt) is tuple:
  141. return dt[0]
  142. else:
  143. return dt