pytest中fixtures调用fixtures及fixture复用性实例分析

发布时间:2022-06-01 15:13:56 作者:iii
来源:亿速云 阅读:122

本篇内容介绍了“pytest中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被多次请求。

“pytest中fixtures调用fixtures及fixture复用性实例分析”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注亿速云网站,小编将为大家输出更多高质量的实用文章!

推荐阅读:
  1. 怎么在Django单元测试中使用Fixtures
  2. Django单元测试中Fixtures用法详解

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

pytest fixtures fixture

上一篇:node.js文件系统模块实例分析

下一篇:Django状态保持搭配与存储如何实现

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》