我可以将 ini 样式配置添加到 pytest 套件吗?

Can I add ini style configuration to pytest suites?

我正在使用 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 文件选项。

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.

可以通过调用 config.getini(name).

来检索 ini 变量的值