【问题标题】:pytest: passing list as arguments from command line is not workingpytest:从命令行传递列表作为参数不起作用
【发布时间】:2020-12-15 12:41:12
【问题描述】:

当我从命令行使用列表作为参数运行 pytest 时,我遇到了以下错误..

pytest -vs test_sample.py --html=results.html --A_list=[A1, A2, A3]

错误:找不到文件:A2,

下面是我的 test_sample.py 代码

import pytest

def test_functionality(A_list):
    print("element in list: {}".format(A_list))

下面是我的 conftest.py 代码

def pytest_addoption(parser):
    parser.addoption("--A_list", action="store", default="default name")

def pytest_generate_tests(metafunc):
    option_value = metafunc.config.option.A_list
    if 'A_list' in metafunc.fixturenames and option_value is not None:
        metafunc.parametrize("A_list", [option_value])

如果我只传递一个像下面这样的元素,这很好用

pytest -vs test_sample.py --html=results.html --A_list=A1

但是,如果我使用如下 A_list 的元素列表运行 pytest,它会失败

    pytest -vs test_sample.py --html=results.html --A_list=[A1, A2, A3]

谁能告诉我如何从命令行将列表作为 pytest 参数传递...

【问题讨论】:

    标签: python-3.x pytest


    【解决方案1】:

    问题是您尝试将 Python 列表作为命令行参数传递。这不起作用 - 命令行参数只是需要解析的字符串。尤其是选项中不能有空格,如果你没有用撇号包围它。

    您可以做的是将列表作为字符串传递,例如通过逗号分隔条目:

    pytest -vs test_sample.py --html=results.html --A_list="A1,A2,A3"
    

    请注意,这里严格不需要撇号,因为您没有空格,但无论如何您都可以使用它们。然后你可以将字符串解析成一个列表:

    def pytest_generate_tests(metafunc):
        option_value = metafunc.config.option.A_list
        if option_value:
            params = option_value.split(",")
            if 'A_list' in metafunc.fixturenames:
                metafunc.parametrize("A_list", params)
    

    【讨论】:

    • 感谢@MrBean Bremen 的回答。我已经在另一个线程中针对多个固定装置发布了类似的问题,如果我能得到相同的解决方案会很好。尤其是 conftest.py 的外观。这是相同的链接。 [链接] (stackoverflow.com/questions/61864930/…)
    • 好的,稍后看看。这个不适合你吗?
    • 谢谢。它对我有用......实际上我在我的代码中使用了 4 个灯具,所以我需要从命令行传递列表作为所有灯具的参数。我在上面的链接中也提到过,你有时间可以看看它
    • 谢谢。我现在已经接受了你的回答.....我以为我已经接受了你的回答,但它没有显示在这里,因为我的声誉低于 15 ..
    猜你喜欢
    • 2020-06-21
    • 2013-07-15
    • 2021-10-10
    • 1970-01-01
    • 1970-01-01
    • 2017-11-22
    • 1970-01-01
    • 2012-03-12
    相关资源
    最近更新 更多