Pytest框架入门03 初始化清除

pytest初始化清除的必要性:

  对于自动化测试框架来说,初始化清除功能至关重要,如果清除功能没有做好,经常会出现一部分测试用例,单独跑可能没有问题,和其它测试用例一起跑就会出现问题。或者另外一批测试用例就会出错。初始化清除,可以减少测试用例之间的依赖性和数据的冲突。

初始化函数与清除函数

1、测试用例级别,也称方法级别(在每个用例或方法执行前后都会操作一次):

   def setup()

   def  teardown()

2、套件级别(在模块文件中定义,分别在整个模块中所有类中的内容执行前后运行):

  def setup_module()

  def teardown_module()

3、套件级别(在类中定义):

  @classmethod

  def setup_class(cls)

  @classmethod

  def teardown_class(cls)

注意:固定函数名称不能写错

示例: 

#测试用例&方法级别初始化与清理函数
def
setup(self): print("setup_function--->") def teardown(self): print("teardown_function--->") def setup_method(cls): print("setup_function--->") def teardown_method(cls): print("teardown_function--->")
# 套件&模块化级别初始化与清除,定义全局方法
def setup_module():
    print("setup_function--->")
 
def teardown_module():
    print("teardown_function--->")
 
class Test01():
 
    def test_01(self):
        print("test pytest")
 
    def test_02(self):
        print("test pytest")
 
class Test02():
 
    def test_03(self):
        print("test pytest")
#套件&类级别初始化与清除
class
Test01(): @classmethod def setup_class(cls): print("setup_function--->") @classmethod def teardown_class(cls): print("teardown_function--->") def test_01(self): print("hello_01") def test_02(self): print("hello_02") class Test02(): def test_03(self): print("hello_03")
原文地址:https://www.cnblogs.com/yu2000/p/13865506.html