def test_withdraw(self, case): my_logger = MyLog() my_logger.debug("执行第{}条案例".format(case.case_id)) data = DoRegex.replace(case.data) data = json.loads(data) if hasattr(Context, 'cookies'): cookies = getattr(Context, 'cookies') else: cookies = None res = Request(method=case.method, url=case.url, data=data, cookies=cookies) if res.get_cookies(): setattr(Context, 'cookies', res.get_cookies()) my_logger.debug(res.get_json()) try: self.assertEqual(case.expected, int(res.get_json()['code'])) except AssertionError as e: my_logger.error("断言失败!") raise e if res.get_json()['msg'] == '取现成功': expected = float(self.start_amount) - float(data['amount']) actual = self.mysql.fetch_one(self.sql)['LeaveAmount'] try: self.assertEqual(expected, actual) except AssertionError as e: raise e else: expected = float(self.start_amount) actual = self.mysql.fetch_one(self.sql)['LeaveAmount'] self.assertEqual(expected, actual)
def test_bidLoan(self, case): data = DoRegex.replace(case.data) data = json.loads(data) print("执行第{}条案例".format(case.case_id)) if hasattr(Context, 'cookies'): cookies = getattr(Context, 'cookies') else: cookies = None res = Request(method=case.method, url=case.url, data=data, cookies=cookies) print(res.get_json()) if res.get_cookies(): setattr(Context, 'cookies', res.get_cookies()) if res.get_json()['msg'] == "竞标成功": expect = float(self.start_amount) - float(data['amount']) actual = self.mysql.fetch_one(self.sql)['LeaveAmount'] try: self.assertEqual(expect, actual) # 一直报错,实际值不正确,数据库数据没有变化 ??? print(expect) print(actual) except Exception as e: print("投标成功断言失败!") raise e else: expect = float(self.start_amount) actual = self.mysql.fetch_one(self.sql)['LeaveAmount'] try: self.assertEqual(expect, actual) print(expect) print(actual) except Exception as e: print("投标失败断言失败!") raise e
def test_recharge(self, case): # 必须传输一条case my_logger = MyLog() data = DoRegex.replace(case.data) # 首先从excel中取出来,然后做正则 data = json.loads(data) # 然后在loads if hasattr(Context, 'cookies'): # 第一次登陆没有cookies,所以要判断 # 参数化处理 cookies = getattr(Context, 'cookies') else: cookies = None res = Request(method=case.method, url=case.url, data=data, cookies=cookies) # 判断有没有cookies if res.get_cookies(): setattr(Context, 'cookies', res.get_cookies()) my_logger.debug(res.get_json()) try: self.assertEqual(str(case.expected), res.get_json()['code']) except AssertionError as e: my_logger.error("{} not found".format(e)) raise e if res.get_json()['msg'] == '充值成功': try: self.assertEqual(str(self.leaveamount + 10), res.get_json()['data']['leaveamount']) except AssertionError as a: my_logger.error("余额不正确,报错{}".format(a))
def test_login(self, case): # 必须传输一条case data = json.loads(case.data) res = Request(method=case.method, url=case.url, data=data) print(res.get_json()) try: self.assertEqual(eval(case.expected), res.get_json()) except AssertionError as e: print("{} not found".format(e)) raise e
def test_getInvestsByMemberId(self, case): data = DoRegex.replace(case.data) # 参数化处理 data = json.loads(data) # 将测试数据由字符串序列化成字典 if hasattr(Context, 'cookies'): # 判断是否有cookies cookies = getattr(Context, 'cookies') # 获取放到上下文里面的cookies else: cookies = None # Request封装类请求 resp = Request(method=case.method, url=case.url, data=data, cookies=cookies) resp_dict = resp.get_json() # 获取请求响应,字典 # 判断返回里面是否有cookies(有说明是登录接口) if resp.get_cookies(): # 判断返回里面是否有cookies setattr(Context, 'cookies', resp.get_cookies()) # 放入到上下文中 print("status_code:", resp.get_status_code()) # 打印响应码 resp_dict = resp.get_json() # 获取请求响应,字典 self.assertEqual(case.expected, int(resp_dict['code'])) # 判断返回的code是否与期望结果一致 # 数据库校验 if resp_dict['msg'] == "获取用户投资列表成功": # 从数据库查invest表中某个用户的全部投资记录 sql_select_invest = "SELECT * FROM future.invest WHERE MemberID = {} ORDER BY Id DESC;".format( Context.invest_member_id) invest_list = self.mysql.fetch_all(sql_select_invest) # 根据用户ID获取invest表中某个用户的投资记录的最大行数 sql_select_row = "SELECT COUNT(Id) FROM future.invest WHERE MemberID = {};".format( Context.invest_member_id) max_row = self.mysql.fetch_one(sql_select_row)['COUNT(Id)'] if invest_list is not None: for i in range(0, max_row): # 每一行数据校验 MyLog.info("正在校验第{}行数据".format(i)) # 判断请求返回的数据详情与数据库里面的详情是否一致 # 多个字段一致才assert通过 self.assertEqual(int(resp_dict['data'][i]['id']), invest_list[i]['Id']) self.assertEqual(int(resp_dict['data'][i]['memberId']), invest_list[i]['MemberID']) self.assertEqual(int(resp_dict['data'][i]['loanId']), invest_list[i]['LoanId']) self.assertEqual(float(resp_dict['data'][i]['amount']), invest_list[i]['Amount']) self.assertEqual(int(resp_dict['data'][i]['isValid']), invest_list[i]['IsValid']) self.assertEqual( resp_dict['data'][i]['createTime'][0:19], invest_list[i]['CreateTime'].strftime( "%Y-%m-%d %H:%M:%S")) MyLog.info("校验结果:PASS")
def test_withdraw(self, item): result = None params = json.loads(DoRegex().replace(item.params)) # 处理初始化数据 url = getattr(contex, 'url') + item.url if hasattr(contex, 'COOKIES'): # 处理COOKIES COOKIES = getattr(contex, 'COOKIES') else: COOKIES = None resp = Request(method=item.method, url=url, data=params, cookies=COOKIES) # 开始HTTP请求 if resp.cookies(): setattr(contex, 'COOKIES', resp.cookies()) # withdraw_title = item['title'][0:4] # if withdraw_title == '成功取现': if resp.get_json()['msg'] == '取现成功': sql = 'SELECT * FROM future.member WHERE MobilePhone = {} '.format( params['mobilephone']) value = MySql().fet_one(sql) data_LeaveAmount = value['LeaveAmount'] # 数据库中的金额 contex_LeaveAmount = getattr(contex, 'LeaveAmount') # 反射类contex中的金额 actual_value = Decimal(contex_LeaveAmount) - Decimal( params['amount']) # 预期金额等于 contex金额减请求参数中的金额 request_value = resp.get_json() excepted_value = json.loads(item.expected) print('data_LeaveAmount:', data_LeaveAmount) print('actual_value:', actual_value) try: # 判断数据库金额是否等于预期金额 | 预期结果和响应报文中的值是否一致 assert data_LeaveAmount == actual_value result = 'Pass' except Exception as e: result = 'Failed' raise e finally: read.write_result(item.caseid + 1, 7, resp.get_txt()) read.write_result(item.caseid + 1, 8, result) elif resp.get_json()['msg'] == '充值成功': result = 'Pass' read.write_result(item.caseid + 1, 7, resp.get_txt()) read.write_result(item.caseid + 1, 8, result) else: try: self.assertEqual(resp.get_txt(), item.expected) result = 'Pass' except Exception as e: result = 'Failed' raise e finally: read.write_result(item.caseid + 1, 7, resp.get_txt()) read.write_result(item.caseid + 1, 8, result)
def test_recharge(self, item): '''通过反射查看是否有COOKIES的值''' if hasattr(contex, 'COOKIES'): COOKIES = getattr(contex, 'COOKIES') else: COOKIES = None params = item.params '''通过读取配置文件替换params中的用户名或密码,并序列化''' params = json.loads(DoRegex().replace(params)) url = getattr(contex, 'url') + item.url resp = Request(method=item.method, url=url, data=params, cookies=COOKIES) '''登陆成功后将获取到的值通过反射写入到配置类中''' if resp.cookies(): setattr(contex, 'COOKIES', resp.cookies()) result = None actual = resp.get_txt() if resp.get_json()['msg'] == '充值成功': sql = 'SELECT * FROM future.member WHERE MobilePhone = "{}" '.format( params['mobilephone']) value = MySql().fet_one(sql=sql) actual_value = value['LeaveAmount'] # 获取充值后的金额 excetp = actual_value - Decimal(params['amount']) # 预期用户金额 excepted = json.loads(item.expected) request_actual = resp.get_json() try: assert Decimal(excetp) == Decimal(getattr(contex,'LeaveAmount')) and int(value['MobilePhone']) == int(params['mobilephone']) \ and request_actual['code'] == excepted['code']and request_actual['msg'] == excepted['msg'] \ and request_actual['status'] == excepted['status'] result = 'Pass' except Exception as e: result = 'Failed' finally: read.write_result(item.caseid + 1, 7, resp.get_txt()) read.write_result(item.caseid + 1, 8, result) else: # 充值失败的值校验响应报文 try: self.assertEqual(actual, item.expected) result = 'Pass' except Exception as e: result = 'Failed' myloger1.mylog.error(e) raise e finally: read.write_result(item.caseid + 1, 7, resp.get_txt()) read.write_result(item.caseid + 1, 8, result)
def test_register(self,case): # 使用正则,首先从数据库查找到最大手机号加1,通过正则替换excel中的参数---还需再改!!! # if case.case_id == 1: # # 从数据库找到最大手机号+1 # max_phone_old = mysql.fetch_one(sql)['mobilephone'] # max_phone = int(max_phone_old) + 1 # print("最大手机号是:",max_phone) # # 新的手机号替换excel中的手机号 # phone = re.findall(pattern='\d{11}', string=case.data)[0] # 先从excel中取出手机号 # case.data = case.data.replace(phone,str(max_phone)) # replace替换 # 也可以不用正则,取出case.data字典里的手机号,直接赋值替换 data = json.loads(case.data) # 从excel中取到的data是一个字符串,loads() 把字符串序列化为字典 if data['mobilephone'] == '${register}': # 判断是否需要进行参数化 max_phone_new = int(max_phone_old) + 1 # 取到数据库里面最大的手机号码,进行加1 data['mobilephone'] = max_phone_new # 赋值替换excel中的手机号 resp = Request(method=case.method, url=case.url, data=data) # request请求时,data一定要是字典类型 print("status_code:", resp.get_status_code()) # 打印响应码 resp_dict = resp.get_json() # 获取请求响应,字典 self.assertEqual(case.expected, resp.get_text()) # 数据库校验 if resp_dict['code'] == 10001: # 注册成功的数据校验,判断数据库member表有这条数据 sql = 'select * from future.member where mobilephone = "{0}"'.format(max_phone_new) member = self.mysql.fetch_one(sql) # member是字典类型 expected = max_phone_new if member is not None: # 正常注册成功,不应该返回None self.assertEqual(expected, member['mobilephone']) else: # 返回None,代表注册成功之后但是数据库里面没有插入数据 print("注册失败,数据库没有插入数据")
def test_recharge(self, case): # 参数化处理 data = DoRegex.replace(case.data) # 将字符串序列化成字典 data = json.loads(data) if hasattr(Context, 'cookies'): # 判断是否有cookies cookies = getattr(Context, 'cookies') # 获取放到上下文里面的cookies else: cookies = None resp = Request(method=case.method, url=case.url, data=data, cookies=cookies) # 通过封装的Request类来完成接口的调用 # 判断有没有cookie if resp.get_cookies(): # 判断返回里面是否有cookies setattr(Context, 'cookies', resp.get_cookies()) # 放入到上下文中 resp_dict = resp.get_json() # 获取请求响应,字典 self.assertEqual(case.expected, int(resp_dict['code'])) # 判断响应返回的code 是否与期望结果一致 actual = self.mysql.fetch_one(self.sql)['LeaveAmount'] # 再次获取账户余额 print("测试{0}后的金额".format(case.title), actual) # 充值成功,判断余额增加 if resp_dict['code'] == '10001' and resp_dict['msg'] == "充值成功": amount = float(data['amount']) # 充值金额 print('充值金额', amount) expect = float(self.before_amount) + amount # 充值成功,期望的账户余额= 原来余额 + 充值金额 self.assertEqual(expect, actual) # 判断期望结果与实际结果是否一致 elif resp_dict['code'] != '10001': expect = self.before_amount # 充值失败,期望结果:余额未增加 self.assertEqual(expect, actual) # 判断期望结果与实际结果是否一致
def test_add(self, case): data = DoRegex.replace(case.data) data = json.loads(data) if hasattr(Context, 'cookies'): cookies = Context.cookies else: cookies = None #请求成功后,返回response resp = Request(method=case.method, url=case.url, data=data, cookies=cookies) if resp.get_cookies(): # 将cookies动态写入上下文管理器中 setattr(Context, 'cookies', resp.get_cookies()) print("用例名称:", case.title) resp_dict = resp.get_json() print(resp.get_text()) self.assertEqual(str(case.expected), resp_dict['code']) # check the response code firstly # Check that the login case is successful if case.title == '管理员正常登录': try: self.assertEqual(str(case.expected), resp_dict['code']) TestResult = 'PASS' do_excel.write_result_by_case_id('add', case.case_id, resp.get_text(), TestResult) except AssertionError as e: TestResult = 'Fail' do_excel.write_result_by_case_id('add', case.case_id, resp.get_text(), TestResult) raise e
def test_register(self, case): # 必须传输一条case data = json.loads(case.data) if data['mobilephone'] == '${register}': data['mobilephone'] = str(int(self.max_phone) + 1) print(data) res = Request(method=case.method, url=case.url, data=data) print(res.get_json()) self.assertEqual(str(case.expected), res.get_json()['code']) # 数据库数据校验 sql = "select l.MobilePhone from future.member l where l.MobilePhone ={}".format( int(self.max_phone) + 1) # print(sql) expected = int(self.max_phone) + 1 member = self.mysql.fetch_one(sql) if member is not None: self.assertEqual(expected, member['MobilePhone'])
def test_login(self, case): data = json.loads(case.data) resp = Request(method=case.method, url=case.url, data=data) # 通过封装的Request类来完成接口的调用 print('test data:', data) print('status_code:', resp.get_status_code()) # 打印响应码 resp_dict = resp.get_json() # 获取请求响应,字典 self.assertEqual(case.expected, resp.get_json_code())
def test_audit(self, case): # 用case变量接收传进来的数据 data = DoRegex.replace(case.data) # 参数化处理 data = json.loads(data) # 将测试数据由字符串序列化成字典 # 先判断有没有cookies if hasattr(Context, 'cookies'): # 判断是否有cookies cookies = getattr(Context, 'cookies') # 获取放到上下文里面的cookies else: cookies = None # Request封装类请求 resp = Request(method=case.method, url=case.url, data=data, cookies=cookies) # request请求时,data一定要是字典类型 print("status_code:", resp.get_status_code()) # 打印响应码 resp_dict = resp.get_json() # 获取请求响应,字典 # 优先判断响应返回的code是否与期望结果一致 self.assertEqual(case.expected, int(resp_dict['code'])) # 判断有没有cookies(有说明是登录接口) if resp.get_cookies(): setattr(Context, 'cookies', resp.get_cookies() ) # --请求request拿到cookies --把cookies放到Context里 # 当创建标的成功时,根据借款人ID查看数据库loan表是否添加数据 if resp_dict['msg'] == "加标成功": # 新增标的成功的数据校验,判断数据库loan表有这条新增的数据 # 再次查询数据库,获取最新的最大标的loan各项信息 sql = "SELECT * FROM future.loan WHERE MemberID = {} ORDER BY Id DESC LIMIT 1;".format( Context.loan_member_id) loan = self.mysql.fetch_one(sql) # loan是字典类型 if loan is not None: # 正常加标成功,不应该返回None,管理员加标成功的数据库校验 max_loan_id_new = self.max_loan_id_old + 1 expected = max_loan_id_new # 期望结果:测试加标成功前的最大标的ID加上1 # 判断数据库里面的标的详情是否与测试数据一致 # 多个字段一致才assert通过 self.assertEqual(expected, loan['Id']) # 实际结果:数据库查询的最大标的ID self.assertEqual(int(data['memberId']), loan['MemberID']) # MemberID是借款人的ID,管理员登录进行操作 self.assertEqual(float(data['amount']), loan['Amount']) self.assertEqual(data['title'], loan['Title']) self.assertEqual(float(data['loanRate']), loan['LoanRate']) self.assertEqual(data['loanTerm'], loan['LoanTerm']) self.assertEqual(data['loanDateType'], loan['LoanDateType']) self.assertEqual(data['repaymemtWay'], loan['RepaymemtWay']) self.assertEqual(data['biddingDays'], loan['BiddingDays']) self.assertEqual(1, loan['Status']) print("测试加标后的最大标的ID是:", max_loan_id_new) # 将创建成功的标的ID写入到上下文中,用于之后投资用 setattr(Context, 'loan_id', str(loan['Id'])) # 放一个str类型的进去,以备后面正则替换 else: # 返回None,表示数据库里面没有插入数据,管理员加标测试失败 raise AssertionError # 当审核成功,需校验数据库loan表中status字段更改 if case.url == '/loan/audit' and resp_dict['code'] == 10001: sql = 'SELECT * FROM future.loan WHERE MemberID = {} ORDER BY CreateTime DESC LIMIT 1;'.format( Context.loan_member_id) loan = self.mysql.fetch_one(sql) self.assertEqual(data['status'], loan['Status'])
def test_login(self,case): register = int(self.max_phone)+1 data = re.sub(pattern='\$\{(.*?)\}', repl=str(register),string=case.data) # 使用正则匹配替换excel中的数据 print('data:',data) data = json.loads(data) #将str反序列化为字典 resp = Request(method=case.method,url=case.url,data=data) print("响应结果:",resp.get_status_code()) resp_dict = resp.get_json() resp_text = json.dumps(resp_dict, ensure_ascii=False, indent=4) print('response: ', resp_text) # 打印响应 #优先判断期望结果与实现结果 expected = json.loads(case.expected) self.assertEqual(expected['code'],resp_dict['code']) sql = 'select * from future.member where mobilephone = "{0}"'.format(str(register)) if resp_dict['msg'] == "注册成功": # 注册成功的数据校验,判断数据库有这条数据 expected = int(self.max_phone) + 1 member = self.mysql.fetch_one(sql) if member is not None: # 正常注册成功就不应该返回None self.assertEqual(expected,int(member['MobilePhone'])) TestResult = 'PASS' do_excel.write_result_by_case_id('register',case.case_id,resp.get_text(),TestResult) else: # 返回None则代表注册成功之后但是数据库里面没有插入数据 TestResult = 'Fail' do_excel.write_result_by_case_id('register',case.case_id,resp.get_text(),TestResult) raise AssertionError else: #注册失败的数据校验,判断数据库没有这条数据,自己写 if resp_dict['msg'] == "手机号码已被注册": expected = data['mobilephone'] mobilephone = self.mysql.fetch_one('select * from future.member where mobilephone = {0}'.format(expected)) if mobilephone is not None: # 若数据库里有这条数据,则说明该手机号已被注册,用例pass self.assertEqual(expected,mobilephone['MobilePhone']) TestResult = 'PASS' do_excel.write_result_by_case_id('register',case.case_id,resp_text,TestResult) else: # 若数据库里没有这条数据,则说明该手机号未被重复注册,用例fail TestResult = 'Fail' do_excel.write_result_by_case_id('register',case.case_id,resp_text,TestResult) else: # 其他所有注册失败用例 expected = register member = self.mysql.fetch_one(sql) if member is None: # 查询数据库里没有这条数据,说明该手机号未被注册,用例pass TestResult = 'PASS' do_excel.write_result_by_case_id('register',case.case_id,resp.get_text(),TestResult) else: TestResult = 'Fail' do_excel.write_result_by_case_id('register',case.case_id,resp.get_text(),TestResult) # def tearDown(self): # print('数据清除') # @classmethod # def tearDownClass(cls): # mysql.close() def tearDown(self): self.mysql.close()
def test_list(self, case): data = DoRegex.replace(case.data) data = json.loads(data) # 先判断有没有cookies if hasattr(Context, 'cookies'): cookies = getattr(Context, 'cookies') else: cookies = None # 通过封装的Request类来完成接口的调用 resp = Request(method=case.method, url=case.url, data=data, cookies=cookies) # 判断返回里面是否有cookies(有说明是登录接口) if resp.get_cookies(): setattr(Context, 'cookies', resp.get_cookies()) # cookies放入到上下文中 print("status_code:", resp.get_status_code()) # 打印响应码 resp_dict = resp.get_json() # 获取请求响应,字典 self.assertEqual(case.expected, int(resp_dict['code'])) # 判断返回的code是否与期望结果一致 # 完成数据库校验 if resp_dict['msg'] == "获取用户列表成功": # 从数据库查到member表全部用户的信息 # member_list是一个列表,列表是按照用户ID顺序排序。其中的元素是一个个字典。 # resp_dict['data'] 也是一个列表,列表是按照用户ID顺序排序。其中的元素是一个个字典。 sql_select_member = "SELECT * FROM future.member WHERE Id != '' ORDER BY Id ASC;" member_list = self.mysql.fetch_all(sql_select_member) # 获取member表最大行数 sql_select_row = "SELECT COUNT(Id) FROM future.member;" max_row = self.mysql.fetch_one(sql_select_row)['COUNT(Id)'] if member_list is not None: # 如果从数据库里面查询出来不是空 for i in range(0, max_row): # 每一行数据校验 # 判断请求返回的数据详情与数据库里面的详情是否与一致 # 多个字段一致才assert通过 self.assertEqual(resp_dict['data'][i]['id'], member_list[i]['Id']) self.assertEqual(resp_dict['data'][i]['mobilephone'], member_list[i]['MobilePhone']) self.assertEqual(resp_dict['data'][i]['pwd'], member_list[i]['Pwd']) self.assertEqual(resp_dict['data'][i]['regname'], member_list[i]['RegName']) self.assertEqual( float(resp_dict['data'][i]['leaveamount']), float(member_list[i]['LeaveAmount'])) self.assertEqual( resp_dict['data'][i]['regtime'][0:19], member_list[i] ['RegTime'].strftime("%Y-%m-%d %H:%M:%S")) self.assertEqual(int(resp_dict['data'][i]['type']), member_list[i]['Type'])
def test_add(self, case): # 必须传输一条case my_logger = MyLog() data = DoRegex.replace(case.data) # 首先从excel中取出来,然后做正则 data = json.loads(data) # 然后在loads if hasattr(Context, 'cookies'): # 第一次登陆没有cookies,所以要判断 cookies = getattr(Context, 'cookies') else: cookies = None res = Request(method=case.method, url=case.url, data=data, cookies=cookies) # 判断有没有cookies if res.get_cookies(): setattr(Context, 'cookies', res.get_cookies()) my_logger.debug(res.get_json()) try: self.assertEqual(str(case.expected), res.get_json()['code']) except AssertionError as e: my_logger.error("断言失败") raise e
def test_list(self, case): my_logger = MyLog() if case.data != None: data = DoRegex.replace(case.data) # 正则调用,替换正则表达式的数据 data = json.loads(data) if hasattr(Context, 'cookies'): cookies = getattr(Context, 'cookies') else: cookies = None res = Request(method=case.method, url=case.url, data=data, cookies=cookies) print(res.get_json()) if res.get_cookies(): setattr(Context, 'cookies', res.get_cookies())
def test_login(self, case): data = json.loads(case.data) logger1.my_logger.info('测试用例名称:{0}'.format(case.title)) logger1.my_logger.info('测试用例数据:{0}'.format(case.data)) resp = Request(method=case.method, url=case.url, data=data) # 通过封装的Request类来完成接口的调用 logger1.my_logger.debug('status_code:{0}'.format( resp.get_status_code())) # 打印响应码 resp_dict = resp.get_json() # 获取请求响应,字典 try: self.assertEqual(case.expected, resp.get_text()) except AssertionError as e: logger1.my_logger.error('测试失败')
def test_invest(self, case): # 参数化处理 data = DoRegex.replace(case.data) # 将测试数据由字符串序列化成字典 data = json.loads(data) if hasattr(Context, 'cookies'): # 判断是否有cookies cookies = getattr(Context, 'cookies') # 获取放到上下文里面的cookies else: cookies = None # 通过封装的Request类来完成接口的调用 resp = Request(method=case.method, url=case.url, data=data, cookies=cookies) print(resp.get_text()) resp_dict = resp.get_json() # 获取请求响应,字典 # 优先判断响应返回的code 是否与期望结果一致 self.assertEqual(case.expected, int(resp_dict['code'])) # 判断有没有cookie if resp.get_cookies(): # 判断返回里面是否有cookies setattr(Context, 'cookies', resp.get_cookies()) # 放入到上下文中 # 当创建标的成功时,根据借款人ID查看数据库loan表是否与添加数据 if resp_dict['msg'] == '加标成功': select_loan = 'select * from future.loan where memberId = {0} order by createtime desc limit 1'.format( Context.loan_member_id) loan = self.mysql.fetch_one(select_loan) if loan is not None: # 如果从数据库里面查询出来不是空,则创建标的成功 # 判断数据库里面的标的详情是否与测试数据一致 self.assertEqual(data['amount'], loan['Amount']) # 多个字段一致才assert通过 # 其他的自己加 # 将创建成功的标的ID写入到上下文中,用于之后投资用 setattr(Context, 'loan_id', str(loan['Id'])) # 放一个str类型的进去,以备后面正则替换 else: raise AssertionError # 如果数据库里面没有数据,就测试失败 # 当审核成功,需校验数据库loan表中status字段更改,自己添加 # 当投资成功时,根据投资人ID查看数据member表中验证余额是否减少 if resp_dict['msg'] == '竞标成功': amount = data['amount'] # 投资金额 actual = self.mysql.fetch_one( self.select_member)['LeaveAmount'] # 投资后的金额 expect = float(self.before_amount) - float( amount) # 期望 = 投资前的余额 - 投资金额 self.assertEqual(expect, actual) elif resp_dict['code'] != '10001': # 投资失败,余额不变 actual = self.mysql.fetch_one( self.select_member)['LeaveAmount'] # 投资后的金额 expect = float(self.before_amount) # 期望 = 投资前的余额 self.assertEqual(expect, actual)
def test_add(self, case): data = DoRegex.replace(case.data) # 通过正则取excel的数据,Context覆盖excel的数据 data = json.loads(data) # 从excel中取到的data是一个字符串,loads()把字符串序列化为字典 # --请求request拿到cookies # 先判断有没有cookies if hasattr(Context, 'cookies'): cookies = getattr(Context, 'cookies') # 获取放到上下文里面的cookies else: cookies = None # 通过封装的Request类来完成接口的调用 resp = Request(method=case.method, url=case.url, data=data, cookies=cookies) # request请求时,data一定要是字典类型 # 判断有没有cookies(有说明是登录接口) if resp.get_cookies(): # 判断返回里面是否有cookies setattr(Context, 'cookies', resp.get_cookies()) # 放入到上下文中 print("status_code:", resp.get_status_code()) # 打印响应码 resp_dict = resp.get_json() # 获取请求响应,字典 self.assertEqual(case.expected, int(resp_dict['code'])) # 判断返回的code是否与期望结果一致 # 完成数据库校验 # 再次查询数据库,获取最新的最大标的loan各项信息 sql = "SELECT * FROM future.loan WHERE MemberID = {} ORDER BY Id DESC LIMIT 1;".format( Context.loan_member_id) loan = self.mysql.fetch_one(sql) # loan是字典类型 if resp_dict['msg'] == "加标成功": # 新增标的成功的数据校验,判断数据库loan表有这条新增的数据 if loan is not None: # 正常加标成功,不应该返回None max_loan_id_new = self.max_loan_id_old + 1 expected = max_loan_id_new # 期望结果:测试加标成功前的最大标的ID加上1 # 判断数据库里面的标的详情是否与测试数据一致 # 多个字段一致才assert通过 self.assertEqual(expected, loan['Id']) # 实际结果:数据库查询的最大标的ID self.assertEqual(int(data['memberId']), loan['MemberID']) # MemberID是借款人的ID,管理员登录进行操作 self.assertEqual(float(data['amount']), loan['Amount']) self.assertEqual(data['title'], loan['Title']) self.assertEqual(float(data['loanRate']), loan['LoanRate']) self.assertEqual(data['loanTerm'], loan['LoanTerm']) self.assertEqual(data['loanDateType'], loan['LoanDateType']) self.assertEqual(data['repaymemtWay'], loan['RepaymemtWay']) self.assertEqual(data['biddingDays'], loan['BiddingDays']) self.assertEqual(1, loan['Status']) print("测试加标后的最大标的ID是:", max_loan_id_new) else: # 返回None,表示数据库里面没有插入数据,管理员加标测试失败 raise AssertionError elif resp_dict['code'] != '10001': expected = self.max_loan_id_old # 期望结果:测试加标成功前的最大标的ID self.assertEqual(expected, loan['Id'])
def test_add(self, case): # 必须传输一条case my_logger = MyLog() data = DoRegex.replace(case.data) # 首先从excel中取出来,然后做正则 data = json.loads(data) # 然后在loads if hasattr(Context, 'cookies'): # 第一次登陆没有cookies,所以要判断 cookies = getattr(Context, 'cookies') else: cookies = None res = Request(method=case.method, url=case.url, data=data, cookies=cookies) # 判断有没有cookies if res.get_cookies(): setattr(Context, 'cookies', res.get_cookies()) my_logger.debug(res.get_json()) try: self.assertEqual(str(case.expected), res.get_json()['code']) except AssertionError as e: my_logger.error("断言失败") raise e resp_dict = res.get_json() if resp_dict['msg'] == '加标成功': select_loan = 'select * from future.loan where memberId = {0} order by createtime desc limit 1'.format( Context.loan_member_id_1) loan = self.mysql.fetch_one(select_loan) if loan is not None: # 如果从数据库里面查询出来不是空,则创建标的成功 # 判断数据库里面的标的详情是否与测试数据一致 self.assertEqual(data['amount'], loan['Amount']) # 多个字段一致才assert通过 # 其他的自己加 # 将创建成功的标的ID写入到上下文中,用于之后投资用 setattr(Context, 'loan_id', str(loan['Id'])) # 放一个str类型的进去,以备后面正则替换 else: raise AssertionError # 如果数据库里面没有数据,就测试失败
def test_loadadd(self, item): global result if hasattr(contex, 'COOKIES'): COOKIES = getattr(contex, 'COOKIES') else: COOKIES = None url = self.url + item.url params = json.loads(DoRegex().replace(item.params)) if item.caseid > 1: params['title'] = self.conf.get('project', 'new_title') resp = Request(method=item.method, url=url, data=params, cookies=COOKIES) if resp.cookies(): COOKIES = setattr(contex,'COOKIES',resp.cookies()) try: self.assertEqual(resp.get_txt(), item.expected) if resp.get_json()['msg'] == '加标成功': sql = 'SELECT * FROM future.loan WHERE MemberID = "{}" AND Title = "{}"'.format( getattr(contex, 'normal_user_id'), params['title']) check_db = self.mysql.fet_one(sql=sql) self.assertEqual(check_db['Title'],params['title']) elif resp.get_json()['msg'] == '登录成功': print('这是登录') else: sql = 'SELECT * FROM future.loan WHERE MemberID = "{}" AND Title = "{}"'.format( getattr(contex, 'normal_user_id'), params['title']) check_db = self.mysql.fet_one(sql=sql) self.assertEqual(check_db, None) result = 'Pass' except Exception as e: result = 'Failed' raise e finally: read.write_result(item.caseid+1, 7,resp.get_txt()) read.write_result(item.caseid+1, 8,result)
def test_recharge(self, case): # 用case变量接收传进来的数据 # 参数化处理 data = DoRegex.replace(case.data) # 通过正则取excel的数据,Context覆盖excel的数据 data = json.loads(data) # 从excel中取到的data是一个字符串,loads()把字符串序列化为字典 MyLog.info("正在执行第{}条用例:{}。".format(case.case_id, case.title)) MyLog.info("测试数据是{}".format(data)) # --请求request拿到cookies # # 先判断有没有cookies if hasattr(Context, 'cookies'): cookies = getattr(Context, 'cookies') # 获取放到上下文里面的cookies else: cookies = None # 通过封装的Request类来完成接口的调用 resp = Request(method=case.method, url=case.url, data=data, cookies=cookies) # request请求时,data一定要是字典类型 # 判断有没有cookies(有说明是登录接口) # --请求request拿到cookies --把cookies放到Context里 # if resp.get_cookies('JSESSIONID'): # setattr(Context,'cookies',{'JSESSIONID':resp.get_cookies('JSESSIONID')}) if resp.get_cookies(): # 判断返回里面是否有cookies setattr(Context, 'cookies', resp.get_cookies()) # 放入到上下文中 print("status_code:", resp.get_status_code()) # 打印响应码 resp_dict = resp.get_json() # 获取请求响应,字典 self.assertEqual(case.expected, int(resp_dict['code'])) # 判断返回的code是否与期望结果一致 # 完成数据库校验,判断充值成功之后账户余额增加正确,充值失败余额不变 # 通过数据库查可以看到充值前的余额,充值后的余额,excel中的case.data可以查到充值金额amount # 数据库校验:期望的充值后的余额=充值金额+充值前的余额,实际的充值后的余额=查询数据库得到充值后的余额 leaveamount_new = mysql.fetch_one(sql) # 再次获取账户余额---测试充值后的余额 actual = float( leaveamount_new['LeaveAmount']) # 实际的账户余额 = 查询数据库得到账户的余额 MyLog.info("测试{}后的余额是:{}元".format(case.title, actual)) if resp_dict['code'] == '10001' and resp_dict[ 'msg'] == "充值成功": # 充值请求后的响应码是10001并且充值成功 amount = float(data['amount']) # 通过excel中的case.data可以查到充值金额amount MyLog.info('充值金额是:{}元'.format(amount)) expected = float(self.leaveamount_old['LeaveAmount'] ) + amount # 充值成功,期望的账户余额=充值前的余额+充值金额 self.assertEqual(expected, actual) # 判断期望结果与实际结果是否一致 MyLog.info("此次测试结果是:PASS") elif resp_dict['code'] != '10001': expected = float(self.leaveamount_old['LeaveAmount'] ) # 充值失败,期望结果:账户余额不变,是充值前的余额 self.assertEqual(expected, actual) # 判断期望结果与实际结果是否一致 MyLog.info("此次测试结果是:PASS")
def test_recharge(self, case): # 参数化处理 data = DoRegex.replace(case.data) data = json.loads(data) if hasattr(Context, 'cookies'): # 判断是否有cookies cookies = getattr(Context, 'cookies') # 获取放到上下文里面的cookies else: cookies = None resp = Request(method=case.method, url=case.url, data=data, cookies=cookies) # 通过封装的Request类来完成接口的调用 # 判断有没有cookie if resp.get_cookies(): # 判断返回里面是否有cookies setattr(Context, 'cookies', resp.get_cookies()) # 放入到上下文中 print('status_code:', resp.get_status_code()) # 打印响应码 resp_dict = resp.get_json() # 获取请求响应,字典 self.assertEqual(case.expected, int(resp_dict['code'])) # 判断返回的code 是否与期望结果一致
def test_charge(self,case): # 对取到的数据,做参数化处理 data = DoRegex.replace(case.data) data = json.loads(data) print("===test data===",data) if hasattr(Context,'cookies'): # 通过上下文判断,来赋值cookies cookies=getattr(Context,'cookies') else: cookies = None resp = Request(method=case.method, url=case.url, data=data,cookies=cookies) # 通过封装的Request类来完成接口的调用 # 判断有没有cookie,如果有cookies(也就是在登陆的时候获取到了cookie),就给上下问context,增加一个cookies属性, # 将登陆获取到的cookies存储起来 if resp.get_cookies(): setattr(Context,'cookies',resp.get_cookies()) print('status_code:', resp.get_status_code()) # 打印响应码 resp_dict = resp.get_json() # 获取请求响应,字典 self.assertEqual(case.expected,resp.get_json_code())
def test_login(self,case): data=json.loads(case.data) # 对取到的data做序列化 if data['mobilephone']=='${register}': data['mobilephone']=max_phone-90000 resp = Request(method=case.method, url=case.url, data=data) # 通过封装的Request类来完成接口的调用 print('test data:',data) print('status_code:', resp.get_status_code()) # 打印响应码 resp_dict = resp.get_json() # 获取请求响应,字典 self.assertEqual(case.expected,resp.get_json_code()) # 注册成功,在数据库校验是否有这条数据 if resp.get_status_code() == "20010": sql='select * from future.member where MobilePhone = "{0}"'.format(max_phone-90000) expected = max_phone-90000 member=mysql.fetch_one(sql) if member is not None: self.assertEqual(expected,member["MobilePhone"]) else: raise AssertionError else: print("注册失败!")
def test_withdraw(self, case): data = DoRegex.replace(case.data) data = json.loads(data) # 先判断有没有cookies if hasattr(Context, 'cookies'): cookies = getattr(Context, 'cookies') # 获取放到上下文里面的cookies else: cookies = None # 通过封装的Request类来完成接口的调用 resp = Request(method=case.method, url=case.url, data=data, cookies=cookies) # request请求时,data一定要是字典类型 # 判断有没有cookies(有说明是登录接口) # --请求request拿到cookies --把cookies放到Context里 if resp.get_cookies(): # 判断返回里面是否有cookies setattr(Context, 'cookies', resp.get_cookies()) # 放入到上下文中 print("status_code:", resp.get_status_code()) # 打印响应码 resp_dict = resp.get_json() # 获取请求响应,字典 self.assertEqual(case.expected, int(resp_dict['code'])) # 判断返回的code是否与期望结果一致 # 完成数据库校验,判断取现成功之后账户余额增加正确,取现失败余额不变 # 通过数据库查可以看到取现前的余额,取现后的余额,excel中的case.data可以查到取现金额amount # 数据库校验:期望的取现后的余额=取现前的余额-取现金额,实际的取现后的余额=查询数据库得到取现后的余额 leaveamount_new = self.mysql.fetch_one( self.sql)['LeaveAmount'] # 再次获取账户余额---测试取现后的余额 actual = float(leaveamount_new) # 实际的账户余额 = 查询数据库得到账户的余额 print("测试{}后的余额是:{}元".format(case.title, actual)) if resp_dict['code'] == '10001' and resp_dict[ 'msg'] == "取现成功": # 取现请求后的响应码是10001并且取现成功 amount = float(data['amount']) print('取现金额是:{}元'.format(amount)) expected = float( self.leaveamount_old) - amount # 取现成功,期望的账户余额=取现前的余额-取现金额 self.assertEqual(expected, actual) # 判断期望结果与实际结果是否一致 elif resp_dict['code'] != '10001': expected = float(self.leaveamount_old) # 取现失败,期望结果:账户余额不变,是取现前的余额 self.assertEqual(expected, actual) # 判断期望结果与实际结果是否一致
def test_register(self, case): data = json.loads(case.data) # 将字符串序列化为字典 if data['mobilephone'] == '${register}': # 判断是否是需要进行参数化 data['mobilephone'] = int(max_phone) + 1 # 取到数据库里面最大的手机号码进行加1 MyLog.info('测试用例名称:{0}'.format(case.title)) MyLog.info('测试用例数据:{0}'.format(case.data)) MyLog.error('测试用例数据error') resp = Request(method=case.method, url=case.url, data=data) # 通过封装的Request类来完成接口的调用 MyLog.debug('status_code:{0}'.format(resp.get_status_code())) resp_dict = resp.get_json() # 获取请求响应,字典 self.assertEqual(case.expected, resp.get_text()) if resp_dict['code'] == 20110: # 注册成功的数据校验,判断数据库有这条数据 sql = 'select * from future.member where mobilephone = "{0}"'.format( max_phone) expected = int(self.max_phone) + 1 member = self.mysql.fetch_one(sql) if member is not None: # 正常注册成功就不应该返回None self.assertEqual(expected, member['mobilephone']) else: # 返回None则代表注册成功之后但是数据库里面没有插入数据 MyLog.error('注册失败') raise AssertionError
def test_generateRepayments(self, case): data = DoRegex.replace(case.data) # 参数化处理 data = json.loads(data) # 将测试数据由字符串序列化成字典 if hasattr(Context, 'cookies'): # 判断是否有cookies cookies = getattr(Context, 'cookies') # 获取放到上下文里面的cookies else: cookies = None # Request封装类请求 resp = Request(method=case.method, url=case.url, data=data, cookies=cookies) print(resp.get_text()) resp_dict = resp.get_json() # 获取请求响应,字典 # 优先判断响应返回的code是否与期望结果一致 self.assertEqual(case.expected, int(resp_dict['code'])) # 判断有没有cookies if resp.get_cookies(): # 判断返回里面是否有cookies setattr(Context, 'cookies', resp.get_cookies()) # 放入到上下文中 # 数据库校验 pass
# 测试一下DoExcel类 do_excel = DoExcel('../datas/cases.xlsx') # 实例化一个DoExcel对象 sheet_names = do_excel.get_sheet_names() # 获取到work boot里面所有的sheet名称的列表 print("sheet 名称列表:", sheet_names) case_list = ['login', 'register'] # 定义一个执行测试用例的列表 for sheet_name in sheet_names: if sheet_name in case_list: # 如果当前的这个sheet_name 不在可执行的case_list里面,就不执行 cases = do_excel.get_cases(sheet_name) print(sheet_name + ' 测试用例个数:', len(cases)) for case in cases: # 遍历测试用例列表,每进for一次,就取一个case实例 print("case信息:", case.__dict__) # 打印case信息 data = eval(case.data) # Excel里面取到data是一个字符串,使用eval函数将字符串转换成字典 resp = Request(method=case.method, url=case.url, data=data) # 通过封装的Request类来完成接口的调用 print('status_code:', resp.get_status_code()) # 打印响应码 resp_dict = resp.get_json() # 获取请求响应,字典 # 通过json.dumps函数将字典转换成格式化后的字符串 resp_text = json.dumps(resp_dict, ensure_ascii=False, indent=4) print('response: ', resp_text) # 打印响应 # 判断接口响应是否和Excel里面expected的值是否一致 if case.expected == resp.get_text(): print("result : PASS") do_excel.write_back_by_case_id( sheet_name=sheet_name, case_id=case.case_id, actual=resp.get_text(), result='PASS') # 期望结果与实际结果一致,就写入PASS到result这个单元格 else: print("result : FAIL") do_excel.write_back_by_case_id( sheet_name=sheet_name,