fixtures调用其他fixtures怎样做,如何理解fixture复用�

Admin 2022-08-13 群英技术资�

关于“fixtures调用其他fixtures怎样做,如何理解fixture复用性”的知识有一些人不是很理解,对此小编给大家总结了相关内容,具有一定的参考借鉴价值,而且易于学习与理解,希望能对大家有所帮助,有这个方面学习需要的朋友就继续往下看吧�

fixtures调用其他fixtures及fixture复用� 

pytest最大的优点之一就是它非常灵活�

它可以将复杂的测试需求简化为更简单和有组织的函数,然后这些函数可以根据自身的需求去依赖别的函数�

fixtures可以调用别的fixtures正是灵活性的体现之一�

一、Fixtures调用别的Fixtures

直接看一个简单示例:

import pytest
# Arrange
@pytest.fixture
def first_entry():
    # 这是一个fixture函数,返回�:"a"
    return "a"
# Arrange
@pytest.fixture
def order(first_entry):
    # 这是另一个fixture函数,请求了上一个fixture函数first_entry()�
    # 并且把first_entry()的返回值,放进了列表[]里,最后返�
    return [first_entry]
def test_string(order):
    # Act
    # 测试函数中请求了第二个fixture函数order,可以拿到返回的[]
    order.append("b")
    # Assert
    assert order == ["a", "b"]

可以看到,pytest中的某个fixture请求别的fixture,就像测试函数请求fixture一样,所有的请求规则都适用�

同样,如果这些事情换我们自己来做的话,应该是下面这样�:

def first_entry():
    return "a"
def order(first_entry):
    return [first_entry]
def test_string(order):
    # Act
    order.append("b")
    # Assert
    assert order == ["a", "b"]
entry = first_entry()
the_list = order(first_entry=entry)
test_string(order=the_list)

二、Fixtures的复用�

pytest中的fixtures还可以让我们像使用普通函数一样,能够定义反复重用的通用setup步骤�

两个不同的测试函数可以请求相同的fixture,每个测试函数都会获得该fixture的各自结果�

这样的优点就是,确保不同的测试函数之间不会相互影响�

我们可以使用这种机制来确保每个测试函数都获得各自新的、干净的、一致的数据�

import pytest
# Arrange
@pytest.fixture
def first_entry():
    return "a"
# Arrange
@pytest.fixture
def order(first_entry):
    return [first_entry]
def test_string(order):
    # Act
    order.append("b")
    # Assert
    assert order == ["a", "b"]
def test_int(order):
    # Act
    order.append(2)
    # Assert
    assert order == ["a", 2]

从代码可以看出,fixture函数order虽然先后被两个测试函数调用,但是每次被调用给出的结果都是一样的。并不会因为在测试函�test_string中,进行�order.append("b")后,就影响了order在测试函�test_int中的返回值�

同样,这些事情换成我们自己来做,那就是这样的�

def first_entry():
    return "a"
def order(first_entry):
    return [first_entry]
def test_string(order):
    # Act
    order.append("b")
    # Assert
    assert order == ["a", "b"]
def test_int(order):
    # Act
    order.append(2)
    # Assert
    assert order == ["a", 2]
entry = first_entry()
the_list = order(first_entry=entry)
test_string(order=the_list)
entry = first_entry()
the_list = order(first_entry=entry)
test_int(order=the_list)

接下来,继续跟着官方文档解读fixtures的特点:一次请求多个fixtures、fixtures被多次请求�


以上就是关于“fixtures调用其他fixtures怎样做,如何理解fixture复用性”的相关知识,感谢各位的阅读,想要掌握这篇文章的知识点还需要大家自己动手实践使用过才能领会,如果想了解更多相关内容的文章,欢迎关注群英网络,小编每天都会为大家更新不同的知识�

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:[email protected]进行举报,并提供相关证据,查实之后,将立刻删除涉嫌侵权内容�

猜你喜欢

成为群英会员,开启智能安全云计算之旅

立即注册
专业资深工程师驻�
7X24小时快速响�
一站式无忧技术支�
免费备案服务
免费拨打  400-678-4567
免费拨打  400-678-4567 免费拨打 400-678-4567 � 0668-2555555
在线客服
微信公众号
返回顶部
返回顶部 返回顶部