Nathan Tregillus
Nathan Tregillus

Reputation: 6334

Unit test to check for ungenerated migrations

Has anyone written a unit test to verify if there are ungenerated migrations in their Django app? I think it should probably look something like:

  1. Call python manage.py makemigrations
  2. scrape results into a parsable object
  3. verify "no migrations were found"
  4. if migrations are found list them, fail the test, and delete the generated files

If not, I am going to write one so that we fail our build.

Upvotes: 3

Views: 1732

Answers (4)

Zathras
Zathras

Reputation: 434

Since Django 1.10 the makemigrations management command has included a --check option. The command will exit with a non-zero status if migrations are missing.

Usage example:

./manage.py makemigrations --check --dry-run

Documentation:

https://docs.djangoproject.com/en/2.0/ref/django-admin/#cmdoption-makemigrations-check

Upvotes: 10

Janusz Skonieczny
Janusz Skonieczny

Reputation: 18982

This should do the trick — no scraping.

It will show names of migrations, but when in doubt you still need to view changes in debugger.

class MigrationsCheck(TestCase):
    def setUp(self):
        from django.utils import translation
        self.saved_locale = translation.get_language()
        translation.deactivate_all()

    def tearDown(self):
        if self.saved_locale is not None:
            from django.utils import translation
            translation.activate(self.saved_locale)

    def test_missing_migrations(self):
        from django.db import connection
        from django.apps.registry import apps
        from django.db.migrations.executor import MigrationExecutor
        executor = MigrationExecutor(connection)
        from django.db.migrations.autodetector import MigrationAutodetector
        from django.db.migrations.state import ProjectState
        autodetector = MigrationAutodetector(
            executor.loader.project_state(),
            ProjectState.from_apps(apps),
        )
        changes = autodetector.changes(graph=executor.loader.graph)
        self.assertEqual({}, changes)

Upvotes: 5

Lyudmil Nenov
Lyudmil Nenov

Reputation: 257

You can steal some code from https://github.com/django/django/blob/master/django/core/management/commands/makemigrations.py#L68. Migrating to newer django versions might require some extra 5 min after that

Upvotes: 0

bwarren2
bwarren2

Reputation: 1387

I would instead use the --dry-run flag and test that it is empty.

Upvotes: 2

Related Questions