def body_replace(self, json_params, replace_value): #将replace_value 转化成字符串 try: self.json_params = eval(str(json_params)) self.replace_value_dict = eval(str(replace_value)) except: loggers.error(u'传入参数为非字典格式') for key, value in self.replace_value_dict.items(): if isinstance(value, dict): for key_i, value_i in value.items(): for ke, va in self.json_params.items(): if str(ke) == str(key_i) and (self.json_params[ke] == "#"): self.json_params[ke] = value[key_i] break else: continue else: for ke, va in self.json_params.items(): if isinstance(va, dict): for k, v in va.items(): if str(k) == str(key) and (va[k] == "#"): va[k] = self.replace_value_dict[key] break else: continue elif str(ke) == str(key) and (self.json_params[ke] == "#"): self.json_params[ke] = self.replace_value_dict[key] break else: continue return self.json_params
def Dict_Map_DB_sum(self, json_params, Expect_Type): if isinstance(json_params, dict): self.json_params = self.dict_map_db(json_params, Expect_Type) else: loggers.error("您的期望结果既不是json也不是SQL查询语句,请修改!") return self.json_params
def search(self, sql,Expect_Type): real_sql = sql.replace("\n"," ") result = {} self.parent.show_log.insert(END,time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) + ":" + "期望结果为SQL语句:\n%s\n" %real_sql,('b')) self.parent.show_log.update() self.parent.show_log.see("end") loggers.info("期望结果为SQL语句:\n%s\n" %real_sql) with self.connection.cursor() as cursor: cursor.execute(real_sql) self.connection.commit() if Expect_Type == "single": result = cursor.fetchone() if result is None: result = {} elif Expect_Type == "multiple": result = cursor.fetchall() if result == (): result = list(result) else: self.parent.show_log.insert(END,time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) + ":" + "测试用例期望类型填写有误,请选择填写json或SQL\n",('b')) self.parent.show_log.update() self.parent.show_log.see("end") loggers.error("测试用例期望类型填写有误,请选择填写json或SQL") result = self.dict_datetime(result) #loggers.info("mysql查询结果:%s" %result) #self.parent.show_log.insert(END,time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) + ":" + "mysql查询结果:%s\n" %result,('b')) #self.parent.show_log.update() #self.parent.show_log.see("end") return result
def read_superior_path(self): path = os.getcwd() parent_path = os.path.dirname(path) path_data_conf = parent_path + self.file if ((os.path.exists(path_data_conf)) == False): loggers.error("请检查是否存在 : %s" % path_data_conf) return path_data_conf
def delete(self): try: #context = ssl._create_unverified_context() data = requests.delete(self.url, headers=self.head) data.raise_for_status() self.parent.show_log.insert( END, time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) + ":" + "URLenCode完整地址:%s\n" % data.url) self.parent.show_log.update() self.parent.show_log.see("end") loggers.info(data.url) page_response = data.text page_response = json.loads(page_response) #self.parent.show_log.insert(END,time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) + ":" + "page_response:%s\n"%page_response) #self.parent.show_log.update() #self.parent.show_log.see("end") return page_response except Exception as e: self.parent.show_log.insert( END, time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) + ":" + 'delete error : %s\n' % e, ('a')) self.parent.show_log.update() self.parent.show_log.see("end") loggers.error('delete error : %s' % e) return str(e)
def put(self): try: #context = ssl._create_unverified_context() response = requests.put(self.url, json=eval(str(self.body)), headers=self.head) response.raise_for_status() self.parent.show_log.insert( END, time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) + ":" + "URL:%s\n" % self.url) self.parent.show_log.update() self.parent.show_log.see("end") self.parent.show_log.insert( END, time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) + ":" + "header:%s\n" % self.head) self.parent.show_log.update() self.parent.show_log.see("end") loggers.info("URL:%s" % self.url) loggers.info("header:%s" % self.head) self.parent.show_log.insert( END, time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) + ":" + "code:%s\n" % response, ('b')) self.parent.show_log.update() self.parent.show_log.see("end") re = response.text re = json.loads(re) #loggers.info("response:%s"%re) #self.parent.show_log.insert(END,time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) + ":" + "response:%s\n"%re) #self.parent.show_log.update() #self.parent.show_log.see("end") return re except Exception as e: self.parent.show_log.insert( END, time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) + ":" + 'put error : %s\n' % e, ('a')) self.parent.show_log.update() self.parent.show_log.see("end") loggers.error('put error : %s' % e)
def __init__(self,parent): self.parent = parent #读取配置文件 '''conf_path = read_path('\pingtest\Control\DataBase_conf.ini') config = configparser.ConfigParser() # 从配置文件中读取数据 config.read(conf_path.read_superior_path(), encoding='utf-8') self.host = config['DataBase_Connection']['host'] self.user = config['DataBase_Connection']['user'] self.password = config['DataBase_Connection']['password']''' try: # Connect to the database self.connection = pymysql.Connect(host='192.168.50.215', user='******', password='******', charset='utf8', cursorclass=pymysql.cursors.DictCursor) except pymysql.err.OperationalError as e: loggers.error("Mysql Error %d: %s" % (e.args[0], e.args[1]))
def _set_result_filedir(self, file_name): self.file_name = file_name ws_path = read_path("/pingtest/Report") self.report_dir = ws_path.read_superior_path() # 获取工作空间路径 if os.path.exists(self.report_dir) is False: os.makedirs(self.report_dir) self.parent.show_log.insert( END, time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) + ":" + "已自动建立测试报告路径:%s\n" % self.report_dir) self.parent.show_log.update() self.parent.show_log.see("end") loggers.info("已自动建立测试报告路径:%s" % self.report_dir) if '' == self.file_name: self.parent.show_log.insert( END, time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) + ":" + 'filename can not be empty\n') self.parent.show_log.update() self.parent.show_log.see("end") loggers.error('filename can not be empty') # 判断是否为目录 elif os.path.isdir(self.report_dir): parent_path, ext = os.path.splitext(file_name) tm = time.strftime('%Y%m%d%H%M%S', time.localtime()) self.file_name = parent_path + "_" + tm + ext self.file_name_fail = parent_path + 'Fail' + "_" + tm + ext os.chdir(self.report_dir) # 转换目录 else: self.parent.show_log.insert( END, time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) + ":" + "%s must point to a dir\n" % self.report_dir) self.parent.show_log.update() self.parent.show_log.see("end") raise loggers.error("%s must point to a dir" % self.report_dir)
def test_post(self, params, expected_result, index): fail_keys = [] response = None currunt_caseid = self.testcase_sheet.row_values(index)[3] Expect_Type = self.testcase_sheet.row_values(index)[8] # 检查期望结果是否为json格式 try: expected_result = self.dict_db.Dict_Map_DB_sum( eval(expected_result.replace("\n", " ")), Expect_Type) except BaseException as e: self.parent.show_log.insert( END, time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) + ":" + "测试用例%s中填写的expected_result字段错误,不是json格式或执行SQL错误\n%s\n" % (currunt_caseid, e), ("a")) self.parent.show_log.update() self.parent.show_log.see("end") return "Error", "期望结果字段错误,不是json格式或执行SQL错误", [] # 更新期望结果字段 self.testcase_sheet.put_cell( index, 9, 1, str(expected_result).replace("'", '''"'''), 0) # 判断catch_result字段是否为字典格式 if self.testcase_sheet.row_values(index)[12].strip().replace("\n", "") == '': pass else: try: self.catch_result = eval( self.testcase_sheet.row_values(index)[12].strip().replace( "\n", "")) except: self.parent.show_log.insert( END, time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) + ":" + "测试用例ID:%s 中填写的catch_result错误,不是字典格式\n" % currunt_caseid, ('a')) self.parent.show_log.update() self.parent.show_log.see("end") loggers.error("测试用例中填写的catch_result错误,不是字典格式") return "Error", "catch_result格式错误,不是字典格式", [] if isinstance(self.catch_result, dict): pass else: self.parent.show_log.insert( END, time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) + ":" + "测试用例ID:%s 中填写的catch_result错误,不是字典格式\n" % currunt_caseid, ('a')) self.parent.show_log.update() self.parent.show_log.see("end") loggers.error(u"测试用例中填写的catch_result错误,不是字典格式") return "Error", "catch_result格式错误,不是字典格式", [] # 请求包体中替换流程列表中的字段 self.json_params = params try: if isinstance(eval(self.json_params), dict): pass else: self.parent.show_log.insert( END, time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) + ":" + "当前用例ID:%s请求包体格式为非Json格式\n" % currunt_caseid, ("a")) self.parent.show_log.update() self.parent.show_log.see("end") return "Error", "请求包体格式错误,不是json格式", [] except BaseException as e: self.parent.show_log.insert( END, time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) + ":" + "当前用例ID:%s请求包体格式为非Json格式\n" % currunt_caseid, ("a")) self.parent.show_log.update() self.parent.show_log.see("end") return "Error", "请求包体格式错误,不是json格式", [] # 替换请求包头字段 if self.catch_result_total != {}: try: self.json_params = self.rdict.body_replace( self.json_params, self.catch_result_total) except: pass for key, value in self.catch_result_total.items(): if value == "Auth": self.Auth_key = key elif value == "URL": self.get_id = key else: continue # 替换请求包体中需要加入随机数的字段 self.json_params = self.radom_dict.radom_replace_sum(self.json_params) if self.Auth_key != '' and self.parent_catch_result not in ('', None, {}): if self.Auth_key in self.parent_response.keys( ) and self.Auth_key in eval(self.parent_catch_result).keys(): if eval(self.parent_catch_result)[self.Auth_key] == 'Auth': self.Auth_key_value = self.parent_response[self.Auth_key] else: self.parent.show_log.insert( END, time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) + ":" + "前一个流程接口返回结果没有%s字段\n" % self.Auth_key) self.parent.show_log.update() self.parent.show_log.see("end") loggers.info("前一个流程接口返回结果没有%s字段\n" % self.Auth_key) if self.get_id != '' and self.get_id_value == '': try: self.get_id_value = self.parent_response[self.get_id] except: self.parent.show_log.insert( END, time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) + ":" + "当前用例ID:%s前置接口返回包体没有%s字段\n" % (currunt_caseid, self.get_id), ("a")) self.parent.show_log.update() self.parent.show_log.see("end") return "Error", "当前用例ID:%s前置接口返回包体没有%s字段\n" % ( currunt_caseid, self.get_id), [] self.parent.show_log.insert( END, time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) + ":" + "替换后请求包体\n %s\n" % self.json_params) self.parent.show_log.update() self.parent.show_log.see("end") loggers.info("替换后请求包体\n %s" % self.json_params) header = { "Accept": "application/json", "Content-Type": "application/json;charset=utf-8", "Accept-Language": "zh-cn,zh;q=0.5" } URL = self.read_excel.read_case_file().row_values(index)[5] if -1 != URL.find("URL"): URL = URL.replace("URL", self.get_id_value) try: head_json = eval( self.read_excel.read_case_file().row_values(index)[16]) except: self.parent.show_log.insert( END, time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) + ":" + "测试用例ID:%s HTTPHeader字段格式不正确,非Json格式\n" % currunt_caseid) self.parent.show_log.update() self.parent.show_log.see("end") return "Error", "HTTPHeader字段格式不正确,不是json格式", [] head_json = dict(head_json, **header) if 'Authentication' in head_json.keys(): if head_json['Authentication'] == "empty": head_json['Authentication'] = '' elif head_json['Authentication'] == "None": head_json['Authentication'] = None elif head_json['Authentication'] is None: head_json['Authentication'] = None elif head_json['Authentication'] == "": head_json['Authentication'] = self.Auth_key_value elif head_json['Authentication'] != "": pass head_json = self.radom_dict.radom_replace_sum(head_json) self.testcase_sheet.put_cell(index, 5, 1, URL, 0) self.testcase_sheet.put_cell(index, 16, 1, str(head_json), 0) test_interface = interface(URL, head_json, self.json_params, self.parent) request_Method = self.testcase_sheet.row_values(index)[4] if request_Method == 'POST': response = test_interface.post() elif request_Method == 'GET': response = test_interface.get() elif request_Method == 'PUT': response = test_interface.put() elif request_Method == 'DELETE': response = test_interface.delete() check_field_str = self.testcase_sheet.row_values(index)[10] check_field_remove = self.testcase_sheet.row_values(index)[11] if check_field_str == "ALL": self.ndict.dict_map_sum(expected_result) check_field_list = self.ndict.new_keys self.parent.show_log.insert( END, time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) + ":" + '需要比对的字段列表: %s\n' % check_field_list) self.parent.show_log.update() self.parent.show_log.see("end") loggers.info('需要比对的字段列表: %s' % check_field_list) elif check_field_str != "": try: check_field_list = eval(check_field_str) except: self.parent.show_log.insert( END, time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) + ":" + '测试用例ID:%s 需要比对的字段为非列表格式,或包含不存在的字段\n' % currunt_caseid) self.parent.show_log.update() self.parent.show_log.see("end") return "Error", "需要比对的字段格式不正确,不是列表格式,或包含不存在的字段", [] self.parent.show_log.insert( END, time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) + ":" + '需要比对的字段列表: %s\n' % check_field_list) self.parent.show_log.update() self.parent.show_log.see("end") loggers.info('需要比对的字段列表: %s' % check_field_list) elif check_field_remove != "": self.ndict.dict_map_sum(expected_result) try: for i in eval(check_field_remove): self.ndict.new_keys.remove(i) check_field_list = self.ndict.new_keys except: self.parent.show_log.insert( END, time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) + ":" + '测试用例ID:%s 不需检查字段为非列表格式,或包含不存在的字段\n' % currunt_caseid) self.parent.show_log.update() self.parent.show_log.see("end") return "Error", "不需检查字段格式不正确,不是列表格式,或包含不存在的字段", [] self.parent.show_log.insert( END, time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) + ":" + '需要比对的字段列表: %s\n' % check_field_list) self.parent.show_log.update() self.parent.show_log.see("end") loggers.info('需要比对的字段列表: %s' % check_field_list) else: self.parent.show_log.insert( END, time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) + ":" + '比对字段Check_field和Check_field_remove都没有填写,请检查用例!\n', ('a')) self.parent.show_log.update() self.parent.show_log.see("end") loggers.error('比对字段Check_field和Check_field_remove都没有填写,请检查用例!') return "Error", "比对字段Check_field和Check_field_remove都没有填写", [] self.testcase_sheet.put_cell(index, 10, 1, str(check_field_list), 0) # 按照Execl标记的Check_field进行检查,以列表形式存在 result = "Pass" result_response = None # 1.验证结果,如果返回None,则说明发送请求错误 if isinstance(response, dict) is False: self.parent.show_log.insert( END, time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) + ":" + 'ERROR:测试用例%s发送请求失败!%s\n' % (currunt_caseid, response), ('a')) self.parent.show_log.update() self.parent.show_log.see("end") loggers.error('ERROR:测试用例%s发送请求失败!%s' % (currunt_caseid, response)) return 'Error', '请求失败:%s' % response, [] else: # 调用字典遍历模块,方便找出所有的键值对 new_response = self.ndict.dict_map_sum(response) new_expected = self.ndict.dict_map_sum(expected_result) self.parent_response = new_response self.parent_catch_result = self.testcase_sheet.row_values( index)[12].strip().replace("\n", "") # 2.比对response和expected字典键的个数和键名称是否一致 #if sorted(new_response.keys()) == sorted(new_expected.keys()): # 3.遍历响应包体字典的所有键值对,与期望值逐一检查 for index_c in range(len(check_field_list)): field_name = check_field_list[index_c] try: if new_response[field_name] == new_expected[field_name]: result = 'Pass' result_response = response continue else: result = 'Fail' result_response = response fail_keys.append(field_name) break except BaseException as e: self.parent.show_log.insert( END, time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) + ":" + 'ERROR:测试用例%s 比对结果时出现异常!%s\n' % (currunt_caseid, e), ('a')) self.parent.show_log.update() self.parent.show_log.see("end") loggers.error('ERROR:测试用例%s 比对结果时出现异常!%s %s' % (currunt_caseid, e, response)) return 'Error', '比对结果时出现异常:%s %s' % (e, response), [] '''else: result = 'Fail,响应包体与期望包体字段不一致' result_response = response self.parent.show_log.insert(END,time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) + ":" + "响应包体与期望包体字段不一致\n") self.parent.show_log.update() self.parent.show_log.see("end") loggers.info("响应包体与期望包体字段不一致!")''' if result == "Pass": checkDB_SQL = self.testcase_sheet.row_values(index)[13] checkDB_result = self.testcase_sheet.row_values(index)[14] if checkDB_SQL.replace("\n", "").strip() != "": db = DB(self.parent) db_result = db.run(checkDB_SQL) self.db_result = db_result if isinstance(db_result, (dict, list)) is False: return 'Error', '期望写入DB结果SQL语句执行失败:%s' % db_result, [] self.testcase_sheet.put_cell(index, 15, 1, str(db_result), 0) if eval(checkDB_result) == db_result: self.parent.show_log.insert( END, time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) + ":" + '写入数据库后结果为%s,比对结果正确\n' % db_result) self.parent.show_log.update() self.parent.show_log.see("end") loggers.info("写入数据库后结果为%s,比对结果正确" % str(db_result)) self.testcase_sheet.put_cell( index, 14, 1, json.dumps(eval(checkDB_result)).encode().decode( "unicode-escape"), 0) self.testcase_sheet.put_cell( index, 15, 1, json.dumps(db_result).encode().decode( "unicode-escape"), 0) else: self.parent.show_log.insert( END, time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) + ":" + '写入数据库后结果为%s,比对结果不正确\n' % db_result, ('a')) self.parent.show_log.update() self.parent.show_log.see("end") loggers.info("写入数据库后结果为%s,比对结果不正确" % str(db_result)) result = "Fail,写入数据库结果不正确" self.report.Fail_num = self.report.Fail_num + 1 self.report.Fail_case_ID.append( self.testcase_sheet.row_values(index)[3]) # 把结果替换给catch_result字段 catch_result_single = self.rdict.body_replace( self.catch_result, response) self.catch_result_total = dict(catch_result_single, **self.catch_result_total) if self.db_result != '' and isinstance( self.db_result, dict): catch_result_single = self.rdict.body_replace( self.catch_result, self.db_result) # 抓取查询DB的结果字段 self.catch_result_total = self.rdict.body_replace( self.catch_result_total, catch_result_single) self.testcase_sheet.put_cell( index, 14, 1, json.dumps(eval(checkDB_result)).encode().decode( "unicode-escape"), 0) self.testcase_sheet.put_cell( index, 15, 1, json.dumps(db_result).encode().decode( "unicode-escape"), 0) else: self.testcase_sheet.put_cell(index, 15, 1, "", 0) if result == "Pass": self.report.Success_num = self.report.Success_num + 1 self.report.Success_case_ID.append( self.testcase_sheet.row_values(index)[3]) # 把结果替换给catch_result字段 catch_result_single = self.rdict.body_replace( self.catch_result, response) self.catch_result_total = dict(catch_result_single, **self.catch_result_total) if self.db_result != '' and isinstance(self.db_result, dict): catch_result_single = self.rdict.body_replace( self.catch_result, self.db_result) # 抓取查询DB的结果字段 self.catch_result_total = self.rdict.body_replace( self.catch_result_total, catch_result_single) self.parent.show_log.insert( END, time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) + ":" + '流程接口可获取字典:%s\n' % self.catch_result_total) self.parent.show_log.update() self.parent.show_log.see("end") loggers.info('流程接口可获取字典:%s' % self.catch_result_total) self.parent.show_log.insert( END, time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) + ":" + "成功用例数集合--%s\n" % self.report.Success_case_ID, ('b')) self.parent.show_log.update() self.parent.show_log.see("end") loggers.info("成功用例数集合--%s" % self.report.Success_case_ID) elif result in ['Fail', 'Fail,响应包体与期望包体字段不一致']: self.report.Fail_num = self.report.Fail_num + 1 self.report.Fail_case_ID.append( self.testcase_sheet.row_values(index)[3]) # 把结果替换给catch_result字段 catch_result_single = self.rdict.body_replace( self.catch_result, response) self.catch_result_total = dict(catch_result_single, **self.catch_result_total) if self.db_result != '' and isinstance(self.db_result, dict): catch_result_single = self.rdict.body_replace( self.catch_result, self.db_result) # 抓取查询DB的结果字段 self.catch_result_total = self.rdict.body_replace( self.catch_result_total, catch_result_single) self.parent.show_log.insert( END, time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) + ":" + '流程接口可获取字典:%s\n' % self.catch_result_total) self.parent.show_log.update() self.parent.show_log.see("end") loggers.info('流程接口可获取字段:%s' % self.catch_result_total) self.parent.show_log.insert( END, time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) + ":" + "失败用例数集合--%s\n" % self.report.Fail_case_ID, ('a')) self.parent.show_log.update() self.parent.show_log.see("end") loggers.info("失败用例数集合--%s" % self.report.Fail_case_ID) self.testcase_sheet.put_cell(index, 15, 1, "", 0) self.parent.show_log.insert( END, time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) + ":" + "测试结果为:%s\n" % result) self.parent.show_log.update() self.parent.show_log.see("end") loggers.info("测试结果为:%s" % result) self.parent.show_log.insert( END, time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) + ":" + "比对失败字段:%s\n" % fail_keys) self.parent.show_log.update() self.parent.show_log.see("end") loggers.info("比对失败字段:%s" % fail_keys) return result, result_response, fail_keys