tests.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  1. import re
  2. from io import StringIO
  3. from unittest import mock, skipUnless
  4. from django.core.management import call_command
  5. from django.db import connection
  6. from django.db.backends.base.introspection import TableInfo
  7. from django.test import TestCase, TransactionTestCase, skipUnlessDBFeature
  8. from .models import PeopleMoreData
  9. def inspectdb_tables_only(table_name):
  10. """
  11. Limit introspection to tables created for models of this app.
  12. Some databases such as Oracle are extremely slow at introspection.
  13. """
  14. return table_name.startswith('inspectdb_')
  15. def special_table_only(table_name):
  16. return table_name.startswith('inspectdb_special')
  17. class InspectDBTestCase(TestCase):
  18. unique_re = re.compile(r'.*unique_together = \((.+),\).*')
  19. def test_stealth_table_name_filter_option(self):
  20. out = StringIO()
  21. call_command('inspectdb', table_name_filter=inspectdb_tables_only, stdout=out)
  22. error_message = "inspectdb has examined a table that should have been filtered out."
  23. # contrib.contenttypes is one of the apps always installed when running
  24. # the Django test suite, check that one of its tables hasn't been
  25. # inspected
  26. self.assertNotIn("class DjangoContentType(models.Model):", out.getvalue(), msg=error_message)
  27. def test_table_option(self):
  28. """
  29. inspectdb can inspect a subset of tables by passing the table names as
  30. arguments.
  31. """
  32. out = StringIO()
  33. call_command('inspectdb', 'inspectdb_people', stdout=out)
  34. output = out.getvalue()
  35. self.assertIn('class InspectdbPeople(models.Model):', output)
  36. self.assertNotIn("InspectdbPeopledata", output)
  37. def make_field_type_asserter(self):
  38. """Call inspectdb and return a function to validate a field type in its output"""
  39. out = StringIO()
  40. call_command('inspectdb', 'inspectdb_columntypes', stdout=out)
  41. output = out.getvalue()
  42. def assertFieldType(name, definition):
  43. out_def = re.search(r'^\s*%s = (models.*)$' % name, output, re.MULTILINE).groups()[0]
  44. self.assertEqual(definition, out_def)
  45. return assertFieldType
  46. def test_field_types(self):
  47. """Test introspection of various Django field types"""
  48. assertFieldType = self.make_field_type_asserter()
  49. # Inspecting Oracle DB doesn't produce correct results (#19884):
  50. # - it reports fields as blank=True when they aren't.
  51. if not connection.features.interprets_empty_strings_as_nulls:
  52. assertFieldType('char_field', "models.CharField(max_length=10)")
  53. assertFieldType('null_char_field', "models.CharField(max_length=10, blank=True, null=True)")
  54. assertFieldType('email_field', "models.CharField(max_length=254)")
  55. assertFieldType('file_field', "models.CharField(max_length=100)")
  56. assertFieldType('file_path_field', "models.CharField(max_length=100)")
  57. assertFieldType('slug_field', "models.CharField(max_length=50)")
  58. assertFieldType('text_field', "models.TextField()")
  59. assertFieldType('url_field', "models.CharField(max_length=200)")
  60. assertFieldType('date_field', "models.DateField()")
  61. assertFieldType('date_time_field', "models.DateTimeField()")
  62. if connection.features.can_introspect_ip_address_field:
  63. assertFieldType('gen_ip_address_field', "models.GenericIPAddressField()")
  64. elif not connection.features.interprets_empty_strings_as_nulls:
  65. assertFieldType('gen_ip_address_field', "models.CharField(max_length=39)")
  66. if connection.features.can_introspect_time_field:
  67. assertFieldType('time_field', "models.TimeField()")
  68. if connection.features.has_native_uuid_field:
  69. assertFieldType('uuid_field', "models.UUIDField()")
  70. elif not connection.features.interprets_empty_strings_as_nulls:
  71. assertFieldType('uuid_field', "models.CharField(max_length=32)")
  72. def test_number_field_types(self):
  73. """Test introspection of various Django field types"""
  74. assertFieldType = self.make_field_type_asserter()
  75. if not connection.features.can_introspect_autofield:
  76. assertFieldType('id', "models.IntegerField(primary_key=True) # AutoField?")
  77. if connection.features.can_introspect_big_integer_field:
  78. assertFieldType('big_int_field', "models.BigIntegerField()")
  79. else:
  80. assertFieldType('big_int_field', "models.IntegerField()")
  81. bool_field_type = connection.features.introspected_boolean_field_type
  82. assertFieldType('bool_field', "models.{}()".format(bool_field_type))
  83. assertFieldType('null_bool_field', 'models.{}(blank=True, null=True)'.format(bool_field_type))
  84. if connection.features.can_introspect_decimal_field:
  85. assertFieldType('decimal_field', "models.DecimalField(max_digits=6, decimal_places=1)")
  86. else: # Guessed arguments on SQLite, see #5014
  87. assertFieldType('decimal_field', "models.DecimalField(max_digits=10, decimal_places=5) "
  88. "# max_digits and decimal_places have been guessed, "
  89. "as this database handles decimal fields as float")
  90. assertFieldType('float_field', "models.FloatField()")
  91. assertFieldType('int_field', "models.IntegerField()")
  92. if connection.features.can_introspect_positive_integer_field:
  93. assertFieldType('pos_int_field', "models.PositiveIntegerField()")
  94. else:
  95. assertFieldType('pos_int_field', "models.IntegerField()")
  96. if connection.features.can_introspect_positive_integer_field:
  97. if connection.features.can_introspect_big_integer_field:
  98. assertFieldType('pos_big_int_field', 'models.PositiveBigIntegerField()')
  99. else:
  100. assertFieldType('pos_big_int_field', 'models.PositiveIntegerField()')
  101. if connection.features.can_introspect_small_integer_field:
  102. assertFieldType('pos_small_int_field', "models.PositiveSmallIntegerField()")
  103. else:
  104. assertFieldType('pos_small_int_field', "models.PositiveIntegerField()")
  105. else:
  106. if connection.features.can_introspect_big_integer_field:
  107. assertFieldType('pos_big_int_field', 'models.BigIntegerField()')
  108. else:
  109. assertFieldType('pos_big_int_field', 'models.IntegerField()')
  110. if connection.features.can_introspect_small_integer_field:
  111. assertFieldType('pos_small_int_field', "models.SmallIntegerField()")
  112. else:
  113. assertFieldType('pos_small_int_field', "models.IntegerField()")
  114. if connection.features.can_introspect_small_integer_field:
  115. assertFieldType('small_int_field', "models.SmallIntegerField()")
  116. else:
  117. assertFieldType('small_int_field', "models.IntegerField()")
  118. @skipUnlessDBFeature('can_introspect_foreign_keys')
  119. def test_attribute_name_not_python_keyword(self):
  120. out = StringIO()
  121. call_command('inspectdb', table_name_filter=inspectdb_tables_only, stdout=out)
  122. output = out.getvalue()
  123. error_message = "inspectdb generated an attribute name which is a Python keyword"
  124. # Recursive foreign keys should be set to 'self'
  125. self.assertIn("parent = models.ForeignKey('self', models.DO_NOTHING)", output)
  126. self.assertNotIn(
  127. "from = models.ForeignKey(InspectdbPeople, models.DO_NOTHING)",
  128. output,
  129. msg=error_message,
  130. )
  131. # As InspectdbPeople model is defined after InspectdbMessage, it should be quoted
  132. self.assertIn(
  133. "from_field = models.ForeignKey('InspectdbPeople', models.DO_NOTHING, db_column='from_id')",
  134. output,
  135. )
  136. self.assertIn(
  137. 'people_pk = models.OneToOneField(InspectdbPeople, models.DO_NOTHING, primary_key=True)',
  138. output,
  139. )
  140. self.assertIn(
  141. 'people_unique = models.OneToOneField(InspectdbPeople, models.DO_NOTHING)',
  142. output,
  143. )
  144. def test_digits_column_name_introspection(self):
  145. """Introspection of column names consist/start with digits (#16536/#17676)"""
  146. out = StringIO()
  147. call_command('inspectdb', 'inspectdb_digitsincolumnname', stdout=out)
  148. output = out.getvalue()
  149. error_message = "inspectdb generated a model field name which is a number"
  150. self.assertNotIn(" 123 = models.CharField", output, msg=error_message)
  151. self.assertIn("number_123 = models.CharField", output)
  152. error_message = "inspectdb generated a model field name which starts with a digit"
  153. self.assertNotIn(" 4extra = models.CharField", output, msg=error_message)
  154. self.assertIn("number_4extra = models.CharField", output)
  155. self.assertNotIn(" 45extra = models.CharField", output, msg=error_message)
  156. self.assertIn("number_45extra = models.CharField", output)
  157. def test_special_column_name_introspection(self):
  158. """
  159. Introspection of column names containing special characters,
  160. unsuitable for Python identifiers
  161. """
  162. out = StringIO()
  163. call_command('inspectdb', table_name_filter=special_table_only, stdout=out)
  164. output = out.getvalue()
  165. base_name = connection.introspection.identifier_converter('Field')
  166. self.assertIn("field = models.IntegerField()", output)
  167. self.assertIn("field_field = models.IntegerField(db_column='%s_')" % base_name, output)
  168. self.assertIn("field_field_0 = models.IntegerField(db_column='%s__')" % base_name, output)
  169. self.assertIn("field_field_1 = models.IntegerField(db_column='__field')", output)
  170. self.assertIn("prc_x = models.IntegerField(db_column='prc(%) x')", output)
  171. self.assertIn("tamaño = models.IntegerField()", output)
  172. def test_table_name_introspection(self):
  173. """
  174. Introspection of table names containing special characters,
  175. unsuitable for Python identifiers
  176. """
  177. out = StringIO()
  178. call_command('inspectdb', table_name_filter=special_table_only, stdout=out)
  179. output = out.getvalue()
  180. self.assertIn("class InspectdbSpecialTableName(models.Model):", output)
  181. def test_managed_models(self):
  182. """By default the command generates models with `Meta.managed = False` (#14305)"""
  183. out = StringIO()
  184. call_command('inspectdb', 'inspectdb_columntypes', stdout=out)
  185. output = out.getvalue()
  186. self.longMessage = False
  187. self.assertIn(" managed = False", output, msg='inspectdb should generate unmanaged models.')
  188. def test_unique_together_meta(self):
  189. out = StringIO()
  190. call_command('inspectdb', 'inspectdb_uniquetogether', stdout=out)
  191. output = out.getvalue()
  192. self.assertIn(" unique_together = (('", output)
  193. unique_together_match = self.unique_re.findall(output)
  194. # There should be one unique_together tuple.
  195. self.assertEqual(len(unique_together_match), 1)
  196. fields = unique_together_match[0]
  197. # Fields with db_column = field name.
  198. self.assertIn("('field1', 'field2')", fields)
  199. # Fields from columns whose names are Python keywords.
  200. self.assertIn("('field1', 'field2')", fields)
  201. # Fields whose names normalize to the same Python field name and hence
  202. # are given an integer suffix.
  203. self.assertIn("('non_unique_column', 'non_unique_column_0')", fields)
  204. @skipUnless(connection.vendor == 'postgresql', 'PostgreSQL specific SQL')
  205. def test_unsupported_unique_together(self):
  206. """Unsupported index types (COALESCE here) are skipped."""
  207. with connection.cursor() as c:
  208. c.execute(
  209. 'CREATE UNIQUE INDEX Findex ON %s '
  210. '(id, people_unique_id, COALESCE(message_id, -1))' % PeopleMoreData._meta.db_table
  211. )
  212. try:
  213. out = StringIO()
  214. call_command(
  215. 'inspectdb',
  216. table_name_filter=lambda tn: tn.startswith(PeopleMoreData._meta.db_table),
  217. stdout=out,
  218. )
  219. output = out.getvalue()
  220. self.assertIn('# A unique constraint could not be introspected.', output)
  221. self.assertEqual(self.unique_re.findall(output), ["('id', 'people_unique')"])
  222. finally:
  223. with connection.cursor() as c:
  224. c.execute('DROP INDEX Findex')
  225. @skipUnless(connection.vendor == 'sqlite',
  226. "Only patched sqlite's DatabaseIntrospection.data_types_reverse for this test")
  227. def test_custom_fields(self):
  228. """
  229. Introspection of columns with a custom field (#21090)
  230. """
  231. out = StringIO()
  232. orig_data_types_reverse = connection.introspection.data_types_reverse
  233. try:
  234. connection.introspection.data_types_reverse = {
  235. 'text': 'myfields.TextField',
  236. 'bigint': 'BigIntegerField',
  237. }
  238. call_command('inspectdb', 'inspectdb_columntypes', stdout=out)
  239. output = out.getvalue()
  240. self.assertIn("text_field = myfields.TextField()", output)
  241. self.assertIn("big_int_field = models.BigIntegerField()", output)
  242. finally:
  243. connection.introspection.data_types_reverse = orig_data_types_reverse
  244. def test_introspection_errors(self):
  245. """
  246. Introspection errors should not crash the command, and the error should
  247. be visible in the output.
  248. """
  249. out = StringIO()
  250. with mock.patch('django.db.connection.introspection.get_table_list',
  251. return_value=[TableInfo(name='nonexistent', type='t')]):
  252. call_command('inspectdb', stdout=out)
  253. output = out.getvalue()
  254. self.assertIn("# Unable to inspect table 'nonexistent'", output)
  255. # The error message depends on the backend
  256. self.assertIn("# The error was:", output)
  257. class InspectDBTransactionalTests(TransactionTestCase):
  258. available_apps = ['inspectdb']
  259. def test_include_views(self):
  260. """inspectdb --include-views creates models for database views."""
  261. with connection.cursor() as cursor:
  262. cursor.execute(
  263. 'CREATE VIEW inspectdb_people_view AS '
  264. 'SELECT id, name FROM inspectdb_people'
  265. )
  266. out = StringIO()
  267. view_model = 'class InspectdbPeopleView(models.Model):'
  268. view_managed = 'managed = False # Created from a view.'
  269. try:
  270. call_command('inspectdb', table_name_filter=inspectdb_tables_only, stdout=out)
  271. no_views_output = out.getvalue()
  272. self.assertNotIn(view_model, no_views_output)
  273. self.assertNotIn(view_managed, no_views_output)
  274. call_command('inspectdb', table_name_filter=inspectdb_tables_only, include_views=True, stdout=out)
  275. with_views_output = out.getvalue()
  276. self.assertIn(view_model, with_views_output)
  277. self.assertIn(view_managed, with_views_output)
  278. finally:
  279. with connection.cursor() as cursor:
  280. cursor.execute('DROP VIEW inspectdb_people_view')
  281. @skipUnlessDBFeature('can_introspect_materialized_views')
  282. def test_include_materialized_views(self):
  283. """inspectdb --include-views creates models for materialized views."""
  284. with connection.cursor() as cursor:
  285. cursor.execute(
  286. 'CREATE MATERIALIZED VIEW inspectdb_people_materialized AS '
  287. 'SELECT id, name FROM inspectdb_people'
  288. )
  289. out = StringIO()
  290. view_model = 'class InspectdbPeopleMaterialized(models.Model):'
  291. view_managed = 'managed = False # Created from a view.'
  292. try:
  293. call_command('inspectdb', table_name_filter=inspectdb_tables_only, stdout=out)
  294. no_views_output = out.getvalue()
  295. self.assertNotIn(view_model, no_views_output)
  296. self.assertNotIn(view_managed, no_views_output)
  297. call_command('inspectdb', table_name_filter=inspectdb_tables_only, include_views=True, stdout=out)
  298. with_views_output = out.getvalue()
  299. self.assertIn(view_model, with_views_output)
  300. self.assertIn(view_managed, with_views_output)
  301. finally:
  302. with connection.cursor() as cursor:
  303. cursor.execute('DROP MATERIALIZED VIEW inspectdb_people_materialized')
  304. @skipUnless(connection.vendor == 'postgresql', 'PostgreSQL specific SQL')
  305. @skipUnlessDBFeature('supports_table_partitions')
  306. def test_include_partitions(self):
  307. """inspectdb --include-partitions creates models for partitions."""
  308. with connection.cursor() as cursor:
  309. cursor.execute('''\
  310. CREATE TABLE inspectdb_partition_parent (name text not null)
  311. PARTITION BY LIST (left(upper(name), 1))
  312. ''')
  313. cursor.execute('''\
  314. CREATE TABLE inspectdb_partition_child
  315. PARTITION OF inspectdb_partition_parent
  316. FOR VALUES IN ('A', 'B', 'C')
  317. ''')
  318. out = StringIO()
  319. partition_model_parent = 'class InspectdbPartitionParent(models.Model):'
  320. partition_model_child = 'class InspectdbPartitionChild(models.Model):'
  321. partition_managed = 'managed = False # Created from a partition.'
  322. try:
  323. call_command('inspectdb', table_name_filter=inspectdb_tables_only, stdout=out)
  324. no_partitions_output = out.getvalue()
  325. self.assertIn(partition_model_parent, no_partitions_output)
  326. self.assertNotIn(partition_model_child, no_partitions_output)
  327. self.assertNotIn(partition_managed, no_partitions_output)
  328. call_command('inspectdb', table_name_filter=inspectdb_tables_only, include_partitions=True, stdout=out)
  329. with_partitions_output = out.getvalue()
  330. self.assertIn(partition_model_parent, with_partitions_output)
  331. self.assertIn(partition_model_child, with_partitions_output)
  332. self.assertIn(partition_managed, with_partitions_output)
  333. finally:
  334. with connection.cursor() as cursor:
  335. cursor.execute('DROP TABLE IF EXISTS inspectdb_partition_child')
  336. cursor.execute('DROP TABLE IF EXISTS inspectdb_partition_parent')
  337. @skipUnless(connection.vendor == 'postgresql', 'PostgreSQL specific SQL')
  338. def test_foreign_data_wrapper(self):
  339. with connection.cursor() as cursor:
  340. cursor.execute('CREATE EXTENSION IF NOT EXISTS file_fdw')
  341. cursor.execute('CREATE SERVER inspectdb_server FOREIGN DATA WRAPPER file_fdw')
  342. cursor.execute('''\
  343. CREATE FOREIGN TABLE inspectdb_iris_foreign_table (
  344. petal_length real,
  345. petal_width real,
  346. sepal_length real,
  347. sepal_width real
  348. ) SERVER inspectdb_server OPTIONS (
  349. filename '/dev/null'
  350. )
  351. ''')
  352. out = StringIO()
  353. foreign_table_model = 'class InspectdbIrisForeignTable(models.Model):'
  354. foreign_table_managed = 'managed = False'
  355. try:
  356. call_command('inspectdb', stdout=out)
  357. output = out.getvalue()
  358. self.assertIn(foreign_table_model, output)
  359. self.assertIn(foreign_table_managed, output)
  360. finally:
  361. with connection.cursor() as cursor:
  362. cursor.execute('DROP FOREIGN TABLE IF EXISTS inspectdb_iris_foreign_table')
  363. cursor.execute('DROP SERVER IF EXISTS inspectdb_server')
  364. cursor.execute('DROP EXTENSION IF EXISTS file_fdw')