无法检查来自测试的 Django 迁移,但可以使用 Django 命令
Not able to inspect Django migrations from test but working from Django command
我希望能够在测试中检查 Django 迁移,这样我就可以在 运行 更广泛的测试之前检查基本的完整性。
我能够在 Django 命令中提出以下内容:
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])
但是当我将其转化为测试时(使用 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])
然后图表(根节点)returns一个空列表。
项目结构如下:
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
命令:
pytest --no-migrations
PS:重点是能够在没有 运行 的情况下检测到迁移错误。
我需要做些什么才能在测试中“看到”迁移吗?
pytest --no-migrations
由于您禁用了迁移,MigrationLoader
将不会加载迁移。
要加载迁移,您可以仅针对该测试覆盖 MIGRATION_MODULES
的设置:
from django.test import override_settings
@override_settings(MIGRATION_MODULES={}) # Add this
def test_multiple_leaf_nodes_in_migration_graph():
...
我希望能够在测试中检查 Django 迁移,这样我就可以在 运行 更广泛的测试之前检查基本的完整性。
我能够在 Django 命令中提出以下内容:
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])
但是当我将其转化为测试时(使用 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])
然后图表(根节点)returns一个空列表。
项目结构如下:
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
命令:
pytest --no-migrations
PS:重点是能够在没有 运行 的情况下检测到迁移错误。
我需要做些什么才能在测试中“看到”迁移吗?
pytest --no-migrations
由于您禁用了迁移,MigrationLoader
将不会加载迁移。
要加载迁移,您可以仅针对该测试覆盖 MIGRATION_MODULES
的设置:
from django.test import override_settings
@override_settings(MIGRATION_MODULES={}) # Add this
def test_multiple_leaf_nodes_in_migration_graph():
...