pytest (二) fixture scope参数使用

fixture参数如下
param scope:function(默认), class, module, session, package
function的作用域在每个测试用例都执行一次
class的作用域在每个类下只执行一次
module的作用域在每个py文件下只执行一次
session的作用域在整个测试工程只执行一次
package和seesion类似
# function
import pytest

@pytest.fixture(scope='function', autouse=True)
def begin():
  print('执行 function')

def test_a():
  print('执行 test_a')

# 结果如下
'''
执行 function
执行 test_a
'''
# class
import pytest

@pytest.fixture(scope='class', autouse=True)
def begin():
  print('执行 class')

class TestCase:
  
  def test_a():
    print('执行 test_a')
  
  def test_b():
    print('执行 test_b')

# 结果如下
'''
执行 class
执行 test_a
执行 test_b
'''
# module
import pytest

@pytest.fixture(scope='module', autouse=True)
def begin():
  print('执行 module')

class TestCaseA:
  
  def test_a():
    print('执行 test_a')
  
  def test_b():
    print('执行 test_b')

class TestCaseB:
  
  def test_c():
    print('执行 test_c')
  
  def test_d():
    print('执行 test_d')

# 结果如下
'''
执行 module
执行 test_a
执行 test_b
执行 test_c
执行 test_d
'''
# session
import pytest

@pytest.fixture(scope='session', autouse=True)
def begin():
  print('执行 session')

a.py
class TestCaseA:
  
  def test_a():
    print('执行 test_a')

b.py
class TestCaseB:
  
  def test_b():
    print('执行 test_c')


# 结果如下
'''
执行 session
执行 test_a
执行 test_b
'''
posted @ 2025-03-17 22:15  アーニャ  阅读(63)  评论(0)    收藏  举报