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

相关推荐
Logintern0917 小时前
pytest的AST 断言重写
pytest
Tinyfacture2 天前
接口自动化之添加商品(pytest)
python·测试工具·自动化·pytest
ji_shuke4 天前
从零深入:基于 Playwright + Pytest + Allure 的企业级 Web 端到端自动化测试框架实战
前端·自动化测试·docker·jenkins·pytest·allure·playwright
祉猷并茂,雯华若锦5 天前
Selenium+Pytest自动化测试框架实战
selenium·测试工具·pytest
祉猷并茂,雯华若锦6 天前
Pytest+Selenium自动化测试:失败自动截图集成Allure报告
selenium·测试工具·pytest
我的xiaodoujiao9 天前
API 接口自动化测试详细图文教程学习系列32--Allure测试报告2
python·学习·测试工具·pytest
一孤程13 天前
Pytest+Selenium搭建自动化框架-保姆级实战教程
selenium·自动化·pytest
名字还没想好☜17 天前
用 pytest fixture 组织可维护的测试:告别一堆重复的 setUp
数据库·python·oracle·pytest·测试
自动化和Linux18 天前
【pytest在pycharm中运行与CMD命令运行区别一】
python·pycharm·pytest
博观而约取厚积而薄发20 天前
Pytest 从入门到精通,一篇就够(超详细实战教程)
python·测试工具·单元测试·自动化·pytest