简体   繁体   中英

How to pass test parameters from pytest_generate_tests to fixtures

I am using pytest and in my conftest.py file, i have added my own defined arguments which i pass from command line. The conftest.py file is as follows

def pytest_addoption(parser):
    parser.addoption("--myoption", action="store", help="...")

def pytest_generate_tests(metafunc):
    if ("callobj" in metafunc.fixturenames):
        if metafunc.config.getoption("--myoption") == "ABC":
            myparam = [ABCobject]
        if metafunc.config.getoption("--myoption") == "XYZ":
            myparam = [XYZobject]
            metafunc.parametrize("abc", myparam)

in test_mytest.py, i have a test like

def test_mytest(callobj):
        assert callobj.performAction() 

Now i have lots of options to test which i can pass through command line arguments

pytest --myoption=ABC

and every option (object) needs different setup which i want to setup from fixtures.

My question is that how can i pass that --myoption parameter object to fixture so that before running test the object could be setup and teardown

Isn't this what you are looking for?

# 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM