zoukankan      html  css  js  c++  java
  • pytest的setup和teardown

    学过unittest的setup和teardown,前置和后置执行功能。pytest也有此功能并且功能更强大,今天就来学习一下吧。

    用例运行级别:

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

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

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

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

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

    demo1:

    import pytest
    # 函数式
    def setup_function():
        print("setup_function")
    
    def teardown_function():
        print("teardown_function")
    
    def setup_module():
        print('setup_module')
    
    def teardown_module():
        print('teardown_module')
    
    def test_one():
        print("正在执行----test_one")
        
    def test_two():
        print("正在执行----test_two")
        
    def test_three():
        print("正在执行----test_three")
      
    if __name__ == "__main__":
        pytest.main(["-s", "test_api.py"])

    结果:

     setup_module只开头运行一次,teardown_module只结束运行一次,setup_function每次运行用例都执行一次,teardown_function每次用例结束都执行一次。

    demo2:

    import pytest
    # 函数式
    class TestCase():
        def setup_class(self):
            print("setup_class")
    
        def teardown_class(self):
            print("teardown_class")
    
        def setup_method(self):
            print('setup_method')
    
        def teardown_method(self):
            print('teardown_method')
    
        def setup(self):
            print('setup')
    
        def teardown(self):
            print('teardown')
    
        def test_one(self):
            print("正在执行----test_one")
            
        def test_two(self):
            print("正在执行----test_two")
            
        def test_three(self):
            print("正在执行----test_three")
      
    if __name__ == "__main__":
        pytest.main(["-s", "test_api.py"])

    结果:

     setup_class只开头执行一次,teardown_class只结束执行一次,setup_method和setup都是在用例执行之前分别执行,setup_method的优先级高于setup,teardown_method和teardown也是同理

    运行的优先级:setup_class》setup_method》setup 》用例》teardown》teardown_method》teardown_class

  • 相关阅读:
    android 实现非GPS 手机定位
    Android 杂谈
    Android完全退出程序代码
    DB2数据库使用系统性能优化深入讨论
    DB2 数据库打算:失失最佳功能的准绳
    教你疾速驾驭DB2数据库中的相关饬令3
    教你快速把握DB2数据库中的相干命令5
    DB2中更新施行方案的几个罕见的方法2
    Oracle与DB2、MySQL取前10笔记实的比拟2
    JDBC衔接DB2、Oracle、MySQL、PostgreSQL
  • 原文地址:https://www.cnblogs.com/huny/p/13374584.html
Copyright © 2011-2022 走看看