Exemplo n.º 1
0
def check_equal(act_v,
                exp_v,
                err_msg=None,
                only_log_error=False,
                show_err=False):
    """
        check actual result does match expected or not
        :param string/list act_v
        :param string/list exp_v
        :param string err_msg
        :param boolean only_log_error
    """

    if err_msg is None:
        err_msg = "断言期望结果:{expectedVal}=实际结果{actualVal}".format(
            actualVal=act_v, expectedVal=exp_v)
    elif show_err is True:
        err_msg += ", 期望结果: {expectedVal},实际结果: {actualVal}".format(
            actualVal=act_v, expectedVal=exp_v)

    if act_v != exp_v:
        log.error(err_msg)
        if only_log_error:
            return False
        else:
            raise AssertionError(err_msg + " 失败")
    else:
        log.check(err_msg + " 成功")
    return True
Exemplo n.º 2
0
 def error_print(self, title=None):  # todo rename
     if self.error_list:
         log.error(title)
         for error in self.error_list:
             # print('\033[1;31;40m', error, '\033[0m')    # 改log
             print("\n")
             log.error(msg=error)
         self.print_order_id_diff()  # query 比较开关
         print("=====================END======================")
Exemplo n.º 3
0
 def retry_len(self, query):
     import peewee, time
     for i in range(3):
         try:
             n = len(query)
             return n
         except peewee.OperationalError as e:
             log.error(e)
             time.sleep(2)
             continue
Exemplo n.º 4
0
    def print_order_id_diff(self):
        if self.error_list:
            log.error("=============仅仅打印orderId不一致的情况===============")
            for error in self.error_list:
                # print('\033[1;31;40m', error, '\033[0m')    # 改log

                if isinstance(error, dict):
                    if 'orderId' in error.get('key', ''):
                        print("\n")
                        log.error(msg=error)
            print(
                "=====================END仅仅打印orderId不一致的情况======================"
            )
Exemplo n.º 5
0
def obj_convert_json(obj):
    """
    对象转化方法,转成dict或者list
    :param obj: 待转对象
    """
    try:
        from enum import Enum
        if isinstance(obj, list):
            # 如返回对象是list
            l = []
            for obj_item in obj:
                if isinstance(obj_item, (int, str, decimal.Decimal, float)):
                    l.append(obj_item)
                else:
                    l.append(obj_convert_json(obj_item))
            return l
        else:
            data = copy.deepcopy(obj.__dict__)
            for k, v in list(data.items()):
                if isinstance(v, (list, tuple)):
                    # 如对象值为list或元组
                    for index, i in enumerate(v):
                        if is_custom_object(i):
                            # 下面这句是我加的,替换掉了再下面那一坨,如果报错,请联系我  -- by cr
                            value = obj_convert_json(i)
                            # v[index] = i.__dict__

                            # value = i.__dict__
                            # for sub_k, sub_v in value.items():
                            #     if self.is_custom_object(sub_v):
                            #         value[sub_k] = self.obj_convert_json(sub_v)
                            #     elif isinstance(sub_v, (list, tuple)):
                            #         for index2, i2 in enumerate(sub_v):
                            #             if self.is_custom_object(i2):
                            #                 sub_v[index2] = i2.__dict__

                            # value = i.__dict__
                            v[index] = value
                elif isinstance(v, (Enum)):  # 枚举类,则取值
                    data[k] = v.value
                elif is_custom_object(v):
                    data[k] = obj_convert_json(v)
                elif isinstance(v, decimal.Decimal):
                    data[k] = float(v)
                elif k.startswith("_"):
                    data.pop(k)
            return data
    except Exception as e:
        log.error("请求参数对象转换成json格式出错!!!!")
        assert False
Exemplo n.º 6
0
def assert_dict_in_another_dict(small, big):
    """
    验证小dict的key和value在大dict中
    """
    small_dict = small.copy()
    big_dict = big.copy()
    diff_list = []
    for k, v in list(dict(small_dict).items()):
        print(("=======compare key as: %s" % k))
        # 浮点数抽取出,单独比较
        if isinstance(v, float) or isinstance(v, decimal.Decimal):
            decimal.getcontext().prec = 4
            small_v = decimal.Decimal(str(v))
            big_v = decimal.Decimal(str(big_dict.get(k)))
            # com.checkEqual(smallV, bigV, "check key: %s, value in big dict is: %s, value in small dict is: %s"
            #                % (k, bigV, smallV))
            if small_v != big_v:
                diff_list.append(
                    "check key: %s, value in big dict is: %s, value in small dict is: %s"
                    % (k, big_v, small_v))
            small_dict.pop(k)
            big_dict.pop(k)
        # 比较空的情况,db和返回值里有时候是None,有时候是空字符串,拉出来单独比较
        elif v is None or v == "":
            check_equal(
                big_dict.get(k) is None or big_dict.get(k) == ""
                or big_dict.get(k) == 0, True,
                "value not equaled, key: %s" % k)
            small_dict.pop(k)
            big_dict.pop(k)
        else:
            check_equal(
                str(big_dict.get(k)), str(v),
                "check key: %s, value in big dict is: %s, value in small dict is: %s"
                % (k, big_dict.get(k), v))
            if str(big_dict.get(k)) != str(v):
                diff_list.append(
                    "check key: %s, value in big dict is: %s, value in small dict is: %s"
                    % (k, big_dict.get(k), v))
    if len(diff_list) > 0:
        log.error(diff_list)
        raise AssertionError(diff_list)
Exemplo n.º 7
0
def covert_resp_to_obj(obj, resp_act):
    """
    接口返回的格式如为list,目标对象需要给最外层的list命名为root,dict无所谓
    :param obj: 目标对象
    :param resp_act: 接口返回值,外层结构为list或dict
    :return:
    """

    if isinstance(resp_act, list):
        # 如果接口返回是个list,则获取接口对象中定义的外层列表属性名,获取不到则报错
        count = len(resp_act)
        root_name = None
        for name in dir(obj):
            if isinstance(getattr(obj, name), list) and name != "error_list":
                root_name = name
        if root_name is None:
            log.error("接口返回结构设置错误!!!!返回值直接为列表,请设置一个空属性包含具体返回对象!!!!")
            assert False
        if len(resp_act) > 0:
            # 如果接口返回的list长度大于0,则遍历返回,按接口生成返回对象
            if isinstance(resp_act[0], (int, float)) is False:
                # base_obj = getattr(obj, root_name)[0]
                # getattr(obj, root_name).pop()
                # for i in range(0, count):
                #     getattr(obj, root_name).append(copy.deepcopy(base_obj))
                #     _generate_resp_obj(getattr(obj, root_name)[i], resp_act[i])
                for i in range(0, count):
                    if i > 0:
                        getattr(obj, root_name).append(
                            copy.deepcopy(getattr(obj, root_name)[0]))
                    covert_resp_to_obj(getattr(obj, root_name)[i], resp_act[i])
            else:
                setattr(obj, root_name, resp_act)
        else:
            setattr(obj, root_name, resp_act)
            log.info("return empty list")
    elif isinstance(resp_act, dict):
        for k, v in list(dict(resp_act).items()):
            if isinstance(v, dict):
                covert_resp_to_obj(getattr(obj, k), v)
                continue
            # 条件:1.是个list,2.resp_object中k对应的每一项均为dict,3.返回list不为空
            if isinstance(v, list) and len(getattr(obj, k)) and len(v) > 0:
                # 如果是个列表,则先取出第一项作为基准,再删除,然后每次遍历的时候deepcopy一个,再赋值
                count = len(v)
                base_obj = getattr(obj, k)[0]
                if isinstance(base_obj, type) is True:
                    base_obj = copy.deepcopy(base_obj)()
                getattr(obj, k).pop()
                for i in range(0, count):
                    getattr(obj, k).append(copy.deepcopy(base_obj))
                    covert_resp_to_obj(getattr(obj, k)[i], v[i])
                continue
            if hasattr(obj, k) is True:
                pass
            else:
                log.warning("接口结构{}定义中不包含属性{},不影响结果,但建议补一下!!!!!!".format(
                    obj, k))
            setattr(obj, k, v)
    elif isinstance(resp_act, (int, str, bool)):
        setattr(obj, "data", resp_act)
    return obj if resp_act is not None else None