pytest官方文档解读fixtures的autouse

作者:把苹果咬哭的测试笔记 时间:2023-06-22 01:18:58 

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

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

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

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

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)的执行过程亦是如此。

来源:https://www.cnblogs.com/pingguo-softwaretesting/p/14475652.html

标签:pytest,fixtures,autouse
0
投稿

猜你喜欢

  • Python Numpy 自然数填充数组的实现

    2023-12-18 16:51:37
  • vue实现下拉菜单树

    2024-05-09 15:18:39
  • 对python中的xlsxwriter库简单分析

    2022-08-22 22:46:01
  • Python用GET方法上传文件

    2022-08-03 01:13:59
  • django中间键重定向实例方法

    2021-04-17 12:34:02
  • python编写暴力破解FTP密码小工具

    2021-11-29 15:32:40
  • Django中ajax发送post请求 报403错误CSRF验证失败解决方案

    2021-06-11 19:47:32
  • Python NumPy教程之数组的基本操作详解

    2021-08-15 16:20:12
  • Mysql5.6修改root密码教程

    2024-01-20 01:10:23
  • python冒泡排序简单实现方法

    2022-09-27 12:28:57
  • Python开发自定义Web框架的示例详解

    2023-05-23 19:43:43
  • Python竟能画这么漂亮的花,帅呆了(代码分享)

    2021-02-04 15:50:00
  • Python将文字转成语音并读出来的实例详解

    2021-11-08 21:23:34
  • 在Python的web框架中编写创建日志的程序的教程

    2021-11-25 05:14:07
  • 使用python turtle画高达

    2021-11-05 20:47:48
  • 后端算法题解LeetCode前缀和示例详解

    2023-03-16 17:31:54
  • GoJs面板绘图模板go.Panel使用示例详解

    2024-05-21 10:14:08
  • 使用python实现mqtt的发布和订阅

    2021-04-16 12:27:53
  • python实现守护进程、守护线程、守护非守护并行

    2021-02-03 09:06:56
  • 如何把数组转换成字符串?

    2009-11-06 13:49:00
  • asp之家 网络编程 m.aspxhome.com