pytest中,fixture的scope可以设置的级别

发布时间 2023-05-20 17:41:56作者: peijiao

function:默认值,表示fixture将在测试函数被调用时执行,并且它们每个测试函数都会运行一次。

@pytest.fixture()

  def my_fixture():

  # setup code here

  yield

  # teardown code here

class:表示fixture将在类内所有测试方法之前和之后执行。一个类有多个测试方法,则该fixture仍只会执行一次。

@pytest.fixture(scope="class")
  def my_fixture():
  # setup code here
  yield
  # teardown code here

module:表示fixture将在模块(即.py文件)中所有测试函数之前执行一次,并在所有测试完成后执行。在同一个模块下多个测试函数使用同一个 fixture,则这个fixture也仅会被执行一次。

@pytest.fixture(scope="module")
  def my_fixture():
  # setup code here
  yield
  # teardown code here

session:表示fixture将在整个测试会话开始时执行,并在所有测试完成后执行。在同一个会话中多个模块使用同一个 fixture,则这个fixture也仅会被执行一次。

@pytest.fixture(scope="session")
  def my_fixture():
  # setup code here
  yield
  # teardown code here