我正在使用pytest在多个环境中运行测试,并且我想将该信息(理想情况下)包含在ini样式的配置文件中。我还想在命令行中覆盖部分或全部配置。我尝试在我的conftest.py
中使用钩子pytest_addoption
,如下所示:
def pytest_addoption(parser):
parser.addoption("--hostname", action="store", help="The host")
parser.addoption("--port", action="store", help="The port")
@pytest.fixture
def hostname(request):
return request.config.getoption("--hostname")
@pytest.fixture
def port(request):
return request.config.getoption("--port")
使用这个,我可以在命令行中添加配置信息,但不是在配置文件中。我也试过添加
[pytest]
addopts = --hostname host --port 311
到我的pytest.ini
文件,但那不起作用。有没有办法做到这一点,而不建立自己的插件?感谢您的宝贵时间。
解析器对象也有一个addini方法,您可以使用该方法通过ini文件指定配置选项。下面是它的文档:https://pytest.org/latest/writing_plugins.html?highlight=addini#_pytest.config.Parser.addini
addini(name, help, type=None, default=None)[source]
注册一个ini-file选项
Name: name of the ini-variable
Type: type of the variable, can be pathlist, args, linelist or bool.
Default: default value if no ini-file option exists but is queried.
ini-variables的值可以通过调用config.getini(name)来获取。
也许这个例子在早期版本的pytest上不起作用,但它实际上为我运行和执行
test_proj/pytest.ini
[pytest]
addopts = --hostname host --port 311
test_proj/conftest.py
def pytest_addoption(parser):
parser.addoption("--hostname", action="store", help="The host")
parser.addoption("--port", action="store", help="The port")
@pytest.fixture
def hostname(request):
return request.config.getoption("--hostname")
@pytest.fixture
def port(request):
return request.config.getoption("--port")
test_proj/test_module.py
def always_true():
assert True
def test_hostname(hostname):
assert hostname == "HOST_X"
def test_port(port):
assert port == "111"
和相应的控制台输出
$ pytest test_proj
============================ test session starts ================================
platform linux -- Python 3.6.8, pytest-4.6.9, py-1.8.1, pluggy-0.13.1
rootdir: ./test_proj, inifile: pytest.ini
collected 2 items
test_proj/test_module.py FF [100%]
=================================== FAILURES ===================================
__________________________________ test_hostname _______________________________
hostname = 'host'
def test_hostname(hostname):
> assert hostname == "HOST_X"
E AssertionError: assert 'host' == 'HOST_X'
E - host
E + HOST_X
test_proj/test_module.py:9: AssertionError
__________________________________ test_port ____________________________________
port = '311'
def test_port(port):
> assert port == "111"
E AssertionError: assert '311' == '111'
E - 311
E + 111
test_proj/test_module.py:12: AssertionError
============================ 2 failed in 0.04 seconds ============================
此外,在命令行指定似乎优先于ini值,这是很好的知道
$ pytest test_proj --host HOST_X --port 111
=========================== test session starts =======================
platform linux -- Python 3.6.8, pytest-4.6.9, py-1.8.1, pluggy-0.13.1
rootdir: ./test_proj, inifile: pytest.ini
collected 2 items
test_proj/test_module.py .. [100%]
======================== 2 passed in 0.01 seconds ========================