pyest固件、及用例执行顺序

阅读目录:
  固件分类
  演示
  用例执行顺序

固件分类

概念: 固件用于执行前的初始化参数、执行后的清理动作

类型 规则
setup_module/ teardown_moduel全局模块级、运行模块前/后运行 (只运行一次)
setup_function/teardown_function函数级、 每个函数用例运行前/后运行
setup_class/teardown_clss类级、 每个class运行前/后运行(只运行一次)
setup_method(setup)/ teardown_method(teardown)方法级、 类中每个方法用例自行前/后运行 <== setup_method和setup、teardown_method和teardown二选一即可

演示

示例: 一个module, 两个函数, 两个类,每个类-两个方法
#! usr/bin/env python
# _*_ coding: utf-8 _*_
# @Author: zcs
# @wx: M_Haynes
# @Blog: https://editor.mdnice.com/?outId=3922c88879f84d9d87275683f6153499
# 备注: 主要用于介绍pytest固件、及用例执行顺序 -- 第三课


# 用例: 一个module, 两个函数, 两个类, 每个类两个方法

def setup_module():
    print("初始化: setup_module --- 全局模块级, 模块运行前 运行一次")

def teardown_module():
    print("清理:teardown_module --- 全局模块级, 模块运行后 运行一次")

def setup_function():
    print("初始化: setup_function -- 函数级, 每个函数用例运行前 运行一次")

def teardown_function():
    print("清理: teardown_function -- 函数级, 每个函数用例运行后  运行一次")

def test_example1():
    print(" ------------test_example1------------")
    assert 1==1

class TestExample3(object):
    def setup_clss(self):
        print("初始化:setup_class --- 类级, 每个class运行前   运行一次")

    def teardown_clss(self):
        print("清理: teardown_class --- 类级, 每个class运行后  运行一次")

    def test_example2(self):
        print(" ------------test_example2------------")
        assert 2==2

    def setup_function(self):
        print("初始化: setup_function")

    def teardown_function(self):
        print("清理: teardown_function")

    def test_example3(self):
        print(" ------------test_example3------------")


class TestExample4(object):
    def setup_class(self):
        print("初始化: setup_class2")

    def teardown_class(self):
        print("清理: teardown_class2")

    def setup_method(self):
        print("初始化: setup_method2")

    def teardown_method(self):
        print("清理: teardown_method2")

    def test_example4(self):
        print(" ------------test_example4------------")

    def test_example5(self):
        print(" ------------test_example5------------")

def test_example6():
    print(" ------------test_example6------------")

运行结果:
image

用例执行顺序:
结论:pytest框架默认根据书写代码的先后顺序来执行
image

本文由mdnice多平台发布


承森的技术栈
1 声望0 粉丝