Monday, October 3, 2016

Speeding up Django tests: Disable migrations during tests

Running all migrations before the testrun can take a lot of time. For some reason, they are very slow. Running 50 migrations could easily take more than 1 minute! Fourtunately, disabling migrations is very easy. Just add the following code to the test's settings file:
# Disable migrations when running tests
    app[app.rfind('.') + 1:]: 'your_app.migrations_not_used_in_tests'
    for app in INSTALLED_APPS
Some of our migrations add data to the database and tests expect this data to be there. To fix that problem we will need to overwrite test runner. Add to the settings file:
TEST_RUNNER = 'your_app.test_runner.CustomDiscoverRunner'
Then create in the project root with the following content:
from django.test.runner import DiscoverRunner

from import create_groups

class CustomDiscoverRunner(DiscoverRunner):
    def setup_databases(self, **kwargs):
        result = super(CustomDiscoverRunner, self).setup_databases(**kwargs)
        return result
After recreating test database directly from the models (what is really fast), test runner will execute create_groups() function which populates database with all necessary data.

No comments:

Post a Comment