Python 【求助】pytest 自定义命令行参数不生效的问题

MAOFANS · 2023年03月02日 · 最后由 tester 回复于 2023年03月07日 · 4818 次阅读

我想要使用自定义命令行参数的方式,向 pytest 脚本传参。

首先我在 conftest.py 里通过 pytest_addoption 函数用来定义命令行的参数,country 为自定义的 fixture,用来获取从命令行传进来的参数值。


import pytest


def pytest_addoption(parser):
    parser.addoption("--country", action="store", default="China",
                     help="set country")


@pytest.fixture()
def country(request):
    return request.config.getoption("--country")

然后在 test.py 中通过 pytest.main 运行

import pytest

def test_demo(country):
    print("当前所在的国家:", country)


if __name__ == '__main__':

    pytest.main(["-s --country=中国"])

执行结果如下:发现自定义命令行参数未生效

请问大佬,这种问题怎么解决啊?

共收到 7 条回复 时间 点赞

我使用你相同的代码,只是将 pytest.main(["-s --country=中国"]) 调整为 pytest.main(["-s", "--country=中国"]) 即可正常输出如下内容

追风 回复

我用了相同的方式,但输出的还是默认值

我尝试如果在命令行使用 pytest -s 运行,就会出现和你一样的现象。不过如果我使用 python .\test_1.py 就会正常输出。你可以查看一下是不是你的运行方式有问题。

追风 回复

我修改了 pycharm 的解释器,不使用 pytest,使用普通方式运行,这样可以成功运行

MAOFANS 回复

恭喜你🍻 🍻


命令行运行可以正常输出。或者把 pytest.main()启动命令单独写在一个根目录文件上

pytest.main() 写在最外层的 conftest.py 即可

需要 登录 后方可回复, 如果你还没有账号请点击这里 注册