简体   繁体   中英

how to test the same function from various modules using pytest

I would like to run my test for a function from different modules (in one module I define the function that calls some C++ code and in the other module I have the same function that calls different code). What is the way to do it using py.test?

You can use metafunc and create conftest.py file with pytest_addoption and pytest_generate_tests functions:

def pytest_addoption(parser):
    parser.addoption("--libname", action="append", default=[],
                     help="name of the tested library")

def pytest_generate_tests(metafunc):
    if 'libname' in metafunc.fixturenames:
        metafunc.parametrize("libname", metafunc.config.option.libname)

And in the function in your tests.py file you can use importlib and ask for libname:

def test_import(libname):
    import importlib
    tested_library = importlib.import_module(libname)
    .......

Now, running your test you should provide the name of the module you want to test: py.test tests.py --libname=your_name1 (you can also add --libname=your_name2 )

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