
在 Django 项目中测试非托管模型(managed = False)可能很棘手,尤其是在测试环境包含托管和非托管模型混合,或涉及多个数据库时。本文探讨几种使用 pytest-django 测试非托管模型的方法,并分析其优缺点。
方法一:临时将所有模型标记为托管
最简单的解决方法是,在测试期间暂时将所有非托管模型标记为托管。 这可以通过修改 conftest.py 文件实现:
<code class="python">@pytest.hookimpl(tryfirst=True)
def pytest_runtestloop():
from django.apps import apps
for app in apps.get_app_configs():
for model in app.get_models():
if not model._meta.managed:
model._meta.managed = True</code>重要:此方法需要在 pytest 命令中添加 --no-migrations 选项。
优点: 简单易行。
缺点: 绕过了迁移测试,这在多人协作开发时可能导致问题。
方法二:手动创建和删除非托管模型
更稳妥的方法是在测试设置中手动创建和删除非托管模型,确保迁移得到测试。 可以使用以下 pytest fixture:
<code class="python">@pytest.fixture(scope="session", autouse=True)
def django_db_setup(django_db_blocker, django_db_setup):
with django_db_blocker.unblock():
for connection in connections.all():
with connection.schema_editor() as schema_editor:
setup_unmanaged_models(connection, schema_editor)
yield
def setup_unmanaged_models(connection, schema_editor):
from django.apps import apps
for model in apps.get_models():
if not model._meta.managed:
if connection.introspection.table_names(cursor=connection.cursor()):
schema_editor.delete_model(model)
schema_editor.create_model(model)
</code>优点: 包含迁移测试。
缺点: 实现较为复杂;transaction=True 不适用(详见下文)。
事务测试与非托管模型
pytest-django 提供了 django_db 和 django_db(transaction=True) 两个 fixture。
django_db:在测试结束时回滚数据库更改。django_db(transaction=True):在每个测试用例后提交更改并截断数据库表。 只有托管模型会被截断。
方法三:在事务测试中临时将非托管模型标记为托管
为了使 transaction=True 与非托管模型兼容,可以在测试运行期间将非托管模型临时标记为托管,使其包含在截断过程中:
<code class="python">def setup_unmanaged_models(connection, schema_editor):
# ... (代码同上) ...
for model in unmanaged_models:
# ... (代码同上) ...
model._meta.managed = True # 关键:临时标记为托管</code>方法四:使用 on_commit hooks 避免 transaction=True (如果适用)
如果你的测试涉及 on_commit hooks,可以使用 pytest-django (>= v.4.4) 的 django_capture_on_commit_callbacks fixture 来避免使用 transaction=True:
<code class="python">@pytest.mark.django_db
def mytest(django_capture_on_commit_callbacks):
with django_capture_on_commit_callbacks(execute=True):
# 测试逻辑
# on_commit hooks 将立即执行</code>总结
选择哪种方法取决于你的项目复杂性和需求。 如果简单性优先,方法一可能足够;如果需要更全面的测试覆盖率,则方法二或三更合适。 方法四提供了在特定场景下更优雅的解决方案。 请根据实际情况选择最合适的方法。
参考:
希望这些信息对您有所帮助! 如果您还有其他方法或技巧,欢迎分享!
以上就是在 Pytest-Django 中处理非托管模型的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号