Pytest学习笔记2:测试用例setup和teardown

8 篇文章 0 订阅
5 篇文章 0 订阅

用例运行级别

  • 模块级(setup_module/teardown_module)开始于模块始末,全局的

  • 函数级(setup_function/teardown_function)只对函数用例生效(不在类中)

  • 类级(setup_class/teardown_class)只在类中前后运行一次(在类中)

  • 方法级(setup_method/teardown_method)开始于方法始末(在类中)

  • 类里面的(setup/teardown)运行在调用方法的前后

  • # coding:utf-8
    import pytest
    # 类和方法
    
    def setup_module():
        print("setup_module:整个.py模块只执行一次")
        print("比如:所有用例开始前只打开一次浏览器")
    
    def teardown_module():
        print("teardown_module:整个.py模块只执行一次")
        print("比如:所有用例结束只最后关闭浏览器")
    
    def setup_function():
        print("setup_function:每个用例开始前都会执行")
    
    def teardown_function():
        print("teardown_function:每个用例结束前都会执行")
    
    def test_one():
        print("正在执行----test_one")
        x = "this"
        assert 'h' in x
    
    def test_two():
        print("正在执行----test_two")
        x = "hello"
        assert 'h' in x
    
    class TestCase():
    
        def setup_class(self):
            print("setup_class:类中所有用例执行之前")
    
        def teardown_class(self):
            print("teardown_class:类中所有用例执行之后")
    
        def setup(self):
            print("setup:类中每个用例执行之前")
        def teardown(self):
            print("teardown:类中每个用例执行之后")
        def setup_method(self):
            print("setup_method:类中每个用例执行之前")
        def teardown_method(self):
            print("teardown_method:类中每个用例执行之后")
    
        def test_three(self):
            print("正在执行----test_three")
            x = "this"
            assert 'h' in x
    
        def test_four(self):
            print("正在执行----test_four")
            x = "hello"
            assert  'h' in x
    
    if __name__ == "__main__":
        pytest.main(["-s", "Testcase2.py"])

    运行结果

  • Testcase2.py setup_module:整个.py模块只执行一次
    比如:所有用例开始前只打开一次浏览器

    setup_function:每个用例开始前都会执行
    .
    正在执行----test_one
    teardown_function:每个用例结束前都会执行
    setup_function:每个用例开始前都会执行
    .正在执行----test_two
    teardown_function:每个用例结束前都会执行
    setup_class:类中所有用例执行之前
    setup_method:类中每个用例执行之前
    setup:类中每个用例执行之前
    .正在执行----test_three
    teardown:类中每个用例执行之后
    teardown_method:类中每个用例执行之后
    setup_method:类中每个用例执行之前
    setup:类中每个用例执行之前
    .正在执行----test_four
    teardown:类中每个用例执行之后
    teardown_method:类中每个用例执行之后
    teardown_class:类中所有用例执行之后
    teardown_module:整个.py模块只执行一次
    比如:所有用例结束只最后关闭浏览器

     setup_module/teardown_module的优先级是最大的,然后函数里面用到的setup_function/teardown_function与类里面的setup_class/teardown_class互不干涉

      类里面的setup_method和teardown_method的功能和setup/teardown功能是一样的,一般二者用其中一个即可

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值