• pytest-setup和teardown


    setup和teardown

    pytest中有类似unittest中setUp,tearDown方法

    一、运行级别

    • 模块级
      作用于一个模块内的所有class和def,对于所有class和def,setup和teardown只执行一次
    setup_module
    teardown_module
    
    • 类级  
      作用于一个class内中的所有test,所有用例只执行一次setup,当所有用例执行完成后,才会执行teardown
    setup_class
    teardown_class
    
    • 函数级  
      作用于单个测试用例(不在类中的函数)
    setup_function
    teardown_function
    
    • 方法级
      作用于单个测试用例(类中的方法)
    setup_method
    teardown_method
    
    • setup/teardown
      定义在类里面和方法级相同
      定义在类外面和函数级相同
    setup
    teardown
    

    二、举例

    #!/usr/bin/python3
    #-*- conding:utf-8 -*-
    
    def setup_module():
        print('模块级,整个py文件运行前执行一次')
    def teardown_module():
        print('模块级,整个py文件运行后执行一次')
        
    def setup_function():
        print('函数级,每个函数用例运行前执行一次')
    def teardown_function():
        print('函数级,每个函数用例运行后执行一次')
    
    
    class Test_class():
        @classmethod
        def setup_class(cls):
            print('类级,整个测试类运行前执行一次')
        @classmethod
        def teardown_class(self):
            print('类级,整个测试类运行后执行一次')
    
        def setup_method(self):
            print('方法级,类中的每个方法用例运行前执行一次')
        def teardown_method(self):
            print('方法级,类中的每个方法用例运行后执行一次')
    
        def setup(self):
            print('定义在类内部,与方法级相同')
        def teardown(self):
            print('定义在类内部,与方法级相同')
    
        def test_1(self):
            print('正在运行 test_1')
    
        def test_2(self):
            print('正在运行 test_2')
    
    def test_3():
        print('正在运行 test_3')
    
    def test_4():
        print('正在运行 test_4')
    
    

    运行结果

    pytest -s
    
    ================================================== test session starts ===================================================
    platform linux -- Python 3.5.3, pytest-5.4.2, py-1.8.1, pluggy-0.13.1
    rootdir: /media/_dde_data/python
    collected 4 items                                                                                                        
    
    test_001.py 模块级,整个py文件运行前执行一次
    类级,整个测试类运行前执行一次
    方法级,类中的每个方法用例运行前执行一次
    定义在类内部,与方法级相同
    正在运行 test_1
    .定义在类内部,与方法级相同
    方法级,类中的每个方法用例运行后执行一次
    方法级,类中的每个方法用例运行前执行一次
    定义在类内部,与方法级相同
    正在运行 test_2
    .定义在类内部,与方法级相同
    方法级,类中的每个方法用例运行后执行一次
    类级,整个测试类运行后执行一次
    函数级,每个函数用例运行前执行一次
    正在运行 test_3
    .函数级,每个函数用例运行后执行一次
    函数级,每个函数用例运行前执行一次
    正在运行 test_4
    .函数级,每个函数用例运行后执行一次
    模块级,整个py文件运行后执行一次
    
    
    =================================================== 4 passed in 0.03s ====================================================
    
  • 相关阅读:
    Office转SWF的一些感想(Office2007和Office2010)
    数据库字段为日期类型时
    C#实现office文档转换为PDF格式
    C#.net word excel powerpoint (ppt) 转换成 pdf 文件
    Servlet基础
    Android加速度传感器实现“摇一摇”,带手机振动
    android完全退出应用程序
    【安卓笔记】作为内部类的广播接收者
    Android中使用广播机制退出多个Activity
    [Android] ImageView.ScaleType设置图解
  • 原文地址:https://www.cnblogs.com/jingxindeyi/p/13069220.html
Copyright © 2020-2023  润新知