def random_phone(): mysql = DoMysql() while True: phone = create_phone() sql = f"select * from member where MobilePhone={phone}" if not mysql.find_count(sql): return phone
def setUp(self): self.db = DoMysql() # 随机产生身份证号,放入上下文 ID_card_No = get_card_id() setattr(Context, 'cre_id', ID_card_No) #实名认证前查询实名认证表记录 auth_sql = 'SELECT COUNT(*) count FROM user_db.t_user_auth_info;' self.before_auth_count = self.db.fetch_one(auth_sql)['count']
def test_001(self,item): global result#指明全球变量 global COOKIES#设置cookies为全局变量 url=item["url"] method=item["method"] param=item["param"] case_id=item["case_id"] modular=item["modular"] title=item["title"] expected=item["expected"] sql=item["sql"] print(sql) param=get_data.GetData().replace(param) print("现在的param是{}".format(param)) if sql is not None: sql=get_data.GetData().replace(sql) print("现在的sql是{}".format(sql)) if sql is not None and eval(sql)["sql_3"] is not None: #投资之前查询数据库用户余额保存下来 before_amount=DoMysql().do_mysql(eval(sql)["sql_3"],1)[0] print("before_sql查询结果是{}".format(before_amount)) my_log.my_info("正在发起{}模块中的第{}条用例:{}".format(modular,case_id,title)) my_log.my_info("测试数据是:{}".format(param)) test_result=DoRequests(url,method,eval(param)).request(cookies=getattr(get_data.GetData,"COOKIES")) #获取用户的member_id if sql is not None and eval(sql)["sql_1"] is not None: member_id=DoMysql().do_mysql(eval(sql)["sql_1"],1)[0] setattr(get_data.GetData,"normal_member_id",str(member_id)) #获取loan_id if sql is not None and eval(sql)["sql_2"] is not None: sql=get_data.GetData().replace(sql) loan_id=DoMysql().do_mysql(eval(sql)["sql_2"],1)[0] setattr(get_data.GetData,"loan_id",str(loan_id)) #投资之后,再做一个查询,查询数据库里面用户的余额 #增加一个判断 if test_result.cookies:#判断请求cookies是否为空 setattr(get_data.GetData,"COOKIES",test_result.cookies) my_log.my_info("测试结果是:{}".format(test_result.json())) my_log.my_info("预期结果是:{}".format(eval(expected))) try: self.assertEqual(eval(expected),test_result.json()) #增加一个判断,判断是否投资之后用户余额减少 if sql is not None and eval(sql)["sql_3"] is not None: after_amount=DoMysql().do_mysql(eval(sql)["sql_3"],1)[0] print("after_sql查询结果是{}".format(after_amount)) invest_amount=eval(param)["amount"] expected_amount=before_amount-after_amount self.assertEqual(invest_amount,expected_amount) result="pass" my_log.my_info("测试通过了") except AssertionError as e: my_log.my_error("测试失败,http请求发生错误") result="failed" raise e finally: row=case_id+1 DoExcel(project_path.case_path,"invest").write_data(row,test_result.text,result)
def test_withdraw(self, item): """ 登录状态下,提现成功 :return: """ # 判断是否需要校验DB if item['check_database'] != None: Mylog().info("需要校验DB------{} ".format(item)) before_sql_result = DoMysql().do_mysql( item['check_database']) # 获取调用接口前DB数据 Mylog().info("掉接口前sql获得的数据是{}".format(before_sql_result)) before_amount = before_sql_result[4] before_freeze_amount = before_sql_result[5] Mylog().info("提现前amount 是{},提现前freeze_amount 是{},待提现金额为{}".format( before_amount, before_freeze_amount, eval(item['data'])['amount'])) Mylog().info("开始调用接口") res = HttpRequest().get_request(item['url'], eval(item['data'])) #返回dict类型 after_sql_result = DoMysql().do_mysql(item['check_database']) Mylog().info("掉接口后sql获得的数据是{}".format(before_sql_result)) after_amount = after_sql_result[4] after_freeze_amount = after_sql_result[5] Mylog().info("提现后amount 是{},提现后freeze_amount 是{},待提现金额为{}".format( after_amount, after_freeze_amount, eval(item['data'])['amount'])) # 判断数据是否更新正确 if after_freeze_amount == before_freeze_amount + eval( item['data'])['amount']: check_result = '数据库校验通过' Mylog().info(check_result) else: check_result = '数据库未校验通过' Mylog().info(check_result) else: res = HttpRequest().get_request(item['url'], eval(item['data'])) check_result = None print(res, type(res)) try: DoAssert().assert_code(item['expected'], res['code']) # assert item['expected']==res.json()['code'] # self.assertEqual(item['expecxted'],res.json()['code']) test_result = 'Pass' except Exception as e: test_result = 'Fail' Mylog().error("执行用例失败{}".format(e)) raise e finally: pass Mylog().info('获取到的结果是{}'.format(res)) DoExcel(test_data_path).write_back("gift_dealer_manage", item['case_id'] + 1, str(res), check_result, test_result)
def test_http_request(self, case): global resp global TestResult Caseid = case['用例序号'] Module = case['模块'] Method = case['请求方式'] Url = case['接口地址'] Case_name = case['用例名'] param = case['参数'] #传参使用字典格式 Sql = case['sql'] Expect_Result = eval(case['预期结果']) #字典格式断言预期结果与实际结果 if case['参数'].find("LOANID") != -1: param = case['参数'].replace('LOANID', str(getattr(GetData, 'LOAN'))) #判断参数内是否含有字段'LOANID',存在该字段则将类属性'LOAN'转换为字符串替换"LOANID" if case['用例序号'] == 2: sql = eval(case['sql'])['sql'] befor_amount = (DoMysql().domysql(sql))[0] #执行第二条用例前,执行用例内sql语句---获取投资前的账户金额 TestLog().info("正在执行{}模块,第{}条用例,用例名:{}".format(Module, Caseid, Case_name)) resp = TestRequest().testrequest(Method, Url, eval(param), getattr(GetData, 'COOKIES')) #获取请求结果 if case['用例序号'] == 1: sql_2 = eval(case['sql'])['sql_2'] loan = DoMysql().domysql(sql_2) setattr(GetData, 'LOAN', loan[0]) # 执行第一条语句时,判断是否存在sql语句,有sql语句则执行,并将结果赋值给类属性'LOAN' if case['用例序号'] == 2: sql = eval(case['sql'])['sql'] after_amount = (DoMysql().domysql(sql))[0] #执行第二条用例后,执行用例内sql语句---获取投资后的账户金额 if resp.cookies: setattr(GetData, 'COOKIES', resp.cookies) try: if case['用例序号'] == 2: amount = float(befor_amount) - float(after_amount) self.assertEqual(float(eval(case['参数'])['amount']), amount) self.assertEqual(Expect_Result, resp.json()) #将请求结果转换为字典格式与预期结果对比 TestResult = 'PASS' except AssertionError as e: TestLog().info("断言失败{}".format(e)) TestResult = 'FAILED' raise e finally: TestLog().info("回写实际结果:{}".format(resp.text)) DoExcel().data_write('invest', Caseid + 1, 9, resp.text) TestLog().info("预期结果::{}".format(Expect_Result)) TestLog().info("回写测试结论:{}".format(TestResult)) DoExcel().data_write('invest', Caseid + 1, 10, TestResult)
class TestUserAuth(unittest.TestCase): def setUp(self): self.db = DoMysql() # 随机产生身份证号,放入上下文 ID_card_No = get_card_id() setattr(Context, 'cre_id', ID_card_No) #实名认证前查询实名认证表记录 auth_sql = 'SELECT COUNT(*) count FROM user_db.t_user_auth_info;' self.before_auth_count = self.db.fetch_one(auth_sql)['count'] @data(*cases) def test_user_auth(self, case): my_logger.info('正在执行第{}条用例:{}'.format(case.case_id, case.title)) my_logger.info('-----------开始检查url地址-------------') url = ReadConfig().get('test_api', 'url_pre') + case.url my_logger.info('请求url:{}'.format(url)) data = DoRegex().replace(case.data) data = json.loads(data) my_logger.info('-----------开始检查参数-------------') my_logger.info('请求参数:{}'.format(data)) res = WebserviceRequest(url).get_result(case.port_name, data) time.sleep(60) my_logger.info('请求结果:{}'.format(res)) try: self.assertEqual(case.expected, res['retInfo']) do_excel.bace_write_by_case_id('verifiedUserAuth', case.case_id, str(res), 'success') Test_result = 'pass' except AssertionError as e: my_logger.error('出错了,{}'.format(e)) do_excel.bace_write_by_case_id('verifiedUserAuth', case.case_id, str(res), 'fail') Test_result = 'fail' raise e except Exception as e: raise e my_logger.info('本条用例测试结果:{}'.format(Test_result)) # 如果发送短信验证码成功 if res['retCode'] == '0' and case.port_name == 'sendMCode': sql_code = 'SELECT Fverify_code FROM sms_db_20.t_mvcode_info_3 where Fmobile_no={0};'.format( getattr(Context, 'normal_mobile')) verify_code = DoMysql().fetch_one(sql_code)['Fverify_code'] if verify_code: # 如果查到验证码就放入上下文 setattr(Context, 'verify_code', verify_code) # 如果注册成功,查询uid放入上下文 if res['retCode'] == '0' and case.port_name == 'userRegister': sql_uid = "SELECT Fuid uid FROM user_db.t_user_info where Fuser_id='{0}' and Fip='{1}' ORDER BY Fcreate_time DESC;".format( getattr(Context, 'user_id'), Context.client_ip) uid = str(DoMysql().fetch_one(sql_uid)['uid']) if uid: # 如果查询到Fuid就放入上下文 setattr(Context, 'uid', uid)
def test_api(self, item): passorfail = None #请求之前完成loanid的替换 if item['data'].find('${loanid}') != -1: if getattr(GetData, 'loanid') == None: id = DoMysql.cnn_db( 'select max(id) from loan where memberid=82')[0] item['data'] = str(item['data']).replace('${loanid}', str(id)) setattr(GetData, 'loanId', id) #利用反射去存储结果 else: item['data'] = str(item['data']).replace( '${loanid}', str(getattr(GetData, 'LoanId'))) #判断sql语句 if item['sql'] == None: #没有sql语句时 print('正在执行的用例是:第{}条用例'.format(item['case_id'])) res = HttpRequest().http_request(item['url'], eval(item['data']), item['http_method'], getattr(GetData, 'COOKIE')) else: #有sql语句时 print('正在执行的用例是:第{}条用例'.format(item['case_id'])) sql = eval(item['sql'])['sql'] #http请求前 before_amount = DoMysql.cnn_db(sql)[0] res = HttpRequest().http_request(item['url'], eval(item['data']), item['http_method'], getattr(GetData, 'COOKIE')) #http请求后 after_amount = DoMysql.cnn_db(sql)[0] amount = abs(after_amount - before_amount) if str(amount) == str(eval(item['data'])['amount']): check_res = '数据库校验正确' else: check_res = '数据库校验失败' DoExcel.write_checkres(testcase_path, item['interface'], item['case_id'], check_res) print(res.json()) if res.cookies: setattr(GetData, 'COOKIE', res.cookies) try: self.assertEqual(str(item['excepted']), res.json()['code']) # 断言,没有断言默认不管对错测试用例都执行通过 passorfail = "成功" except Exception as e: print('失败用例{},{}:{}'.format(item['interface'], item['case_id'], res.json())) passorfail = "失败" raise e finally: DoExcel.write_back(testcase_path, item['interface'], item['case_id'], str(res.json()), passorfail)
def test_http_request(self, a): # print("测试数据是:",a) # print("目前正在执行第%s条用例"%a[0]) logger.info("测试数据是:{0}".format(a)) logger.info("目前正在执行第%s条用例" % a[0]) global COOKIES # IP+a[4] ip地址与uri的拼接 res = HttpRequest(IP + a[4], a[5]).http_request(a[3], cookies=COOKIES) if res.cookies != {}: # 判断长度或者是判断是否为空{} COOKIES = res.cookies # 只有登录才会产生cookies # print(res.json()) # 检查数据库 # eval(a[6]) print(a[7]['sql_data']) print(type(a[7]['sql_data'])) sql_result = DoMysql().do_mysql(a[7]['sql'], (str(a[7]['sql_data']), )) try: self.assertEqual(str(sql_result), a[7]['expected']) check_sql_result = 'PASS' except AssertionError as e: check_sql_result = 'FAIL' raise e finally: self.t.write_data(a[0] + 1, 2, str(sql_result), check_sql_result) try: self.assertEqual(str(a[6]), res.json()['code']) result = 'PASS' # self.t.write_data(a[0]+1,str(res.json()),test_result) except AssertionError as e: result = 'Fail' # self.t.write_data(a[0]+1,str(res.json()),test_result) raise e # 跟return一样 中断代码 finally: # self.t.write_data(a[0] + 1, 1, str(res.json()), result)
class TestRegister(unittest.TestCase): def setUp(self): self.db = DoMysql() sql = 'SELECT COUNT(*) count FROM user_db.t_user_info;' self.before_line_count = self.db.fetch_one(sql)['count'] @data(*cases) def test_register(self, case): my_logger.info('正在执行第{}条用例:{}'.format(case.case_id, case.title)) my_logger.info('-----------开始检查url地址-------------') url = ReadConfig().get('test_api', 'url_pre') + case.url my_logger.info('请求url:{}'.format(url)) # 因注册的用户名不能重复,做随机处理 last_user_id = random_string.create_str() setattr(Context, 'user_id', last_user_id) # 因测试验证码超时需要新的手机号验证 if case.title == '发送短信验证码用于超时': normal_mobile = mobile_phone.creat_mobile() setattr(Context, 'normal_mobile', normal_mobile) data = DoRegex.replace(case.data) data = json.loads(data) my_logger.info('-----------开始检查参数-------------') my_logger.info('注册请求参数:{0}'.format(data)) if case.title == '注册验证码超时': time.sleep(500)
def test_user_auth(self, case): my_logger.info('正在执行第{}条用例:{}'.format(case.case_id, case.title)) my_logger.info('-----------开始检查url地址-------------') url = ReadConfig().get('test_api', 'url_pre') + case.url my_logger.info('请求url:{}'.format(url)) data = DoRegex().replace(case.data) data = json.loads(data) my_logger.info('-----------开始检查参数-------------') my_logger.info('请求参数:{}'.format(data)) res = WebserviceRequest(url).get_result(case.port_name, data) time.sleep(60) my_logger.info('请求结果:{}'.format(res)) try: self.assertEqual(case.expected, res['retInfo']) do_excel.bace_write_by_case_id('verifiedUserAuth', case.case_id, str(res), 'success') Test_result = 'pass' except AssertionError as e: my_logger.error('出错了,{}'.format(e)) do_excel.bace_write_by_case_id('verifiedUserAuth', case.case_id, str(res), 'fail') Test_result = 'fail' raise e except Exception as e: raise e my_logger.info('本条用例测试结果:{}'.format(Test_result)) # 如果发送短信验证码成功 if res['retCode'] == '0' and case.port_name == 'sendMCode': sql_code = 'SELECT Fverify_code FROM sms_db_20.t_mvcode_info_3 where Fmobile_no={0};'.format( getattr(Context, 'normal_mobile')) verify_code = DoMysql().fetch_one(sql_code)['Fverify_code'] if verify_code: # 如果查到验证码就放入上下文 setattr(Context, 'verify_code', verify_code)
def test_001(self, item): global result #指明全球变量 global COOKIES #设置cookies为全局变量 url = item["url"] method = item["method"] param = item["param"] #返回的是字符串类型的数据 case_id = item["case_id"] modular = item["modular"] title = item["title"] expected = item["expected"] sql = item["sql"] if sql != None: sql = get_data.GetData().replace(sql) print(sql) param = get_data.GetData().replace(param) print(param) my_log.my_info("正在发起{}模块中的第{}条用例:{}".format(modular, case_id, title)) my_log.my_info("测试数据是:{}".format(param)) test_result = DoRequests( url, method, eval(param)).request(cookies=getattr(get_data.GetData, "COOKIES")) #增加一个判断是否查询数据库 if sql != None: #如果测试用例中的query不为none就进行数据库查询操作 sql_data = DoMysql().do_mysql(eval(sql)["sql"], 1) member_id = sql_data[0] setattr(get_data.GetData, "normal_member_id", str(member_id)) print(getattr(get_data.GetData, "normal_member_id")) #增加一个判断 是在完成完请求之后才去判断 if test_result.cookies: #判断请求cookies是否为空 setattr(get_data.GetData, "COOKIES", test_result.cookies) my_log.my_info("测试结果是:{}".format(test_result.json())) my_log.my_info("预期结果是:{}".format(eval(expected))) # expected=eval(expected) # test_result=test_result.json() # # if case_id==2: # expected["data"]=test_result["data"] try: self.assertEqual( eval(expected)["status"], test_result.json()["status"]) self.assertEqual( eval(expected)["code"], test_result.json()["code"]) self.assertEqual(eval(expected)["msg"], test_result.json()["msg"]) result = "pass" my_log.my_info("测试通过了") except AssertionError as e: my_log.my_error("测试失败,http请求发生错误") result = "failed" raise e finally: row = case_id + 1 DoExcel(project_path.case_path, "get_InvestsByMemberId").write_data( row, test_result.text, result)
def test_cases(self, case): global TestResult # 全局变量 # global COOKIES#声明是一个全局变量 method = case['Method'] url = case['Url'] param = eval(case['Params']) # 发起测试 my_log.info('-------正在测试{}模块里面第{}条测试用例:{}'.format(case['Module'], case['CaseId'], case['Title'])) my_log.info('测试数据是:{}'.format(case)) # 投资前查询数据库获取余额,保存 if case['sql'] is not None: sql = eval(case['sql'])['sql'] before_amount = DoMysql().do_mysql(sql)[0] resp = HttpRequest().http_request(method, url, param, cookies=getattr(GetData, 'COOKIE')) # 传参 # 实实在在的http请求发生之后才去加一个判断,判断是否产生了cookies if resp.cookies: # 判断请求的cookies是否为空 不为空其实就是True setattr(GetData, 'COOKIE', resp.cookies) # 我们可以更新COOKIES这个全局变量的值 try: self.assertEqual(eval(case['ExpectedResult']), resp.json()) # 再加一个断言 与的关系 # 投资后的查询数据库的余额 if case['sql'] is not None: sql = eval(case['sql'])['sql'] after_amount = DoMysql().do_mysql(sql)[0] invest_amount = param['amount'] # 投资金额 expect_amount = before_amount - invest_amount self.assertEqual(expect_amount, after_amount) TestResult = 'Pass' # 请注意这里 except Exception as e: TestResult = 'Failed' my_log.error('http请求测试用例出错了,错误是:{}'.format(e)) raise e # 处理完异常之后 不要留在家里 要抛出去! raise e finally: self.t.write_back(case['CaseId'] + 1, 9, resp.text) # 请注意这里 self.t.write_back(case['CaseId'] + 1, 10, TestResult) my_log.info('实际结果:{}'.format(resp.json())) # http发送请求拿到的实际返回值
def test_001(self, item): global result #指明全球变量 global COOKIES #设置cookies为全局变量 url = item["url"] method = item["method"] param = item["param"] case_id = item["case_id"] modular = item["modular"] title = item["title"] expected = item["expected"] sql = item["sql"] print(sql) param = get_data.GetData().replace(param) print("现在的param是{}".format(param)) if sql is not None: sql = get_data.GetData().replace(sql) print(type(sql)) print("现在的sql是{}".format(sql)) my_log.my_info("正在发起{}模块中的第{}条用例:{}".format(modular, case_id, title)) my_log.my_info("测试数据是:{}".format(param)) test_result = DoRequests( url, method, eval(param)).request(cookies=getattr(get_data.GetData, "COOKIES")) #获取loan_id if sql is not None and eval(sql)["sql"] is not None: print("测试的sql{}".format(eval(sql)["sql"])) sql = get_data.GetData().replace(sql) loan_id = DoMysql().do_mysql(eval(sql)["sql"], 1)[0] setattr(get_data.GetData, "loan_id", str(loan_id)) #增加一个判断 if test_result.cookies: #判断请求cookies是否为空 setattr(get_data.GetData, "COOKIES", test_result.cookies) my_log.my_info("测试结果是:{}".format(test_result.json())) my_log.my_info("预期结果是:{}".format(eval(expected))) try: self.assertEqual( eval(expected)["status"], test_result.json()["status"]) self.assertEqual( eval(expected)["code"], test_result.json()["code"]) self.assertEqual(eval(expected)["msg"], test_result.json()["msg"]) result = "pass" my_log.my_info("测试通过了") except AssertionError as e: my_log.my_error("测试失败,http请求发生错误") result = "failed" raise e finally: row = case_id + 1 DoExcel(project_path.case_path, "get_InvestsByLoanId").write_data(row, test_result.text, result)
def test_001(self, item): global result # 指明全局变量 global COOKIES # 设置cookies为全局变量 global before_amount url = item["url"] method = item["method"] param = item["param"] case_id = item["case_id"] modular = item["modular"] title = item["title"] expected = item["expected"] sql = item["sql"] param = get_data.GetData().replace(param) print("目前的param是{}".format(param)) if sql is not None: sql = get_data.GetData().replace(sql) print("目前的sql是{}".format(sql)) before_amount = DoMysql().do_mysql(eval(sql)["sql"])[0] my_log.my_info("充值之前账户余额:{}".format(before_amount)) my_log.my_info("正在发起{}模块中的第{}条用例:{}".format(modular, case_id, title)) my_log.my_info("测试数据是:{}".format(param)) test_result = DoRequests( url, method, eval(param)).request(cookies=getattr(get_data.GetData, "COOKIES")) # 增加一个判断 if test_result.cookies: # 判断请求cookies是否为空 setattr(get_data.GetData, "COOKIES", test_result.cookies) my_log.my_info("测试结果是:{}".format(test_result.text)) my_log.my_info("预期结果是:{}".format(eval(expected))) try: self.assertEqual( eval(expected)["code"], test_result.json()["total"]) # if sql is not None: # after_amount = DoMysql().do_mysql(eval(sql)["sql"], 1)[0] # recharge_amount = int(eval(param)["amount"]) # my_log.my_info("充值的金额是:{}".format(str(recharge_amount))) # expected_amount = recharge_amount + before_amount # my_log.my_info("充值之后的用户余额:{}".format(expected_amount)) # self.assertEqual(expected_amount, after_amount) # expected = expected.replace("expectedamount", str(expected_amount)) # self.assertEqual(eval(expected)["status"], test_result.json()["status"]) # self.assertEqual(eval(expected)["code"], test_result.json()["code"]) # self.assertEqual(eval(expected)["msg"], test_result.json()["msg"]) result = "pass" my_log.my_info("测试通过了") except AssertionError as e: my_log.my_error("测试失败,http请求发生错误") result = "failed" raise e finally: row = case_id + 1 DoExcel(project_path.case_path, "invest").write_data(row, test_result.text, result)
def test_login(self, data_item): global TOKEN print('正在进行第{0}条用例:{1}'.format(data_item['id'], data_item['description'])) self.logger.info('正在进行第{0}条用例:{1}'.format(data_item['id'], data_item['description'])) params = eval(data_item['param']) if data_item['module'] == '登录': if params['mobilecaptcha'] == 'code': #去数据库查询验证码替换 for i in [2]: sql = 'SELECT idstring FROM `pre_captcha_mobile` WHERE mobile={0} ORDER BY captchaid DESC LIMIT 1'.format( params['phone']) code = DoMysql().do_mysql(sql) params['mobilecaptcha'] = code[0][0] else: params['access_token'] = TOKEN print('测试数据为{0}'.format(params)) self.logger.info('测试数据为{0}'.format(params)) res = HttpRequtser().http_request(data_item['url'], params, data_item['HttpMethod'], verify=False, headers=header) print('测试结果是{0}'.format(res.json())) self.logger.info('测试结果是{0}'.format(res.json())) if data_item['module'] == '登录': if res.json( )['data']['access_token']: # 任何非空数据的布尔值都为True cookies是一个类字典的格式 TOKEN = res.json()['data'][ 'access_token'] # 如果cookies不为空 就替换全局变量的COOKIES 修改全局变量 try: self.assertEqual(str(data_item['ExpectedResult']), str(res.json()['error_code'])) self.assertEqual(res.status_code, 200) print('用例通过') self.logger.info('用例通过') TestResult = 'PASS' Comment = None except AssertionError as e: print('用例失败错误是{}'.format(e)) self.logger.error('用例失败错误是{}'.format(e)) TestResult = 'Failed' Comment = res.json()['error_message'] raise e finally: DoExce(project_path.test_case_path).write_back( 'login', data_item['id'] + 1, res.json()['error_code'], TestResult, Comment)
def post_sql(self, sql_param): ''' SQL后置处理,有更改、删除和新增操作,暂时不支持查询和参数提取操作 :param sql_param: 单元格里的参数 :return: 暂无返回 ''' self.logger.info('——进入SQL后置处理——') if isinstance(sql_param, dict): sql_param = [sql_param] for sub_sql in sql_param: sql = sub_sql['sql'] db = sub_sql.get('db') if sub_sql.get('db') else 1 DoMysql(self.logger).commit_mysql(sql, db=db) self.logger.info('——SQL后置处理完成——')
def test_http_request(self, case): global resp global TestResult Caseid = case['用例序号'] Module = case['模块'] Method = case['请求方式'] Url = case['接口地址'] Case_name = case['用例名'] param = (case['参数']) #传参使用字典格式 Sql = case['sql'] Expect_Result = eval(case['预期结果']) #字典格式断言预期结果与实际结果 if case['参数'].find('loanid') != -1: param = case['参数'].replace('loanid', str(getattr(GetData, 'RES'))) #判断参数内是否含有字段'loanid',有的话就把‘loanid字段替换为类属性'RES'的值’ TestLog().info("正在执行{}模块,第{}条用例,用例名:{}".format(Module, Caseid, Case_name)) resp = TestRequest().testrequest(Method, Url, eval(param), getattr(GetData, 'COOKIES')) #实际结果 if case['sql']: res = (DoMysql().domysql(eval(Sql)['sql']))[0] setattr(GetData, 'RES', res) #判断sql是否为空,不为空则执行sql,获取到sql执行结果,并赋值给雷属性‘RES’ if resp.cookies: setattr(GetData, 'COOKIES', resp.cookies) try: self.assertEqual(eval(case['预期结果']), resp.json()) #将请求结果转换为字典格式与预期结果对比 TestResult = 'PASS' except AssertionError as e: TestLog().info("断言失败{}".format(e)) TestResult = 'FAILED' raise e finally: TestLog().info("回写实际结果:{}".format(resp.text)) DoExcel().data_write('add_loan', Caseid + 1, 9, resp.text) TestLog().info("预期结果::{}".format(Expect_Result)) TestLog().info("回写测试结论:{}".format(TestResult)) DoExcel().data_write('add_loan', Caseid + 1, 10, TestResult)
def setUpClass(cls): logger.info('前置操作,连接数据库') cls.mysql = DoMysql() warnings.simplefilter('ignore', ResourceWarning)
my_logger.info('本条用例测试结果:{}'.format(Test_result)) # 如果发送短信验证码成功 if res['retCode'] == '0' and case.port_name == 'sendMCode': sql_code = 'SELECT Fverify_code FROM sms_db_20.t_mvcode_info_3 where Fmobile_no={0};'.format( getattr(Context, 'normal_mobile')) verify_code = DoMysql().fetch_one(sql_code)['Fverify_code'] if verify_code: # 如果查到验证码就放入上下文 setattr(Context, 'verify_code', verify_code) # 如果注册成功,查询uid放入上下文 if res['retCode'] == '0' and case.port_name == 'userRegister': sql_uid = "SELECT Fuid uid FROM user_db.t_user_info where Fuser_id='{0}' and Fip='{1}' ORDER BY Fcreate_time DESC;".format( getattr(Context, 'user_id'), Context.client_ip) uid = str(DoMysql().fetch_one(sql_uid)['uid']) if uid: # 如果查询到Fuid就放入上下文 setattr(Context, 'uid', uid) # 实名认证成功后,数据验证,验证数据库影响行数是否为1 if res['retCode'] == '0' and case.port_name == 'verifyUserAuth': expected = self.before_auth_count + 1 # 预期结果=实名认证前记录数 + 1 auth_sql = 'SELECT COUNT(*) count FROM user_db.t_user_auth_info;' # 实名认证成功后再次查询记录数 actual = DoMysql().fetch_one(auth_sql)['count'] self.assertEqual(expected, actual) my_logger.info('实名认证成功后,查询影响实名认证表行数等于1') def tearDown(self): self.db.close() my_logger.info('关闭数据库连接,测试环境还原')
def setUpClass(cls): cls.service = WebService() cls.mysql = DoMysql() cls.mylog.info('开始执行用例')
def test_001(self, item): global result #指明全球变量 global COOKIES #设置cookies为全局变量 global before_amount global withdraw_amount url = item["url"] method = item["method"] param = item["param"] case_id = item["case_id"] modular = item["modular"] title = item["title"] expected = item["expected"] sql = item["sql"] #参数化测试数据 param = get_data.GetData().replace(param) my_log.my_info("目前的param是{}".format(param)) #判断是否需要执行sql 如果需要执行则运行代码 if sql is not None: sql = get_data.GetData().replace(sql) print("目前的sql是{}".format(sql)) before_amount = DoMysql().do_mysql(eval(sql)["sql"])[0] my_log.my_info("体现之前的用户余额是:{}".format(before_amount)) my_log.my_info("正在发起{}模块中的第{}条用例:{}".format(modular, case_id, title)) #传入参数 进行接口测试 test_result = DoRequests( url, method, eval(param)).request(cookies=getattr(get_data.GetData, "COOKIES")) # print(test_result) #打印测试结果与实际结果 # my_log.my_info("目前的测试结果是{}".format(test_result.json())) # my_log.my_info("预期结果是:{}".format(eval(expected))) #增加一个判断 传递cookies if test_result.cookies: #判断请求cookies是否为空 setattr(get_data.GetData, "COOKIES", test_result.cookies) #打印出测试结果与预期结果 my_log.my_info("测试结果是:{}".format(test_result.json())) my_log.my_info("预期结果是:{}".format(eval(expected))) #测试结果与预期结果进行断言 try: if sql is not None: after_amount = DoMysql().do_mysql(eval(sql)["sql"], 1)[0] my_log.my_info("提现之后的用户余额是:{}".format(after_amount)) withdraw_amount = int(eval(param)["amount"]) my_log.my_info("提现金额是:{}".format(str(withdraw_amount))) expected_amount = before_amount - withdraw_amount self.assertEqual(expected_amount, after_amount) expected = expected.replace("expectedamount", str(expected_amount)) my_log.my_info("预期的用户余额是:{}".format(expected_amount)) self.assertEqual( eval(expected)["status"], test_result.json()["status"]) self.assertEqual( eval(expected)["code"], test_result.json()["code"]) self.assertEqual(eval(expected)["msg"], test_result.json()["msg"]) result = "pass" my_log.my_info("测试通过了") except AssertionError as e: my_log.my_error("测试失败,http请求发生错误") result = "failed" raise e finally: #写回测试结果 row = case_id + 1 DoExcel(project_path.case_path, "withdraw").write_data(row, test_result.text, result)
except AssertionError as e: my_logger.error('出错了,{}'.format(e)) do_excel.bace_write_by_case_id('register', case.case_id, str(res), 'fail') Test_result = 'fail' raise e except Exception as e: raise e my_logger.info('本条用例测试结果:{}'.format(Test_result)) if case.title == '成功发送短信验证码': # 如果发送短信验证码成功请求成功,查询验证码 sql_code = 'SELECT Fverify_code FROM sms_db_20.t_mvcode_info_3 where Fmobile_no={0};'.format( getattr(Context, 'normal_mobile')) verify_code = DoMysql().fetch_one(sql_code)['Fverify_code'] if verify_code: # 如果查到验证码就放入上下文 setattr(Context, 'verify_code', verify_code) else: # 如果为空,上下文中验证码为空 setattr(Context, 'verify_code', None) # 注册成功数据验证 if res['retCode'] == '0' and case.port_name == 'userRegister': # 验证如果注册成功,影响数据库的行数是否等于1 expected = self.before_line_count + 1 # 期望结果=请求前行数 + 1 # print('期望结果:', expected) sql2 = 'SELECT COUNT(*) count FROM user_db.t_user_info;' actual = DoMysql().fetch_one(sql2)['count'] # 实际结果=请求注册后行数 # print('实际结果:', actual) self.assertEqual(expected, actual)
def setUp(self): self.db = DoMysql() sql = 'SELECT COUNT(*) count FROM user_db.t_user_info;' self.before_line_count = self.db.fetch_one(sql)['count']
def setUpClass(cls): cls.url = config.get("api", "url") cls.request = HttpRequest() cls.mysql = DoMysql()
def setUpClass(cls): print("begin") cls.request = HttpRequest() cls.mysql = DoMysql()
def setUpClass(cls): cls.http = HttpSession() cls.mysql = DoMysql()
def test_http_request(self, case): # global COOKIES #声明COOKIES为全局变量 global resp global TestResult # global before_amount # global after_amount Caseid = case['用例序号'] Module = case['模块'] Method = case['请求方式'] Url = case['接口地址'] Case_name = case['用例名'] param = eval(case['参数']) #传参使用字典格式 Sql = case['sql'] Expect_Result = case['预期结果'] #字典格式断言预期结果与实际结果 if case['sql'] is not None: before_amount = (DoMysql().domysql(eval(case['sql'])['sql']))[0] #充值前账户金额 TestLog().info("正在执行{}模块,第{}条用例,用例名:{}".format(Module, Caseid, Case_name)) getattr(GetData, 'COOKIES') resp = TestRequest().testrequest(Method, Url, param, cookies=getattr(GetData, 'COOKIES')) #获取请求结果 getattr(GetData,'COOKIES') --反射,获取类属性的值 if case['sql'] is not None: after_amount = (DoMysql().domysql(eval(case['sql'])['sql']))[0] setattr(GetData, 'leaveamout', after_amount) if Expect_Result.find('money') != -1: Expect_Result = case['预期结果'].replace( 'money', str(getattr(GetData, 'leaveamout'))) #充值后账户金额 if resp.cookies: #判断请求结果cookies是否为真 setattr(GetData, 'COOKIES', resp.cookies) #反射,将登陆产生的cookie赋值给变量COOKIES try: if case['sql'] is not None: #sql不为空的情况下再判断 Expect_amount = float(before_amount) + float(param['amount']) #预期金额=原金额+充值金额 self.assertEqual(after_amount, Expect_amount) #断言实际金额与预期金额 self.assertEqual(eval(Expect_Result), resp.json()) #将请求结果转换为字典格式与预期结果对比 TestResult = 'PASS' except AssertionError as e: TestLog().info("断言失败{}".format(e)) TestResult = 'FAILED' raise e finally: TestLog().info("回写实际结果:{}".format(resp.text)) DoExcel().data_write('recharge', Caseid + 1, 9, resp.text) TestLog().info("预期结果::{}".format(Expect_Result)) TestLog().info("回写测试结论:{}".format(TestResult)) DoExcel().data_write('recharge', Caseid + 1, 10, TestResult)
def setUpClass(cls): cls.request = HttpRequest() cls.mysql = DoMysql()
def test_http_request(self, a): logger.info("测试数据是:{0}".format(a)) #!!!括号中不能用逗号的方式传递变量值 logger.info("目前正在执行第%s条用例" % a['case_id']) global COOKIES logger.info("请求的地址为:%s" % (ip + a['url'])) logger.info("请求的参数为:%s" % a['params']) # print('a5的类型',type(a[5])) #此方法是针对list形式 # res=HttpRequest(ip+a[4],(a[5])).httpRequest(a[3],cookies=COOKIES) #此方法是针对字典取值,可以根据key取value值 res = HttpRequest(ip + a['url'], eval(a['params'])).httpRequest(a['method'], cookies=COOKIES) if res.cookies != {}: #判断cookies是否为空用{},或用len(res.cookies)==0 COOKIES = res.cookies # print(res.json()) #检查数据库的值 # sql_result=DoMysql().do_mysql(a[7]['sql'],(str(a[7]['sql_data']),)) #判断是否对数据库进行检查 if a['check_sql'] != None: #是否需要对数据库进行检查 sql_result = DoMysql().do_mysql(eval(a['check_sql'])['sql']) try: self.assertEqual( eval(a['check_sql'])['expected'], str(sql_result) ) #!!!a['check_sql]['expected'] 这种用法错误,应将前面转换成字典类型 check_sql_result = 'PASS' except AssertionError as e: check_sql_result = 'FAIL' raise e finally: self.t.write_data( int(a['case_id']) + 1, 2, str(sql_result), check_sql_result) #判断是否存在id和regtime需要替换 if a['expect_result'].find("${id}") != -1 and a['expect_result'].find( '${regtime}') != -1: #获取手机号 从params里面去获取手机号 mobilephone = eval(a['params'])['mobilephone'] #!!! 记住,字典的键值要用“” #替换id member_id = DoMysql().do_mysql( 'select id from member where mobilephone=%s' % mobilephone)[0] #sql返回是元组类型 #替换regtime regtime = DoMysql().do_mysql( 'select regtime from member where mobilephone=' + mobilephone)[0] expected_result = eval(a['expect_result']) expected_result['data']['id'] = member_id expected_result['data']['regtime'] = str(regtime) + '.0' else: expected_result = eval(a['expect_result']) #检查excel中的预期值 try: self.assertEqual(expected_result, res.json()) #!!!预期结果要转换成str result = 'PASS' except AssertionError as e: logger.error("断言报错信息是%s" % e) result = 'FAIL' raise e #!!!终止后面的代码 finally: self.t.write_data( int(a['case_id']) + 1, 1, str(res.json()), result)
def setUpClass(cls): cls.mysql = DoMysql() warnings.simplefilter("ignore", ResourceWarning)