首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用pytest-django测试非托管模型

如何使用pytest-django测试非托管模型
EN

Stack Overflow用户
提问于 2020-05-05 15:17:55
回答 1查看 280关注 0票数 0

在我的django项目中,我有5个应用程序,总共有15个模型,它们都是非托管的。我用pytest-django编写了一些测试,当我运行它们时,由于找不到表而失败。

如何为所有这些模型创建数据库条目,以便测试不会失败?

EN

回答 1

Stack Overflow用户

发布于 2020-05-05 15:17:55

您可以覆盖conftest.py文件中的django_db_setup装置:

代码语言:javascript
复制
@pytest.fixture(scope="session")
def django_db_setup(django_db_blocker):

    with django_db_blocker.unblock():

        from django.apps import apps

        models_list = apps.get_models()
        for model in models_list:
            with connection.schema_editor() as schema_editor:
                schema_editor.create_model(model)

                if model._meta.db_table not in connection.introspection.table_names():
                    raise ValueError(
                        "Table `{table_name}` is missing in test database.".format(
                            table_name=model._meta.db_table
                        )
                    )

        yield

        for model in models_list:
            with connection.schema_editor() as schema_editor:
                schema_editor.delete_model(model)

这将在运行测试之前为非托管模型创建表,并在测试后删除这些表。

票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61607752

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档