Python 如何使用pytest测试不同模块中的相同功能 我想从不同的模块运行一个函数的测试(在一个模块中,我定义了调用C++代码的函数,而在另一个模块中,我有相同的函数调用不同的代码)。使用py.test的方法是什么?

Python 如何使用pytest测试不同模块中的相同功能 我想从不同的模块运行一个函数的测试(在一个模块中,我定义了调用C++代码的函数,而在另一个模块中,我有相同的函数调用不同的代码)。使用py.test的方法是什么?,python,pytest,Python,Pytest,您可以使用metafunc并使用pytest\u addoption和pytest\u generate\u tests函数创建conftest.py文件: def pytest_addoption(parser): parser.addoption("--libname", action="append", default=[], help="name of the tested library") def pytest_generate_t

您可以使用metafunc并使用
pytest\u addoption
pytest\u generate\u tests
函数创建
conftest.py
文件:

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)
tests.py
文件的函数中,您可以使用importlib并请求libname:

def test_import(libname):
    import importlib
    tested_library = importlib.import_module(libname)
    .......
现在,在运行测试时,您应该提供要测试的模块的名称:
py.tests.py--libname=your_name1
(您也可以添加
--libname=your_name2

查看文档和自定义装置。部分参数化测试和metafunc对象感谢您的建议,我决定使用
pytest\u generate\u tests(metafunc)
,它可以正常工作。回答这个问题,并将您的代码发布到社区&链接到材料。谢谢好的,我已经做了,但是改变了原来的问题,所以它更符合我最终使用的解决方案。