pytest 中的setup和teardown

模块级别:setup_module、teardown_module

函数级别:setup_function、teardown_function,不在类中的方法

类级别:setup_class、teardown_class

方法级别:setup_method、teardown_method

方法细化级别:setup、teardown

示例:

import pytest
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_1():
    print("正在执行用例1")
    x = "this"
    assert 'h' in x
def test_2():
    print("正在执行用例2")
    assert 1 == 1
class TestClass(object):
    def setup_class(self):
        print("setup_class(self):每个类之前执行一次,只执行一次")
    def teardown_class(self):
        print("teardown_class(self):每个类之后执行一次,只执行一次")
    def test_A(self):
        print("正在执行用例A")
        x = "this"
        assert 'h' in x
    def test_B(self):
        print("正在执行B")
        assert 1 == 1
if __name__ == "__main__":
    pytest.main(["-s", "test_setup_terdown_pytest.py"])

执行结果如下:

collected 4 items

test_myShop.py setup_module():在模块最之前执行,且只执行一次
setup_function():每个方法之前执行
正在执行用例1
.teardown_function():每个方法之后执行
setup_function():每个方法之前执行
正在执行用例2
.teardown_function():每个方法之后执行
setup_class(self):每个类之前执行一次,只执行一次
正在执行用例A
.正在执行B
.teardown_class(self):每个类之后执行一次,只执行一次
teardown_module:在模块之后执行,且只执行一次


============================== 4 passed in 0.02s ==============================

可以看到互相之间没有影响,执行顺序为:

setup_module()
setup_function()
test_1
teardown_function()
setup_function()
test_2
teardown_function()
setup_class(self)
test_A
test_B
teardown_class(self)
teardown_module
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值