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): # 参数化处理 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_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_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_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_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_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_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_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_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_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_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_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_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
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_generateRepayments(self,case): setattr(Context,'not_generate_loan_id',str(not_generate_loan_id)) # setattr(Context,'full_loan_id',str(full_loan_id)) setattr(Context,'not_exist_loan_id',str(int(max_loan_id)+2)) # 跑用例之前最大id,运行完之后id+1,保证不存在需再加1 data = DoRegex.replace(case.data) # 正则匹配,用配置文件的基础数据替换正则表达式代替的内容 data = json.loads(data) # str反序列化为dict # 判断是否有cookies,解决数据依赖 if hasattr(Context,'cookies'): cookies = Context.cookies else: cookies = None # 发起request请求 resp = Request(method=case.method,url=case.url,data=data,cookies=cookies) print("用例名称:",case.title) #请求成功后,返回response resp_dict = resp.get_json() print(resp.get_text()) # 优化对excel中expected和实际返回结果作断言 expectVal = case.expected if (expectVal is None) or (str(expectVal).strip().strip('\n') is ''): # 对空单元格异常处理 expectVal = '' self.assertEqual(str(expectVal), resp_dict['code']) # 判断response中是否有cookies,反射方法写到Context类中 if resp.get_cookies(): setattr(Context,'cookies',resp.get_cookies()) if resp_dict['msg'] =='登录成功': try: self.assertEqual(case.expected,eval(resp_dict['code'])) TestResult = 'PASS' do_excel.write_result_by_case_id('generateRepayments',case.case_id,resp.get_text(),TestResult) except AssertionError as e: TestResult = 'Fail' do_excel.write_result_by_case_id('generateRepayments',case.case_id,resp.get_text(),TestResult) raise e # 当创建标的成功时,根据借款人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 = mysql.fetch_one(select_loan) #查询到投标金额 if loan is not None: self.assertEqual(data['amount'],loan['Amount']) # 实际加标金额与数据库加标金币是否一致 self.assertEqual(data['loanRate'],str(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']) # 将创建成功的标的ID写入到上下文中,用于之后投资用 setattr(Context,'loan_id',str(loan['Id'])) # 放一个str类型的进去,以备后面正则替换 TestResult = 'PASS' do_excel.write_result_by_case_id('generateRepayments',case.case_id,resp.get_text(),TestResult) else: TestResult = 'Fail' do_excel.write_result_by_case_id('generateRepayments',case.case_id,resp.get_text(),TestResult) raise AssertionError # 当审核成功,需校验数据库loan表中status字段更改,自己添加 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 = mysql.fetch_one(select_loan) #查询到投标金额 if loan is not None: self.assertEqual(data['status'],loan['Status']) TestResult = 'PASS' do_excel.write_result_by_case_id('generateRepayments',case.case_id,resp.get_text(),TestResult) else: TestResult = 'Fail' do_excel.write_result_by_case_id('generateRepayments',case.case_id,resp.get_text(),TestResult) raise AssertionError elif resp_dict['status'] == 0: try: self.assertEqual(str(case.expected),resp_dict['code']) TestResult = 'PASS' do_excel.write_result_by_case_id('generateRepayments',case.case_id,resp.get_text(),TestResult) except AssertionError as e: TestResult = 'Fail' do_excel.write_result_by_case_id('generateRepayments',case.case_id,resp.get_text(),TestResult) raise e # 生成回款计划 校验数据库 select_invest = 'SELECT * FROM future.invest a inner join future.repayment b on a.id = b.investid where MemberID = {0} order by investid desc'.format(Context.normal_member_id) invest = mysql.fetch_one(select_invest) #查询回款记录 if resp_dict['msg'] == '生成回款计划成功': if invest is not None: self.assertEqual(resp_dict['data'][0]['investId'],str(invest['InvestId'])) TestResult = 'PASS' do_excel.write_result_by_case_id('generateRepayments',case.case_id,resp.get_text(),TestResult) else: TestResult = 'Fail' do_excel.write_result_by_case_id('generateRepayments',case.case_id,resp.get_text(),TestResult) raise AssertionError elif resp_dict['code'] != 10001: if invest is not None: self.assertEqual(str(case.expected),resp_dict['code']) TestResult = 'PASS' do_excel.write_result_by_case_id('generateRepayments',case.case_id,resp.get_text(),TestResult) else: TestResult = 'Fail' do_excel.write_result_by_case_id('generateRepayments',case.case_id,resp.get_text(),TestResult)
def test_getLoanList(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'] == "获取标列表成功": # 从数据库查到loan表全部标的信息 # loan_list是一个列表,列表是按照标的ID顺序排序。其中的元素是一个个字典。 # resp_dict['data'] 也是一个列表,列表是按照标的ID顺序排序。其中的元素是一个个字典。 sql_select_loan = "SELECT * FROM future.loan WHERE Id != '' ORDER BY Id ASC;" loan_list = self.mysql.fetch_all(sql_select_loan) # 获取loan表最大行数 sql_select_row = "SELECT COUNT(Id) FROM future.loan;" max_row = self.mysql.fetch_one(sql_select_row)['COUNT(Id)'] if loan_list is not None: # 如果从数据库里面查询出来不是空 for i in range(0, max_row): # 每一行数据校验 # 判断数据库里面的标的详情是否与请求返回的数据详情一致 # 多个字段一致才assert通过 self.assertEqual(int(resp_dict['data'][i]['id']), loan_list[i]['Id']) self.assertEqual(int(resp_dict['data'][i]['memberId']), loan_list[i]['MemberID']) self.assertEqual(resp_dict['data'][i]['title'], loan_list[i]['Title']) self.assertEqual(float(resp_dict['data'][i]['amount']), float(loan_list[i]['Amount'])) self.assertEqual(float(resp_dict['data'][i]['loanRate']), float(loan_list[i]['LoanRate'])) self.assertEqual(int(resp_dict['data'][i]['loanTerm']), loan_list[i]['LoanTerm']) self.assertEqual(int(resp_dict['data'][i]['loanDateType']), loan_list[i]['LoanDateType']) self.assertEqual(int(resp_dict['data'][i]['repaymemtWay']), loan_list[i]['RepaymemtWay']) self.assertEqual(int(resp_dict['data'][i]['biddingDays']), loan_list[i]['BiddingDays']) self.assertEqual(int(resp_dict['data'][i]['status']), loan_list[i]['Status']) self.assertEqual( resp_dict['data'][i]['createTime'][0:19], loan_list[i] ['CreateTime'].strftime("%Y-%m-%d %H:%M:%S")) # 时间是空值时,怎么校验??? # self.assertEqual(resp_dict['data'][i]['biddingStartTime'][0:19], loan_list[i]['BiddingStartTime'].strftime("%Y-%m-%d %H:%M:%S")) # self.assertEqual(resp_dict['data'][i]['fullTime'][0:19],loan_list[i]['FullTime'].strftime("%Y-%m-%d %H:%M:%S")) MyLog.info("正在校验数据库第{}行数据,结果:PASS".format(i + 1))
def test_invest(self, case): setattr(Context, 'cannot_loan_id', str(cannot_load_id)) setattr(Context, 'full_loan_id', str(full_loan_id)) setattr(Context, 'not_exist_loan_id', str(int(max_loan_id) + 2)) # 跑用例之前最大id,运行完之后id+1,保证不存在需再加1 data = DoRegex.replace(case.data) # 正则匹配,用配置文件的基础数据替换正则表达式代替的内容 data = json.loads(data) # str反序列化为dict # 判断是否有cookies,解决数据依赖 if hasattr(Context, 'cookies'): cookies = Context.cookies else: cookies = None # 发起request请求 resp = Request(method=case.method, url=case.url, data=data, cookies=cookies) print("用例名称:", case.title) #请求成功后,返回response resp_dict = resp.get_json() print(resp.get_text()) # 优化对excel中expected和实际返回结果作断言 expectVal = case.expected if (expectVal is None) or (str(expectVal).strip().strip('\n') is ''): # 对空单元格异常处理 expectVal = '' self.assertEqual(str(expectVal), resp_dict['code']) # 判断response中是否有cookies,反射方法写到Context类中 if resp.get_cookies(): setattr(Context, 'cookies', resp.get_cookies()) if resp_dict['msg'] == '登录成功': try: self.assertEqual(case.expected, eval(resp_dict['code'])) TestResult = 'PASS' do_excel.write_result_by_case_id('invest', case.case_id, resp.get_text(), TestResult) except AssertionError as e: TestResult = 'Fail' do_excel.write_result_by_case_id('invest', case.case_id, resp.get_text(), TestResult) raise e # 当创建标的成功时,根据借款人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']) # 实际加标金额与数据库加标金币是否一致 self.assertEqual(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']) # 将创建成功的标的ID写入到上下文中,用于之后投资用 setattr(Context, 'loan_id', str(loan['Id'])) # 放一个str类型的进去,以备后面正则替换 TestResult = 'PASS' do_excel.write_result_by_case_id('invest', case.case_id, resp.get_text(), TestResult) else: TestResult = 'Fail' do_excel.write_result_by_case_id('invest', case.case_id, resp.get_text(), TestResult) raise AssertionError # 当审核成功,需校验数据库loan表中status字段更改,自己添加 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['status'], loan['Status']) TestResult = 'PASS' do_excel.write_result_by_case_id('invest', case.case_id, resp.get_text(), TestResult) else: TestResult = 'Fail' do_excel.write_result_by_case_id('invest', case.case_id, resp.get_text(), TestResult) raise AssertionError # 当投资成功时,根据投资人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) print("竞标成功后余额为{0}:".format(actual)) TestResult = 'PASS' do_excel.write_result_by_case_id('invest', case.case_id, resp.get_text(), TestResult) #投资失败,余额不变 elif resp_dict['status'] == 0: # 投资失败 try: actual = self.mysql.fetch_one( self.select_member)['LeaveAmount'] expect = float(self.before_amount) # 余额应等于投资前的金额 self.assertEqual(expect, actual) print("竞标失败余额为{0}:".format(actual)) TestResult = 'PASS' do_excel.write_result_by_case_id('invest', case.case_id, resp.get_text(), TestResult) except AssertionError as e: TestResult = 'Fail' do_excel.write_result_by_case_id('invest', case.case_id, resp.get_text(), TestResult) raise e
def test_recharge(self, case): #参数化 register = int(max_phone) + 1 data = DoRegex.replace(case.data) #正则 查找并替换$表达式 data = re.sub(pattern='\#\{(.*?)\}', repl=str(register), string=data) # 使用正则匹配替换#表达式register data = json.loads(data) #将str反序列化为字典 #处理cookies if hasattr(Context, 'cookies'): cookies = getattr(Context, 'cookies') else: cookies = None resp = Request(method=case.method, url=case.url, data=data, cookies=cookies) #判断有没有cookies,动态获取cookies if resp.get_cookies(): setattr(Context, 'cookies', resp.get_cookies()) 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) # 打印响应 # 请求完后后,优先判断返回code self.assertEqual(case.expected, int(resp_dict['code'])) actural = mysql.fetch_one( self.select_member)['LeaveAmount'] # 查询数据库中该用户的实际余额 if resp_dict['msg'] == '登录成功': try: self.assertEqual(case.expected, eval(resp_dict['code'])) TestResult = 'PASS' do_excel.write_result_by_case_id('recharge', case.case_id, resp.get_text(), TestResult) except AssertionError as e: TestResult = 'Fail' do_excel.write_result_by_case_id('recharge', case.case_id, resp.get_text(), TestResult) raise e # 充值需要校验数据库,查询数据库中的 leaveamount是否与实际金额一致 elif resp_dict['msg'] == '充值成功': expected = self.before_amount + int( data['amount']) # 充值成功余额 = 充值前+充值金额 self.assertEqual(expected, actural) TestResult = 'PASS' do_excel.write_result_by_case_id('recharge', case.case_id, resp.get_text(), TestResult) elif resp_dict['msg'] == '此手机号对应的会员不存在': sql_member = 'select * from future.member where mobilephone = {0}'.format( register) member = mysql.fetch_one(sql_member) if member is None: # 如果数据中不存在,表示未被注册,无法充值 TestResult = 'PASS' do_excel.write_result_by_case_id('recharge', case.case_id, resp.get_text(), TestResult) else: TestResult = 'Fail' do_excel.write_result_by_case_id('recharge', case.case_id, resp.get_text(), TestResult) else: # 其他异常场景也需要校验数据库 try: expected = self.before_amount # 充值失败 = 充值前 self.assertEqual(expected, actural) TestResult = 'PASS' do_excel.write_result_by_case_id('recharge', case.case_id, resp.get_text(), TestResult) except AssertionError as e: TestResult = 'Fail' do_excel.write_result_by_case_id('recharge', case.case_id, resp.get_text(), TestResult) raise e
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'])) # 判断有没有cookies if resp.get_cookies(): # 判断返回里面是否有cookies setattr(Context, 'cookies', resp.get_cookies()) # 放入到上下文中 # 当创建标的成功时,根据借款人ID查看数据库loan表是否添加数据 if resp_dict['msg'] == '加标成功': sql_select_loan = 'SELECT * FROM future.loan WHERE MemberID = {} ORDER BY CreateTime DESC LIMIT 1;'.format( Context.loan_member_id) loan = self.mysql.fetch_one(sql_select_loan) # 管理员加标成功的数据库校验 if loan is not None: # 如果从数据库里面查询出来不是空,则创建标的成功 # 判断数据库里面的标的详情是否与测试数据一致 # 多个字段一致才assert通过 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']) # 将创建成功的标的ID写入到上下文中,用于之后投资用 setattr(Context, 'loan_id', str(loan['Id'])) # 放一个str类型的进去,以备后面正则替换 else: # 如果数据库里面没有数据,则管理员加标测试失败 raise AssertionError # 当审核成功,需校验数据库loan表中status字段更改 if resp_dict['msg'] == "更新状态成功:竞标开始,当前标为竞标中状态": sql_select_loan = 'SELECT * FROM future.loan WHERE MemberID = {} ORDER BY CreateTime DESC LIMIT 1;'.format( Context.loan_member_id) loan = self.mysql.fetch_one(sql_select_loan) self.assertEqual(data['status'], loan['Status']) # 当投资成功时,根据投资人ID查看数据member表中验证余额是否减少 if resp_dict['msg'] == "竞标成功": amount = float(data['amount']) # 投资金额 print('投资竞标金额是:{}元'.format(amount)) leaveamount_new = self.mysql.fetch_one( self.sql_select_member)['LeaveAmount'] # 投资后的金额 actual = float(leaveamount_new) expected = float(self.leaveamount_old) - float( amount) # 期望结果 = 投资前的余额 - 投资金额 self.assertEqual(expected, actual) print("测试{}后的账户余额是:{}元".format(case.title, float(actual))) elif resp_dict['code'] != '10001': # 投资失败,余额不变 leaveamount_new = self.mysql.fetch_one( self.sql_select_member)['LeaveAmount'] # 投资后的金额 actual = leaveamount_new print("测试{}后的账户余额是:{}元".format(case.title, float(actual))) expected = self.leaveamount_old # 期望结果 = 投资前的余额 self.assertEqual(expected, actual) # 当投资成功时,根据标的ID查看invest表,每投资一次,验证invest表新增一条记录---再补充! pass # 用户余额有变动的话,会在资金流水表插入一条记录 ---再补充! pass