AIM - 我试图将配置变量'db_str'传递给我的pytest脚本(test_script.py)
db_str变量在development.ini
中定义我尝试过使用命令
pytest -c development.ini regression_tests/test_script.py
但它不起作用
错误
> conn_string = config['db_string']
KeyError: 'db_string'
我尝试使用conftest.py,但没有用
#contest.py code
import pytest
def pytest_addoption(parser):
parser.addoption("--set-db_st",
action="store",help="host='localhost' dbname='xyz' user='portaladmin'")
@pytest.fixture
def db_str(request):
return request.config.getoption("--set-db_str")
Pytest代码
from S4M_pyramid.modelimport MyModel
from S4M_pyramid.lib.deprecated_pylons_globals import config
import subprocess
config['db_str'] = db_str
def test_get_dataset_mapping_id():
result = MyModel.get_dataset_mapping_id()
assert len(result) >1
如何将变量'db_str'从development.ini或任何其他ini文件传递给pytest脚本
答案 0 :(得分:1)
逻辑是填充:
get_database_string
fixture中使用已解析的配置来获取数据库连接字符串get_database_string
fixture获取连接字符串<强> conftest.py 强>
import os
from configparser import ConfigParser
# in root of the project there is file project_paths.py
# with the following code ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
import project_paths
def pytest_addoption(parser):
"""Pytest hook that defines list of CLI arguments with descriptions and default values
:param parser: pytest specific argument
:return: void
"""
parser.addoption('--env', action='store', default='development',
help='setup environment: development')
@pytest.fixture(scope="function")
def get_database_string(get_config):
"""Fixture that returns db_string
:param get_config: fixture that returns ConfigParser object that access
to config file
:type: ConfigParser
:return: Returns database connection string
:rtype: str
"""
return get_config['<section name>']['db_string']
@pytest.fixture(scope="function")
def get_config(request):
"""Functions that reads and return ConfigParser object that access
to config file
:rtype: ConfigParser
"""
environment = request.config.getoption("--env")
config_parser = ConfigParser()
file_path = os.path.join(project_paths.ROOT_DIR, '{}.ini'.format(environment))
config_parser.read(file_path)
return config_parser
<强> test_file.py 强>
import pytest
def test_function(get_database_string)
print(get_database_string)
>>> <data base string from development.ini>
答案 1 :(得分:0)
如pytest_addoption所述:
添加选项
要添加命令行选项,请调用parser.addoption(...)。
要添加ini文件值,请调用 parser.addini (...)。
获取选项:
以后可以分别通过config对象访问选项:
config.getoption(name)检索命令行选项的值。
config.getini(name) ,以检索从ini样式文件中读取的值。
conftest.py:
def pytest_addoption(parser):
parser.addini('foo', '')
test.py:
def test_func(request):
request.config.getini('foo')