【Pytest学习3】setup和teardown简单用法,fixture里面的scope等于setup,用yield等于teardown

前言

学过unittest的都知道里面用前置和后置setup和teardown非常好用,在每次用例开始前和结束后都去执行一次。
当然还有更高级一点的setupClass和teardownClass,需配合@classmethod装饰器一起使用,在做selenium自动化的时候,它的效率尤为突出,可以只启动一次浏览器执行多个用例。
pytest框架也有类似于setup和teardown的语法,并且还不止这四个

用例运行级别

  • 模块级(setup_module/teardown_module)开始于模块始末,全局的

  • 函数级(setup_function/teardown_function)只对函数用例生效(不在类中)

  • 类级(setup_class/teardown_class)只在类中前后运行一次(在类中)

  • 方法级(setup_method/teardown_method)开始于方法始末(在类中)

  • 类里面的(setup/teardown)运行在调用方法的前后

1.pytest框架支持函数和类两种用例方式,先看函数里面的前置与后置用法:

setup、teardown

先介绍第一个大家都比较熟悉的与unittest中的书写一直,这个可以在类中使用,也可以在类外进行使用。

该方法每条用例都会执行

复制代码
import pytest

def setup():
    print('这是测试用例的前置')

def teardown():
    print('这是测试用例的后置')

def test01():
    print('用例01')

def test02():
    print('用例02')

if __name__ == '__main__':
    pytest.main(['-s'])
复制代码

setup_module、teardown_module

该方法表示只能类外面执行用例过程中,只执行1次。相当于unittest中的setupclass和teardownclass方法

复制代码
import pytest

def setup_module():
    print('这是测试用例的前置')

def teardown_module():
    print('这是测试用例的后置')

def test01():
    print('用例01')

def test02():
    print('用例02')

if __name__ == '__main__':
    pytest.main(['-s','test_02.py'])
复制代码

setup_function、teardown_function

该方法表示在类外面执行用例过程中,每次都会执行前置和后置。

复制代码
import pytest

def setup_function():
    print('这是测试用例的前置')

def teardown_function():
    print('这是测试用例的后置')

def test01():
    print('用例01')

def test02():
    print('用例02')

if __name__ == '__main__':
    pytest.main(['-s','test_02.py'])
复制代码

setup_method、teardown_method

该方法表示在类中每次执行测试用例前,测试前置和测试后置都会执行一次

复制代码
# coding:utf-8
import pytest

class Test():

    def setup_method(self):
        print('这是setup函数前置内容')

    def teardown_method(self):
        print('这是teardown函数后置内容')

    def test01(self):
        print('这是测试用例1')

    def test02(self):
        print('这是测试用例2')


if __name__ == '__main__':
    pytest.main(['-s','test_01.py'])
复制代码

setup_class、teardown_class

该方法表示在类中执行测试用例前,只执行1次测试前置和测试后置

复制代码
# coding:utf-8
import pytest

class Test():

    def setup_class(self):
        print('这是setup函数前置内容')

    def teardown_class(self):
        print('这是teardown函数后置内容')

    def test01(self):
        print('这是测试用例1')

    def test02(self):
        print('这是测试用例2')


if __name__ == '__main__':
    pytest.main(['-s','test_01.py'])
复制代码

组合混用

上面介绍了每种方法的单独用法,那么如果这些方法都一起使用?会怎么样?

setup_class和setup_method、setup混合

复制代码
# coding:utf-8
import pytest

class Test():
    def setup_method(self):
        print('这是setup_method用例前置内容')

    def setup_class(self):
        print('这是setup_class用例前置内容')

    def setup(self):
        print('这是setup用例前置内容')

    def teardown_class(self):
        print('这是teardown_class用例后置内容')

    def teardown_method(self):
        print('这是teardown_method用例后置内容')

    def teardown(self):
        print('这是teardown用例后置内容')

    def test01(self):
        print('这是测试用例1')

    def test02(self):
        print('这是测试用例2')


if __name__ == '__main__':
    pytest.main(['-s','test_01.py'])
复制代码

通过上面测试结果可以看出来,其中执行顺序:setup_class>>setup_method>>setup,其中setup和setup_method都是表示执行每条用例前都需要进行执行前置内容

setup_module、setup_function组合

复制代码
import pytest

def setup():
    print('这是setup测试用例前置内容')

def setup_function():
    print('这是setup_function测试用例前置内容')

def setup_module():
    print('这是setup_module测试用例前置内容')

def teardown_module():
    print('这是teardown_module测试用例后置内容')

def teardown():
    print('这是teardown测试用例后置内容')

def teardown_function():
    print('这是teardown_function测试用例后置内容')

def test01():
    print('用例01')

def test02():
    print('用例02')

if __name__ == '__main__':
    pytest.main(['-s','test_02.py'])
复制代码

通过上述测试发现,执行顺序:setup_module>>setup_function>>setup。其中setup_module表示执行用例只执行一次前置。

总结:

setup_module/teardown_module的优先级是最大的,然后函数里面用到的setup_function/teardown_function与类里面的setup_class/teardown_class互不干涉

1、setup_class和setup_module执行用例时,只执行一次前置和后置

2、setup_class,setup_method,setup是在类中执行的

3、setup_module,setup_function,setup是在类外执行的

4、其中setup类中,类外都可以执行。

fixture通过scope参数可以控制setup级别,既然有setup作为用例之前的操作,用例执行完之后那肯定也有teardown操作。
这里用到fixture的teardown操作并不是独立的函数,用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):
    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	est_f1.py 打开浏览器,并且打开百度首页
用例1:搜索python-1
.用例2:搜索python-2
.用例3:搜索python-3
.

========================== 3 passed in 0.01 seconds ===========================

从结果看出,虽然test_s1,test_s2,test_s3三个地方都调用了open函数,但是它只会在第一个用例前执行一次

2.如果test_s1不调用,test_s2(调用open),test_s3不调用,运行顺序会是怎样的?

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

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

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

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

def test_s3():
    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	est_f1.py 用例1:搜索python-1
.打开浏览器,并且打开百度首页
用例2:搜索python-2
.用例3:搜索python-3
.

========================== 3 passed in 0.01 seconds ===========================

从结果看出,module级别的fixture在当前.py模块里,只会在用例(test_s2)第一次调用前执行一次

yield执行teardown

1.前面讲的是在用例前加前置条件,相当于setup,既然有setup那就有teardown,fixture里面的teardown用yield来唤醒teardown的执行

# 新建一个文件test_f1.py
# coding:utf-8
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"])

运行结果:

============================= 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	est_f1.py 打开浏览器,并且打开百度首页
用例1:搜索python-1
.用例2:搜索python-2
.用例3:搜索python-3
.执行teardown!
最后关闭浏览器


========================== 3 passed in 0.01 seconds ===========================

yield遇到异常

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

# 新建一个文件test_f1.py
# coding:utf-8
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"])

运行结果:

YOYO	est_f1.py 打开浏览器,并且打开百度首页
用例1:搜索python-1
F
open = None

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

D:YOYO	est_f1.py:16: NameError
用例2:搜索python-2
.用例3:搜索python-3
.执行teardown!
最后关闭浏览器

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

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

# 官方文档案例
# content of test_yield2.py

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终结函数

1.除了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

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

声明 欢迎转载,但请保留文章原始出处:) 博客园:https://www.cnblogs.com/chenxiaomeng/ 如出现转载未声明 将追究法律责任~谢谢合作
原文地址:https://www.cnblogs.com/chenxiaomeng/p/14814802.html