python-如何使用命令行在pytest中传递多个参数?

前端之家收集整理的这篇文章主要介绍了python-如何使用命令行在pytest中传递多个参数? 前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我想将输入作为命令行选项传递给pytest文件. https://stackoverflow.com/a/42145604/8031479这个问题很有帮助,但我不知道添加多个解析器采用.

我尝试将其添加到我的conftest.py文件中,但没有帮助:

  1. def pytest_addoption(parser):
  2. """
  3. This function is used to extract input1 and input2 values from the command line
  4. """
  5. parser.addoption(
  6. "--input1",action="store",default="input1"
  7. )
  8. parser.addoption(
  9. "--input2",default="input2"
  10. )

我的test.py文件内容

  1. import pytest
  2. @pytest.fixture()
  3. def get_input1(input1):
  4. print 'input1:',input1
  5. return input1
  6. # @pytest.mark.unit
  7. @pytest.fixture()
  8. def get_input2(input2):
  9. print 'input2:',input2
  10. return input2
  11. def test_hello(get_input1,get_input2):
  12. print 'testing pytest fixtures with command line options'
  13. print get_input1,get_input2

这是我运行test.py文件的命令:

  1. py.test test.py --input1="hello" --input2="world"

我收到此错误消息:

  1. @pytest.fixture()
  2. def get_input1(input1):
  3. E fixture 'input1' not found
  4. > available fixtures: cache,capfd,capfdbinary,caplog,capsys,capsysbinary,doctest_namespace,get_input1,get_input2,Metadata,monkeypatch,pytestconfig,record_property,record_xml_attribute,recwarn,tmp_path,tmp_path_factory,tmpdir,tmpdir_factory
  5. > use 'pytest --fixtures [testpath]' for help on them.
最佳答案
您可以通过以下方式使其工作:

conftest.py:

  1. import pytest
  2. def pytest_addoption(parser):
  3. parser.addoption("--input1",default="default input1")
  4. parser.addoption("--input2",default="default input2")
  5. @pytest.fixture
  6. def input1(request):
  7. return request.config.getoption("--input1")
  8. @pytest.fixture
  9. def input2(request):
  10. return request.config.getoption("--input2")

test.py:

  1. import pytest
  2. @pytest.mark.unit
  3. def test_print_name(input1,input2):
  4. print ("Displaying input1: %s" % input1)
  5. print("Displaying input2: %s" % input2)

CLI:

  1. >py.test -s test.py --input1 tt --input2 12
  2. ================================================= test session starts =================================================
  3. platform win32 -- Python 3.7.0,pytest-4.1.1,py-1.7.0,pluggy-0.8.1
  4. rootdir: pytest,inifile:
  5. collected 1 item
  6. test.py Displaying input1: tt
  7. Displaying input2: 12
  8. .
  9. ============================================== 1 passed in 0.04 seconds ===============================================

猜你在找的Python相关文章