test_base.py 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  1. import os
  2. import shutil
  3. import tempfile
  4. from contextlib import contextmanager
  5. from importlib import import_module
  6. from django.apps import apps
  7. from django.db import connections
  8. from django.db.migrations.recorder import MigrationRecorder
  9. from django.test import TransactionTestCase
  10. from django.test.utils import extend_sys_path
  11. from django.utils.module_loading import module_dir
  12. class MigrationTestBase(TransactionTestCase):
  13. """
  14. Contains an extended set of asserts for testing migrations and schema operations.
  15. """
  16. available_apps = ["migrations"]
  17. def tearDown(self):
  18. # Reset applied-migrations state.
  19. for db in connections:
  20. recorder = MigrationRecorder(connections[db])
  21. recorder.migration_qs.filter(app='migrations').delete()
  22. def get_table_description(self, table, using='default'):
  23. with connections[using].cursor() as cursor:
  24. return connections[using].introspection.get_table_description(cursor, table)
  25. def assertTableExists(self, table, using='default'):
  26. with connections[using].cursor() as cursor:
  27. self.assertIn(table, connections[using].introspection.table_names(cursor))
  28. def assertTableNotExists(self, table, using='default'):
  29. with connections[using].cursor() as cursor:
  30. self.assertNotIn(table, connections[using].introspection.table_names(cursor))
  31. def assertColumnExists(self, table, column, using='default'):
  32. self.assertIn(column, [c.name for c in self.get_table_description(table, using=using)])
  33. def assertColumnNotExists(self, table, column, using='default'):
  34. self.assertNotIn(column, [c.name for c in self.get_table_description(table, using=using)])
  35. def _get_column_allows_null(self, table, column, using):
  36. return [c.null_ok for c in self.get_table_description(table, using=using) if c.name == column][0]
  37. def assertColumnNull(self, table, column, using='default'):
  38. self.assertEqual(self._get_column_allows_null(table, column, using), True)
  39. def assertColumnNotNull(self, table, column, using='default'):
  40. self.assertEqual(self._get_column_allows_null(table, column, using), False)
  41. def assertIndexExists(self, table, columns, value=True, using='default'):
  42. with connections[using].cursor() as cursor:
  43. self.assertEqual(
  44. value,
  45. any(
  46. c["index"]
  47. for c in connections[using].introspection.get_constraints(cursor, table).values()
  48. if c['columns'] == list(columns)
  49. ),
  50. )
  51. def assertIndexNotExists(self, table, columns):
  52. return self.assertIndexExists(table, columns, False)
  53. def assertFKExists(self, table, columns, to, value=True, using='default'):
  54. with connections[using].cursor() as cursor:
  55. self.assertEqual(
  56. value,
  57. any(
  58. c["foreign_key"] == to
  59. for c in connections[using].introspection.get_constraints(cursor, table).values()
  60. if c['columns'] == list(columns)
  61. ),
  62. )
  63. def assertFKNotExists(self, table, columns, to, value=True):
  64. return self.assertFKExists(table, columns, to, False)
  65. @contextmanager
  66. def temporary_migration_module(self, app_label='migrations', module=None):
  67. """
  68. Allows testing management commands in a temporary migrations module.
  69. Wrap all invocations to makemigrations and squashmigrations with this
  70. context manager in order to avoid creating migration files in your
  71. source tree inadvertently.
  72. Takes the application label that will be passed to makemigrations or
  73. squashmigrations and the Python path to a migrations module.
  74. The migrations module is used as a template for creating the temporary
  75. migrations module. If it isn't provided, the application's migrations
  76. module is used, if it exists.
  77. Returns the filesystem path to the temporary migrations module.
  78. """
  79. temp_dir = tempfile.mkdtemp()
  80. try:
  81. target_dir = tempfile.mkdtemp(dir=temp_dir)
  82. with open(os.path.join(target_dir, '__init__.py'), 'w'):
  83. pass
  84. target_migrations_dir = os.path.join(target_dir, 'migrations')
  85. if module is None:
  86. module = apps.get_app_config(app_label).name + '.migrations'
  87. try:
  88. source_migrations_dir = module_dir(import_module(module))
  89. except (ImportError, ValueError):
  90. pass
  91. else:
  92. shutil.copytree(source_migrations_dir, target_migrations_dir)
  93. with extend_sys_path(temp_dir):
  94. new_module = os.path.basename(target_dir) + '.migrations'
  95. with self.settings(MIGRATION_MODULES={app_label: new_module}):
  96. yield target_migrations_dir
  97. finally:
  98. shutil.rmtree(temp_dir)