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

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

服务器之家 - 脚本之家 - Python - pytest官方文档解读fixtures的autouse

pytest官方文档解读fixtures的autouse

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

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

现在我们已经知道了,fixtures是一个非常强大的功能。

那么有的时候,我们可能会写一个fixture,而这个fixture所有的测试函数都会用到它。

那这个时候,就可以用autouse自动让所有的测试函数都请求它,不需要在每个测试函数里显示的请求一遍。

具体用法就是,将autouse=True传递给fixture的装饰器即可。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import pytest
@pytest.fixture
def first_entry():
    return "a"
@pytest.fixture
def order(first_entry):
    return []
@pytest.fixture(autouse=True)
def append_first(order, first_entry):
    return order.append(first_entry)
def test_string_only(order, first_entry):
    assert order == [first_entry]
def test_string_and_int(order, first_entry):
    order.append(2)
    assert order == [first_entry, 2]

先来看第一个测试函数test_string_only(order, first_entry)的执行情况:

  • 虽然在测试函数里请求了2个fixture函数,但是order拿到的并不是[],first_entry拿到的也并不是"a"。
  • 因为存在了一个autouse=True的fixture函数,所以append_first先会被调用执行。
  • 在执行append_first过程中,又分别请求了order、 first_entry这2和fixture函数。
  • 接着,append_first对分别拿到的[]和"a"进行append处理,最终返回了["a"]。所以,断言assert order == [first_entry]是成功的。

同理,第二个测试函数test_string_and_int(order, first_entry)的执行过程亦是如此。

以上就是pytest官方文档解读fixtures的autouse的详细内容,更多关于pytest解读fixtures的autouse的资料请关注服务器之家其它相关文章!

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

延伸 · 阅读

精彩推荐