def read_excel(self, file_path): case_list = [] try: book = xlrd.open_workbook(file_path) sheet = book.sheet_by_index(0) log.info("开始读取测试用例 %s" % file_path) for row in range(1, sheet.nrows): line = sheet.row_values(row)[1:8] line[2] = self.params_func(line[2]) # 参数化 case_list.append(line) log.debug("成功读取第%d条用例 %s" % (row, line)) log.info("测试用例读取完毕 %s" % file_path) except Exception as e: log.error("读取用例文件出错,文件名是:%s" % file_path) log.error("具体的错误信息是%s" % traceback.format_exc()) return case_list
def post_delete( cls, sender, instance, using, **kwargs, ): if instance.captured_images.get('ocr_image', None) is not None: try: from utils.static_util import StaticUtil StaticUtil.delete(instance.ocr_camera.camera_id, instance.history_id) except Exception as exc: log.error( f'InOutHistory [{instance.history_id}] - remove images failed: {exc}' )
def send_mail(all_count, pass_count, file_name): log.debug('开始发送邮件') content = ''' 各位好! 本次接口测试结果如下:总共运行%s条用例,通过%s条,失败【%s】条。 详细信息请查看附件。 ''' % (all_count, pass_count, all_count - pass_count) subject = '%s-接口测试报告' % time.strftime('%Y-%m-%d %H:%M:%S') try: mail = yagmail.SMTP(**EMAIL_INFO) mail.send(to=TO, cc=CS, subject=subject, contents=content, attachments=file_name) except Exception as e: log.error("发送邮件出错了,错误信息是:\n%s" % traceback.format_exc()) else: log.info("发送邮件成功")
def req(self): log.info("开始发起请求:\nurl:%s\nmethod:%s\nheaders:%s\nreq_data:%s" % (self.url, self.method, self.headers, self.data)) try: if self.is_json == '是': res = requests.request(self.method, self.url, params=self.data, json=self.data, headers=self.headers).json() else: res = requests.request(self.method, self.url, params=self.data, data=self.data, headers=self.headers).json() except Exception as e: log.error('请求 %s的时候出错了,请求参数是:%s,错误信息是 %s' % (self.url, self.data, traceback.format_exc())) self.res = {"msg": "请求接口出错了", "error_msg": traceback.format_exc()} self.text = ' {"msg":"请求接口出错了","error_msg":%s} ' % traceback.format_exc() else: self.res = res self.text = str(res) log.info('请求 %s 成功,响应参数 %s' % (self.url, self.res))
def get_queryset(self, request): queryset = super().get_queryset(request) try: request.GET = request.GET.copy() container_code = request.GET.pop('container_code', None) inout = request.GET.pop('inout', None) start_date = request.GET.pop('start_date', None) end_date = request.GET.pop('end_date', None) if container_code is not None and container_code[0] != '*': if container_code[0] != '-1': queryset = queryset.filter(container_code=container_code[0]) else: queryset = queryset.filter(container_code=None) if inout is not None and inout[0] != '*': queryset = queryset.filter(inout=inout[0]) if start_date is not None and start_date[0] != '': try: start_date_dt = datetime.datetime.strptime(start_date[0], '%d/%m/%Y, %H:%M') queryset = queryset.filter( history_datetime__gte=start_date_dt ) except Exception as error: print('query date fail', error) pass if end_date is not None and end_date[0] != '': try: end_date_dt = datetime.datetime.strptime(end_date[0], '%d/%m/%Y, %H:%M') queryset = queryset.filter( history_datetime__lte=end_date_dt ) except Exception as error: print('query date fail', error) pass except Exception as exc: log.error(f'Query histories failed: {exc}') return queryset
def set_rele(self, data): ''' 关联参数,以线程id为key, 取相应线程的关联参数替换到请求参数 :param data: 请求参数 :return: 关联好的请求参数 ''' reles = re.findall(r'\{(.*?)\}', data) if reles: log.debug("开始设置关联参数 %s" % data) thread_rels = RELEVANCE_DATA.get(self.tid) for rele_k in reles: log.debug("获取关联参数 %s" % rele_k) rel_data = thread_rels.get(rele_k) if thread_rels else '' if rel_data: rele_v = '{' + rele_k + '}' data = data.replace(rele_v, rel_data) log.debug("关联参数设置成功 %s=%s" % (rele_k, rel_data)) else: log.error("没有找到关联参数 %s" % rele_k) return self.str_to_dic(data)
def write_excel(file_path, res_list): # [ ['请求参数','实际结果','状态','备注(失败原因)']] try: log.info('现在开始写报告了:文件名是 %s 内容:%s' % (file_path, res_list)) book = xlrd.open_workbook(file_path) new_book = copy.copy(book) sheet = new_book.get_sheet(0) for row, res in enumerate(res_list, 1): # 实际结果 状态 原因 对应 8 9 10 这3列 for col, val in enumerate(res[1:], 8): sheet.write(row, col, val) # 请求参数对应第3列 sheet.write(row, 3, str(res[0])) # 写 xlsx格式会报错,替换下 file_name = os.path.basename(file_path).replace('xlsx', 'xls') new_name = time.strftime('%Y%m%d%H%M%S') + '_' + file_name report_file = os.path.join(REPORT_PATH, new_name) new_book.save(report_file) log.info('报告生成完成,文件名是%s' % report_file) return report_file except: log.error("生成 %s 的测试报告失败,报错如下:%s" % (file_path, traceback.format_exc()))
def do_check(self): # 如果预期结果为空 直接返回True通过 if not self.expected_res: return True log.debug("开始校验...预期结果 %s,实际结果 %s" % (self.expected_res, self.actual_res)) expected_lis = self.expected_res.split("&") for exp in expected_lis: check_flag = False for sym in self.symbol: if sym in exp: # 预期结果里有对应的运损符,将flag置为True check_flag = True log.debug("开始校验%s" % exp) exp_k, exp_v = exp.split(sym) act_lis = jsonpath.jsonpath(self.actual_res, '$..%s' % exp_k) # 因为预期结果处理得到的数据是字符串 # 这里也需要处理为字符串,不然eval会报错 act_v = str(act_lis[0]) if act_lis else '' sym = "==" if sym == "=" else sym log.debug("校验表达式%s %s %s" % (act_v, sym, exp_v)) res = eval("act_v %s exp_v" % sym) if res != True: self.reason = '预期结果 %s,实际结果 %s' \ % (self.expected_res, self.actual_res) log.error(self.reason) self.status = "失败" return False # 预期结果里内有有对应的运损符 用例失败 if not check_flag: self.reason = '预期结果 %s,实际结果 %s' \ % (self.expected_res, self.actual_res) log.error(self.reason) self.status = "失败" return False log.debug("校验成功...预期结果 %s,实际结果 %s" % (self.expected_res, self.actual_res))
def extract_info(cls, container_str): container_code = '' length = '-' height = '-' try: # part1 = container_code[:10] # part2 = container_code[10] # part3 = container_code[11:15] # # container_owner_code = container_code[:3] # container_type_char = container_code[3] # container_type = CONTAINER_TYPES[container_type_char] container_code = container_str.replace(container_str[-5:-1], '') length = container_str[-5] length = length if length in ('2', '4', 'L', 'M') else '-' height = container_str[-4] height = height if height in ('0', '2', '5') else '-' except Exception as exc: log.error(f'Extract container info failed: {exc}') return container_code, length, height
def req(self): log.info( "开始发起请求:\nurl:%s\nmethod:%s\nheaders:%s\nreq_data:%s\n待关联的参数:%s" % (self.url, self.method, self.headers, self.data, self.rele)) try: if self.is_json == '是': res = requests.request(self.method, self.url, params=self.data, json=self.data, headers=self.headers).json() else: res = requests.request(self.method, self.url, params=self.data, data=self.data, headers=self.headers).json() # 如果存在关联参数,从响应数据里取关联参数 if self.rele: # 以线程id为key,同一个线程的关联参数放一起 RELEVANCE_DATA.setdefault(self.tid, {}) for k, v in self.rele.items(): log.debug("开始获取关联参数 %s" % v) val = jsonpath.jsonpath(res, "$..%s" % v) if val: RELEVANCE_DATA[self.tid][k] = val[0] log.debug("获取关联参数成功 %s=%s,已加载至关联参数池" % (v, val[0])) else: RELEVANCE_DATA[self.tid][k] = '' log.error("获取关联参数失败 %s" % v) log.error("响应数据 %s 里没有关联参数 %s" % (res, v)) except Exception as e: log.error('请求 %s的时候出错了,请求参数是:%s,错误信息是 %s' % (self.url, self.data, traceback.format_exc())) self.res = {"msg": "请求接口出错了", "error_msg": traceback.format_exc()} self.text = ' {"msg":"请求接口出错了","error_msg":%s} ' % traceback.format_exc( ) else: self.res = res self.text = str(res) log.info('请求 %s 成功,响应参数 %s' % (self.url, self.res))