Pytest06-pytest的setup和teardown函数

发布时间 2024-01-05 15:28:32作者: 测试老宅男扶摇

高清B站视频链接

pytest的setup和teardown函数

用例前置和后置

# 类外面
setup_module/teardown_module:在当前文件中,所有的用例执行之前以及之后执行
setup_function/teardown_function: 在每个测试函数之前以及之后执行
setup/teardown: 在每个测试函数之前以及之后执行
# 类里面
setup_class/teardown_class
setup_method/teardown_method:测试方法
setup/teardown:测试方法

其中setup和teardown 可以在类的外面和里面使用

不同的setup函数最好不要混用,在最新版本里面是不支持混用的

代码案例

文件:test_setup01.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 作者:扶摇
"""
    不同的setup函数最好不要混用,在最新版本里面是不支持混用的
    setup_module/teardown_module:在当前文件中,所有的用例执行之前以及之后执行
    setup/teardown: 在当前文件中,所有的用例执行之前以及之后执行
    setup_function/teardown_function: 在每个测试函数之前以及之后执行
"""
import pytest

def multiply(a,b):
    return a*b

# def setup_module():
#     print("文件级的代码预置逻辑")
# def teardown_module():
#     print("文件级的代码后置逻辑")

# def setup_function():
#     print("setup_function")
# def teardown_function():
#     print("teardown_function")

# def setup():
#     print("setup")
#
# def teardown():
#     print("teardown")

# 测试用例
def test01():
    print(multiply(3,4))

def test02():
    print(multiply(4,5))

if __name__ == '__main__':
    pytest.main(['-vs','test_setup01.py'])

文件:test_setup02.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 作者:扶摇
"""
    setup_class/teardown_class:测试类前后
    setup_method/teardown_method:测试方法
    setup/teardown   Support for nose tests is deprecated and will be removed in a future release.
"""
import pytest

def multipyl(a,b):
    return  a * b

class TestMult:
    # @classmethod
    # def setup_class(cls):
    #     print("==========setup_class==========")
    #
    # @classmethod
    # def teardown_class(cls):
    #     print("==========teardown_class==========")
    def setup_method(self):
        print("setup_method")

    def teardown_method(self):
        print("teardown_method")

    # 测试用例
    def test01(self):
        print(multipyl(3,4))

    def test02(self):
        print(multipyl(4,5))

if __name__ == '__main__':
    pytest.main(['-vs','test_setup02.py'])

测试技术交流请联系我

备注博客园扶摇

【学习软件测试/Python自动化测试技术/领取Python自动化测试学习路线图/简历优化】
视频链接:
课程服务介绍

自动化全栈学习路线图讲解

软件测试面试合集

Python编程刷题合集

Pytest入门到实战

Python接口自动化合集

PythonWeb自动化合集

性能测试合集

Jmeter接口自动化测试实战全集

2023GPT探索发现合集

加微信(备注博客园扶摇)即可免费领取下面的自动化测试资料和一份软件测试面试宝典