Python 如何在Django中更快地测试迁移?
我试过写作。基本上,我想在两次迁移之间测试数据库和数据的当前状态。我使用了Python 如何在Django中更快地测试迁移?,python,django,unit-testing,Python,Django,Unit Testing,我试过写作。基本上,我想在两次迁移之间测试数据库和数据的当前状态。我使用了MigrationExecutor,如下所示: executor = MigrationExecutor(connection) old_apps = executor.loader.project_state(self.migrate_from).apps executor.migrate(self.migrate_from) # do something here executor.migrate(self.migra
MigrationExecutor
,如下所示:
executor = MigrationExecutor(connection)
old_apps = executor.loader.project_state(self.migrate_from).apps
executor.migrate(self.migrate_from)
# do something here
executor.migrate(self.migrate_to)
我们在项目中有这么多迁移文件,所以使用单元测试运行所有迁移文件需要很多时间。通常,我会在asettings\u test.py
中将迁移模块设置为None
:
MIGRATION_MODULES: {
'my_app': None
}
使用此设置,测试将运行得非常快。问题是无法再找到要测试的迁移文件(self.migrate\u from
和self.migrate\u to
):
django.db.migrations.exceptions.NodeNotFoundError: Node ('poleluxe', '0090_auto_previous_migration') not a valid node
所以我不得不在测试中再次包含迁移模块
有没有一种方法可以在不运行所有迁移文件的情况下包含迁移文件?在我的例子中,我想跳过从0001
到0089
的所有迁移,只运行0090
(作为self.migration\u from
)和0091
(作为self.migrate\u to
)
我正在考虑压缩前89次迁移,并将结果与
0090
和0091
一起放在一个单独的文件夹中,然后在测试中参考该迁移文件夹。但是,我不确定这是否是一个很好的解决方案。这是我到目前为止所理解的,如果我不正确,请指导我
问题
@override\u setting
和setUpClass())启动得更早
MIGRATION\u MODULES
设置,因为在那里我只找到了正确的点
通过这种方式,不仅可以在运行测试时禁用所有迁移以加快速度,还可以测试迁移文件
settings.py进行的所有迁移
MIGRATION_MODULES = {app: None for app in INSTALLED_APPS}
--nomigrations
选项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()
@override\u设置
不起作用,因为Django在@override\u设置
之前启动并运行迁移--nomigrations
不起作用不太确定,但我的解决办法是禁用从django设置而不是pytest django的迁移你读过这种测试吗?读过。事实上,我已经在帖子中提到了这一点。