每个测试功能都需要调用模块作用域的夹具

时间:2019-10-25 07:00:22

标签: python pytest

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”,我会得到相同的输出

1 个答案:

答案 0 :(得分:1)

在定义灯具范围时有一个小错误。现在,您将范围作为参数传递给Fixture函数。应该在@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,这是默认值,除非用户指定。