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的便捷之处。

相关推荐
杨梅树19 小时前
pytest中mark的使用
pytest
测试开发技术3 天前
如何在 Pytest 中调用其他用例返回的接口参数?
面试·自动化·pytest·接口·接口测试·api测试
思则变4 天前
[Pytest][Part 4]多种测试运行方式
pytest
程序员三藏4 天前
如何使用Pytest进行测试?
自动化测试·软件测试·python·测试工具·职场和发展·测试用例·pytest
一个处女座的测试6 天前
Python语言+pytest框架+allure报告+log日志+yaml文件+mysql断言实现接口自动化框架
python·mysql·pytest
思则变9 天前
[Pytest][Part 1]Pytest 自动化测试框架
pytest
思则变10 天前
[Pytest] [Part 2]增加 log功能
开发语言·python·pytest
思则变11 天前
[Pytest][Part 3]检测python package状态
pytest
cooldream200925 天前
pytest 框架详解与实战指南
pytest·测试
慕城南风25 天前
【pytest进阶】Pytest之conftest详解
pytest