2
0

tests.py 7.1 KB

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