四、Pytest Fixtures 详解

1.什么是fixture?

答:fixture是在测试函数运行前后,由pytest执行的外壳函数。fixture中的代码可以定制,满足多变的测试需求,包括定义传入测试中的数据集、配置测试前系统的初始状态、为批量测试提供数据源。等等。

2.声明fixture
@pytest.fixture()装饰器用于声明函数是一个fixture,下面是一个返回数值的简单fixture
ch3/test_fixtures.py
import pytest


@pytest.fixture()
def some_data():
"""返回特定数值"""
  return 42


def test_some_data(some_data):
"""在测试中使用fixture返回数值"""
 assert some_data == 4
3.通过conftest.py共享fixture

conftest.py中的fixture可以供所在目录及其子目录下的测试文件使用。

4.使用fixture执行配置及销毁逻辑
与unnitest的对比:
import unittest
# 单元测试用例
class TestDict(unittest.TestCase):
def setUp(self):
  # 测试数据库中,进行连接数据库
        print("setUp")
def test_now(self):
print("我才是测试函数")
 
  def tearDown(self):
        # 测试数据库中,关闭数据库
        print("tearDown")
ch3/a/tasks_proj/test/conftest.py
import pytest


@pytest.fixture()
def task_db():
"""测试函数开始前的操作"""
#  #setup:start db


yield #测试进行中,该fixture会返回给测试函数yield后面的值


"""在测试中使用fixture返回数值"""
 #teardown:close 
5.使用--setup-show回溯fixture的执行过程

--setup-show选项用于查看测试过程执行的是什么,以及执行的先后顺序。fixture名称签名的F和S代表的是fixture的作用范围,F代表函数级别的作用范围,S代表会话级别的作用范围。

6.使用fixture传递测试数据
fixture非常适合存放测试数据,并且它可以返回任何数据。
ch3/test_fixtures.py
import pytest


@pytest.fixture()
def some_data():
"""返回特定数值"""
  return 42


def test_some_data(some_data):
"""在测试中使用fixture返回数值"""
 assert some_data == 4
7.使用多个fixture
ch3/test_fixtures.py
import pytest


@pytest.fixture()
def some_data():
"""返回特定数值"""
  return 42
  
def other_data():
"""返回特定数值"""
  return 5


def test_some_data(some_data, other_data):
"""在测试中使用fixture返回数值"""
 assert some_data == 42
 assert other_data == 
8.指定fixture的作用范围
import pytest




@pytest.fixture(scope='function')
def func_scope():
    print("函数级别的fixtue")
@pytest.fixture(scope='module')
def module_scope():
    print("模块级别的fixtue")
@pytest.fixture(scope='session')
def session_scope():
    print("会话级别的fixtue")
@pytest.fixture(scope='class')
def class_scope():
    print("类级别的fixtue")




def test_func_01(func_scope,module_scope,session_scope):
    print("执行函数一")
def test_func_02(func_scope,module_scope,session_scope):
    print("执行函数2")
@pytest.mark.usefixtures('class_scope')
class Test_class():
    def test_func_03(self):
        print("执行类函数3")




    def test_func_04(self):
        print("执行类

执行结果:

test_add.py 
会话级别的fixtue
模块级别的fixtue
函数级别的fixtue
.执行函数一
函数级别的fixtue
.执行函数2
类级别的fixtue
.执行类函数3
.执行类函数4
9.为fixture重命名
@pytest.fixture(name="renamezhang")
def some():
    return 1


def test_someA(renamezhang):
    assert True
原文地址:https://www.cnblogs.com/hlsam/p/13152730.html