首页 > 解决方案 > 模块范围的夹具被每个测试功能调用

问题描述

pytest 正在为每个预期的测试功能调用模块级夹具,每个模块只应调用一次夹具

#content of test_fin.py
import pytest
import time
import logging


@pytest.fixture
def do_setup_tear(scope="module"):
    logging.getLogger().info('doing setup stuff if needed')
    yield None
    logging.getLogger().info('teardown')


def test_do_this():
    time.sleep(5) 
    assert True

def test_do_that(do_setup_tear):
    time.sleep(5)
    assert True

def test_do_thing(do_setup_tear):
    time.sleep(5) 
    assert True

实际结果:

============================= test session starts =============================
platform win32 -- Python 3.7.0, pytest-5.2.2, py-1.8.0, pluggy-0.13.0
rootdir: C:\Users\<username>\PycharmProjects\blabla\tests, inifile: pytest.ini
plugins: allure-pytest-2.8.6
collected 3 items

test_fin.py::test_do_this PASSED                                         [ 33%]
test_fin.py::test_do_that
------------------------------- live log setup --------------------------------
2019-10-25 12:12:36 INFO doing setup stuff if needed
PASSED                                                                   [ 66%]
------------------------------ live log teardown ------------------------------
2019-10-25 12:12:41 INFO teardown

test_fin.py::test_do_thing
------------------------------- live log setup --------------------------------
2019-10-25 12:12:41 INFO doing setup stuff if needed
PASSED                                                                   [100%]
------------------------------ live log teardown ------------------------------
2019-10-25 12:12:46 INFO teardown


============================= 3 passed in 15.06s ==============================

我在这里错过了什么吗。如果我修改scope="module"为 `scope="function" 我会得到相同的输出

标签: pythonpytest

解决方案


您如何定义夹具范围存在一个小错误。现在,您将作用域作为参数传递给夹具函数。应该用它就@pytest.fixture行了。

@pytest.fixture(scope="module")
def do_setup_tear():
    logging.getLogger().info('doing setup stuff if needed')
    yield None
    logging.getLogger().info('teardown')

如果我将 scope="module" 修改为 scope="function" 我会得到相同的输出

这是因为现在function除非用户指定,否则夹具范围是默认值。


推荐阅读