脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|shell|

服务器之家 - 脚本之家 - Python - pytest官方文档解读fixtures调用fixtures及fixture复用性

pytest官方文档解读fixtures调用fixtures及fixture复用性

2023-02-24 11:32把苹果咬哭的测试笔记 Python

这篇文章主要为大家介绍了pytest官方文档解读fixtures调用fixtures及fixture复用性,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪

fixtures调用其他fixtures及fixture复用性 

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

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

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

一、Fixtures调用别的Fixtures

直接看一个简单示例:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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一样,所有的请求规则都适用。

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

?
1
2
3
4
5
6
7
8
9
10
11
12
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的各自结果。

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

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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中的返回值。

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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复用性 的详细内容,更多关于pytest fixtures调用复用性的资料请关注服务器之家其它相关文章!

原文链接:https://www.cnblogs.com/pingguo-softwaretesting/p/14473173.html

延伸 · 阅读

精彩推荐