自动化测试框架Pytest No.4(Pytest:fixture之yield实现teardown)

一、fixture之yield实现teardown

pytest中fixture通过scope参数控制setup级别,setup作为用例之前的操作,teardown操作作为用例执行完之后的操作。
fixture的teardown操作并不是独立的函数,用yield关键字唤醒teardown操作。

scope=“module”

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

import pytest

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

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

def test_s2(open):
    print("用例2:搜索python-2")

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

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

在这里插入图片描述

import pytest

@pytest.fixture(scope="module")
def open():
    print("打开浏览器,并且打开百度首页")
# test_s1不调用
def test_s1():
    print("用例1:搜索python-1")
# test_s2调用open
def test_s2(open):
    print("用例2:搜索python-2")
# test_s3不调用
def test_s3():
    print("用例3:搜索python-3")

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

在这里插入图片描述
上述场景中,module级别的fixture只会在第一次调用前执行一次。

yield执行teardown

fixture里面用yield来唤醒teardown的执行。

import pytest

@pytest.fixture(scope="module")
def open():
    print("打开浏览器,并且打开百度首页")
    
    yield
    print("执行teardown!")
    print("最后关闭浏览器")

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

def test_s2(open):
    print("用例2:搜索python-2")

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

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

在这里插入图片描述

yield执行时遇到异常

  1. 如果其中一个用例出现异常,不影响yield后面的teardown执行,运行结果互不影响,并且全部用例执行完之后,yield呼唤teardown操作。
import pytest

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

    yield
    print("执行teardown!")
    print("最后关闭浏览器")

def test_s1(open):
    print("用例1:搜索python-1")
    # 如果第一个用例异常了,不影响其他的用例执行
    # 模拟异常
    raise NameError

def test_s2(open):
    print("用例2:搜索python-2")

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

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

在这里插入图片描述

  1. 如果在setup就异常了,那么是不会去执行yield后面的teardown内容。

  2. yield也可以配合with语句使用,以下是官方文档给的案例。

# 官方文档案例
import smtplib
import pytest

@pytest.fixture(scope="module")
def smtp():
    with smtplib.SMTP("smtp.gmail.com") as smtp:
        yield smtp  # provide the fixture value

二、addfinalizer终结函数

除了yield可以实现teardown,在request-context对象中注册addfinalizer方法也可以实现终结函数。

# 官方文档案例
# content of conftest.py
import smtplib
import pytest

@pytest.fixture(scope="module")
def smtp_connection(request):
    smtp_connection = smtplib.SMTP("smtp.gmail.com", 587, timeout=5)
    def fin():
        print("teardown smtp_connection")
        smtp_connection.close()
    request.addfinalizer(fin)
    return smtp_connection  # provide the fixture value

yield和addfinalizer方法都是在测试完成后呼叫相应的代码。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值