14、pytest像用参数一样使用fixture

官方实例

python 复制代码
# content of test_fruit.py
import pytest

class Fruit:
    def __init__(self, name):
        self.name = name
        self.cubed = False
        
    def cube(self):
        self.cubed = True
        
class FruitSalad:
    def __init__(self, *fruit_bowl):
        self.fruit = fruit_bowl
        self._cube_fruit()
        
    def _cube_fruit(self):
        for fruit in self.fruit:
            fruit.cube()
            
# Arrange
@pytest.fixture
def fruit_bowl():
    return [Fruit("apple"),Fruit("banana")]
    
    
def test_fruit_salad(fruit_bowl):
    # Act
    fruit_salad = FruitSalad(*fruit_bowl)
    
    # Assert
    assert all(fruit.cubed for fruit in fruit_salad.fruit)

解读与实操

在基本级别上,测试函数通过将它们声明为参数来请求它们所需的fixture。

当pytest运行测试时,它会查看该测试函数中的参数,然后搜索与这些参数名称相同的fixture。一旦pytest找到它们,它就运行这些fixture,捕获它们返回的内容,并将这些对象作为参数传递给测试函数。

场景应用

fixture是pytest最强大的功能之一,随着深入接触,会发现fixture的便捷之处。

相关推荐
测试老哥15 小时前
Pytest自动化测试框架tep环境变量、fixtures、用例三者之间的关系
自动化测试·软件测试·python·测试工具·测试用例·pytest·职场发展
小小测试开发16 小时前
Agent 安全测试:pytest 原生红队框架 RAMPART 实战解析
人工智能·pytest
不拘一格的叶三少5 天前
Pytest + Playwright 自动化测试工程设计要点 & 目录结构
测试工具·pytest
努力搬砖的咸鱼6 天前
意图理解:让Agent从需求描述自动生成Pytest测试策略
人工智能·python·ai·单元测试·pytest·agent
St_rive9 天前
Pytest skip&&skipif跳过⽤例
运维·服务器·pytest
努力搬砖的咸鱼12 天前
AI Agent测试全景图:它到底改变了什么
人工智能·python·ai·集成测试·pytest·agent·ai编程
X1A0RAN13 天前
自动化流水线提效·微观篇:pytest 执行顺序优化
自动化·pytest
久久学姐21 天前
Python+Playwright+Pytest+BDD,用FSM打造高效测试框架
python·pytest·bdd·playwright·fsm
小白上线*^_^*21 天前
Pytest 自动化测试框架速通指南(二)
软件测试·pytest·python测试框架·ai测试基础