def get_timestamp_from_time(assigned_time=None, magnitude="s"): """ 功能:将一个形如"2019-10-10 09:00:00"的时间转为时间戳 场景1:获取当前秒级时间戳 get_timestamp_from_time() 场景2:获取当前毫秒级时间戳 get_timestamp_from_time(magnitude="ms") 场景3:获取指定时间(2019-10-10 09:00:00)对应的秒级时间戳 get_timestamp_from_time(assigned_time="2019-10-10 09:00:00") :param assigned_time: 需要转为时间戳的时间,时间格式要求:2019-10-10 09:00:00 :param magnitude: 时间戳数量级:秒(s)、毫秒(ms)、微妙(us) :return: 返回一个时间戳 """ validator.check_paramType_str(magnitude) if magnitude == "s": factor = 1 elif magnitude == "ms": factor = 1000 elif magnitude == "us": factor = 1000000 else: raise exceptions.ListOptionsException( "不期望的magnitude值:{}".format(magnitude)) if assigned_time is None: return int(time.time() * factor) validator.check_paramType_str(assigned_time) t = time.strptime(assigned_time, _TIME_FORMAT) return int(time.mktime(t) * factor)
def get_time_from_timestamp(timestamp=None, time_format=None): """ 功能:将一个时间戳转为指定时间格式的时间,默认转为的时间格式为:%Y-%m-%d %H:%M:%S 场景1:获取当前时间,时间格式为:%Y-%m-%d %H:%M:%S get_time_from_timestamp() 场景2:获取当前时间,时间格式为:%H:%M:%S get_time_from_timestamp(time_format="%H:%M:%S") 场景3:根据指定时间戳来获取时间,时间格式为:%Y-%m-%d %H:%M:%S get_time_from_timestamp(timestamp=1569850832) :param timestamp: 待转换为时间的时间戳,默认为当前时间戳 :param time_format: 待转换成的时间格式,默认时间格式:%Y-%m-%d %H:%M:%S :return: 返回一个指定格式的时间 """ if time_format is None: time_format = _TIME_FORMAT validator.check_paramType_str(time_format) if timestamp is None: return datetime.datetime.now().strftime(time_format) validator.check_paramType_int(timestamp) local_time = time.localtime(timestamp) time_data = time.strftime(time_format, local_time) return time_data
def md5(str): """ 功能:将一个字符串进行md5加密 :param str: 待加密的字符串 :return: md5值 """ validator.check_paramType_str(str) m = hashlib.md5() m.update(str.encode("utf8")) return m.hexdigest()
def base_yaml_info(self, yaml_file=None, module_key=None, func_key=None, curr_file=None): """ 功能:先将yaml文件转为字典,再在字典中通过key取value。 :param yaml_file: yaml文件 :param module_key: 字典的key :param curr_file: 默认填写 __file__ :return: """ # TODO(dongjun): module_key 如果只有一个key时,自动读取 if not yaml_file: curr_dir = os.path.dirname(curr_file) yaml_file_list = FileHelper.get_files_from_folderOrFolderlist( curr_dir, ".yaml", recursive=False) if len(yaml_file_list) == 1: yaml_file = yaml_file_list[0] elif len(yaml_file_list) == 0: raise exceptions.FileException( "当前目录下不存在yaml文件:{}".format(curr_dir)) else: raise exceptions.FileException( "当前目录下存在多个yaml文件,请明确指明yaml路径,:{}".format(curr_dir)) if not module_key: module_key = "" validator.check_file_isFile(yaml_file) validator.check_paramType_str(module_key) api_dictInfo = YamlHelper.load_yaml_file(yaml_file) api_info = api_dictInfo.get(module_key) if module_key is "": return api_dictInfo elif api_info: if func_key: api_info = api_info.get(func_key) if api_info: return api_info raise exceptions.DictException( "yaml中func_key不存在。yaml_path:{},目标key:{}".format( yaml_file, func_key)) return api_info else: raise exceptions.DictException( "yaml中module_key不存在。yaml_path:{},目标key:{}".format( yaml_file, module_key))
def assert_actual_lt_expect(self, desc_msg, actual_value, expect_value): """ 断言方法:actual_value < expect_value :param desc_msg: 需要校验的值 :param actual_var: 实际值 :param expect_var: 期望值 """ validator.check_paramType_str(desc_msg) validator.check_paramType_int(actual_value, expect_value) with allure.step('[断言校验]实际值小于期望值:{}'.format(desc_msg)): AllureHelper.attachText("", "实际值:{}".format(actual_value)) AllureHelper.attachText("", "期望值:{}".format(expect_value)) assert expect_value < actual_value
def assert_actual_equal_expect(self, desc_msg, actual_value, expect_value): """ 断言方法:expect_value等于actual_value :param desc_msg: 需要校验的值 :param actual_var: 实际值 :param expect_var: 期望值 """ validator.check_paramType_str(desc_msg) if type(actual_value) != type(expect_value): actual_value = str(actual_value) expect_value = str(expect_value) with allure.step('[断言校验]实际值等于期望值:{}'.format(desc_msg)): AllureHelper.attachText("", "实际值:{}".format(actual_value)) AllureHelper.attachText("", "期望值:{}".format(expect_value)) assert expect_value == actual_value
def create_filepath(filepath): validator.check_paramType_str(filepath) if not os.path.isabs(filepath): raise exceptions.FileException("参数必须是绝对路径") filedir = filepath[0:filepath.rfind(os.sep)] if not os.path.isdir(filedir): try: os.makedirs(filedir) # log.log_info("创建文件夹成功:{}".format(path)) except Exception as e: raise exceptions.FileException("执行os.makedirs失败,异常:{}".format(e)) if not os.path.isfile(filepath): with open(filepath, mode='w', encoding='utf-8'): pass else: pass
def assert_actual_notContain_expect(self, desc_msg, actual_value, expect_value): """ 断言方法:expect_value不被actual_value包含 :param desc_msg: 对不期望被包含内容的一个解释说明 :param actual_var: 实际值 :param expect_var: 期望值 """ if not isinstance(actual_value, str): actual_value = str(actual_value) if not isinstance(expect_value, str): expect_value = str(expect_value) validator.check_paramType_str(desc_msg, expect_value, actual_value) with allure.step('[断言校验]实际值不包含期望值:{}'.format(desc_msg)): AllureHelper.attachText("", "实际值:{}".format(actual_value)) AllureHelper.attachText("", "期望值:{}".format(expect_value)) assert expect_value not in actual_value
def get_custom_time(timestamp_offset, assigned_time=None): """ 功能:获取一个相对时间(相对于某个时间超前或滞后) 场景1:获取超前于当前时间10s的时间 get_custom_time(timestamp_offset=10) 场景2:获取滞后于当前时间10s的时间 get_custom_time(timestamp_offset=-10) 场景2:获取超前于"2019-10-01 09:09:09"时间20s的时间 get_custom_time(timestamp_offset=20, assigned_time="2019-10-01 09:09:09") :param assigned_time: 参数时间点,默认为当前时间(格式:%Y-%m-%d %H:%M:%S) :param timestamp_offset: 秒级时间戳偏移量(正整数表示超前m秒,负整数表示滞后m秒) :return: 返回一个时间,时间格式为:%Y-%m-%d %H:%M:%S """ validator.check_paramType_int(timestamp_offset) if assigned_time is None: assigned_time = TimeHelper.get_time_from_timestamp() validator.check_paramType_str(assigned_time) # TODO: 通过正则来校验参数格式为:%Y-%m-%d %H:%M:%S timestamp = TimeHelper.get_timestamp_from_time(assigned_time) new_timestamp = timestamp + timestamp_offset return TimeHelper.get_time_from_timestamp(timestamp=new_timestamp)
def parse_csv_param(self, test_data: dict, module_key: str): """ 功能: 解析csv中的参数 :param test_data: 一行字典形式的用例数据 :param module_key: :return: 返回一个list """ validator.check_paramType_dict(test_data) validator.check_paramType_str(module_key) csvKeys_list = test_data.keys() keywords_list = ["$", "$(", "(", ")"] generator_objs_list = test_data["generator_objs_list"] = list() for csvKey in csvKeys_list: value = test_data[csvKey] if not value: continue # 解析依赖字段 if any(keyword in value for keyword in keywords_list): pattern = r"\$\((.*?)\)" c = re.compile(pattern, re.S) depend_fields_list = re.findall(c, value) # depend_fields_list 返回的是到所有$()中的内容 print("depend_fields_list: {}".format(depend_fields_list)) depend_values_list = [] if depend_fields_list: depend_fields_format = re.sub(r"\$\(.*?\)", r"{}", value) for depend_field in depend_fields_list: # 遍历每一个$()中匹配到的内容 print("depend_field:{}".format(depend_field)) depend_key = None # 如果depend_field包含有点, 则有两种情况(有key和无key) if "." in depend_field: depend_field, depend_key = depend_field.split(".") if not depend_key: depend_key = csvKey func_name = "depend_{}".format(depend_field) generator_obj = self._get_depend_param(func_name) generator_objs_list.append(generator_obj) depend_param = generator_obj.__next__() print(depend_param) if not isinstance(depend_param, dict): depend_values_list.append(depend_param) else: if not depend_key: depend_key = csvKey depend_param = depend_param.get(depend_key) if not depend_param: raise Exception( "依赖字典中的key不存在:{}".format(depend_key)) depend_values_list.append(depend_param) # 待填充列表: 对应所有实际在{}中填充的值 print("depend_values_list: {}".format(depend_values_list)) value = depend_fields_format.format(*depend_values_list) # 解析列表 if value.startswith("["): if not value.endswith("]"): raise CsvContentException( "这不是一个列表字符串: {}".format(value)) try: value = eval(value) test_data[csvKey] = value continue except: raise CsvContentException( "这不是一个列表字符串: {}".format(value)) # 解析字典 if value.startswith("{"): if not value.endswith("}"): raise CsvContentException( "这不是一个字典字符串: {}".format(value)) try: tmp_value = eval(value) test_data[csvKey] = tmp_value continue except: raise CsvContentException( "这不是一个字典字符串: {}".format(value)) test_data[csvKey] = value continue else: raise exceptions.CsvContentException( "csv填写内容异常: {}".format(value)) if not isinstance(value, str): continue # 解析随机字段 if isinstance(value, str) and (value.lower() == "r" or value.lower() == "random"): func_name = "random_{}_{}".format(module_key, csvKey) test_data[csvKey] = self._get_random_param(func_name) continue # 解析列表 if value.startswith("["): if not value.endswith("]"): raise CsvContentException("这不是一个列表字符串: {}".format(value)) try: value = eval(value) test_data[csvKey] = value continue except: raise CsvContentException("这不是一个列表字符串: {}".format(value)) # 解析字典 if value.startswith("{"): if not value.endswith("}"): raise CsvContentException("这不是一个字典字符串: {}".format(value)) try: tmp_value = eval(value) test_data[csvKey] = tmp_value continue except: raise CsvContentException("这不是一个字典字符串: {}".format(value)) # 解析空字符串 if value in ["e", "empty"]: test_data[csvKey] = "" continue # 解析布尔值False if value in ["False", "false", "f", "F"]: test_data[csvKey] = False continue # 解析布尔值True if value in ["True", "true", "t", "T"]: test_data[csvKey] = True continue return test_data