Python 使用命令行和fixture中的数据库详细信息进行pytest

Python 使用命令行和fixture中的数据库详细信息进行pytest,python,django,pytest,pytest-django,Python,Django,Pytest,Pytest Django,我正试图通过从命令行传递的值初始化DbforPytest。我不能在不同的test setting.py中指定值,也不能在settings.py的test选项中指定值;它只能通过命令行使用 我在confttest.py中设置了额外的命令行选项,以获取数据库详细信息: def pytest_addoption(parser): parser.addoption( "--dbconnection", action="store", default = "novalue", he

我正试图通过从命令行传递的值初始化DbforPytest。我不能在不同的test setting.py中指定值,也不能在settings.py的test选项中指定值;它只能通过命令行使用

我在confttest.py中设置了额外的命令行选项,以获取数据库详细信息:

def pytest_addoption(parser):
    parser.addoption(
        "--dbconnection", action="store", default = "novalue", help="test db value"
    )
是否有任何方法可以访问conftest.py中的这些值?好的,我可以使用fixture在测试中获取值,但是我想用这些命令行参数覆盖
django\u db\u modify\u db\u设置来更改数据库

这可能吗?在处理命令行之前是否初始化了数据库?我试过一些实验,结果确实如此。有没有其他的解决办法来让这个工作

是否有任何方法可以访问conftest.py中的这些值

您可以访问所有装置(通过
request.config
)和(大多数)hook impl中的命令行参数

在处理命令行之前是否初始化了数据库

不,在解析命令行之后,数据库会在很久之后初始化。在
pytest\u configure
hooks中可以访问命令行参数,并且数据库连接在
django\u db\u设置
fixture之前未初始化,因此在第一次调用
pytest\u runtest\u设置
hooks之前也未初始化

示例,从
addopt
hook扩展:

import pytest


def pytest_addoption(parser):
    parser.addoption(
        "--dbconnection", action="store", default = "novalue", help="test db value"
    )


@pytest.fixture(scope='session')
def django_db_modify_db_settings(request):
    from django.conf import settings
    testdb_settings = settings.DATABASES['default']['TEST']
    dbconn = request.config.getoption('--dbconnection')
    if dbconn == 'infile':
        testdb_settings['NAME'] = '/tmp/testdb.sqlite'
    elif dbconn == 'inmem':
        testdb_settings['NAME'] = ':memory:'
    else:
        raise RuntimeError('Unknown option value.')
运行
pytest--dbconnection=inmem
将使用内存中的数据库,运行
pytest--dbconnection=infle
将使用该文件(您可以使用
--reuse db
重新运行,以验证数据库文件是否已创建)