pytest-コマンドラインは、カスタムパラメータをテストファイルに転送します.

6026 ワード

仕事の中で1つの問題に出会って、シリアル文字COM 6を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")