Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在Django中更快地测试迁移?_Python_Django_Unit Testing - Fatal编程技术网

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)
我们在项目中有这么多迁移文件,所以使用单元测试运行所有迁移文件需要很多时间。通常,我会在a
settings\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
一起放在一个单独的文件夹中,然后在测试中参考该迁移文件夹。但是,我不确定这是否是一个很好的解决方案。

这是我到目前为止所理解的,如果我不正确,请指导我

问题

  • 需要应用迁移
  • Django比任何其他进程(如
    @override\u setting
    setUpClass())启动得更早
  • 解决方案

    即使TestClass没有完全初始化,也要在TestClass最开始时覆盖
    MIGRATION\u MODULES
    设置,因为在那里我只找到了正确的点

    通过这种方式,不仅可以在运行测试时禁用所有迁移以加快速度,还可以测试迁移文件

  • 禁用从
    settings.py进行的所有迁移

    MIGRATION_MODULES = {app: None for app in INSTALLED_APPS}
    
  • (可选)如果使用pytest django,请从pytest设置中删除
    --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()
    
  • 试用信息

  • TestClass或TestMethod上的
    @override\u设置
    不起作用,因为Django在
    @override\u设置
    之前启动并运行迁移
  • pytest django与
    --nomigrations
    不起作用不太确定,但我的解决办法是禁用从django设置而不是pytest django的迁移

  • 你读过这种测试吗?读过。事实上,我已经在帖子中提到了这一点。