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

相关推荐
工具人55559 小时前
pytest练习
pytest
好家伙VCC11 小时前
# Pytest发散创新:从基础测试到智能断言的实战进阶指南在现代软
java·python·pytest
小罗和阿泽1 天前
GUI 自动化测试 pywinauto测试框架
开发语言·python·功能测试·测试工具·pytest
文人sec1 天前
抛弃 Postman!用 Pytest+Requests+Allure+Playwright+Minium 搭建高逼格接口+UI自动化测试平台
自动化测试·python·测试工具·ui·pytest·playwright
曲幽2 天前
FastAPI单元测试实战:别等上线被喷才后悔,TestClient用对了真香!
python·单元测试·pytest·api·fastapi·web·httpx·testclient·依赖项覆盖
小罗和阿泽2 天前
接口测试系列 接口自动化测试 pytest框架(四)
pytest
python开发笔记2 天前
pytest(16) mark用法
pytest
忘忧记2 天前
pytest 基础用法教程
pytest
我的xiaodoujiao3 天前
3、API 接口自动化测试详细图文教程学习系列3--相关Python基础知识2
python·学习·测试工具·pytest