pytest简易教程(05):fixture实现自定义前置、后置
pytest简易教程汇总,详见:https://www.cnblogs.com/uncleyong/p/17982846
自定义前置(setup)、后置(teardown)
fixture可以实现自定义测试用例的前置、后置,是通过yield来区分前后置的,前后置均可以单独存在;
写在yield前面的就是前置条件,写在后面的就是后置条件;
如果yield前面的代码出异常了,yield后面的代码不会执行;但是,如果是测试用例出异常,yield前后的代码还是都会执行。
示例:仅test_a和test_b需要前置登录后置退出
方法一:yield
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author : 韧
# @wx :ren168632201
# @Blog :https://www.cnblogs.com/uncleyong/
import pytest
@pytest.fixture()
def login():
print("---前置:登录")
yield
print("---后置:退出")
def test_a(login):
print("--------------test_a")
class Test01:
def test_b(self, login):
print("--------------test_b")
def test_c(self):
print("--------------test_c")
结果:

方法二:addfinalizer终结函数
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author : 韧
# @wx :ren168632201
# @Blog :https://www.cnblogs.com/uncleyong/
import pytest
@pytest.fixture()
def login(request):
print("---前置:登录")
def after():
print("---后置:退出")
request.addfinalizer(after)
def test_a(login):
print("--------------test_a")
class Test01:
def test_b(self, login):
print("--------------test_b")
def test_c(self):
print("--------------test_c")
结果:

如果yield前面的代码出异常了,yield后面的代码不会执行
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author : 韧
# @wx :ren168632201
# @Blog :https://www.cnblogs.com/uncleyong/
import pytest
@pytest.fixture()
def fun():
print("---前置")
raise Exception("自定义异常")
yield
print("---后置")
def test_a(fun):
print("--------------test_a")
结果:

如果是测试用例出异常,yield前后的代码都会执行
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author : 韧
# @wx :ren168632201
# @Blog :https://www.cnblogs.com/uncleyong/
import pytest
@pytest.fixture()
def fun():
print("---前置")
yield
print("---后置")
def test_a(fun):
print("--------------test_a")
raise Exception("自定义异常")
结果:

__EOF__
本文作者:持之以恒(韧)
关于博主:擅长性能、全链路、自动化、企业级自动化持续集成(DevTestOps)、测开等
面试必备:项目实战(性能、自动化)、简历笔试,https://www.cnblogs.com/uncleyong/p/15777706.html
测试提升:从测试小白到高级测试修炼之路,https://www.cnblogs.com/uncleyong/p/10530261.html
欢迎分享:如果您觉得文章对您有帮助,欢迎转载、分享,也可以点击文章右下角【推荐】一下!
关于博主:擅长性能、全链路、自动化、企业级自动化持续集成(DevTestOps)、测开等
面试必备:项目实战(性能、自动化)、简历笔试,https://www.cnblogs.com/uncleyong/p/15777706.html
测试提升:从测试小白到高级测试修炼之路,https://www.cnblogs.com/uncleyong/p/10530261.html
欢迎分享:如果您觉得文章对您有帮助,欢迎转载、分享,也可以点击文章右下角【推荐】一下!

浙公网安备 33010602011771号