首页 > 解决方案 > 具有全局范围的 py.test 夹具

问题描述

我正在寻找一种在py.test. 这似乎scope="session"最接近我的需要,但它似乎与scope="module"级别选项类似。夹具启动的总n次数,其中n是模块的数量。

基本上,我有这种初始化缓慢且资源匮乏的服务,可以进行形态分析

@pytest.fixture(scope='session', autouse=True)
def morfanalyzer():
    from myapp.nlp.morfservice import MorfAnalyzerService
    morfservice = MorfAnalyzerService()

    def f():
        morfservice.run(debug=True)

    thread = Thread(target=f)
    thread.start()

    yield morfservice

    morfservice.stop()
    thread.join()

我像使用它一样

@pytest.mark.usefixtures(morfanalyzer.__name__)
def test_this_stage(morfanalyzer):
    assert False

我想要的是,在运行所有测试之前,将启动该服务的一个副本,并在一切运行后拆除。

标签: pythontestingpytestfixtures

解决方案


通过scope="session"在您的夹具中指定,您将拥有一个会话范围的实例。您可以使用 cli 标志检查固定装置的设置和拆卸,如 3.0变更日志setup-show中所反映的那样

同样正如@hoefling 在评论中指出的那样,一旦设置autouse=True了标记测试usefixtures就不再需要了。


推荐阅读