Skip to content

Instantly share code, notes, and snippets.

@blueyed
Last active December 9, 2020 16:20
Show Gist options
  • Star 28 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save blueyed/4fb0a807104551f103e6 to your computer and use it in GitHub Desktop.
Save blueyed/4fb0a807104551f103e6 to your computer and use it in GitHub Desktop.
Test Django data migrations
"""
Test (data) migrations in Django.
This uses py.test/pytest-django (the `transactional_db` fixture comes from there),
but could be easily adopted for Django's testrunner:
from django.test.testcases import TransactionTestCase
class FooTestcase(TransactionTestCase):
def test_with_django(self):
This example tests that some fields are properly migrated from a `Profile` model
to `User`.
"""
from django.db import connection
from django.db.migrations.executor import MigrationExecutor
def test_migrate_profile_to_user(transactional_db):
executor = MigrationExecutor(connection)
app = "YOUR_APP"
migrate_from = [(app, "000X_before")]
migrate_to = [(app, "000X_after")]
executor.migrate(migrate_from)
old_apps = executor.loader.project_state(migrate_from).apps
# Create some old data.
Profile = old_apps.get_model(app, "Profile")
old_profile = Profile.objects.create(email="email",
firstname="firstname",
lastname="lastname")
# Migrate forwards.
executor.loader.build_graph() # reload.
executor.migrate(migrate_to)
new_apps = executor.loader.project_state(migrate_to).apps
# Test the new data.
Profile = new_apps.get_model(app, "Profile")
User = new_apps.get_model(app, "UserEntry")
assert 'firstname' not in Profile._meta.get_all_field_names()
user = User.objects.get(email='email')
profile = Profile.objects.get(user__email='email')
assert user.profile.pk == old_profile.pk == profile.pk
assert profile.user.email == 'email'
assert profile.user.first_name == 'firstname'
assert profile.user.last_name == 'lastname'
Copy link

ghost commented Jul 4, 2017

I have the same problem as @Pomax 😕

Copy link

ghost commented Jul 4, 2017

Never mind. I think that it's because of the fact that I have migrations disabled in my settings_test.py file..

🙈

@Pycz
Copy link

Pycz commented Jul 25, 2017

What to do if I have not reversible migrations? How to prevent migrations before tests?

@legshort
Copy link

If you want to disable all migrations for regular test code and also want to test migration scenario, you can try this.
Any feedback would be welcome and I explained this at https://stackoverflow.com/a/46312855/2951749
The code base is here https://www.caktusgroup.com/blog/2016/02/02/writing-unit-tests-django-migrations/

settings.py

MIGRATION_MODULES = {app: None for app in INSTALLED_APPS}

Test.py

class TestMigrations(TestCase):
    origin_modules = getattr(settings, 'MIGRATION_MODULES', {})
    setattr(settings, 'MIGRATION_MODULES', {})
    
    ...

    @classmethod
    def tearDownClass(cls):
        setattr(settings, 'MIGRATION_MODULES', cls.origin_modules)
        super().tearDownClass()

@asfaltboy
Copy link

asfaltboy commented May 8, 2018

Thanks @TauPan your version worked for me on Django 2.0 too.

Unfortunately, there is no support for pytest.raises for exceptions that occur during migrations, and possibly other issues, let's try to discuss it over at pytest-dev/pytest-django#593

EDIT: I used @TauPan's updates (Gist-spection!) and cleaned my own fork a bit and allowed specifying a list of target migrations (when conditions span across multiple apps).

@sobolevn
Copy link

I have made a pypi package out of this gist with some extra features.
Check it out: https://github.com/wemake-services/django-test-migrations

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment