def test_register(self, case): # 我写在了里面---为了能每次都读取数据号码+1 mysql = MysqlUtil() # 实例化对象(进行了一次数据库的连接) sql = "SELECT MAX(MobilePhone) FROM future.member WHERE MobilePhone LIKE '152%';" # 传一条sql进来 max = mysql.fetch_one(sql)[0] # 找到最大手机号码, 元组里取第1个值 print("开始执行第{0}行用例".format(case.case_id)) import json data_dict = json.loads(case.data) # Excel字符串转成字典 if data_dict['mobilephone'] == '${register_mobile}': # 判断是否等于标记 data_dict['mobilephone'] = int(max) + 1 # 将最大手机号码+1 赋值给mobilephone # 使用封装好的request来完成请求 resp = self.request.request(case.method, case.url, data_dict) # 实例对象已移到外面,这里要加self. # 将返回结果与期望结果对比 try: self.assertEqual(case.expected, resp.text, 'register error') # 一致就写入Excel的结果PASS,并且 self.do_excel.write_back(case.case_id + 1, resp.text, 'PASS') # 实例对象已放外面,类变量加self. print("第{0}行用例执行结果:PASS".format(case.case_id)) except AssertionError as e: self.do_excel.write_back(case.case_id + 1, resp.text, 'FAIL') # 实例对象已放外面,类变量加self.调用 print("第{0}行用例执行结果:FAIL".format(case.case_id)) raise e
class RegisterTest(unittest.TestCase): do_excel = DoExcel(contants.case_file) cases = do_excel.get_cases('register') @classmethod def setUpClass(cls): cls.request = Request() # 实例化对象 def setUp(self): self.mysql = MysqlUtil(return_dict=True) sql = "select max(mobilephone) as max_phone from future.member" self.max = self.mysql.fetch_one(sql)['max_phone'] @data(*cases) def test_register(self, case): logger.info("开始执行第{}条用例".format(case.id)) data_dict = json.loads(case.data) if data_dict['mobilephone'] == "${register_mobile}": data_dict['mobilephone'] = int(self.max) + 1 # 使用封装好的request 来完成请求 resp = self.request.request(case.method, case.url, data_dict) # 将返回结果和期望结果进行匹配 try: self.assertEqual(case.expected, resp.json()['code'], "login error") if resp.json()['msg'] == '注册成功': sql = 'select * from future.member where mobilephone = {}'.format( data_dict['mobilephone']) results = self.mysql.fetch_all(sql) self.assertEqual(1, len(results)) member = results[0] self.assertEqual(0, member['LeaveAmount']) # 一致就写入Excel的结果为pass,并且 self.do_excel.write_result('register', case.id + 1, resp.text, 'PASS') logger.info("第{}条用例执行结果:PASS".format(case.id)) except AssertionError as e: self.do_excel.write_result('register', case.id + 1, resp.text, 'FAIL') logger.error("第{}条用例执行结果:FAIL".format(case.id)) raise e def tearDown(self): pass @classmethod def tearDownClass(cls): cls.request.session.close()
class RegisterTest(unittest.TestCase): do_excel = DoExcel(contants.excel_path) register_cases = do_excel.read_data('register') @classmethod def setUpClass(cls): cls.request = Request() def setUp(self): self.mysql = MysqlUtil(return_dict=True) sql = 'select max(mobilephone) as max_phone from future.member' self.max = self.mysql.fetch_one(sql)['max_phone'] # logger.info(type(max), max) # @unittest.skip('不要执行') @data(*register_cases) def test_register(self, case): logger.info('开始执行第{0}条用例'.format(case.id)) data_dict = json.loads(case.data) #字典 if data_dict['mobilephone'] == '${phone}': data_dict['mobilephone'] = int(self.max) + 1 if data_dict['mobilephone'] == '${phone2}': data_dict['mobilephone'] = int(self.max) + 2 resp = self.request.request(case.method, case.url, data_dict) try: self.assertEqual(case.expected, resp.text) if resp.json()['msg'] == '注册成功': sql = 'select * from future.member where mobilephone ={0}'.\ format(data_dict['mobilephone']) results = self.mysql.fetch_all(sql) #列表里嵌套字典 self.assertEqual(1, len(results)) #首先判断是否有成功插入数据 member = results[0] #获取到这一条数据,是一个字典 self.assertEqual(0, member['LeaveAmount']) #判断注册成功余额是否为0 self.assertEqual(1, member['Type']) # 判断注册用户类型是否为1 self.assertNotEqual(data_dict['pwd'], member['Pwd']) # 判断密码是否加密 if 'regname' in data_dict.keys(): self.assertEqual(data_dict['regname'], member['RegName']) else: self.assertEqual('小蜜蜂', member['RegName']) #判断用户名是小蜜蜂 self.do_excel.write_data('register', case.id + 1, resp.text, 'PASS') logger.info('第{0}条用例执行结果:pass'.format(case.id)) except AssertionError as e: self.do_excel.write_data('register', case.id + 1, resp.text, 'FAIL') logger.error('第{0}条用例执行结果:fail'.format(case.id)) raise e def tearDown(self): self.mysql.close() @classmethod def tearDownClass(cls): cls.request.session.close()
class RegisterTest(unittest.TestCase): do_excel = DoExcel(contants.case_file) # 传入cases.xlsx cases = do_excel.get_cases('register') request = Request() # 实例化对象 def setUp(self): self.mysql = MysqlUtil(return_dict=True) # 创建数据连接 sql = "select max(mobilephone) as max_phone from future.member" # 查询最大手机号 self.max = self.mysql.fetch_one(sql)[ 'max_phone'] # 执行SQL,并且返回最近的一条数据,是元祖,使用下标取第一个值 @data(*cases) def test_register(self, case): print("开始执行第{0}用例".format(case.id)) # 替换手机号码 data = case.data # excel里面读取出来是字符串 # 字符串的查找并替换 # if data.find('${register_mobile}') > -1: # data.s.replace('${register_mobile}', self.max) # 字典,根据KEY取值,然后判断,是否需要替换 import json data = json.loads(data) if data['mobilephone'] == '${register_mobile}': data['mobilephone'] = int(self.max) + 1 # 使用封装好的request 来完成请求 resp = self.request.request(case.method, case.url, data) # 这里data传str或者dict都OK ,因为方法里面会做判断 # 将返回结果和期望结果进行匹配 try: self.assertEqual(case.expected, resp.text, "register error ") if resp.json()['msg'] == '注册成功': sql = 'select * from future.member where mobilephone = {0}' \ .format(data['mobilephone']) results = self.mysql.fetch_all(sql) # 首先判断是否有成功插入数据 self.assertEqual(1, len(results)) member = results[0] # 获取到这一条数据,是一个字典 self.assertEqual(0, member['LeaveAmount']) # 判断注册成功余额应该是0 # 一致就写入Excel的结果为PASS,并且 self.do_excel.write_result("register", case.id + 1, resp.text, 'PASS') print("第{0}用例执行结果:PASS".format(case.id)) except AssertionError as e: self.do_excel.write_result("register", case.id + 1, resp.text, 'FAIL') print("第{0}用例执行结果:FAIL".format(case.id)) raise e def tearDown(self): self.mysql.close()
def getMcode(mobile): if type(mobile) == str and len(mobile) == 11: str1 = mobile[-2:] str2 = mobile[-3] sql = "select Fverify_code from sms_db_" + str1 + ".t_mvcode_info_" + str2 + \ " where Fmobile_no=" + mobile + " GROUP BY Fsend_time DESC" print(sql) A = MysqlUtil() res = str(A.fetchone(sql)) A.close_database() else: res = None return res
class RegisterTest(unittest.TestCase): request = HttpRequest() doexcel = DoExcel(cases_dir) cases = doexcel.read("register") #获取注册的测试用例 # print(type(max_mobilephone))#数据库取出来的vachar类型,也就是str类型 def setUp(self): #每个用例执行开始前,都要运行,获取数据库里面最大的手机号 self.mysql = MysqlUtil() # 创建数据库连接,打开查询页面 sql = "select MAX(MobilePhone)from future.member" # 查询数据库里面最大的手机号 self.max_mobilephone = self.mysql.fetch_one(sql)[ 0] # 从数据库里面查询出来的数据类型是:元组,要用下标取值;数据库里面最大的手机号是:max_mobilephone @data(*cases) def test_register(self, case): logger.info("正在执行{}条用例,用例标题是:{}".format(case["case_id"], case["title"])) import json data_dict = json.loads( case["data"]) #excel表中的data数据是str类型,需要转成json字典格式的字符串 if data_dict[ "mobilephone"] == "$register_mobilephone": #转成json格式,可以根据key取值,判断value是否等于excel表中做的标记$register_mobilephone data_dict["mobilephone"] = int( self.max_mobilephone ) + 1 #如果value等于excel表中做的标记$register_mobilephone,那查出来的最大手机号再加上1,再去请求 # 调用请求接口,接口请求后,会有返回结果,也就是实际结果 res = self.request.request(case["method"], case["url"], data_dict) #把case[data]换成最新的data_dict字典去做请求 #预期结果和实际结果的断言 try: self.assertEqual(case["expectedresult"], res.text, "register error!!!") #断言成功,测试结果就写PASS self.doexcel.write_back("register", case["case_id"] + 1, res.text, "PASS") logger.error("第{}条用例执行的结果是:PASS".format(case["case_id"])) except AssertionError as e: # 断言失败,测试结果就写Fail self.doexcel.write_back("register", case["case_id"] + 1, res.text, "FAIL") logger.error("第{}条用例执行的结果是:FAIL".format(case["case_id"])) raise e def tearDown(self): self.mysql.close()
def test_invest(self, case): logger.info("开始执行第{0}行用例".format(case.case_id)) logger.info('Expected:{0}'.format(case.expected)) # 查看期望结果 # 查找参数化数据,动态替换 data_new = context.replace_new(case.data) # Str测试数据 # 使用封装好的request 来完成请求 resp = self.request.request(case.method, case.url, data_new) # 将返回结果和期望结果进行匹配 try: self.assertEqual( json.loads(case.expected)['code'], resp.json()['code'], 'invest error') # resp.text改成resp.json()['code'] 只通过code判断 # 一致就写入Excel结果为PASS,并且 self.do_excel.write_back(case.case_id + 1, resp.text, 'PASS') logger.info("第{0}行用例执行结果:PASS".format(case.case_id)) # 加标后的标id不能直接配置文件替换,需要到数据库查询,而且根据借款人的memberID查询加成功的标loan_id # setUpClass()里面创建实例对象 # 引入mysql模块中的MysqlUtil类 # 在tearDownClass()里添加关闭,数据库用完必须关 # 还要引入Context类 进行替换 # 判断是否加标成功,如果成功过就按照借款人ID去数据库拆线呢最新标的记录 if resp.json()['msg'] == '加标成功': mysql = MysqlUtil() loan_member_id = getattr(Context, 'loan_member_id') logger.debug('loan_member_id的取值:{0}{1}'.format( type(loan_member_id), loan_member_id)) sql = "SELECT Id FROM future.loan WHERE MemberID={0} ORDER BY CreateTime DESC LIMIT 1;".format( loan_member_id ) # 注意:表名loan前面必须加数据库名future.loan否则会报错(1046, 'No database selected') # 创建sql语句。注意:没有分号。 loan_id = mysql.fetch_one(sql)[ 0] # 传入sql查询得到一个元组,再取第[0]个值是int类型,再赋值 logger.debug('self.loan_id的取值:{0}{1}'.format( type(loan_id), loan_id)) setattr(Context, 'loan_id', str(loan_id)) # 函数:给类或实例对象动态的去添加属性或者方法。 # 注意:后面的loan_id是int类型需要转换成str类型,context.replace_new.value和key需要时str类型 否则后续正则替换会报错。使用魔术方法 动态添加load_id。 mysql.close() except AssertionError as e: self.do_excel.write_back(case.case_id + 1, resp.text, 'FAIL') logger.error("断言出错了:{}".format(e)) logger.error("第{0}行用例执行结果:FAIL".format(case.case_id)) raise e
def setUpClass(cls): cls.admin_request = Request() # 实例化对象 cls.request = Request() cls.mysql = MysqlUtil() # 前提条件1: 管理员登录,加标,审核 admin_login_param = '{"mobilephone":"${admin_user}","pwd":"${admin_pwd}"}' admin_login_param = context.replace_new(admin_login_param) cls.admin_request.request("/member/login", "get", params=admin_login_param) logger.info("管理员登录完成") admin_add_param = '{"memberId":"${loan_member_id}","title":"add_loan_test by YYSF","amount":20000,"loanRate":"12.0","loanTerm":3,"loanDateType":0,"repaymemtWay":11,"biddingDays":5}' admin_add_param = context.replace_new(admin_add_param) cls.admin_request.request("/loan/add", "get", params=admin_add_param) loan_member_id = getattr(Context, "loan_member_id") loan_id_sql="select id from loan where memberID='{0}'" \ " order by createTime desc limit 1".format(loan_member_id) loan_id = cls.mysql.fetchone(loan_id_sql)[0] logger.info("管理员加标完成") setattr(Context, 'loan_id', str(loan_id)) admin_audit_param = {"id": loan_id, "status": 4} cls.admin_request.request("/loan/audit", "post", params=admin_audit_param) logger.info("管理员审核完成") #前提条件2:用户正常登录 login_param = '{"mobilephone":"${normal_user}","pwd":"${normal_pwd}"}' login_param = context.replace_new(login_param) cls.request.request("/member/login", "post", params=login_param) logger.info("投资人登录成功")
class RegisterTest(unittest.TestCase): '这是测试注册接口的类' # 使用doexcel_study中的方法调用 do_excel_regitser = DoExcel(contants.excel_file) # 传入do_excel_study.xlsx cases_register = do_excel_regitser.read_excel( "register") # 读取register_sheet @classmethod # 为什么用类方法? 整个类只执行一次! def setUpClass(cls): # 每个测试类里面去运行的操作都放到类方法里面 cls.request = Request() # 实例化对象 def setUp(self): # self.write_register = DoExcel(contants.excel_file, "register") # 创建一个对象写入 logger.info("开始执行用例") def tearDown(self): logger.info("用例执行结束") @classmethod def tearDownClass(cls): cls.request.session.close() # 关闭session请求 cls.mysql.close() # 关闭数据库连接 mysql = MysqlUtil() sql = "select max(mobilephone) from future.member" max = mysql.fetch_one(sql)[0] # 执行SQL,并且返回最近的一条数据,是元祖,使用下标取第一个值 # print(max) @data(*cases_register) def test_register(self, case): # 测试注册 logger.info("开始执行第{}条用例: {}".format(case.case_id, case.title)) logger.debug('url:{}'.format(case.url)) logger.debug('data:{}'.format(case.data)) logger.debug('method:{}'.format(case.method)) logger.debug('expected:{}'.format(case.expected)) data_dict = json.loads(case.data) if data_dict['mobilephone'] == '#@mobilephone': # 取最大电话号码+1 data_dict['mobilephone'] = int(self.max) + 1 # resp = self.request.request(case.method, case.url, data_dict) data_dict = json.dumps(data_dict) # 把字典转换成字符串传入context进行转换 # print(data_dict, type(data_dict)) register_data_new = Context.replace_new(data_dict) resp = self.request.request(case.method, case.url, register_data_new) try: # self.assertEqual(case.expected, resp.text) self.assertEqual(case.expected, json.loads(resp.text)['code']) self.do_excel_regitser.write_excel('register', case.case_id + 1, resp.text, 'PASS') # 读取sheet,写入结果 logger.info("第{0}用例执行结果:PASS".format(case.case_id)) except AssertionError as e: self.do_excel_regitser.write_excel('register', case.case_id + 1, resp.text, 'FAIL') logger.error("第{0}用例执行结果:FAIL".format(case.case_id)) logger.error("断言出错了".format(e)) raise e
class WithdrawTest(unittest.TestCase): do_excel = DoExcel(contants.excel_path) withdraw_cases = do_excel.read_data("withdraw") @classmethod def setUpClass(cls): cls.request = Request() def setUp(self): self.mysql = MysqlUtil(return_dict=True) # logger.info(type(max), max) @data(*withdraw_cases) def test_withdraw(self, case): logger.info('开始执行第{0}条用例'.format(case.id)) data_dict = json.loads(case.data) sql_1 = 'select LeaveAmount from future.member where mobilephone =18566668888' results_1 = self.mysql.fetch_one(sql_1) member_1 = results_1['LeaveAmount'] resp = self.request.request(case.method, case.url, data_dict) try: self.assertEqual(case.expected, resp.json()['code']) if resp.json()['msg'] == '取现成功': sql_2 = 'select * from future.member where mobilephone ={0}'. \ format(data_dict['mobilephone']) results_2 = self.mysql.fetch_all(sql_2) member_2 = results_2[0] self.assertEqual(member_1 - 500000, member_2['LeaveAmount'])#判断取现后余额是否正确 sql_3 = 'select paymembermoney from future.financelog where paymemberid = 1115526 ' \ 'ORDER BY createtime DESC LIMIT 1' results_3 = self.mysql.fetch_one(sql_3) member_3 = results_3['paymembermoney'] self.assertEqual(member_2['LeaveAmount'],member_3)#判断会员流水记录表余额是否与会员表余额一致 self.do_excel.write_data('withdraw',case.id + 1, resp.text, 'PASS') logger.info('第{0}条用例执行结果:pass'.format(case.id)) except AssertionError as e: self.do_excel.write_data('withdraw',case.id + 1, resp.text, 'FAIL') logger.error('第{0}条用例执行结果:fail'.format(case.id)) raise e def tearDown(self): self.mysql.close() @classmethod def tearDownClass(cls): cls.request.session.close()
class RegisterTest(unittest.TestCase): do_excel = DoExcel(constants.case_file) # 读取cases.xlsx register_cases = do_excel.get_cases('register') request = Request() # 实例化对象 mysql = MysqlUtil(return_dict=True) sql = 'select max(mobilephone) as max_mobilephone from future.member' def setUp(self): self.max_mobilephone = self.mysql.fetch_one( self.sql)['max_mobilephone'] @data(*register_cases) def test_register(self, case): logger.info("开始执行第{0}用例".format(case.id)) import json data_dict = json.loads(case.data) if data_dict['mobilephone'] == '${register_mobile}': data_dict['mobilephone'] = int( self.max_mobilephone) + 1 # 数据库中最大手机号+1 if 'regname' in data_dict.keys(): regname = data_dict['regname'] else: regname = None # print(regname) # 使用封装好的request 来完成请求 resp = self.request.request(case.method, case.url, data_dict) # print(resp.json()) try: # 将返回结果和期望结果进行匹配 self.assertEqual(case.expected, resp.text, 'register error') # 一致就写入Excel的结果为Pass self.do_excel.write_result('register', case.id + 1, resp.text, 'Pass') if resp.json()['msg'] == '注册成功': sql = "select * from future.member where mobilephone = '{0}'".format( data_dict['mobilephone']) result = self.mysql.fetch_all(sql) # 首先判断是否有成功插入数据 self.assertEqual(1, len(result), '注册成功时,仅在数据库中插入一条数据') # 判断注册成功余额应该是0 self.assertEqual(0, result[0]['LeaveAmount'], '注册成功后,初始余额应该是0') # 判断regname if regname: self.assertEqual(regname, result[0]['RegName']) else: self.assertEqual('小蜜蜂', result[0]['RegName']) logger.info("第{0}用例执行结果:PASS".format(case.id)) except AssertionError as e: # 不一致就写入Excel的结果为Fail,并抛出异常 self.do_excel.write_result('register', case.id + 1, resp.text, 'Fail') logger.error("第{0}用例执行结果:FAIL".format(case.id)) raise e @classmethod def tearDownClass(cls): cls.mysql.close()
def test_invest(self,case): readconfig = ReadConfig() pre_url = readconfig.get("api","pre_url") print("开始执行第{}个测试用例:".format(case.case_id)) case.data = replace(case.data) resp = self.request.request(method=case.method,url = pre_url+case.url,data=case.data) doexcels = doexcel.DoExcel(contants.case_file, "invest") try: self.assertEqual(case.expected,resp.text) doexcels.write_back(row=case.case_id + 2, col=8, value="PASS", sheet_name="invest") #加一层判断,判断加标是否成功,如果成功,就把标的的ID查出来反射给类的属性,以便下一条用例取 if resp.json()["msg"] == "加标成功": load_member_id = getattr(Context,"loan_member_id") mysql = MysqlUtil() sql = "select Id from future.loan where MemberID={} order by CreateTime desc limit 1".format(load_member_id) loan_id = mysql.fetchone(sql)[0] setattr(Context,"loan_id",str(loan_id)) except AssertionError as e: doexcels.write_back(row=case.case_id + 2, col=8, value="FAIlED", sheet_name="invest") doexcels.write_back(case.case_id + 2,7,resp.text,sheet_name="invest") print(resp.text)
class APITest(unittest.TestCase): do_excel = DoExcel(contants.case_file) # 传入cases.xlsx login_cases = do_excel.get_cases('login') # 获取登录用例 request = Request() # 实例化对象 @unittest.skip("忽略测试,不要运行") @data(*login_cases) def test_login(self, case): print("开始执行第{0}用例".format(case.id)) # 使用封装好的request 来完成请求 resp = self.request.request(case.method, case.url, case.data) # 将返回结果和期望结果进行匹配 try: self.assertEqual(case.expected, resp.text, "login error ") # 一致就写入Excel的结果为PASS,并且 self.do_excel.write_result('login', case.id + 1, resp.text, 'PASS') print("第{0}用例执行结果:PASS".format(case.id)) except AssertionError as e: self.do_excel.write_result('login', case.id + 1, resp.text, 'FAIL') print("第{0}用例执行结果:FAIL".format(case.id)) raise e register_cases = do_excel.get_cases('register') # 获取注册用例 mysql = MysqlUtil() # 创建数据连接 sql = "select max(mobilephone) from future.member" # 查询最大手机号 max = mysql.fetch_one(sql)[0] # 执行SQL,并且返回最近的一条数据,是元祖,使用下标取第一个值 print(type(max)) @data(*register_cases) def test_register(self, case): print("开始执行第{0}用例".format(case.id)) import json data_dict = json.loads(case.data) # Excel字符串转成字典 if data_dict['mobilephone'] == '${register_mobile}': # 判断是否等于标记 data_dict['mobilephone'] = int( self.max) + 1 # 将最大手机号码+1 赋值给mobilephone # 使用封装好的request 来完成请求 resp = self.request.request(case.method, case.url, data_dict) # 这里注意要传做过特换的字典!!!! # 将返回结果和期望结果进行匹配 try: self.assertEqual(case.expected, resp.text, "register error ") # 一致就写入Excel的结果为PASS,并且 self.do_excel.write_result('register', case.id + 1, resp.text, 'PASS') print("第{0}用例执行结果:PASS".format(case.id)) except AssertionError as e: self.do_excel.write_result('register', case.id + 1, resp.text, 'FAIL') print("第{0}用例执行结果:FAIL".format(case.id)) raise e
class TestApi(unittest.TestCase): do_excel = DoExcel(contants.cases_dir) #do_excel cases_login = do_excel.read_excel('login') cases_register = do_excel.read_excel('register') request_1 = RequestMethod() #request mysql = MysqlUtil() #数据库 my_logger = logger.get_logger( logger_name="TestApi") #各个模块中的logger_name可设置成一个名字 def setUp(self): pass #@unittest.skip("不要运行")#被装饰的方法将不会被执行 @data(*cases_login) #登录接口测试 def test_login(self, case): self.my_logger.info("开始执行第{}条登录用例".format(case.case_id)) resp = self.request_1.request_method(case.method, case.url, case.data) try: self.assertEqual(case.expectedresult, resp.text) self.do_excel.write_back(case.case_id + 1, resp.text, "Pass") #问题一:为啥登录的实际结果可以写进Excel,执行结果pass/failed却写不进Excel呢????????? self.my_logger.info("第{}条登录用例执行结果:Pass".format(case.case_id)) except AssertionError as e: self.do_excel.write_back(case.case_id + 1, resp.text, "Failed") self.my_logger.error("第{}条登录用例执行结果:Failed".format(case.case_id)) raise e def tearDown(self): pass @unittest.skip("不执行注册用例") @data(*cases_register) #注册接口测试 def test_register(self, case): self.my_logger.info("开始执行第{}条注册用例".format(case.case_id)) sql = "select max(mobilephone) from future.member" max = self.mysql.fetch_one(sql)[ 0] # 返回结果是元组类型数据,放在此处,执行每一条用例时都会替换新的手机号 data_dict = json.loads(case.data) #case.data从Excel取出是字符串格式,需转换为字典 if data_dict["mobilephone"] == "${register_mobile}": #手机号参数化 data_dict["mobilephone"] = int(max) + 1 print(data_dict["mobilephone"]) resp = self.request_1.request_method(case.method, case.url, data_dict) try: self.assertEqual(case.expectedresult, resp.text) self.do_excel.write_back(case.case_id + 1, resp.text, "Pass") self.my_logger.info("第{}条注册用例执行结果:Pass".format(case.case_id)) except AssertionError as e: self.do_excel.write_back(case.case_id + 1, resp.text, "Failed") self.my_logger.error("第{}条注册用例执行结果:Failed".format(case.case_id)) raise e
class RegisterTest(unittest.TestCase): cases = doexcel.DoExcel(contants.case_file, "reg").get_data("reg") request = Request() def setUp(self): pass def tearDown(self): pass mysql = MysqlUtil() sql = "select max(mobilephone) from future.member" max = mysql.fetchone(sql)[0] @data(*cases) def test_reg(self, case): print("开始执行第{}个测试用例:".format(case.case_id)) import json data_dict = json.loads(case.data) if data_dict["mobilephone"] == "${register_mobile}": data_dict["mobilephone"] = int(self.max) + 1 read_config = ReadConfig() pre_url = read_config.get("api", "pre_url") resp = self.request.request(method=case.method, url=pre_url + case.url, data=data_dict) doexcels = doexcel.DoExcel(contants.case_file, "reg") try: self.assertEqual(case.expected, resp.text) doexcels.write_back(row=case.case_id + 1, col=8, value="PASS", sheet_name="reg") except AssertionError as e: doexcels.write_back(row=case.case_id + 1, col=8, value="FAIlED", sheet_name="reg") doexcels.write_back(case.case_id + 1, 7, resp.text, sheet_name="reg") print(resp.text)
class TestRegister(unittest.TestCase): """ 描述登录接口的类 """ do_excel = DoExcel(contants.case_file) # 利用.实现上下级,来引入其他目录下的文件 cases = do_excel.read_data('register') req = RequestMethod() # 实例化Reqeust类的对象 mysql = MysqlUtil() #实例化对象 sql = "select max(mobilephone) from future.member" #sql查询语言 max = mysql.fetch_one(sql)[0] #调用fetch_one(sql)获取查询结果,结果是元组,用索引取值 mysql.close() def setUp(self): # Setup(self)是unittest里的方法,执行一次test_方法这个setup执行一次。 # 如果是每条用例测试前都想执行一次的操作,可以放在这个方法里 pass @data(*cases) def test_register(self,case): import json case_dict=json.loads(case.data) #json.loads()将传进来的data字符串转化为字典 if case_dict['mobilephone']=='phonenumber': #通过字典关键字取值做判断 case_dict['mobilephone']=int(self.max)-319 #重新给这个注册的号码赋值为数据库中唯一的一个值 print((int(self.max)-319)) resp = self.req.request_method(case.method, case.url, case_dict) # 返回请求结果 print("case.expected:{}".format(case.expected)) try: self.assertEqual(resp.text,case.expected,"register Error") self.do_excel.write_data('register', case.case_id + 1, resp.text, 'PASS') except AssertionError as e: self.do_excel.write_data('register', case.case_id + 1, resp.text, 'FAIL') raise e def tearDown(self): pass
def setUpClass(cls): # 每个测试类里面去运行的操作放到类方法里面 cls.request = Request() cls.mysql = MysqlUtil()
def setUpClass(cls): cls.mysql = MysqlUtil()
def setUpClass(cls): cls.request = Request() # 实例化对象 cls.mysql = MysqlUtil()
def setUpClass(cls): # 每个测试类里面去运行的操作都放到类方法里面 print("\m这是一个类方法") cls.request = Request() # 实例化对象 cls.mysql = MysqlUtil()
def setUpClass(cls): logger.info("************开始执行withdraw模块测试用例*****************") cls.mysql = MysqlUtil()
def setUpClass(cls): cls.request = Request() # 建立session会话,实例化对象 cls.context = Context() cls.mysql = MysqlUtil() #实例化mysql对象,实例化一次即可
class TestApiMethod(unittest.TestCase): '这是测试接口的类' cases_register = DoExcel(contants.excel_file, "register").read_excel() cases_login = DoExcel(contants.excel_file, "login").read_excel() cases_recharge = DoExcel(contants.excel_file, "recharge").read_excel() cases_withdraw = DoExcel(contants.excel_file, "withdraw").read_excel() cases_add = DoExcel(contants.excel_file, "add").read_excel() cases_audit = DoExcel(contants.excel_file, "audit").read_excel() cases_bidLoan = DoExcel(contants.excel_file, "bidLoan").read_excel() @classmethod # 每个测试类里面去运行的操作都放到类方法里面 def setUpClass(cls): # 为什么用类方法? 整个类只执行一次! cls.request = Request() # sql不能放这里,会报错:AttributeError: 'TestApiMethod' object has no attribute 'max' def setUp(self): # warnings.simplefilter("ignore", ResourceWarning) self.write_register = DoExcel(contants.excel_file, "register") # 创建一个对象写入 self.write_login = DoExcel(contants.excel_file, "login") self.write_recharge = DoExcel(contants.excel_file, "recharge") self.write_withdraw = DoExcel(contants.excel_file, "withdraw") self.write_add = DoExcel(contants.excel_file, "add") self.write_audit = DoExcel(contants.excel_file, "audit") self.write_bidLoan = DoExcel(contants.excel_file, "bidLoan") my_log.info("开始执行用例") def tearDown(self): my_log.info("用例执行结束") pass @classmethod def tearDownClass(cls): cls.request.session.close() # 关闭session会话 # cls.cursor.close() cls.mysql.close() # 关闭数据库连接 mysql = MysqlUtil() sql = "select max(mobilephone) from future.member" max = mysql.fetch_one(sql)[0] # 执行SQL,并且返回最近的一条数据,是元祖,使用下标取第一个值 global Max Max = int(max) + 1 # @unittest.skip("忽略测试,不要运行") @data(*cases_register) def test_register(self, case): # 测试注册 my_log.info("开始执行第{}条用例: {}".format(case.case_id, case.title)) my_log.info('url:{}'.format(case.url)) my_log.info('data:{}'.format(case.data)) my_log.info('method:{}'.format(case.method)) my_log.info('expected:{}'.format(case.expected)) dict_data = json.loads(case.data) if dict_data['mobilephone'] == '#@mobilephone': dict_data['mobilephone'] = int(self.max) + 1 # print(dict_data) # print(type(dict_data)) result = self.request.request(case.method, case.url, dict_data) try: self.assertEqual(case.expected, result.text) TestResult = "Pass" except AssertionError as e: TestResult = "Failed" my_log.error("断言出错了".format(e)) raise e finally: self.write_register.write_excel(case.case_id + 1, result.text, TestResult) # 写入测试实际结果 my_log.info('注册的结果:{}'.format(json.loads(result.text)['msg'])) @unittest.skip("忽略测试,不要运行") @data(*cases_login) def test_login(self, case): # 测试登陆 my_log.info("开始执行第{}条用例: {}".format(case.case_id, case.title)) my_log.info('url:{}'.format(case.url)) my_log.info('data:{}'.format(case.data)) my_log.info('method:{}'.format(case.method)) my_log.info('expected:{}'.format(case.expected)) login_data_new = Context.replace(case.data, login_information) result = self.request.request(case.method, case.url, login_data_new) """ # 读取配置替换参数 # login_dict = json.loads(case.data) # if login_dict["mobilephone"] == "${login_mobile_phone}": # login_dict["mobilephone"] = recharge_member_phone # if login_dict["pwd"] == "${login_mobile_pwd}": # login_dict["pwd"] = recharge_member_pwd # result = self.request.request(case.method, case.url, login_dict) """ try: # self.assertEqual(case.expected, result.text) self.assertEqual( json.loads(case.expected)['msg'], json.loads(result.text)['msg']) TestResult = "Pass" except AssertionError as e: TestResult = "Failed" my_log.error("断言出错了".format(e)) raise e finally: self.write_login.write_excel(case.case_id + 1, result.text, TestResult) # 写入测试实际结果 my_log.info('登陆的结果:{}'.format(json.loads(result.text)['msg'])) @unittest.skip("忽略测试,不要运行") @data(*cases_recharge) def test_recharge(self, case): # 测试充值 my_log.info("开始执行第{}条用例: {}".format(case.case_id, case.title)) my_log.info('url:{}'.format(case.url)) my_log.info('data:{}'.format(case.data)) my_log.info('method:{}'.format(case.method)) my_log.info('expected:{}'.format(case.expected)) recharge_data_new = Context.replace(case.data, recharge_information) result = self.request.request(case.method, case.url, recharge_data_new) """ recharge_dict = json.loads(case.data) if recharge_dict["mobilephone"] == "$$mobilephone$$": recharge_dict["mobilephone"] = recharge_member_phone result = self.request.request(case.method, case.url, recharge_dict) """ try: self.assertEqual( json.loads(case.expected)["msg"], json.loads(result.text)["msg"]) TestResult = "Pass" except AssertionError as e: TestResult = "Failed" my_log.error("断言出错了".format(e)) raise e finally: self.write_recharge.write_excel(case.case_id + 1, result.text, TestResult) # 写入测试实际结果 my_log.info('充值的结果:{}'.format(json.loads( result.text)["msg"])) # 第一条用例登陆失败,写入的对比结果不对 @unittest.skip("忽略测试,不要运行") @data(*cases_withdraw) def test_withdraw(self, case): # 测试取现 my_log.info("开始执行第{}条用例: {}".format(case.case_id, case.title)) my_log.info('url:{}'.format(case.url)) my_log.info('data:{}'.format(case.data)) my_log.info('method:{}'.format(case.method)) my_log.info('expected:{}'.format(case.expected)) withdraw_data_new = Context.replace(case.data, withdraw_information) result = self.request.request(case.method, case.url, withdraw_data_new) """ withdraw_dict = json.loads(case.data) if withdraw_dict['mobilephone'] == '**mobilephone**': withdraw_dict['mobilephone'] = withdraw_member_phone result = self.request.request(case.method, case.url, withdraw_dict) """ try: self.assertEqual( json.loads(case.expected)['msg'], json.loads(result.text)['msg']) TestResult = "Pass" except AssertionError as e: TestResult = "Failed" my_log.error("断言出错了".format(e)) raise e finally: self.write_withdraw.write_excel(case.case_id + 1, result.text, TestResult) # 写入测试实际结果 my_log.info('提现的结果:{}'.format(json.loads( result.text)['msg'])) # 第一条用例登陆失败,写入的对比结果不对 @unittest.skip("忽略测试,不要运行") @data(*cases_add) def test_add(self, case): # 测试创建标的 # my_log.info("开始执行第{}条用例: {}".format(case.case_id, case.title)) # my_log.info('url:{}'.format(case.url)) # my_log.info('data:{}'.format(case.data)) # my_log.info('method:{}'.format(case.method)) # my_log.info('expected:{}'.format(case.expected)) add_data_new = Context.replace(case.data, add_information) result = self.request.request(case.method, case.url, add_data_new) # 还有问题 登录后在获取变量执行就会跳过 # add_dict = json.loads(case.data) # if add_dict["memberId"] == "**123456**": # add_dict["memberId"] = withdraw_member_id # result = self.request.request(case.method, case.url, add_dict) result = self.request.request(case.method, case.url, case.data) try: self.assertEqual( json.loads(case.expected)['msg'], json.loads(result.text)['msg']) TestResult = "Pass" except AssertionError as e: TestResult = "Failed" my_log.error("断言出错了".format(e)) raise e finally: self.write_add.write_excel(case.case_id + 1, result.text, TestResult) # 写入测试实际结果 my_log.info('新建项目的结果:{}'.format(json.loads(result.text)['msg'])) @unittest.skip("忽略测试,不要运行") @data(*cases_audit) def test_audit(self, case): # 测试创建标的 my_log.info("开始执行第{}条用例: {}".format(case.case_id, case.title)) my_log.info('url:{}'.format(case.url)) my_log.info('data:{}'.format(case.data)) my_log.info('method:{}'.format(case.method)) my_log.info('expected:{}'.format(case.expected)) result = self.request.request(case.method, case.url, case.data) try: self.assertEqual( json.loads(case.expected)['msg'], json.loads(result.text)['msg']) TestResult = "Pass" if json.loads(case.data)['status'] == 4: # 如果状态为竞标(4),显示标的 global id id = json.loads(case.data)['id'] # print('id的值:{}'.format(id)) except AssertionError as e: TestResult = "Failed" my_log.error("断言出错了".format(e)) raise e finally: self.write_audit.write_excel(case.case_id + 1, result.text, TestResult) # 写入测试实际结果 my_log.info('审核的结果:{}'.format(json.loads(result.text)['msg'])) @unittest.skip("忽略测试,不要运行") @data(*cases_bidLoan) def test_bidLoan(self, case): # 测试创建标的 my_log.info("开始执行第{}条用例: {}".format(case.case_id, case.title)) my_log.info('url:{}'.format(case.url)) my_log.info('data:{}'.format(case.data)) my_log.info('method:{}'.format(case.method)) my_log.info('expected:{}'.format(case.expected)) bidLoan_data_new = Context.replace(case.data, bidLoan_information) result = self.request.request(case.method, case.url, bidLoan_data_new) # 还有问题 登录后在获取变量执行就会跳过 # bidLoan_dict = json.loads(case.data) # if bidLoan_dict["mobilephone"] == "@123@": # bidLoan_dict["mobilephone"] = recharge_member_phone # if bidLoan_dict["memberId"] == "123": # bidLoan_dict["memberId"] = recharge_member_id # result = self.request.request(case.method, case.url, bidLoan_dict) try: self.assertEqual( json.loads(case.expected)["msg"], json.loads(result.text)["msg"]) TestResult = "Pass" except AssertionError as e: TestResult = "Failed" my_log.error("断言出错了".format(e)) raise e finally: self.write_bidLoan.write_excel(case.case_id + 1, result.text, TestResult) # 写入测试实际结果 my_log.info('竞标的结果:{}'.format(json.loads(result.text)["msg"]))
def setUp(self): self.mysql = MysqlUtil(return_dict=True)
def setUp(self): self.mysql = MysqlUtil(return_dict=True) sql = 'select max(mobilephone) as max_phone from future.member' self.max = self.mysql.fetch_one(sql)['max_phone']
def setUpClass(cls): logger.info("************开始执行register模块测试用例*****************") cls.mysql = MysqlUtil()
class APITest(unittest.TestCase): do_excel = DoExcel(constants.case_file) # 读取cases.xlsx login_cases = do_excel.get_cases('login') # 指定读取login测试数据 register_cases = do_excel.get_cases('register') request = Request() # 实例化对象 mysql = MysqlUtil() sql = 'select max(mobilephone) from future.member' @classmethod def setUpClass(cls): pass @classmethod def tearDownClass(cls): pass def setUp(self): self.max_mobilephone = self.mysql.fetch_one(self.sql)[0] def tearDown(self): pass @unittest.skip('调过不执行') @data(*login_cases) def test_login(self, case): logger.info("开始执行第{0}用例".format(case.id)) # 使用封装好的request 来完成请求 resp = self.request.request(case.method, case.url, case.data) try: # 将返回结果和期望结果进行匹配 self.assertEqual(case.expected, resp.text, 'login error') # 一致就写入Excel的结果为Pass self.do_excel.write_result('login', case.id + 1, resp.text, 'Pass') logger.info("第{0}用例执行结果:PASS".format(case.id)) except AssertionError as e: # 不一致就写入Excel的结果为Fail,并抛出异常 self.do_excel.write_result('login', case.id + 1, resp.text, 'Fail') logger.error("第{0}用例执行结果:FAIL".format(case.id)) raise e # mysql = MysqlUtil() # sql = 'select max(mobilephone) from future.member' # max_mobilephone = mysql.fetch_one(sql)[0] @data(*register_cases) def test_register(self, case): logger.info("开始执行第{0}用例".format(case.id)) import json data_dict = json.loads(case.data) if data_dict['mobilephone'] == '${register_mobile}': data_dict['mobilephone'] = int( self.max_mobilephone) + 1 # 数据库中最大手机号+1 # 使用封装好的request 来完成请求 resp = self.request.request(case.method, case.url, data_dict) try: # 将返回结果和期望结果进行匹配 self.assertEqual(case.expected, resp.text, 'register error') # 一致就写入Excel的结果为Pass self.do_excel.write_result('register', case.id + 1, resp.text, 'Pass') logger.info("第{0}用例执行结果:PASS".format(case.id)) except AssertionError as e: # 不一致就写入Excel的结果为Fail,并抛出异常 self.do_excel.write_result('register', case.id + 1, resp.text, 'Fail') logger.error("第{0}用例执行结果:FAIL".format(case.id)) raise e
def setUp(self): self.mysql = MysqlUtil(return_dict=True) # 创建数据连接 sql = "select max(mobilephone) as max_phone from future.member" # 查询最大手机号 self.max = self.mysql.fetch_one(sql)[ 'max_phone'] # 执行SQL,并且返回最近的一条数据,是元祖,使用下标取第一个值
def getuid(user_id): sql = "select Fuid FROM user_db.t_user_info where Fuser_id = '" + user_id + "'" A = MysqlUtil() res = str(A.fetchone(sql)) A.close_database() return res
def setUpClass(cls): # 每个测试类里面去运行的操作放到类方法里面 logger.debug("\n这是一个类方法") cls.request = Request() # 实例化对象 cls.mysql = MysqlUtil()