pytest-命令行传入自定义的参数到测试文件中

工作中遇到一个问题,想把串口字符COM6传入pytest测试文件中,翻阅了不少资料,把心得总结如下:

1, 是经过conftest.py文件传入,代码如下:

Suppose we want to write a test that depends on a command line option. Here is a basic pattern to achieve this:

# 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")

Let’s run this without supplying our new option:

$ pytest -q test_sample.py
F                                                                    [100%]
================================= FAILURES =================================
_______________________________ test_answer ________________________________

cmdopt = 'type1'

    def test_answer(cmdopt):
        if cmdopt == "type1":
            print ("first")
        elif cmdopt == "type2":
            print ("second")
>       assert 0 # to see what was printed
E       assert 0

test_sample.py:6: AssertionError
--------------------------- Captured stdout call ---------------------------
first
1 failed in 0.12 seconds

And now with supplying a command line option:

$ pytest -q --cmdopt=type2
F                                                                    [100%]
================================= FAILURES =================================
_______________________________ test_answer ________________________________

cmdopt = 'type2'

    def test_answer(cmdopt):
        if cmdopt == "type1":
            print ("first")
        elif cmdopt == "type2":
            print ("second")
>       assert 0 # to see what was printed
E       assert 0

test_sample.py:6: AssertionError
--------------------------- Captured stdout call ---------------------------
second
1 failed in 0.12 seconds

这种方法的好处是,直接把参数传给测试函数

2, 直接在测试文件中调用 pytest.config.getoption("--cmdopt")


先在conftest.py文件中添加参数
# content of conftest.py
import pytest

def pytest_addoption ( parser ):
    parser . addoption ( "--cmdopt" , action = "store" , default = "type1" ,
        help = "my option: type1 or type2" )

然后在测试文件中直接调用pytest.config.getoption("--cmdopt")

你可能感兴趣的:(Pytest)