pytest的fixture梳理

fixture特性

夹具是在测试中用于提供共享资源、设置测试环境或模拟行为的工具。

1. 可以重复使用,多个用例可以使用同一个fixture

2. 一个测试用例可以使用多个装置

python 复制代码
import pytest
# Arrange
@pytest.fixture
def first_entry():
    return "a"

# Arrange
@pytest.fixture
def second_entry():
    return 2

# Arrange
@pytest.fixture
def order(first_entry, second_entry):
    return [first_entry, second_entry]

2.1 如果多个装置存在yield,则是先进后出

python 复制代码
import pytest

@pytest.fixture
def a():
    print("hello")
    yield
    print("this is a")

@pytest.fixture
def b():
    print("world")
    yield
    print("this is b")

def test_demo(a, b):
    print("this is test_demo")

if __name__ == '__main__':
    pytest.main(["-sv", "test1.py"])

3. fixture的返回值不需要接收

  • 如果一个fixture存在返回值,那么可以通过函数名直接使用其返回值,如下所示:
python 复制代码
import pytest
@pytest.fixture
def first_entry():
    return "a"

def test_a(first_entry):
    print(first_entry)

if __name__ == '__main__':
    pytest.main(["-sv","test1.py"])

4. fixfure多重嵌套

  • 如下append_firsttest_string_only并且此fixture缓存即order,根据gpt即我的测试
    如果一个 fixture 被请求了多次,但它的作用范围是函数级别(默认),那么这个 fixture 在每次请求时都会重新执行一次,而不会缓存。这会导致每次请求获得的数据都是独立的,不受前一次请求的影响。

所以一般不要使用缓存,保证起独立性

python 复制代码
import pytest

# Arrange
@pytest.fixture
def first_entry():
    return "a"


# Arrange
@pytest.fixture
def order():
    return []
    
# Act
@pytest.fixture
def append_first(order, first_entry):
    order.append(first_entry)
    return order

def test_string_only(append_first, order, first_entry):
    # Assert
    print(append_first) # ['a']
    print(order) ['a']
    assert order == [first_entry]

pytest.main(["-sv", "test1.py"])

5自动使用fixture,不需要请求

  • 设置和清理环境、全局配置,例如数据库连接、日志设置等可以使用,笔者用的不多
python 复制代码
import pytest

@pytest.fixture
def first_entry():
    return "a"
    
@pytest.fixture(autouse=True)
def order():
    return "hello world"

def test_a(order):
    print(order)

pytest.main(["-sv", "test1.py"])

6 动态定义fixture范围

7 安全拆卸的fixture

8fixture的request

9 fixture的参数化

相关推荐
知识中的海王2 分钟前
猿人学web端爬虫攻防大赛赛题第7题——动态字体,随风漂移
爬虫·python
手机忘记时间7 分钟前
在R语言中如何将列的名字改成别的
java·前端·python
愚润求学17 分钟前
【Linux】自定义shell的编写
linux·运维·服务器·开发语言·c++·笔记
Hello server27 分钟前
利用 Python pyttsx3实现文字转语音(TTS)
python·学习·语音识别
小王努力学编程44 分钟前
高并发内存池(二):项目的整体框架以及Thread_Cache的结构设计
开发语言·c++·学习·算法
陈奕昆1 小时前
4.3【LLaMA-Factory实战】教育大模型:个性化学习路径生成系统全解析
人工智能·python·学习·llama·大模型微调
码出钞能力1 小时前
对golang中CSP的理解
开发语言·后端·golang
金融数据出海2 小时前
黄金、碳排放期货市场API接口文档
java·开发语言·spring boot·后端·金融·区块链
豌豆花下猫2 小时前
Python 潮流周刊#101:Rust 开发的 Python 类型检查工具(摘要)
后端·python·ai
m0_578267862 小时前
从零开始的python学习(六)P86+P87+P88
python·学习