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

相关推荐
欲游山河十万里6 小时前
pytest(三)——参数化@pytest.mark.parametrize
pytest
奶茶精Gaaa4 天前
pytest
pytest
霍格沃兹测试开发学社测试人社区6 天前
软件测试学习笔记丨Pytest 学习指南
软件测试·笔记·测试开发·学习·pytest
神即道 道法自然 如来8 天前
测试面试题:pytest断言时,数据是符点类型,如何断言?
pytest
high_tea8 天前
pytest - 多线程提速
python·pytest
傻啦嘿哟10 天前
自动化测试框架集成:将Selenium集成到pytest与unittest中
selenium·测试工具·pytest
一名在八月份找工作的测试员10 天前
自动化学习1:pytest自动化框架的基本用法:注意事项/断言assert/测试结果分析
学习·自动化·pytest
什么时候才能变强11 天前
Pytest-如何将allure报告发布至公司内网
linux·服务器·pytest
一名在八月份找工作的测试员12 天前
自动化学习2:pytest的高级用法(mark标记/fixture/hook)
学习·自动化·pytest