【问题标题】:How to test unmanaged models using pytest-django如何使用 pytest-django 测试非托管模型
【发布时间】:2020-05-05 07:17:55
【问题描述】:

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

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

【问题讨论】:

    标签: django django-models pytest pytest-django


    【解决方案1】:

    您可以覆盖conftest.py 文件中的django_db_setup 夹具:

    @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)
    

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

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-07-02
    • 2013-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-09
    • 2020-01-29
    相关资源
    最近更新 更多