tests.py 21 KB

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