Skip to main content
 首页 » 编程设计

python之从另一个 pip 安装的包针对本地代码运行 py.test 测试

2025年04月02日11sxdcgaq8080

我正在构建一个包,它提供 (1) 固定接口(interface)和 (2) 可插拔驱动程序。所需的驱动程序将由软件包的用户选择。我的包将包含至少一个驱动程序,但我希望其他开发人员能够实现和验证符合包接口(interface)的驱动程序。因此,我希望这些开发人员能够针对他们的驱动程序运行我的测试。

目前,我正在使用 py.test 的参数化装置将我的驱动程序注入(inject)到我的测试中:

# conftest.py 
import my_pkg 
import pytest 
 
@pytest.fixture(params=[my_pkg.MyDriver]) 
def driver(request): 
    return request.param 
# my_pkg/tests/conftest.py 
import my_pkg 
import pytest 
 
@pytest.fixture 
def my_interface(driver): 
    return my_pkg.MyInterface(driver) 
# my_pkg/tests/test_my_interface.py 
def test_that_it_does_the_right_thing(my_interface): 
    assert my_interface.some_method() == "some return value" 

我以这种方式构建它,希望有人能够针对他们的 driver fixture 版本收集并运行我的测试。换句话说,他们的包看起来像这样:

# setup.py 
from setuptools import setup 
 
setup( 
    # ... 
    install_requires=["my-pkg"]) 
# conftest.py 
import their_pkg 
import pytest 
 
@pytest.fixture(params=[their_pkg.TheirDriver]) 
def driver(request): 
    return request.param 

显然这还不足以让它工作,因为 py.test 似乎没有提供从外部包注入(inject)测试的选项。 但这怎么可能呢?

( This question 似乎在概念上相似,但作者似乎完全在一个代码库中工作。我想要一个完全独立 pip 安装的包,以便能够引用包含在我的 pip 安装包。)

请您参考如下方法:

I solved this 作者:

  1. 实现 a custom py.test collector,从我的包中移植必要的测试套件,
  2. 要求消费者在他们的一个测试文件中实例化我的自定义类 my_pkg.MyDriverSuite,然后,
  3. 编写使用 pytest_pycollect_makeitem Hook 的 a custom py.test plugin 来拦截自定义实例并注入(inject)我的收集器。

(注意:这种方法避免了参数化装置的使用。)


自定义收集器是迄今为止最难弄清楚的部分,因为它需要大量挖掘 py.test 内部结构,并最终重新实现核心 py.test 收集器的精简版本,Session,带有自定义 session Config,其 rootdir 设置为我的包。