• unittest前置依赖用例测试失败时跳过当前用例


    本文主要参考了:https://blog.csdn.net/xugexuge/article/details/87538375

    在原博主方案基础上增加了如下功能:

    1. 在自动化测试工程中,会存在多个脚本文件,不同脚本文件中可能存在同名方法。因此改进方案中可以通过脚本名+类名+方法名来定义前置用例
    2. 希望将跳过的用例标记为失败。实际测试中,前置用例失败导致后续用例失败,前置后置都应该统计为失败。
    3. 可以手工指定多个用例作为前置用例
    4. 前置用例的常见场景,如每个类对应一个测试场景,这个类中的方法都依赖前一个方法(当然第一个方法除外)
    5. 通过元类,可以默认为当前类所有方法加上依赖前一个方法的装饰器

    在chatgpt的辅助下,完整代码如下:

    import enum
    import inspect
    import os
    from functools import wraps
    
    
    class DependencyType(enum.Enum):
        """
        前置用例定义类型
        """
        CURRENT_CLASS_PREVIOUS_CASE = 1  # 当前类中的前一个用例(默认)
        ANY_PREVIOUS_CASE = 2  # 任何前一个用例(一般用于某个类的第一个方法依赖上一个类)
        CUSTOM_PATH = 3  # 自定义用例定义,格式:python文件名.类名.方法名(文件名、类名允许为空,适用于非空字段组合在全局唯一)
        NO_DEPENDENCY = 4  # 无需依赖,用于反向注释(比如默认类中的方法都依赖前一个方法,但是其中的一个方法无需)
    
    
    def skip_when_dependency_fail(dependency_type=DependencyType.CURRENT_CLASS_PREVIOUS_CASE, dependency_path_arr: [] = None):
        """
        :param dependency_type: 依赖用例定位方法,默认当前用例前一个方法
        :param dependency_path_arr: 依赖的用例函数名,默认为空
        :return: wrapper_func
        """
    
        def wrapper_func(test_func):
            @wraps(test_func)  # @wraps:避免被装饰函数自身的信息丢失
            def inner_func(self):
                # 获取当前测试用例的类名和方法名
                current_class_name = self.__class__.__name__
                current_method_name = test_func.__name__
                current_file = os.path.splitext(os.path.basename(inspect.getfile(self.__class__)))[0]
    
                check_dependency_case_result(self, current_file, current_class_name, current_method_name, dependency_type, dependency_path_arr)
    
                return test_func(self)
    
            return inner_func
    
        return wrapper_func
    
    
    def check_dependency_case_result(self, current_file_name, current_class_name, current_method, dependency_type, dependency_path_arr: [] = None):
        """
        查找当前用例的前一个用例
        :param current_file_name: 当前执行的用例文件名名
        :param current_class_name: 当前执行的用例所在类名
        :param current_method: 当前执行的用例方法名
        :param dependency_type: 查找类型,可以是CURRENT_CLASS_PREVIOUS_METHOD或PREVIOUS_METHOD
        :param dependency_path_arr: 依赖用例路径
        :return 上一个方法的全路径
        """
    
        if dependency_type == DependencyType.NO_DEPENDENCY:
            return
    
        all_result = self._outcome.result.result
        if not hasattr(self._outcome.result, 'result') or not all_result or len(all_result) == 0:
            raise ValueError("当前不存在任何前置用例")
    
        # 获取当前类中的所有测试方法
        current_test_methods = [method for method in dir(self.__class__) if method.startswith("test_")]
        # 当前方法在当前类的顺序
        current_index_of_current_class = current_test_methods.index(current_method)
    
        if dependency_type == DependencyType.CURRENT_CLASS_PREVIOUS_CASE and current_index_of_current_class <= 0:
            raise ValueError("当前用例在当前类中无前置方法")
    
        # 非自定义前置依赖,则直接从当前测试结果中取最后一个测试结果
        if dependency_type == DependencyType.CURRENT_CLASS_PREVIOUS_CASE or dependency_type == DependencyType.ANY_PREVIOUS_CASE:
            # 判断所有已运行用例的最后一个
            last_result = all_result[-1]
            if last_result[0] != 0:  # 第0个为用例测试结果,结果0 表示用例通过
                raise self.failureException("前置用例:{} 未通过,跳过该用例并标记失败".format(last_result[1].id()))  # 第1个为TestCase object
    
        elif dependency_type == DependencyType.CUSTOM_PATH:
    
            assert dependency_path_arr is not None and len(dependency_path_arr) > 0, "用例选择类型为自定义时,用例路径不允许为空"
            has_dependency_not_success = False  # 前置用例是异常
            exception_descript = ''
    
            for dependency_path in dependency_path_arr:
                # 选择类型为自定义路径,解析自定义路径来获取前置用例的标识
                dependency_parts = dependency_path.split('.')
                if len(dependency_parts) == 3:
                    if dependency_path == f"{current_file_name}.{current_class_name}.{current_method}":
                        raise ValueError("{} 前置用例不允许为自身".format(dependency_path))
                else:
                    raise ValueError("无效的依赖定义:{}. 格式: 'py_file_name.ClassName.method_name'(其中py_file_name、ClassName允许为空)".format(dependency_path))
                previous_file, previous_class, previous_method = dependency_parts
                match_count = 0  # 自定义用例匹配数量
                match_case_id = ''  # 所有匹配的用例路径
                for result in all_result:
                    result_case_id = result[1].id()
                    case_name, case_class, case_method = result_case_id.split(".")
                    if (previous_file == case_name or not previous_file) and (previous_class == case_class or not previous_class) and previous_method == case_method:
                        match_count += 1
                        match_case_id += f"{result_case_id};"
                        if result[0] != 0:  # 第0个为用例测试结果,结果0 表示用例通过
                            exception_descript += "前置用例:{} 未通过,跳过该用例并标记失败;".format(result_case_id)
                            has_dependency_not_success = True
                if match_count == 0:
                    raise ValueError("自定义前置用例: {} 未找到".format(dependency_path))
                elif match_count > 1:
                    raise ValueError("自定义前置用例: {} 匹配数量: {},匹配结果: {} 超过 1".format(dependency_path, match_count, match_case_id))
    
            if has_dependency_not_success:
                raise self.failureException(exception_descript)
    
        else:
            raise ValueError("未支持的前置依赖选择类型: {}".format(dependency_type))
    
    
    class DefaultSkipWhenDependencyFailMeta(type):
        def __new__(mcs, name, bases, attributes):
            test_methods = [method_name for method_name in attributes if method_name.startswith('test_')]
            first_method = test_methods[0] if test_methods else None
            for method_name in test_methods:
                test_func = attributes[method_name]
                # 检如果该方法没有被skip_when_dependency_fail()装饰器装饰,并且不是该类中的第一个方法
                if method_name != first_method and not hasattr(test_func, "__wrapped__"):
                    attributes[method_name] = skip_when_dependency_fail()(test_func)
            return super().__new__(mcs, name, bases, attributes)
    
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123

    使用方法示例:

    
    class InitCase1(unittest.TestCase, metaclass=DefaultSkipWhenDependencyFailMeta):
    
        def test_0100(self):
            pass
    
        def test_0200(self):
            raise "手工测试失败"
    
        def test_0300(self):
            pass
    
        @skip_when_dependency_fail(dependency_type=DependencyType.NO_DEPENDENCY)
        def test_0400(self):
            pass
    
        def test_0500(self):
            raise "手工测试失败"
    
    class InitCase2(unittest.TestCase):
    
        @skip_when_dependency_fail(dependency_type=DependencyType.ANY_PREVIOUS_CASE)
        def test_p0100(self):
            pass
    
        def test_p0200(self):
            pass
    
        def test_p0300(self):
            pass
    
        @skip_when_dependency_fail(dependency_type=DependencyType.CUSTOM_PATH, dependency_path_arr=['..test_p0100', '..test_p0200'])
        def test_p0400(self):
            pass
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
  • 相关阅读:
    教你亲手制作一个虚拟数字人,超全步骤详解
    停更的公众号
    秒杀系统常见问题—库存超卖
    LeakCanary 源码详解(2)
    云原生之使用Docker部署开源建站工具Halo-V2.10版本
    [附源码]Python计算机毕业设计Django时间管理软件app
    CUDA优化之LayerNorm性能优化实践
    第十章 结构体
    Vue-cli3.0脚手架安装
    【MySQL基础 | 中秋特辑】多表查询详细总结
  • 原文地址:https://blog.csdn.net/jiangshanwe/article/details/133744111