[英]pytest with database details from command line and fixtures
I am trying to initialize the db for pytest through values passed from command line.我正在尝试通过从命令行传递的值来初始化 pytest 的数据库。 I cannot specify the values in a different test setting.py, nor can I specify it in TEST option in settings.py;
我不能在不同的测试 setting.py 中指定值,也不能在 settings.py 的 TEST 选项中指定它; it is only available through command line.
它只能通过命令行使用。
I have setup extra command line options in confttest.py, to get the db details:我在 conftest.py 中设置了额外的命令行选项,以获取数据库详细信息:
def pytest_addoption(parser):
parser.addoption(
"--dbconnection", action="store", default = "novalue", help="test db value"
)
Is there any way I can access these values in conftest.py?有什么办法可以在 conftest.py 中访问这些值吗? AFAIK, I can use fixtures to get the value in the test, but I would like to override
django_db_modify_db_settings
to change the database, with these command line arguments. AFAIK,我可以使用固定装置来获取测试中的值,但我想覆盖
django_db_modify_db_settings
以使用这些命令行参数更改数据库。
Is this possible?这可能吗? Is the database initialized before the command line is processed?
是否在处理命令行之前初始化了数据库? I tried some experiments and it does look so.
我尝试了一些实验,看起来确实如此。 Is there any other workaround to getting this working?
有没有其他解决方法可以让这个工作?
Is there any way I can access these values in conftest.py?
有什么办法可以在 conftest.py 中访问这些值吗?
You can access the command line arguments in all fixtures (via request.config
) and (most) hook impls.您可以访问所有装置(通过
request.config
)和(大多数)钩子实现中的命令行参数。
Is the database initialized before the command line is processed?
是否在处理命令行之前初始化了数据库?
No, the database is initialized a lot later after the command line was parsed.不,在解析命令行后,数据库会在很晚之后被初始化。 The command line args become accessible in
pytest_configure
hooks, and the database connection is not initialized before the django_db_setup
fixture, so not before the first invocation of pytest_runtest_setup
hooks.命令行参数可以在
pytest_configure
钩子中访问,并且数据库连接在django_db_setup
固定装置之前没有初始化,所以在pytest_runtest_setup
钩子的第一次调用之前不是。
Example, extended from your addopt
hook:示例,从您的
addopt
钩子扩展:
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.')
Running pytest --dbconnection=inmem
will use the in-memory db, running pytest --dbconnection=infile
will use the file (you can rerun with --reuse-db
to verify the db file is created).运行
pytest --dbconnection=inmem
将使用内存数据库,运行pytest --dbconnection=infile
将使用该文件(您可以使用--reuse-db
重新运行以验证数据库文件是否已创建)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.