【问题标题】:How can we accept multiple values for one command line option in pytest我们如何在 pytest 中接受一个命令行选项的多个值
【发布时间】:2023-03-31 06:45:02
【问题描述】:

我希望用户能够将多个值传递给一个命令行参数。例如,如果我的竞赛.py 的内容有:

parser.addoption("--url", action="store")

那么我希望用户能够做到这一点:

python -m pytest test_file.py --url "www.example1.com" "www.example2.com"

这个问题基本上是如何为一个选项接受多个参数。

【问题讨论】:

    标签: python command-line-arguments pytest


    【解决方案1】:

    您应该将操作从 store 更改为 append

    parser.addoption('-u', '--url',
        type=str,
        action='append')
    

    【讨论】:

    • 但这没有按预期工作!现在,当我通过类似 python -m pytest test_file.py --url "www.example1.com" "www.example2.com" 之类的东西时,它会给出一个错误提示“找不到文件:www.example2.com”,除非我删除两者之间的空间。因此,如果我通过 python -m pytest test_file.py --url "www.example1.com""www.example2.com" (参数之间没有空格),那么它实际上是附加的,但是像这样的单个字符串: ['www .example1.comwww.example2.com']
    • @RajatBhardwaj args = parser.parse_args()
    • 您能详细说明一下吗?这些是我的竞赛.py 的内容:<html><code>def pytest_addoption(parser): parser.addoption("--url", type=str, action="append") parser = addoption(parser) </code></html> 然后我使用它:'''def pytest_configure(config): config = configure(config) if config.getoption("url"): urls = config. getoption("url") '''
    【解决方案2】:

    对我来说,以下工作正常

    
    
    

    content of conftest.py

    import pytest

    def pytest_addoption(parser): parser.addoption( "-E", action="append", metavar="NAME", help="only run tests matching the environment NAME.", ) #opts, args = parser.parse_args(["-E"])

    def pytest_configure(config): # register an additional marker config.addinivalue_line( "markers", "env(name): mark test to run only on named environment" ) def pytest_runtest_setup(item): envnames = [mark.args[0] for mark in item.iter_markers(name="env")] if envnames: if ( item.config.getoption("-E") is not None )and (not any( x in envnames for x in item.config.getoption("-E")[0].split(",") )): pytest.skip("test requires env in {!r}".format(envnames))

    【讨论】:

      猜你喜欢
      • 2017-07-04
      • 2018-08-14
      • 1970-01-01
      • 2021-01-14
      • 2020-08-27
      • 2020-06-25
      • 1970-01-01
      • 2017-04-27
      • 1970-01-01
      相关资源
      最近更新 更多