pytest初始化的类别和作用域
  • 模块级别(Module level setup/teardown):作用于一个模块内的所有class和def,对于所有class和def,setup和teardown只执行一次
def setup\_module(module):  
  
"""   
  
setup any state specific to the   
execution of the given module.  
  
"""  
  
def teardown\_module(module):  
  
"""   
teardown any state that was previously   
setup with a setup\_module
method.
"""
  • 类级别(Class level setup/teardown):作用于一个class内中的所有test,所有用例只执行一次setup,当所有用例执行完成后,才会执行teardown
@classmethod  
def setup\_class(cls):  
  
""" setup any state specific to the execution   
of the given class (which
usually contains tests).
"""  
  
  
@classmethod  
def teardown\_class(cls):
 """ teardown any state that was previously   
setup with a call to
setup\_class.
"""
  • 方法和函数级别(Method and function level setup/teardown):作用于单个测试用例,若用例没有执行(如被skip了)或失败了,则不会执行teardown
def setup\_method(self, method):  
  
"""   
setup any state tied to the execution   
of the given method in a
class. setup\_method is invoked for   
every test method of a class.
"""  
  
  
def teardown\_method(self, method):  
  
"""  
teardown any state that was   
previously setup with a setup\_method
call.
"""

若用例直接写在模块中,而不是在类中,则用:

def setup\_function(function):  
  
"""   
setup any state tied to the execution of the given function.
Invoked for every test function in the module.
"""  
  
def teardown\_function(function):  
  
"""   
teardown any state that was previously setup with  
 a setup\_function call.
"""
  • pytest.fixture()装饰函数,结合yield实现初始化和teardown
    举个例子(pytest)文档中的:
import smtplib  
import pytest  
@pytest.fixture(scope="module")def smtp():
    smtp = smtplib.SMTP("smtp.gmail.com", 587, timeout=5)
      
    yield smtp # provide the fixture value
    print("teardown smtp")  
  

    smtp.close()

运行结果:

$ pytest -s -q --tb=no
FFteardown smtp2 failed in 0.12 seconds
pytest用例初始化操作的示例

为了体现初始化和环境恢复,本节演示采用邮件发送的脚本,可查看邮件发送的脚本:python发送邮件脚本或者参考文章:SMTP发送邮件。

1、setup_method(self, method)
  • 在test_method.py中构建了3个测试用例,每个用例在执行前后都会执行setup_method/teardown_method连接smtp和断开smtp。
  • 查看结果,采用pytest -s -q 运行,-s 可以查看打印信息,-q减少输出信息:

pytest如何使用debug模式_功能测试

test_method结果.png
*