tests.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  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. @skipUnlessDBFeature('can_introspect_json_field', 'supports_json_field')
  73. def test_json_field(self):
  74. out = StringIO()
  75. call_command('inspectdb', 'inspectdb_jsonfieldcolumntype', stdout=out)
  76. output = out.getvalue()
  77. if not connection.features.interprets_empty_strings_as_nulls:
  78. self.assertIn('json_field = models.JSONField()', output)
  79. self.assertIn('null_json_field = models.JSONField(blank=True, null=True)', output)
  80. def test_number_field_types(self):
  81. """Test introspection of various Django field types"""
  82. assertFieldType = self.make_field_type_asserter()
  83. if not connection.features.can_introspect_autofield:
  84. assertFieldType('id', "models.IntegerField(primary_key=True) # AutoField?")
  85. if connection.features.can_introspect_big_integer_field:
  86. assertFieldType('big_int_field', "models.BigIntegerField()")
  87. else:
  88. assertFieldType('big_int_field', "models.IntegerField()")
  89. bool_field_type = connection.features.introspected_boolean_field_type
  90. assertFieldType('bool_field', "models.{}()".format(bool_field_type))
  91. assertFieldType('null_bool_field', 'models.{}(blank=True, null=True)'.format(bool_field_type))
  92. if connection.features.can_introspect_decimal_field:
  93. assertFieldType('decimal_field', "models.DecimalField(max_digits=6, decimal_places=1)")
  94. else: # Guessed arguments on SQLite, see #5014
  95. assertFieldType('decimal_field', "models.DecimalField(max_digits=10, decimal_places=5) "
  96. "# max_digits and decimal_places have been guessed, "
  97. "as this database handles decimal fields as float")
  98. assertFieldType('float_field', "models.FloatField()")
  99. assertFieldType('int_field', "models.IntegerField()")
  100. if connection.features.can_introspect_positive_integer_field:
  101. assertFieldType('pos_int_field', "models.PositiveIntegerField()")
  102. else:
  103. assertFieldType('pos_int_field', "models.IntegerField()")
  104. if connection.features.can_introspect_positive_integer_field:
  105. if connection.features.can_introspect_big_integer_field:
  106. assertFieldType('pos_big_int_field', 'models.PositiveBigIntegerField()')
  107. else:
  108. assertFieldType('pos_big_int_field', 'models.PositiveIntegerField()')
  109. if connection.features.can_introspect_small_integer_field:
  110. assertFieldType('pos_small_int_field', "models.PositiveSmallIntegerField()")
  111. else:
  112. assertFieldType('pos_small_int_field', "models.PositiveIntegerField()")
  113. else:
  114. if connection.features.can_introspect_big_integer_field:
  115. assertFieldType('pos_big_int_field', 'models.BigIntegerField()')
  116. else:
  117. assertFieldType('pos_big_int_field', 'models.IntegerField()')
  118. if connection.features.can_introspect_small_integer_field:
  119. assertFieldType('pos_small_int_field', "models.SmallIntegerField()")
  120. else:
  121. assertFieldType('pos_small_int_field', "models.IntegerField()")
  122. if connection.features.can_introspect_small_integer_field:
  123. assertFieldType('small_int_field', "models.SmallIntegerField()")
  124. else:
  125. assertFieldType('small_int_field', "models.IntegerField()")
  126. @skipUnlessDBFeature('can_introspect_foreign_keys')
  127. def test_attribute_name_not_python_keyword(self):
  128. out = StringIO()
  129. call_command('inspectdb', table_name_filter=inspectdb_tables_only, stdout=out)
  130. output = out.getvalue()
  131. error_message = "inspectdb generated an attribute name which is a Python keyword"
  132. # Recursive foreign keys should be set to 'self'
  133. self.assertIn("parent = models.ForeignKey('self', models.DO_NOTHING)", output)
  134. self.assertNotIn(
  135. "from = models.ForeignKey(InspectdbPeople, models.DO_NOTHING)",
  136. output,
  137. msg=error_message,
  138. )
  139. # As InspectdbPeople model is defined after InspectdbMessage, it should be quoted
  140. self.assertIn(
  141. "from_field = models.ForeignKey('InspectdbPeople', models.DO_NOTHING, db_column='from_id')",
  142. output,
  143. )
  144. self.assertIn(
  145. 'people_pk = models.OneToOneField(InspectdbPeople, models.DO_NOTHING, primary_key=True)',
  146. output,
  147. )
  148. self.assertIn(
  149. 'people_unique = models.OneToOneField(InspectdbPeople, models.DO_NOTHING)',
  150. output,
  151. )
  152. def test_digits_column_name_introspection(self):
  153. """Introspection of column names consist/start with digits (#16536/#17676)"""
  154. out = StringIO()
  155. call_command('inspectdb', 'inspectdb_digitsincolumnname', stdout=out)
  156. output = out.getvalue()
  157. error_message = "inspectdb generated a model field name which is a number"
  158. self.assertNotIn(" 123 = models.CharField", output, msg=error_message)
  159. self.assertIn("number_123 = models.CharField", output)
  160. error_message = "inspectdb generated a model field name which starts with a digit"
  161. self.assertNotIn(" 4extra = models.CharField", output, msg=error_message)
  162. self.assertIn("number_4extra = models.CharField", output)
  163. self.assertNotIn(" 45extra = models.CharField", output, msg=error_message)
  164. self.assertIn("number_45extra = models.CharField", output)
  165. def test_special_column_name_introspection(self):
  166. """
  167. Introspection of column names containing special characters,
  168. unsuitable for Python identifiers
  169. """
  170. out = StringIO()
  171. call_command('inspectdb', table_name_filter=special_table_only, stdout=out)
  172. output = out.getvalue()
  173. base_name = connection.introspection.identifier_converter('Field')
  174. self.assertIn("field = models.IntegerField()", output)
  175. self.assertIn("field_field = models.IntegerField(db_column='%s_')" % base_name, output)
  176. self.assertIn("field_field_0 = models.IntegerField(db_column='%s__')" % base_name, output)
  177. self.assertIn("field_field_1 = models.IntegerField(db_column='__field')", output)
  178. self.assertIn("prc_x = models.IntegerField(db_column='prc(%) x')", output)
  179. self.assertIn("tamaño = models.IntegerField()", output)
  180. def test_table_name_introspection(self):
  181. """
  182. Introspection of table names containing special characters,
  183. unsuitable for Python identifiers
  184. """
  185. out = StringIO()
  186. call_command('inspectdb', table_name_filter=special_table_only, stdout=out)
  187. output = out.getvalue()
  188. self.assertIn("class InspectdbSpecialTableName(models.Model):", output)
  189. def test_managed_models(self):
  190. """By default the command generates models with `Meta.managed = False` (#14305)"""
  191. out = StringIO()
  192. call_command('inspectdb', 'inspectdb_columntypes', stdout=out)
  193. output = out.getvalue()
  194. self.longMessage = False
  195. self.assertIn(" managed = False", output, msg='inspectdb should generate unmanaged models.')
  196. def test_unique_together_meta(self):
  197. out = StringIO()
  198. call_command('inspectdb', 'inspectdb_uniquetogether', stdout=out)
  199. output = out.getvalue()
  200. self.assertIn(" unique_together = (('", output)
  201. unique_together_match = self.unique_re.findall(output)
  202. # There should be one unique_together tuple.
  203. self.assertEqual(len(unique_together_match), 1)
  204. fields = unique_together_match[0]
  205. # Fields with db_column = field name.
  206. self.assertIn("('field1', 'field2')", fields)
  207. # Fields from columns whose names are Python keywords.
  208. self.assertIn("('field1', 'field2')", fields)
  209. # Fields whose names normalize to the same Python field name and hence
  210. # are given an integer suffix.
  211. self.assertIn("('non_unique_column', 'non_unique_column_0')", fields)
  212. @skipUnless(connection.vendor == 'postgresql', 'PostgreSQL specific SQL')
  213. def test_unsupported_unique_together(self):
  214. """Unsupported index types (COALESCE here) are skipped."""
  215. with connection.cursor() as c:
  216. c.execute(
  217. 'CREATE UNIQUE INDEX Findex ON %s '
  218. '(id, people_unique_id, COALESCE(message_id, -1))' % PeopleMoreData._meta.db_table
  219. )
  220. try:
  221. out = StringIO()
  222. call_command(
  223. 'inspectdb',
  224. table_name_filter=lambda tn: tn.startswith(PeopleMoreData._meta.db_table),
  225. stdout=out,
  226. )
  227. output = out.getvalue()
  228. self.assertIn('# A unique constraint could not be introspected.', output)
  229. self.assertEqual(self.unique_re.findall(output), ["('id', 'people_unique')"])
  230. finally:
  231. with connection.cursor() as c:
  232. c.execute('DROP INDEX Findex')
  233. @skipUnless(connection.vendor == 'sqlite',
  234. "Only patched sqlite's DatabaseIntrospection.data_types_reverse for this test")
  235. def test_custom_fields(self):
  236. """
  237. Introspection of columns with a custom field (#21090)
  238. """
  239. out = StringIO()
  240. orig_data_types_reverse = connection.introspection.data_types_reverse
  241. try:
  242. connection.introspection.data_types_reverse = {
  243. 'text': 'myfields.TextField',
  244. 'bigint': 'BigIntegerField',
  245. }
  246. call_command('inspectdb', 'inspectdb_columntypes', stdout=out)
  247. output = out.getvalue()
  248. self.assertIn("text_field = myfields.TextField()", output)
  249. self.assertIn("big_int_field = models.BigIntegerField()", output)
  250. finally:
  251. connection.introspection.data_types_reverse = orig_data_types_reverse
  252. def test_introspection_errors(self):
  253. """
  254. Introspection errors should not crash the command, and the error should
  255. be visible in the output.
  256. """
  257. out = StringIO()
  258. with mock.patch('django.db.connection.introspection.get_table_list',
  259. return_value=[TableInfo(name='nonexistent', type='t')]):
  260. call_command('inspectdb', stdout=out)
  261. output = out.getvalue()
  262. self.assertIn("# Unable to inspect table 'nonexistent'", output)
  263. # The error message depends on the backend
  264. self.assertIn("# The error was:", output)
  265. class InspectDBTransactionalTests(TransactionTestCase):
  266. available_apps = ['inspectdb']
  267. def test_include_views(self):
  268. """inspectdb --include-views creates models for database views."""
  269. with connection.cursor() as cursor:
  270. cursor.execute(
  271. 'CREATE VIEW inspectdb_people_view AS '
  272. 'SELECT id, name FROM inspectdb_people'
  273. )
  274. out = StringIO()
  275. view_model = 'class InspectdbPeopleView(models.Model):'
  276. view_managed = 'managed = False # Created from a view.'
  277. try:
  278. call_command('inspectdb', table_name_filter=inspectdb_tables_only, stdout=out)
  279. no_views_output = out.getvalue()
  280. self.assertNotIn(view_model, no_views_output)
  281. self.assertNotIn(view_managed, no_views_output)
  282. call_command('inspectdb', table_name_filter=inspectdb_tables_only, include_views=True, stdout=out)
  283. with_views_output = out.getvalue()
  284. self.assertIn(view_model, with_views_output)
  285. self.assertIn(view_managed, with_views_output)
  286. finally:
  287. with connection.cursor() as cursor:
  288. cursor.execute('DROP VIEW inspectdb_people_view')
  289. @skipUnlessDBFeature('can_introspect_materialized_views')
  290. def test_include_materialized_views(self):
  291. """inspectdb --include-views creates models for materialized views."""
  292. with connection.cursor() as cursor:
  293. cursor.execute(
  294. 'CREATE MATERIALIZED VIEW inspectdb_people_materialized AS '
  295. 'SELECT id, name FROM inspectdb_people'
  296. )
  297. out = StringIO()
  298. view_model = 'class InspectdbPeopleMaterialized(models.Model):'
  299. view_managed = 'managed = False # Created from a view.'
  300. try:
  301. call_command('inspectdb', table_name_filter=inspectdb_tables_only, stdout=out)
  302. no_views_output = out.getvalue()
  303. self.assertNotIn(view_model, no_views_output)
  304. self.assertNotIn(view_managed, no_views_output)
  305. call_command('inspectdb', table_name_filter=inspectdb_tables_only, include_views=True, stdout=out)
  306. with_views_output = out.getvalue()
  307. self.assertIn(view_model, with_views_output)
  308. self.assertIn(view_managed, with_views_output)
  309. finally:
  310. with connection.cursor() as cursor:
  311. cursor.execute('DROP MATERIALIZED VIEW inspectdb_people_materialized')
  312. @skipUnless(connection.vendor == 'postgresql', 'PostgreSQL specific SQL')
  313. @skipUnlessDBFeature('supports_table_partitions')
  314. def test_include_partitions(self):
  315. """inspectdb --include-partitions creates models for partitions."""
  316. with connection.cursor() as cursor:
  317. cursor.execute('''\
  318. CREATE TABLE inspectdb_partition_parent (name text not null)
  319. PARTITION BY LIST (left(upper(name), 1))
  320. ''')
  321. cursor.execute('''\
  322. CREATE TABLE inspectdb_partition_child
  323. PARTITION OF inspectdb_partition_parent
  324. FOR VALUES IN ('A', 'B', 'C')
  325. ''')
  326. out = StringIO()
  327. partition_model_parent = 'class InspectdbPartitionParent(models.Model):'
  328. partition_model_child = 'class InspectdbPartitionChild(models.Model):'
  329. partition_managed = 'managed = False # Created from a partition.'
  330. try:
  331. call_command('inspectdb', table_name_filter=inspectdb_tables_only, stdout=out)
  332. no_partitions_output = out.getvalue()
  333. self.assertIn(partition_model_parent, no_partitions_output)
  334. self.assertNotIn(partition_model_child, no_partitions_output)
  335. self.assertNotIn(partition_managed, no_partitions_output)
  336. call_command('inspectdb', table_name_filter=inspectdb_tables_only, include_partitions=True, stdout=out)
  337. with_partitions_output = out.getvalue()
  338. self.assertIn(partition_model_parent, with_partitions_output)
  339. self.assertIn(partition_model_child, with_partitions_output)
  340. self.assertIn(partition_managed, with_partitions_output)
  341. finally:
  342. with connection.cursor() as cursor:
  343. cursor.execute('DROP TABLE IF EXISTS inspectdb_partition_child')
  344. cursor.execute('DROP TABLE IF EXISTS inspectdb_partition_parent')
  345. @skipUnless(connection.vendor == 'postgresql', 'PostgreSQL specific SQL')
  346. def test_foreign_data_wrapper(self):
  347. with connection.cursor() as cursor:
  348. cursor.execute('CREATE EXTENSION IF NOT EXISTS file_fdw')
  349. cursor.execute('CREATE SERVER inspectdb_server FOREIGN DATA WRAPPER file_fdw')
  350. cursor.execute('''\
  351. CREATE FOREIGN TABLE inspectdb_iris_foreign_table (
  352. petal_length real,
  353. petal_width real,
  354. sepal_length real,
  355. sepal_width real
  356. ) SERVER inspectdb_server OPTIONS (
  357. filename '/dev/null'
  358. )
  359. ''')
  360. out = StringIO()
  361. foreign_table_model = 'class InspectdbIrisForeignTable(models.Model):'
  362. foreign_table_managed = 'managed = False'
  363. try:
  364. call_command('inspectdb', stdout=out)
  365. output = out.getvalue()
  366. self.assertIn(foreign_table_model, output)
  367. self.assertIn(foreign_table_managed, output)
  368. finally:
  369. with connection.cursor() as cursor:
  370. cursor.execute('DROP FOREIGN TABLE IF EXISTS inspectdb_iris_foreign_table')
  371. cursor.execute('DROP SERVER IF EXISTS inspectdb_server')
  372. cursor.execute('DROP EXTENSION IF EXISTS file_fdw')