Reputation: 1962
I want to be able to inspect Django migrations within a test, so I can check basic sanity before running more expansive tests.
I was able to come up with the following in a Django command:
from django.core.management.base import BaseCommand
from django.db.migrations.loader import MigrationLoader
class Command(BaseCommand):
help = "Check migrations"
def handle(self, *args, **options):
self.migration_loader = MigrationLoader(None)
self.migration_loader.build_graph()
for root_node in self.migration_loader.graph.root_nodes():
app_name = root_node[0]
print(app_name, root_node[0])
But when I translate that into a test (using pytest):
from django.db.migrations.loader import MigrationLoader
def test_multiple_leaf_nodes_in_migration_graph():
migration_loader = MigrationLoader(None)
migration_loader.build_graph()
for root_node in migration_loader.graph.root_nodes():
app_name = root_node[0]
print(app_name, root_node[0])
Then the graph (root nodes) returns an empty list.
The project is structured as follows:
django_project/
settings.py
... # other Django core files
tests/
test_above.py
django_app/
models.py
... # other files from this app
management/commands/
command_above.py
pytest.ini
pytest.ini:
[pytest]
DJANGO_SETTINGS_MODULE = django_project.settings
python_files = tests.py test_*.py
The command:
pytest --no-migrations
PS: the whole point of this is to be able to detect migration errors without running them.
Is there anything I need to do so I can "see" migrations within the test?
Upvotes: 3
Views: 763
Reputation: 43083
pytest --no-migrations
Since you disabled migrations, the MigrationLoader
won't load the migrations.
To load the migrations, you can override settings for MIGRATION_MODULES
just for that test:
from django.test import override_settings
@override_settings(MIGRATION_MODULES={}) # Add this
def test_multiple_leaf_nodes_in_migration_graph():
...
Upvotes: 1