gpt4 book ai didi

django - 在 Django 1.7 中运行单元测试时禁用迁移

转载 作者:行者123 更新时间:2023-11-28 19:32:34 25 4
gpt4 key购买 nike

Django 1.7 引入 database migrations .

在 Django 1.7 中运行单元测试时,它会强制执行迁移,这需要很长时间。所以我想跳过 django 迁移,并在最终状态下创建数据库。

我知道忽略迁移可能是一种不好的做法,因为那部分代码不会被测试。但事实并非如此:我正在 CI 测试服务器 (jenkins) 中运行完整的迁移。我只想跳过速度很重要的本地测试中的迁移。


一些上下文:

在 Django 1.6 之前,当使用 South 时,我使用 SOUTH_TESTS_MIGRATE设置:

By default, South’s syncdb command will also apply migrations if it’s run in non-interactive mode, which includes when you’re running tests - it will run every migration every time you run your tests.

If you want the test runner to use syncdb instead of migrate - for example, if your migrations are taking way too long to apply - simply set SOUTH_TESTS_MIGRATE = False in settings.py.

但是,syncdb 已经不存在了,现在是migrate

在 Django 1.8 中,我将使用 --keepdb 参数:

The --keepdb option can be used to preserve the test database between test runs. This has the advantage of skipping both the create and destroy actions which greatly decreases the time to run tests, especially those in a large test suite. If the test database does not exist, it will be created on the first run and then preserved for each subsequent run. Any unapplied migrations will also be applied to the test database before running the test suite.

所以这个问题仅限于Django 1.7。

最佳答案

this workaround ,由 Bernie Sumption 发布到 Django 开发人员邮件列表:

If makemigrations has not yet been run, the "migrate" command treats an app as unmigrated, and creates tables directly from the models just like syncdb did in 1.6. I defined a new settings module just for unit tests called "settings_test.py", which imports * from the main settings module and adds this line:

MIGRATION_MODULES = {"myapp": "myapp.migrations_not_used_in_tests"}

Then I run tests like this:

DJANGO_SETTINGS_MODULE="myapp.settings_test" python manage.py test

This fools migrate into thinking that the app is unmigrated, and so every time a test database is created it reflects the current structure of models.py.

在Django 1.9中,这种情况is improved somewhat ,您可以将值设置为 None:

MIGRATION_MODULES = {"myapp": None}

关于django - 在 Django 1.7 中运行单元测试时禁用迁移,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25161425/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com