Last active
April 6, 2022 04:37
-
-
Save melinath/0f32e2fd61ad776871ccae8901e57fd8 to your computer and use it in GitHub Desktop.
Testing migrations
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.apps import apps | |
from django.core.management import call_command | |
from django.db.models.signals import pre_migrate, post_migrate | |
from django.test import TransactionTestCase | |
# See https://www.caktusgroup.com/blog/2016/02/02/writing-unit-tests-django-migrations/ | |
# for the original code. | |
class MigrationTest(TransactionTestCase): | |
@property | |
def app(self): | |
return apps.get_containing_app_config(type(self).__module__).name | |
migrate_from = None | |
migrate_to = None | |
def _reloadAppliedMigrations(self): | |
self.executor.loader.build_graph() | |
def setUp(self): | |
assert self.migrate_from and self.migrate_to, \ | |
"TestCase '{}' must define migrate_from and migrate_to properties".format(type(self).__name__) | |
# Reverse to the original migration | |
call_command('migrate', self.app, self.migrate_from, verbosity=0) | |
app_config = apps.get_app_config(self.app) | |
pre_migrate.connect(self.setUpBeforeMigration, sender=app_config) | |
post_migrate.connect(self.setUpAfterMigration, sender=app_config) | |
call_command('migrate', self.app, self.migrate_to, verbosity=0) | |
pre_migrate.disconnect(self.setUpBeforeMigration, sender=app_config) | |
post_migrate.disconnect(self.setUpAfterMigration, sender=app_config) | |
def setUpBeforeMigration(self, apps, **kwargs): | |
pass | |
def setUpAfterMigration(self, apps, **kwargs): | |
""" | |
Do not override this method. | |
""" | |
self.apps = apps | |
def tearDown(self): | |
call_command('migrate', verbosity=0) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment