【问题标题】:pytest-django django_db_server fixture not workingpytest-django django_db_server 夹具不工作
【发布时间】:2022-06-11 21:23:10
【问题描述】:

我想使用专门的测试数据库对我的 Django 应用程序进行单元测试。我正在使用pytestpytest-django。根据pytest-django 说明,我在conftest.py 文件中提供了我自己的自定义django_db_setup 夹具,如下所示:

from pathlib import Path

import pytest
from django.conf import settings


@pytest.fixture(scope='session')
def django_db_setup():
    base_dir = Path(__file__).parent
    path = base_dir / 'test_db.sqlite3'
    assert path.exists()
    assert path.is_file()

    settings.DATABASES['default'] = {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': path
    }

我可以确认在运行单元测试时正在执行此代码,并且正在找到 test_db.sqlite3 数据库。但是,单元测试仍然指的是我的开发数据库而不是我的测试数据库。

如何让pytest-django 引用我的测试数据库而不是我的开发数据库?

【问题讨论】:

    标签: python django pytest pytest-django


    【解决方案1】:

    我几天前才开始探索 pytest 和 pytest-django,但我正在使用测试数据库,方法是在我的项目根文件夹中创建一个 pytest.ini 文件,如下所示:

    [pytest]
    DJANGO_SETTINGS_MODULE = myproject.test_settings
    

    文件夹树是这样的:

    myproject
      |  
      ------app_one
      |
      ------myproject
        |
        ------settings.py
        |
        --------test_settings.py
    

    test_settings.py 文件如下所示

    from .settings import *
    
    
    DATABASES = {
        "default": {
            "ENGINE": "django.db.backends.sqlite3",
            "NAME": "db_test.sqlite3",
        }
    }
    
    

    您可以在docs 中查看更多信息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-11
      • 1970-01-01
      • 2016-07-27
      • 2020-12-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多