【问题标题】:How to pass arguments in pytest by command line如何通过命令行在pytest中传递参数
【发布时间】:2017-04-14 07:08:49
【问题描述】:

我有一个代码,我需要从终端传递名称等参数。 这是我的代码以及如何传递参数。我收到一个我不理解的“找不到文件”类错误。

我已经在终端尝试了命令:pytest <filename>.py -almonds 我应该把名字印成“杏仁”

@pytest.mark.parametrize("name")
def print_name(name):
    print ("Displaying name: %s" % name)

【问题讨论】:

  • 要考虑的是,pytest 真的希望你能够在命令行上指定多个测试文件。在这种情况下,命令行参数会发生什么?每个人都使用-almonds吗?如果两个不同的测试需要不同的参数怎么办?

标签: python testing pytest command-line-arguments


【解决方案1】:

根据official document,标记装饰器应如下所示。

@pytest.mark.parametrize("arg1", ["StackOverflow"])
def test_mark_arg1(arg1):
    assert arg1 == "StackOverflow" #Success
    assert arg1 == "ServerFault" #Failed

运行

python -m pytest <filename>.py
  • 注意1:函数名必须以test_开头
  • 注意2:pytest 将重定向stdout (print),因此直接运行stdout 将无法在屏幕上显示任何结果。此外,您无需在测试用例的函数中打印结果。
  • 注意3:pytest是python运行的模块,无法直接获取sys.argv

如果您真的想获得外部可配置参数,您应该在脚本中实现它。 (例如加载文件内容)

with open("arguments.txt") as f:
    args = f.read().splitlines()
...
@pytest.mark.parametrize("arg1", args)
...

【讨论】:

    【解决方案2】:

    在你的 pytest 测试中,不要使用@pytest.mark.parametrize:

    def test_print_name(name):
        print ("Displaying name: %s" % name)
    

    conftest.py:

    def pytest_addoption(parser):
        parser.addoption("--name", action="store", default="default name")
    
    
    def pytest_generate_tests(metafunc):
        # This is called for every test. Only get/set command line arguments
        # if the argument is specified in the list of test "fixturenames".
        option_value = metafunc.config.option.name
        if 'name' in metafunc.fixturenames and option_value is not None:
            metafunc.parametrize("name", [option_value])
    

    然后你可以使用命令行参数从命令行运行:

    pytest -s tests/my_test_module.py --name abc
    

    【讨论】:

    • 什么是@pytest.mark.unit?你为什么用它?看来您的代码没有它也可以工作,我可以省略它吗?
    • 不要使用它。我从答案中删除了它。过去,它在旧版本的 pytest 中得到支持甚至推荐。在较新版本的 pytest 中,它已被删除且不受支持。
    • 使用测试类时会发生什么? :)
    • 您能否指出如何在测试“fixturenames”列表中添加参数,正如您在回答中所说的那样。
    • 可以在pytest documentation上看到对pytest_generate_tests的解释
    【解决方案3】:

    我在这里偶然发现如何传递参数,但我想避免参数化测试。接受的答案确实很好地解决了从命令行参数化测试的确切问题,但我想提供一种替代方法来将命令行参数传递给特定测试。下面的方法使用一个夹具,如果指定了夹具但参数未指定,则跳过测试:

    test.py

    def test_name(name):
        assert name == 'almond'
    

    conftest.py

    import pytest
    
    def pytest_addoption(parser):
        parser.addoption("--name", action="store")
    
    @pytest.fixture(scope='session')
    def name(request):
        name_value = request.config.option.name
        if name_value is None:
            pytest.skip()
        return name_value
    

    例子:

    $ py.test tests/test.py
    =========================== test session starts ============================
    platform linux -- Python 3.7.1, pytest-4.0.0, py-1.7.0, pluggy-0.8.0
    rootdir: /home/ipetrik/dev/pytest_test, inifile:
    collected 1 item
    
    tests/test.py s                                                      [100%]
    
    ======================== 1 skipped in 0.06 seconds =========================
    

    $ py.test tests/test.py --name notalmond
    =========================== test session starts ============================
    platform linux -- Python 3.7.1, pytest-4.0.0, py-1.7.0, pluggy-0.8.0
    rootdir: /home/ipetrik/dev/pytest_test, inifile:
    collected 1 item
    
    tests/test.py F                                                      [100%]
    
    ================================= FAILURES =================================
    ________________________________ test_name _________________________________
    
    name = 'notalmond'
    
        def test_name(name):
    >       assert name == 'almond'
    E       AssertionError: assert 'notalmond' == 'almond'
    E         - notalmond
    E         ? ---
    E         + almond
    
    tests/test.py:5: AssertionError
    ========================= 1 failed in 0.28 seconds =========================
    

    $ py.test tests/test.py --name almond
    =========================== test session starts ============================
    platform linux -- Python 3.7.1, pytest-4.0.0, py-1.7.0, pluggy-0.8.0
    rootdir: /home/ipetrik/dev/pytest_test, inifile:
    collected 1 item
    
    tests/test.py .                                                      [100%]
    
    ========================= 1 passed in 0.03 seconds =========================
    

    【讨论】:

    • python3 -m pytest test.py --name qwe 给出错误:pytest.py: error: unrecognized arguments: --name qwe。我没有py.test,在这种情况下我该怎么办,你能澄清一下吗?
    • @ged - 以您的称呼方式称呼它对我有用。请注意,您应该有两个文件 - conftest.py 和 test.py。我已经编辑了答案以使其更清楚。
    【解决方案4】:

    使用conftest.py 中的pytest_addoption 挂钩函数来定义一个新选项。
    然后在自己的夹具中使用pytestconfig 夹具来获取名称。
    您也可以在测试中使用 pytestconfig 以避免编写自己的夹具,但我认为让选项拥有自己的名称会更简洁一些。

    # conftest.py
    
    def pytest_addoption(parser):
        parser.addoption("--name", action="store", default="default name")
    
    # test_param.py 
    
    import pytest
    
    @pytest.fixture(scope="session")
    def name(pytestconfig):
        return pytestconfig.getoption("name")
    
    def test_print_name(name):
            print(f"\ncommand line param (name): {name}")
    
    def test_print_name_2(pytestconfig):
        print(f"test_print_name_2(name): {pytestconfig.getoption('name')}")
    
    # in action
    
    $ pytest -q -s --name Brian test_param.py
    
    test_print_name(name): Brian
    .test_print_name_2(name): Brian
    .
    

    【讨论】:

    • 我遵循了这个模式,在我的例子中还添加了一个 pytest 标记 @pytest.mark.model_diagnostics 来描述那些需要输入的测试,例如pytest -m model_diagnostics --fp-model=./model.h5。这也需要“注册”您的商标,例如在您的pytest.ini
    【解决方案5】:

    根据命令行选项将不同的值传递给测试函数
    假设我们要编写一个依赖于命令行选项的测试。这里有一个 实现这一目标的基本模式:

    # content of test_sample.py
    def test_answer(cmdopt):
        if cmdopt == "type1":
            print("first")
        elif cmdopt == "type2":
            print("second")
        assert 0  # to see what was printed
    
    For this to work we need to add a command line option and provide the cmdopt through a fixture function:
    
    # content of conftest.py
    import pytest
    
    
    def pytest_addoption(parser):
        parser.addoption(
            "--cmdopt", action="store", default="type1", help="my option: type1 or type2"
        )
    
    
    @pytest.fixture
    def cmdopt(request):
        return request.config.getoption("--cmdopt")
    

    参考: https://docs.pytest.org/en/latest/example/simple.html#pass-different-values-to-a-test-function-depending-on-command-line-options

    然后你可以调用它:

    pytest --cmdopt type1
    

    【讨论】:

      【解决方案6】:

      如果你习惯了 argparse,你可以在 arparse 中照常准备

      import argparse
      import sys
      
      DEFAULT_HOST = test99
      #### for --host parameter ###
      def pytest_addoption(parser):
          parser.addoption("--host")   # needed otherwhise --host will fail pytest
      
      parser = argparse.ArgumentParser(description="run test on --host")
      parser.add_argument('--host', help='host to run tests on (default: %(default)s)', default=DEFAULT_HOST)
      args, notknownargs = parser.parse_known_args()
      if notknownargs:
          print("pytest arguments? : {}".format(notknownargs))
      sys.argv[1:] = notknownargs
      
      #
      then args.hosts holds you variable, while sys.args is parsed further with pytest.
      

      【讨论】:

        【解决方案7】:

        您所要做的就是在conftest.py 中使用pytest_addoption(),最后使用request 夹具:

        # conftest.py
        
        from pytest import fixture
        
        
        def pytest_addoption(parser):
            parser.addoption(
                "--name",
                action="store"
            )
        
        @fixture()
        def name(request):
            return request.config.getoption("--name")
        

        现在你可以运行你的测试了

        def my_test(name):
            assert name == 'myName'
        

        使用:

        pytest --name myName
        

        【讨论】:

          【解决方案8】:

          这是一种解决方法,但它会将参数带入测试。根据要求,这可能就足够了。

          def print_name():
              import os
              print(os.environ['FILENAME'])
              pass
          

          然后从命令行运行测试:

          FILENAME=/home/username/decoded.txt python3 setup.py test --addopts "-svk print_name"
          

          【讨论】:

            猜你喜欢
            • 2017-08-04
            • 2014-10-17
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2022-06-15
            • 2019-06-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多