Python Pytest自动化测试 yield实现teardown

本文介绍了Python Pytest框架中如何使用`scope="module"`、`yield`和`addfinalizer`来实现测试的setup和teardown操作。重点讲解了`yield`在teardown过程中的应用,以及`addfinalizer`作为终结函数的作用,帮助提升测试的效率和资源管理。
摘要由CSDN通过智能技术生成

Time will tell.


我们在往期的章节中有讲到过fixture通过scope参数控制setup级别。既然有setup作为用例之前前的操作,用例执行完之后那肯定也有teardown操作。用到fixtureteardown操作并不是独立函数,用yield关键字呼唤teardown操作。


一、scope=”module”

1.fixture参数 scope=”module” ,module作用是整个.py文件都会生效,用例调用时,参数写上函数名称就行。

# 新建一个文件test_f1.py
# coding:utf-8

import pytest

@pytest.fixture(scope="module")
def open():
    print("打开浏览器,并且打开百度首页")

def test_s1(open):
    print("用例1:搜索python-1")

def test_s2(open):  # 不传login
    print("用例2:搜索python-2")

def test_s3(open):
    print("用例3:搜索python-3")

if __name__ == "__main__":
    pytest.main(["-s", "test_f1.py"])
    

运行结果:

============================= test session starts =============================
platform win32 -- Python 3.6.0, pytest-3.6.3, py-1.5.4, pluggy-0.6.0
rootdir: D:\, inifile:
collected 3 items

..\..\..\..\..\..\YOYO\test_f1.py 打开浏览器,并且打开百度首页
.用例1:搜索python-1
.用例2:搜索python-2
.用例3:搜索python
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值