def send_import(self, data): try: if data["url"]: url = data["url"] else: url = None if data["method"].lower() == "post": method = "post" elif data["method"].lower() == "get": method = "get" else: method = None if data["headers"]: h = eval(data["headers"]) else: h = None if data["body"]: body = eval(data["body"]) else: body = None except Exception as e: Log().error(e) try: requests.packages.urllib3.disable_warnings() res = requests.request(url=url, method=method, headers=h, data=json.dumps(body), verify=False) except Exception as e: Log().error(e)
def send_req(self, data, session): try: if data["url"]: url = data["url"] else: url = None if data["method"].lower() == "post": method = "post" elif data["method"].lower() == "get": method = "get" else: method = None if data["headers"]: h = eval(data["headers"]) else: h = None if data["body"]: body1 = eval(data["body"]) body = dict(body1, **session) Log().info("合并后的data为{}".format(body)) else: body = None except Exception as e: Log().error(e) try: requests.packages.urllib3.disable_warnings() res = requests.request(url=url, method=method, headers=h, data=json.dumps(body), verify=False) except Exception as e: Log().error(e) return res
def send_mail(file): # f = open(file,'rb') # mail_body = f.read() # f.close() # --------- 读取config.ini配置文件 --------------- HOST = Tool().get_config("user", "HOST_SERVER") SENDER = Tool().get_config("user", "FROM") RECEIVER = Tool().get_config("user", "TO") USER = Tool().get_config("user", "user") PWD = Tool().get_config("user", "password") SUBJECT = Tool().get_config("user", "SUBJECT") #msg = MIMEText(mail_body, "html", "utf-8") msg = MIMEMultipart() msg['Subject'] = Header(SUBJECT, "utf-8") msg['from'] = SENDER msg['to'] = RECEIVER att = MIMEApplication(open(file, 'rb').read()) att.add_header('Content-Disposition', 'attachment', filename=file) msg.attach(att) try: server = smtplib.SMTP() server.connect(HOST) server.login(USER, PWD) server.sendmail(SENDER, RECEIVER, msg.as_string()) server.quit() Log().info("邮件发送成功!") except Exception as e: Log.error("失败: " + str(e))
def read_importdata(self,file=setting.testcasedir): wb=openpyxl.load_workbook(file) sheet=wb["Sheet2"] url = sheet.cell(2, 1).value method = sheet.cell(2, 2).value headers = sheet.cell(2, 3).value body = sheet.cell(2, 4).value packetName = sheet.cell(2, 5).value namenum = sheet.cell(2, 6).value code = sheet.cell(2, 7).value limitDate = time.strftime("%Y/%m/%d", time.localtime()) now = datetime.datetime.now() starttime = str(now.strftime('%Y-%m-%d')) + " 00:00:00" dif = datetime.timedelta(days=0) tomorrow = now - dif endtime = tomorrow.strftime('%Y-%m-%d') endtime += " 23:59:59" startDate = now.strftime('%Y-%m-%d') name="周彦龙" + str(namenum) packetName="test委案"+str(packetName) billcode=str(code)+str(code)+"11" customercode=name+"333333333333333333" if body.find("${packetName}")!=-1: body=body.replace("${packetName}",str(packetName)) if body.find("${packetMerCode}")!=-1: body=body.replace("${packetMerCode}",str(code)) if body.find("${limitDate}")!=-1: body=body.replace("${limitDate}",str(limitDate)) if body.find("${name}")!=-1: body=body.replace("${name}",str(name)) data = {"url": url, "headers": headers, "method": method, "body": body,"name":name,"billcode": billcode, "customercode": customercode, "packetName": packetName,"starttime": starttime, "endtime": endtime, "startDate": startDate} Log().info("读取导入数据中packetName:{},name:{},billcode:{},customercode:{}".format(packetName,name,billcode,customercode)) return data
def get_list_data(self, data, session, key): try: if data["url"]: url = data["url"] else: url = None if data["method"].lower() == "post": method = "post" elif data["method"].lower() == "get": method = "get" else: method = None if data["headers"]: h = eval(data["headers"]) else: h = None if data["body"]: body1 = eval(data["body"]) body = dict(body1, **session) else: body = None except Exception as e: Log().error(e) try: requests.packages.urllib3.disable_warnings() res = requests.request(url=url, method=method, headers=h, data=json.dumps(body), verify=False) body = eval(res.request.body) me = body["method"] method = str(me) + "_response" re = res.json()[method]["list"] Log().info("响应的list数据为{}".format(re)) value = re[0][key] for r in re: if r[key] == value: return value else: return False except Exception as e: Log().error(e)
def select(self, db, sql): try: # 连接数据库 self.conn = connect(host=host, user=user, password=password, db=db, charset='utf8mb4', cursorclass=cursors.DictCursor) except OperationalError as e: Log().error("Mysql Error %d: %s" % (e.args[0], e.args[1])) try: real_sql = sql cursor = self.conn.cursor() cursor.execute(real_sql) data = cursor.fetchall()[0] return data except Exception as e: Log().error("查询数据库结果错误{}".format(e))
def update_importdata(self,file=setting.testcasedir): wb=openpyxl.load_workbook(file) sheet=wb["Sheet2"] packetName = sheet.cell(2, 5).value name = sheet.cell(2, 6).value code = sheet.cell(2, 7).value packetNamenew=int(packetName)+1 codenew=int(code)+1 namenew=int(name)+1 sheet.cell(2, 5).value = packetNamenew sheet.cell(2, 6).value = namenew sheet.cell(2, 7).value = codenew Log().info("更新后的packet:{},namenum:{},code:{}".format(sheet.cell(2, 5).value,sheet.cell(2, 6).value,sheet.cell(2, 7).value)) wb.save(file)
def adminlogin(): data = { 'url': 'https://admintest.robot.com/api/manage/login', 'headers': '{"Content-Type": "application/json;charset=UTF-8","Accept": "application/json, text/plain, */*"}', 'method': 'post', 'body': '{"account":"zhouyanlong1","password":"******"}' } res = requests.request(url=data["url"], method=data["method"], headers=eval(data["headers"]), data=data["body"], verify=False) re = res.json() session_data = re["data"]["session"] session = {"session": session_data} Log().info("管理端获取到的session为{}".format(session)) return session
def login(): requests.packages.urllib3.disable_warnings() data = { 'url': 'https://test.robotsh.com/api/business/login', 'headers': '{"Content-Type": "application/json;charset=UTF-8", "Accept": "application/json, text/plain, */*"}', 'method': 'post', 'body': '{"account":"zhou3","password":"******","platform":"robot"}' } res = requests.request(url=data["url"], method=data["method"], headers=eval(data["headers"]), data=data["body"], verify=False) re = res.json() session_data = re["data"]["session"] session = {"session": session_data} Log().info("商户端获取到的session为{}".format(session)) return session
def read_data(self,file): #wb=openpyxl.load_workbook("../config/apicase.xlsx") apidata = Read_Excel().read_importdata() wb = openpyxl.load_workbook(file) sheet=wb["Sheet1"] test_data=[] flag=Tool().get_config("casemanage","num") try: for i in range(2, sheet.max_row + 1): module = sheet.cell(i, 1).value id = sheet.cell(i, 2).value usecase = sheet.cell(i, 3).value url = sheet.cell(i, 4).value header = sheet.cell(i, 6).value method = sheet.cell(i, 5).value body = sheet.cell(i, 7).value if body is not None: if body.find("${packet_name}") != -1: body = body.replace("${packet_name}", apidata["packetName"]) if body.find("${billcode}") != -1: body = body.replace("${billcode}", apidata["billcode"]) if body.find("${customercode}") != -1: body = body.replace("${customercode}", str(apidata["customercode"])) if body.find("${name}") != -1: body = body.replace("${name}", str(apidata["name"])) if body.find('${starttime}') != -1: body = body.replace('${starttime}', str(apidata["starttime"])) if body.find('${endtime}') != -1: body = body.replace('${endtime}', str(apidata["endtime"])) if body.find('${startDate}') != -1: body = body.replace('${startDate}', str(apidata["startDate"])) code = sheet.cell(i, 8).value msg = sheet.cell(i, 9).value checkdata=sheet.cell(i,10).value if checkdata is not None: if checkdata.find("${packet_name}") != -1: checkdata = checkdata.replace("${packet_name}", apidata["packetName"]) if checkdata.find("${billcode}") != -1: checkdata = checkdata.replace("${billcode}", apidata["billcode"]) if checkdata.find("${customercode}") != -1: checkdata = checkdata.replace("${customercode}", str(apidata["customercode"])) if checkdata.find("${name}") != -1: checkdata = checkdata.replace("${name}", str(apidata["name"])) sqldata=sheet.cell(i,11).value if sqldata is not None: if sqldata.find("${packet_name}") != -1: sqldata = sqldata.replace("${packet_name}", apidata["packetName"]) if sqldata.find("${billcode}") != -1: sqldata = sqldata.replace("${billcode}", apidata["billcode"]) if sqldata.find("${customercode}") != -1: sqldata = sqldata.replace("${customercode}", str(apidata["customercode"])) if sqldata.find("${name}") != -1: sqldata = sqldata.replace("${name}", str(apidata["name"])) sqlassert = sheet.cell(i, 12).value if sqlassert is not None: if sqlassert.find("${packet_name}") != -1: sqlassert = sqldata.replace("${packet_name}", apidata["packetName"]) if sqlassert.find("${billcode}") != -1: sqlassert = sqldata.replace("${billcode}", apidata["billcode"]) if sqlassert.find("${customercode}") != -1: sqlassert = sqldata.replace("${customercode}", str(apidata["customercode"])) if sqlassert.find("${name}") != -1: sqlassert = sqlassert.replace("${name}", str(apidata["name"])) data = {"module": module, "id": id,"usecase":usecase, "url": url, "headers": header, "method": method, "body": body, "code": code, "msg": msg,"checkdata":checkdata,"sqldata":sqldata,"sqlassert":sqlassert} #print(data) if flag == "all": test_data.append(data) # 从config获取到的值均为str,eval转成list elif id in eval(flag): test_data.append(data) except Exception as e: Log().error(e) return test_data
def test_case(self, testdata): Log().info("管理端用例{}:{}正在执行".format(testdata["id"], testdata["usecase"])) Log().info("用例{}的请求数据为{}".format(testdata["id"], testdata)) Log().info("session为{},类型为{}".format(session, type(session))) re = Send_Request().send_req(testdata, session) res = re.json() Log().info("响应结果为{}".format(res)) body = eval(re.request.body) me = body["method"] method = str(me) + "_response" # 返回报错 if "error_response" in res.keys(): res_code = int(res["error_response"]["code"]) res_msg = res["error_response"]["msg"] Log().info("用例{}的响应code为{},响应msg为{}".format( testdata["id"], res_code, res_msg)) if res_code == int( testdata["code"]) and res_msg == testdata["msg"]: Read_Excel().write_excel( int(testdata["id"]) - 174, "成功", setting.testcaseadmindir) Log().info("用例{}:成功".format(testdata["id"])) else: Read_Excel().write_excel( int(testdata["id"]) - 174, "失败", setting.testcaseadmindir) Log().info("用例{}:失败".format(testdata["id"])) self.assertEqual( res_code, int(testdata["code"]), "响应code为{0},预期code为{1}".format(res_code, testdata["code"])) self.assertEqual( res_msg, testdata["msg"], "响应msg为{0},预期msg为{1}".format(res_msg, testdata["msg"])) # 需要sql校验 elif testdata["sqldata"] is not None: db = eval(testdata["sqldata"])[0] sql = eval(testdata["sqldata"])[1] sql_assert = testdata["sqlassert"] sql_res = DB().select(db, sql) Log().info("sql查询的结果为{},预期结果为{}".format(str(sql_res), sql_assert)) if str(sql_res) == sql_assert: Read_Excel().write_excel( int(testdata["id"]) - 174, "成功", setting.testcaseadmindir) Log().info("用例{}:成功".format(testdata["id"])) else: Read_Excel().write_excel( int(testdata["id"]) - 174, "失败", setting.testcaseadmindir) Log().info("用例{}:失败".format(testdata["id"])) self.assertEqual( str(sql_res), sql_assert, "sql查询的结果为{},预期结果为{}".format(str(sql_res), sql_assert)) # 返回字典 elif testdata["checkdata"] is not None and testdata["body"].find( "pageSize") != -1: Log().info("请求包含分页,响应的字典数据为{}".format(res[method])) checkkey = eval(testdata['checkdata'])[0] checkvalue = eval(testdata['checkdata'])[1] res_list = Send_Request().get_list_data(testdata, session, checkkey) Log().info("响应中需要断言的数据为{},checkvalue为{}".format( res_list, checkvalue)) if str(res_list) == checkvalue: Read_Excel().write_excel( int(testdata["id"]) - 174, "成功", setting.testcaseadmindir) Log().info("用例{}:成功".format(testdata["id"])) else: Read_Excel().write_excel( int(testdata["id"]) - 174, "失败", setting.testcaseadmindir) Log().info("用例{}:失败".format(testdata["id"])) self.assertEqual( str(res_list), checkvalue, "响应data为{0},预期data为{1}".format(str(res_list), checkvalue)) # 返回list elif testdata["checkdata"] is not None and testdata["body"].find( "pageSize") == -1: Log().info("请求不包含分页,响应的list数据为{}".format(res[method])) checkkey = eval(testdata['checkdata'])[0] checkvalue = eval(testdata['checkdata'])[1] res_list = Send_Request().get_res_data(testdata, session, checkkey) Log().info("响应中需要断言的数据为{},checkvalue为{}".format( res_list, checkvalue)) if res_list == checkvalue: Read_Excel().write_excel( int(testdata["id"]) - 174, "成功", setting.testcaseadmindir) Log().info("用例{}:成功".format(testdata["id"])) else: Read_Excel().write_excel( int(testdata["id"]) - 174, "失败", setting.testcaseadmindir) Log().info("用例{}:失败".format(testdata["id"])) self.assertEqual( res_list, checkvalue, "响应data为{0},预期data为{1}".format(res_list, checkvalue)) # 返回为空 elif testdata["checkdata"] is None and "total" in res[method].keys(): Log().info("响应结果应该为空,响应的total为{}".format(res[method]["total"])) if int(res[method]["total"]) == 0: Read_Excel().write_excel( int(testdata["id"]) - 174, "成功", setting.testcaseadmindir) Log().info("用例{}:成功".format(testdata["id"])) else: Read_Excel().write_excel( int(testdata["id"]) - 174, "失败", setting.testcaseadmindir) Log().info("用例{}:失败".format(testdata["id"])) self.assertEqual(int(res[method]["total"]), 0, "响应data为{0}".format(int(res[method]["total"]))) else: Read_Excel().write_excel( int(testdata["id"]) - 174, "成功", setting.testcaseadmindir) Log().info("用例{}:成功".format(testdata["id"]))
def setUp(self) -> None: Log().info("test starts")
def tearDown(self) -> None: Log().info("test ends")