class longin(unittest.TestCase): file_name = os.path.join(DATA_DIR, 'liukun.xlsx') excel = Excel(file_name, 'longin') case = excel.read_data() @ddt.data(*case) def test_login(self, item): #准备用例数据 url = conf.get('url', 'url') + item['url'] params = eval(item['data']) method = item['method'] title = item['title'] expected = item['expected'] response = requests.request(method=method, url=url, json=params) res = response.json() print('实际结果:{}'.format(res)) print('预期结果:{}'.format(expected)) try: self.assertEqual(str(expected), jsonpath(res, '$.statusCode')[0]) except AssertionError as e: log.error('{}用例执行失败'.format(item['title'])) self.excel.write_data(row=item['case_id'] + 1, column=7, value='失败') raise e else: log.error('{}用例执行成功'.format(item['title'])) self.excel.write_data(row=item['case_id'] + 1, column=7, value='成功')
class TestWithdraw(unittest.TestCase): excel = Excel(os.path.join(DATA_DIR, "cases.xlsx"), "withdraw") cases = excel.read_data() @classmethod def setUpClass(cls): # 登录 获取token id # 登录url login_url = conf.get("env", "base_url") + "/member/login" # 请求头 headers = eval(conf.get("env", "headers")) # 登录的参数 mobile_phone = conf.get("test_data", "mobile") pwd = conf.get("test_data", "pwd") params = {"mobile_phone": mobile_phone, "pwd": pwd} # 发送登录请求 response = requests.post(url=login_url, json=params, headers=headers) res = response.json() # 获取token token = jsonpath(res, "$..token")[0] cls.token = "Bearer" + " " + token cls.member_id = jsonpath(res, "$..id")[0] @myddt.data(*cases) def test_withdraw(self, item): # 第一步:准备数据 case_id = item["case_id"] # 请求地址 url = conf.get("env", "base_url") + item["url"] item["data"] = replace_data(item["data"], TestWithdraw) params = eval(item["data"]) method = item["method"] headers = eval(conf.get("env", "headers")) headers["Authorization"] = self.token expected = eval(item["expected"]) sql = item["check_sql"] if sql: s_amount = db.find_data(sql.format(self.member_id)) s_money = s_amount[0]["leave_amount"] response = requests.request(url=url, method=method, json=params, headers=headers) res = response.json() # 第三步 :断言 try: self.assertEqual(res["code"], expected["code"]) self.assertEqual(res["msg"], expected["msg"]) if sql: e_amount = db.find_data(sql.format(self.member_id)) e_money = s_amount[0]["leave_amount"] self.assertEqual(float(s_money - e_money), params["amount"]) except AssertionError as e: log.error("用例执行失败:{}".format(item["title"])) self.excel.write_data(row=case_id + 1, column=8, value="失败") raise e else: log.info("用例执行通过:{}".format(item["title"])) self.excel.write_data(row=case_id + 1, column=8, value="通过")
class TestUpdateV3(unittest.TestCase): excel = Excel(file_name=os.path.join(DATA_DIR, 'cases.xlsx'), sheet_name='update') cases = excel.read_excel() @classmethod def setUpClass(cls): fixture.setup_login(TestUpdateV3) @myddt.data(*cases) def test_update(self, item): # 获取请求接口 url = conf.get('env', 'base_url') + item['url'] # 获取请求数据 params = eval(item['data']) # 请求参数添加timestamp和sign crypt_info = HandleSign.generate_sign(self.token_value) params['timestamp'] = crypt_info['timestamp'] params['sign'] = crypt_info['sign'] # 获取请求方法 method = item['method'] # 获取请求头v2 # headers = eval(conf.get('env', 'headers')) # 请求头 v3 headers = eval(conf.get('env', 'headers')) headers['Authorization'] = self.token # 预计结果 expected = eval(item['expected']) # 请求接口获得实际结果 response = requests.request(method=method, url=url, json=params, headers=headers) res = response.json() print('预计结果:', expected) print('实际结果:', res) # 断言判断 try: self.assertEqual(res['code'], expected['code']) self.assertEqual(res['msg'], expected['msg']) except AssertionError as e: log.error("用例{},执行失败".format(item['title'])) log.exception(e) self.excel.write_excel(row=item['case_id'] + 1, column=8, value='未通过') raise e else: log.info("用例{},执行成功".format(item['title'])) self.excel.write_excel(row=item['case_id'] + 1, column=8, value='通过')
class TestRegister(unittest.TestCase): excel = Excel(os.path.join(DATA_DIR, "cases.xlsx"), "register") cases = excel.read_data() @myddt.data(*cases) def test_register(self, item): # 第一步:准备数据 # /member/register # http://api.lemonban.com/futureloan url = conf.get("env", "base_url") + item["url"] headers = eval(conf.get("env", "headers")) # 判断参数中是否有手机号需要替换 if "*phone*" in item["data"]: phone = self.random_phone() # 将参数中的*phone*替换成手机号码 item["data"] = item["data"].replace("*phone*", phone) params = eval(item["data"]) expected = eval(item["expected"]) method = item["method"] # 第二步:请求接口,获取实际结果 response = requests.request(url=url, method=method, json=params, headers=headers) res = response.json() print("预期结果:", expected) print("实际结果:", response.text) # 第三步:断言 try: self.assertEqual(expected["code"], res["code"]) self.assertEqual(expected["msg"], res["msg"]) # 用例校验的sql写在excel中如何获取? sql = item["check_sql"] if sql: res = db.find_data(sql.format(params["mobile_phone"])) # 断言是否能够查询到数据 self.assertTrue(res) except AssertionError as e: log.error("用例{},执行未通过".format(item["title"])) log.exception(e) raise e else: log.info("用例{},执行通过".format(item["title"])) @staticmethod def random_phone(): """随机生成一个未注册手机号""" while True: phone = "131" for i in range(8): i = random.randint(0, 9) phone += str(i) # 判断改手机号是否已注册 sql = "SELECT * FROM futureloan.member WHERE mobile_phone={}".format(phone) res = db.find_data(sql) if not res: return phone
class TestWithdraw(unittest.TestCase): excel = Excel(os.path.join(DATA_DIR, "cases.xlsx"), "withdraw") cases = excel.read_data() @classmethod def setUpClass(cls): """写该用例类执行之前的前置 登录,获取token,和用户id """ fixture.setup_login(cls) @myddt.data(*cases) def test_withdraw(self, item): # 第一步:准备数据 url = conf.get("env", "base_url") + item["url"] # 请求参数 item["data"] = replace_data(item["data"], TestWithdraw) params = eval(item["data"]) # 请求头 headers = eval(conf.get("env", "headers")) # 请求头中要添加token headers["Authorization"] = self.token # 请求方法 method = item["method"] # 预期结果 expected = eval(item["expected"]) sql = item["check_sql"] if sql: s_amount = db.find_data(sql.format(self.member_id)) s_money = s_amount[0]["leave_amount"] # 第二步:请求接口,获取结果 response = requests.request(url=url, method=method, json=params, headers=headers) res = response.json() print("预期结果:", expected) print("实际结果:", res) # 第三步:断言 try: self.assertEqual(expected["code"], res["code"]) self.assertEqual(expected["msg"], res["msg"]) if sql: e_amount = db.find_data(sql.format(self.member_id)) e_money = e_amount[0]["leave_amount"] self.assertEqual(float(s_money - e_money), params["amount"]) except AssertionError as e: log.error("用例{},执行未通过".format(item["title"])) log.exception(e) raise e else: log.info("用例{},执行通过".format(item["title"]))
class TestAdd(unittest.TestCase): excel = Excel(os.path.join(DATA_DIR, "cases.xlsx"), "add") cases = excel.read_data() @myddt.data(*cases) def test_add(self, item): # 第一步:获取参数 case_id = item["case_id"] # 请求的url url = conf.get("env", "base_url") + item["url"] # 请求的方法 method = item["method"] # 请求的headers headers = eval(conf.get("env", "headers")) if item["interface"] == "add": headers["Authorization"] = self.token # 请求的参数 item["data"] = replace_data(item["data"], TestAdd) params = eval(item["data"]) # 预期的结果 expected = eval(item["expected"]) # 判断执行前的数据库状态 sql = item["check_sql"] # 第二步 发送请求 response = requests.request(url=url, method=method, json=params, headers=headers) res = response.json() if item["interface"] == "login": # 提取token和用户id保存为类属性 TestAdd.token = "Bearer" + " " + jsonpath(res, "$..token")[0] TestAdd.member_id = jsonpath(res, "$..id")[0] print("预期结果:", expected) print("实际结果:", res) try: self.assertEqual(res["code"], expected["code"]) self.assertEqual(res["msg"], expected["msg"]) if item["interface"] == "add": if sql: sql = replace_data(sql, TestAdd) res = db.find_data(sql) self.assertTrue(res) except AssertionError as e: log.error("用例执行失败:{}".format(item["title"])) log.exception(e) raise e self.excel.write_data(row=case_id + 1, column=8, value="失败") else: log.info("用例执行通过:{}".format(item["title"])) self.excel.write_data(row=case_id + 1, column=8, value="通过")
class TestAdd(unittest.TestCase): """新增项目的测试用例类""" @classmethod def setUpClass(cls): """请求登录接口获取token和member_id""" fixture.setup_login(TestAdd) excel = Excel(file_name=os.path.join(DATA_DIR, 'cases.xlsx'), sheet_name='add') case = excel.read_excel() @myddt.data(*case) def test_add(self, item): # 请求接口的url url = conf.get('env', 'base_url') + item['url'] # 请求参数 params = eval(replace_data(item['data'], TestAdd)) # 请求头 headers = eval(conf.get('env', 'headers')) headers['Authorization'] = self.token # 请求方法 method = item['method'] # 预期结果 expected = eval(item['expected']) # 请求接口获得请求结果 response = requests.request(method=method, url=url, json=params, headers=headers) res = response.json() print('预期结果:', expected) print('实际结果:', res) # 断言 try: self.assertEqual(res['code'], expected['code']) self.assertEqual(res['code'], expected['code']) if item['check_sql']: result = db.find_data( (item['check_sql']).format(jsonpath(res, '$..id')[0])) self.assertTrue(result) except AssertionError as e: log.error('用例{},执行失败'.format(item['title'])) log.exception(e) self.excel.write_excel(row=item['case_id'] + 1, column=8, value='未通过') raise e else: log.info('用例{},执行成功'.format(item['title'])) self.excel.write_excel(row=item['case_id'] + 1, column=8, value='通过')
class TestLogin(unittest.TestCase): excel = Excel(os.path.join(DATA_DIR, 'cases.xlsx'), 'login') case = excel.read_data() @myddt.data(*case) def test_login(self, case_data): # 准备用例数据 # 请求接口 url = conf.get("env", "base_url") + case_data["url"] # 请求头 headers = eval(conf.get("env", "headers")) case_row = case_data["case_id"] + 1 # 预期结果 excepted = eval(case_data["expected"]) # 请求参数 if "*phone*" in case_data["data"]: phone = self.random_phone() case_data["data"] = case_data["data"].replace("*phone*", phone) params = eval(case_data["data"]) # 请求方法 method = case_data["method"] # 调用接口,获取实际结果 response = requests.request(url=url, method=method, json=params, headers=headers) res = response.json() # 断言 try: self.assertEqual(excepted["code"], res["code"]) self.assertEqual(excepted["msg"], res["msg"]) except AssertionError as e: self.excel.write_data(row=case_row, column=8, value='失败') log.error("{}用例执行失败,失败信息如下:".format(case_data['title'])) log.exception(e) raise e else: self.excel.write_data(row=case_row, column=8, value='通过') log.info("{}用例执行通过".format(case_data['title'])) @staticmethod def random_phone(): phone = "176" for i in range(8): i = random.randint(0, 9) phone += str(i) return phone
class TestAdd(unittest.TestCase): excel = Excel(os.path.join(DATA_DIR, "cases.xlsx"), "add") cases = excel.read_data() @classmethod def setUpClass(cls): """写该用例类执行之前的前置 登录,获取token,和用户id """ fixture.setup_login(cls) @data(*cases) def test_add(self, item): # 第一步:准备用例数据 url = conf.get("env", "base_url") + item["url"] headers = eval(conf.get("env", "headers")) headers["Authorization"] = self.token # 替换用例参数 item["data"] = replace_data(item["data"], TestAdd) params = eval(item["data"]) # 请求方法 method = item["method"] # 预期结果 expected = eval(item["expected"]) # 第二步:请求接口,获取实际返回的结果 response = requests.request(url=url, method=method, json=params, headers=headers) res = response.json() # 第三步:断言 try: self.assertEqual(expected["code"], res["code"]) self.assertEqual(expected["msg"], res["msg"]) # 进行数据库校验 if item["check_sql"]: loan_id = jsonpath(res, "$..id")[0] sql = item["check_sql"].format(loan_id) result = db.find_data(sql) self.assertTrue(result) except AssertionError as e: log.error("用例{},执行未通过".format(item["title"])) log.exception(e) raise e else: log.info("用例{},执行通过".format(item["title"]))
class TestInfoV3(unittest.TestCase): excel = Excel(file_name=os.path.join(DATA_DIR, 'cases.xlsx'), sheet_name='info') cases = excel.read_excel() @classmethod def setUpClass(cls): fixture.setup_login(TestInfoV3) @myddt.data(*cases) def test_info(self, item): # 请求接口 url = conf.get('env', 'base_url') + replace_data( item['url'], TestInfoV3) # 请求方法 method = item['method'] # 请求头v2 # headers = eval(conf.get('env', 'headers')) # 请求头v3 headers = eval(conf.get('env', 'headersV3')) headers['Authorization'] = self.token # 预期结果 expected = eval(item['expected']) # 请求接口获得实际结果 response = requests.request(method=method, url=url, headers=headers) res = response.json() print('预计结果:', expected) print('实际结果:', res) # 断言 try: self.assertEqual(res['code'], expected['code']) self.assertEqual(res['code'], expected['code']) except AssertionError as e: log.exception(e) log.error('用例{},执行未通过'.format(item['title'])) self.excel.write_excel(row=item['case_id'] + 1, column=8, value='未通过') raise e else: log.info('用例{},执行通过'.format(item['title'])) self.excel.write_excel(row=item['case_id'] + 1, column=8, value='通过')
class TestAudit(unittest.TestCase): excel = Excel(os.path.join(DATA_DIR, "cases.xlsx"), "audit") cases = excel.read_excel() @classmethod def setUpClass(cls): """获取token,和member_id""" # ----------------普通用户登录---------------- fixture.setup_login(TestAudit) # ----------------管理员用户登录------------------------- fixture.setup_login_admin(TestAudit) def setUp(self): """新增一个待审核的项目,以便审核""" fixture.setup_add(TestAudit) @myddt.data(*cases) def test_audit(self, item): # 第一步:准备用例数据 url = conf.get("env", "base_url") + item["url"] headers = eval(conf.get("env", "headers")) headers["Authorization"] = self.admin_token # 替换用例参数 item["data"] = replace_data(item["data"], TestAudit) params = eval(item["data"]) # 请求方法 method = item["method"] # 预期结果 expected = eval(item["expected"]) # 第二步:请求接口,获取实际返回的结果 response = requests.request(url=url, method=method, json=params, headers=headers) res = response.json() # 第三步:断言 try: self.assertEqual(expected["code"], res["code"]) self.assertEqual(expected["msg"], res["msg"]) if item["title"] == "审核通过": TestAudit.pass_loan_id = params["loan_id"] except AssertionError as e: log.error("用例{},执行未通过".format(item["title"])) log.exception(e) self.excel.write_excel(row=item['case_id'] + 1, column=8, value='未通过') raise e else: log.info("用例{},执行通过".format(item["title"])) self.excel.write_excel(row=item['case_id'] + 1, column=8, value='通过')
class TestLogin(unittest.TestCase): excel = Excel(os.path.join(DATA_DIR, 'cases.xlsx'), 'login') case_data = excel.read_excel() @myddt.data(*case_data) def test_login(self, item): """测试登录的测试用例方法""" # 测试数据 params = eval(item['data']) method = item['method'] # 预期结果 expected = eval(item['expected']) # 请求头 headers = eval(conf.get('env', 'headers')) # 接口地址 login_url = conf.get('env', 'base_url') + item['url'] # 实际结果 response = requests.request(url=login_url, json=params, method=method, headers=headers) res = response.json() # 随机生成的手机号,代替用例数据中的 *phone* print('预期结果:', expected) print('实际结果:', res) # 断言判断 try: self.assertEqual(expected['code'], res['code']) self.assertEqual(expected['msg'], res['msg']) except AssertionError as e: log.error('用例{},执行未通过'.format(item['title'])) self.excel.write_excel(row=(item['case_id'] + 1), column=8, value='未通过') log.exception(e) raise e else: log.info('用例{},执行通过'.format(item['title'])) self.excel.write_excel(row=(item['case_id'] + 1), column=8, value='通过')
class SmsCode(unittest.TestCase): file_name = os.path.join(DATA_DIR, 'liukun.xlsx') excel = Excel(file_name, 'smscode') case = excel.read_data() @ddt.data(*case) def test_smscode(self, item): #准备用例数据 #接口地址 url = conf.get('url', 'url') + item['url'] #请求参数 params = eval(item['data']) #预期结果 expected = item['expected'] #请求方式 method = item['method'] #title title = item['title'] #调用接口请求 response = requests.request(method=method, url=url, json=params) #实际结果 res = response.json() print('实际结果:{}'.format(res)) print('预期结果:{}'.format(expected)) try: self.assertEqual(str(expected), jsonpath(res, '$.statusCode')[0]) except AssertionError as e: self.excel.write_data(row=item['case_id'] + 1, column=7, value='失败') log.error('{}用例执行失败'.format(title)) raise e else: self.excel.write_data(row=item['case_id'] + 1, column=7, value='成功') log.info('{}用例执行通过!!!'.format(title))
class MingWEN(unittest.TestCase): file_name = os.path.join(DATA_DIR, 'liukun.xlsx') excel = Excel(file_name, 'mingwen') cases = excel.read_data() @ddt.data(*cases) def test01_mingwen(self, item): # 第一步:准备用例数据 # 接口地址 url1 = conf.get('url', 'url') url = url1 + item['url'] print(url) # 请求参数 params = eval(item['data']) # 预期结果 expected = item['expected'] method = item['method'] title = item['title'] # 第二步:调用接口获取实际结果 responts = requests.request(method=method, url=url, json=params) res = responts.json() print('实际结果:{}'.format(res)) print('预期结果:{}'.format(expected)) # 断言 try: self.assertEqual(str(expected), res['statusCode']) except AssertionError as e: self.excel.write_data(row=item['case_id'] + 1, column=7, value='失败') log.info('{}用例执行失败'.format(title)) raise e else: self.excel.write_data(row=item['case_id'] + 1, column=7, value='通过') log.info('{}用例执行成功========'.format(title))
class TestLogin(unittest.TestCase): excel = Excel(file_path, "login") cases = excel.read_data() @myddt.data(*cases) def test_login(self, item): # 第一步:准备用例数据 # 接口地址 url = conf.get("env", "base_url") + item["url"] # 请求头 headers = eval(conf.get("env", "headers")) # 请求参数 item["data"] = replace_data(item["data"], TestLogin) params = eval(item["data"]) # 预取结果 expected = eval(item["expected"]) # 请求方法 method = item["method"] # 第二步:调用接口,获取实际结果 response = requests.request(method, url=url, json=params, headers=headers) res = response.json() print("预期结果:", expected) print("实际结果:", response.text) # 第三步:断言 try: self.assertEqual(expected["code"], res["code"]) self.assertEqual(expected["msg"], res["msg"]) except AssertionError as e: log.error("用例{},执行未通过".format(item["title"])) log.exception(e) raise e else: log.info("用例{},执行通过".format(item["title"]))
class test_newpaypd(unittest.TestCase): @classmethod def setUpClass(cls): """登录接口""" fixture.setUp_login(cls) file_name = os.path.join(DATA_DIR, 'liukun.xlsx') excel = Excel(file_name, 'newpaypd') case = excel.read_data() @ddt.data(*case) def test_newpay(self, item): """设置交易密码""" # 准备用例数据 url = conf.get('url', 'url') + item['url'] # 准备数据 params = eval(replace_data(item['data'], test_newpaypd)) print(params) # 获取请求方式 method = item['method'] # 获取实际结果 response = requests.request(method=method, url=url, json=params) res = response.json() print('实际结果:{}'.format(res))
class TestRechargeV3(unittest.TestCase): excel = Excel(file_name=os.path.join(DATA_DIR, 'cases.xlsx'), sheet_name='recharge') case_data = excel.read_excel() @classmethod def setUpClass(cls): """用例类执行前需要执行内容""" fixture.setup_login(TestRechargeV3) @myddt.data(*case_data) def test_recharge(self, item): """充值接口测试用例方法""" # 请求头v2(配置文件中获取的为str类型) # headers = eval(conf.get('env', 'headers')) # 请求头为v3 headers = eval(conf.get('env', 'headersV3')) # 将 token 字段添加到请求头中 headers["Authorization"] = self.token # 请求参数 """参数化 member_id 开始""" # if '#member_id#' in item['data']: # # 将替换 #member_id# self.member_id # item['data'] = item['data'].replace('#member_id#', str(self.member_id)) # params = eval(item['data']) params = eval(replace_data(item['data'], TestRechargeV3)) """参数化 member_id 结束""" # 获取时间戳和sign值,添加到请求参数中 cryto_info = HandleSign.generate_sign(self.token_value) params['timestamp'] = cryto_info['timestamp'] params['sign'] = cryto_info['sign'] # 请求方法 method = item['method'] # 请求接口 recharge_url = conf.get('env', 'base_url') + item['url'] # 预期结果 expected = eval(item['expected']) # 获取充值前数据库中的金额 sql = item['check_sql'] if sql: start_amount = db.find_data(sql.format( self.member_id))[0]['leave_amount'] # 实际结果 response = requests.request(method=method, url=recharge_url, json=params, headers=headers) res = response.json() print('预期结果:', expected) print('实际结果:', res) try: # 将充值前后的金额之差,与充值的金额比较,相等则通过,不等则失败 if sql: # 获取充值后数据库中的金额 end_amount = db.find_data(sql.format( self.member_id))[0]['leave_amount'] # 断言前后数据库中数值的变化和实际传入参数的大小是否一致 self.assertEqual(float(end_amount - start_amount), eval(item['data'])['amount']) self.assertEqual(expected["code"], res["code"]) self.assertEqual(expected["msg"], res["msg"]) except AssertionError as e: log.error("用例{},执行未通过".format(item["title"])) self.excel.write_excel(row=(item['case_id'] + 1), column=8, value='未通过') log.exception(e) raise e else: log.info("用例{},执行通过".format(item["title"])) self.excel.write_excel(row=(item['case_id'] + 1), column=8, value='通过')
class TestAudit(unittest.TestCase): excel = Excel(os.path.join(DATA_DIR, "cases.xlsx"), "audit") cases = excel.read_data() @classmethod def setUpClass(cls): """审核项目的前置:管理员和普通用户登录""" # ----------------普通用户登录---------------- fixture.setup_login(cls) # ----------------管理员用户登录--------------- fixture.setup_login_admin(cls) def setUp(self): """添加项目,提取项目id""" url = conf.get("env", "base_url") + "/loan/add" params = { "member_id": self.member_id, "title": "借钱找对象过七夕", "amount": 2000, "loan_rate": 12.0, "loan_term": 3, "loan_date_type": 1, "bidding_days": 5 } headers = eval(conf.get("env", "headers")) headers["Authorization"] = self.token response = requests.request(url=url, method="post", json=params, headers=headers) res = response.json() # 将项目id保存为类属性 TestAudit.loan_id = jsonpath(res, "$..id")[0] @data(*cases) def test_audit(self, item): # 第一步:准备用例数据 url = conf.get("env", "base_url") + item["url"] headers = eval(conf.get("env", "headers")) headers["Authorization"] = self.admin_token # 替换用例参数 item["data"] = replace_data(item["data"], TestAudit) params = eval(item["data"]) # 请求方法 method = item["method"] # 预期结果 expected = eval(item["expected"]) # 第二步:请求接口,获取实际返回的结果 response = requests.request(url=url, method=method, json=params, headers=headers) res = response.json() # 第三步:断言 try: self.assertEqual(expected["code"], res["code"]) self.assertEqual(expected["msg"], res["msg"]) if item["title"] == "审核通过": TestAudit.pass_loan_id = params["loan_id"] # 进行数据库校验 if item["check_sql"]: sql = item["check_sql"].format(params["loan_id"]) result = db.find_data(sql)[0] self.assertEqual(expected["status"], result["status"]) except AssertionError as e: log.error("用例{},执行未通过".format(item["title"])) log.exception(e) raise e else: log.info("用例{},执行通过".format(item["title"]))
# -*- coding: utf-8 -*- import unittest import json from lib.ddt import ddt, data from common.handle_log import Log from common.handle_request import Request from common.handle_excel import Excel from common.handle_dir import CASE_FILE_PATH, CONFIGS_FILE_PATH from common.handle_conf import Config from common.handle_context import Context from common.handle_mysql import MySql cf = Config(CONFIGS_FILE_PATH) # 配置文件对象 file = Excel(CASE_FILE_PATH, "school_management") # excel文件 data_list = file.get_cases() # 获取文件中的数据 log = Log().get_logger() # 日志对象 req = Request() # 请求对象 # 创建mysql连接对象(连接的是payment库) mysql = MySql(cf.get_value("db_msg", "user1"), cf.get_value("db_msg", "pwd1"), cf.get_value("db_msg", "database1")) @ddt class Testcase(unittest.TestCase): @classmethod def setUpClass(cls): """ 初始化 :return: """
Author:hw data:2020/11/17 12:33 ============ """ import jsonpath import requests from common.handle_db import db from common.handle_conf import conf from common.handle_path import DATA_DIR from common.handle_excel import Excel from common import myddt from common.handle_log import Log import os import unittest from common.handle_replacedata import replace_data sh = Excel(os.path.join(DATA_DIR, "case.xlsx"), "withdraw") sh.open() case_data = sh.read_excel() log = Log.create_log() @myddt.ddt class TestWithdraw(unittest.TestCase): @classmethod def setUpClass(cls): url = conf.get("api", "baseUrl") + "/member/login" params = { "mobile_phone": conf.get("testdata", "mobile_phone"), "pwd": conf.get("testdata", "pwd") } headers = eval(conf.get("api", "headers"))
# -*- coding:utf-8 -*- import unittest import json from lib.ddt import ddt, data from common.handle_log import Log from common.handle_request import Request from common.handle_excel import Excel from common.handle_dir import CASE_FILE_PATH, CONFIGS_FILE_PATH from common.handle_conf import Config from common.handle_context import Context cf = Config(CONFIGS_FILE_PATH) # 配置文件对象 file = Excel(CASE_FILE_PATH, "home_page") # excel文件 data_list = file.get_cases() # 获取文件中的数据 log = Log().get_logger() # 日志对象 req = Request() # 请求对象 @ddt class Testcase(unittest.TestCase): @classmethod def setUpClass(cls): """ 初始化 :return: """ log.info("{:*^40s}".format("运营商首页开始执行用例")) @classmethod def tearDownClass(cls):
class TestAudit(unittest.TestCase): excel_audit = Excel(os.path.join(DATA_DIR,"cases.xlsx"),"audit") case_audit = excel_audit.read_data() @classmethod def setUpClass(cls): """ 普通用户登录,管理员登录 """ login_url = conf.get("env", "base_url") + "/member/login" # 请求头 headers = eval(conf.get("env", "headers")) # 登录的参数 mobile_phone = conf.get("test_data", "mobile") pwd = conf.get("test_data", "pwd") params = { "mobile_phone": mobile_phone, "pwd": pwd } # 发送登录请求 response = requests.post(url=login_url, json=params, headers=headers) res = response.json() # 获取token token = jsonpath(res, "$..token")[0] cls.token = "Bearer" + " " + token cls.member_id = jsonpath(res, "$..id")[0] # 管理员登录 login_url = conf.get("env", "base_url") + "/member/login" # 请求头 headers = eval(conf.get("env", "headers")) # 管理员登录的参数 admin_params = { "mobile_phone": conf.get("test_data","admin_mobile"), "pwd": conf.get("test_data","admin_pwd") } # 发送登录请求 response = requests.post(url=login_url, json=admin_params, headers=headers) res = response.json() # 获取管理员的token cls.admin_token = "Bearer" + " " + jsonpath(res, "$..token")[0] def setUp(self): """ 使用普通用户添加项目,然后提取项目ID """ add_url = conf.get("env","base_url") + "/loan/add" headers = eval(conf.get("env","headers")) headers["Authorization"] = self.token params = { "member_id":self.member_id, "title":"sun".format(random.randint(0,100)), "amount":1000, "loan_rate":5.76, "loan_term":6, "loan_date_type":1, "bidding_days":1 } response = requests.request(url=add_url,method="post",json=params,headers=headers) res = response.json() # 将项目ID保存为类属性 TestAudit.project_id = jsonpath(res,"$..id")[0] @myddt.data(*case_audit) def test_audit(self,item): #第一步:请求参数 case_id = item["case_id"] url = conf.get("env", "base_url") + item["url"] method = item["method"] headers = eval(conf.get("env","headers")) headers["Authorization"] = self.admin_token print(headers) item["data"] = replace_data(item["data"],TestAudit) params = eval(item["data"]) expected = eval(item["expected"]) # 数据库的校验 sql = item["check_sql"] #第二步:发送请求 response = requests.request(url= url,method=method,json=params,headers=headers) res = response.json() print("实际结果",res) print("预期结果",expected) #第三步: 断言 try: self.assertEqual(res["code"], expected["code"]) self.assertEqual(res["msg"], expected["msg"]) if item["title"] == "审核通过": TestAudit.pass_project_id = params["loan_id"] if sql: res = db.find_data(sql.format(self.project_id)) status = res[0]["status"] self.assertEqual(status,expected["status"]) except AssertionError as e: log.error("用例执行失败:{}".format(item["title"])) log.exception(e) self.excel_audit.write_data(row=case_id + 1, column=8, value="失败") raise e else: log.info("用例执行通过:{}".format(item["title"])) self.excel_audit.write_data(row=case_id + 1, column=8, value="通过")
Author:hw data:2020/10/28 17:39 ============ """ import unittest import os from common.handle_excel import Excel from common import myddt from common.handle_log import Log from common.handle_path import DATA_DIR import requests import random import json from common.handle_conf import conf from common.handle_db import db sh = Excel(os.path.join(DATA_DIR, "case.xlsx"), "register") sh.open() case_data = sh.read_excel() log = Log.create_log() @myddt.ddt class TestRegister(unittest.TestCase): @myddt.data(*case_data) def test_register(self, item): if "#mobile_phone#" in item["params"]: self.mobile_id = self.random_phone() item["params"] = item["params"].replace("#mobile_phone#", str(self.mobile_id)) params = eval(item["params"]) url = conf.get("api", "baseUrl") + item["url"]
# -*- coding: utf-8 -*- import unittest import json from lib.ddt import ddt, data from common.handle_log import Log from common.handle_request import Request from common.handle_excel import Excel from common.handle_dir import CASE_FILE_PATH, CONFIGS_FILE_PATH from common.handle_conf import Config from common.handle_context import Context from common.handle_mysql import MySql cf = Config(CONFIGS_FILE_PATH) # 配置文件对象 file = Excel(CASE_FILE_PATH, "tag_list") # excel文件 data_list = file.get_cases() # 获取文件中的数据 log = Log().get_logger() # 日志对象 req = Request() # 请求对象 # 创建mysql连接对象(连接的是payment库) mysql = MySql(cf.get_value("db_msg", "user1"), cf.get_value("db_msg", "pwd1"), cf.get_value("db_msg", "database1")) @ddt class Testcase(unittest.TestCase): @classmethod def setUpClass(cls): """ 初始化 :return: """
import jsonpath import ddt import allure from common.handle_EnvData import clear_data from common.handle_excel import Excel from common.handle_logger import logger from common.handle_request import send_request """ 请求播放接口 """ # 读取Excel文件数据 s = Excel("播放") cases = s.read_all_data() @allure.feature("请求播放地址") @ddt.ddt() class Test_paly (object): # 设置前置 @classmethod def setup_class(cls): logger.info("===== 开始测试 =====") # 清理EnvData类中可能设置的属性 clear_data() # 设置后置 @classmethod
class TestWithdrawV3(unittest.TestCase): """测试提现接口的测试用例类""" excel = Excel(file_name=os.path.join(DATA_DIR, 'cases.xlsx'), sheet_name='withdraw') case = excel.read_excel() print() @classmethod def setUpClass(cls): """测试用例类执行""" fixture.setup_login(TestWithdrawV3) @myddt.data(*case) def test_withdraw(self, item): """测试提现接口的方法""" # 请求接口 url = conf.get('env', 'base_url') + item['url'] # 请求参数 # if '#member_id#' in item['data']: # item['data'] = item['data'].replace('#member_id#', str(self.member_id)) # params = eval(item['data']) params = eval(replace_data(item['data'], TestWithdrawV3)) # 请求参数中添加 timestamp 和 sign crypt_info = HandleSign.generate_sign(self.token_value) params['timestamp'] = crypt_info['timestamp'] params['sign'] = crypt_info['sign'] # 请求头v2 # headers = eval(conf.get('env', 'headers')) # 请求头v3 headers = eval(conf.get('env', 'headersV3')) headers['Authorization'] = self.token method = item['method'] # 获取数据库中的提现之前的余额 sql = item['check_sql'] if sql: s_amount = db.find_data(sql.format( self.member_id))[0]['leave_amount'] # 预期结果 expected = eval(item['expected']) # 请求参数获得实际结果 response = requests.request(method=method, url=url, headers=headers, json=params) res = response.json() print('预期结果:', expected) print('实际结果:', res) # 断言结果 try: if sql: e_amount = db.find_data(sql.format( self.member_id))[0]['leave_amount'] self.assertTrue(float(s_amount - e_amount), jsonpath(res, '$..leave_amount')[0]) self.assertEqual(jsonpath(res, '$.code')[0], expected['code']) self.assertEqual(jsonpath(res, '$.msg')[0], expected['msg']) except AssertionError as e: log.error('用例{}:执行失败'.format(item['title'])) log.exception(e) self.excel.write_excel(row=item['case_id'] + 1, column=8, value='未通过') raise e else: log.info('用例{}:执行通过'.format(item['title'])) self.excel.write_excel(row=item['case_id'] + 1, column=8, value='通过')
Author:hw data:2020/11/17 12:33 ============ """ import jsonpath import requests from common.handle_db import db from common.handle_conf import conf from common.handle_path import DATA_DIR from common.handle_excel import Excel from common import myddt from common.handle_log import Log import os import unittest from common.handle_replacedata import replace_data sh = Excel(os.path.join(DATA_DIR, "case.xlsx"), "loanaudit") sh.open() case_data = sh.read_excel() log = Log.create_log() @myddt.ddt class TestAudit(unittest.TestCase): @classmethod def setUpClass(cls): #管理员账户登录并新增项目 url = conf.get("api", "baseUrl") + "/member/login" params = { "mobile_phone": conf.get("testdata", "admin_mobile"), "pwd": conf.get("testdata", "admin_pwd") }
class TestInvest(unittest.TestCase): """投资项目的接口""" excel = Excel(os.path.join(DATA_DIR, "cases.xlsx"), "invest") cases = excel.read_data() @classmethod def setUpClass(cls): """投资接口的前置条件""" # 1、登录(三个用户) # 管理员 fixture.setup_login_admin(cls) # 借款人 fixture.setup_login(cls) # 投资人 fixture.setup_login_invest(cls) # 2、添加项目(借款人) """添加项目,提取项目id""" fixture.setup_add(cls) # 3、审核项目(管理员) aduit_url = conf.get("env", "base_url") + "/loan/audit" params = {"loan_id": cls.loan_id, "approved_or_not": True} headers = eval(conf.get("env", "headers")) headers["Authorization"] = cls.admin_token response = requests.request(url=aduit_url, method="patch", json=params, headers=headers) # print("审核的结果:", response.json()) @data(*cases) def test_invest(self, item): """执行投资的用例""" # 第一步:准备用例数据 url = conf.get("env", "base_url") + item["url"] params = eval(replace_data(item["data"], TestInvest)) headers = eval(conf.get("env", "headers")) headers["Authorization"] = self.invest_token method = item["method"] expected = eval(item["expected"]) # 用例执行之前查询sql if item["check_sql"]: # 查询投资表记录 sql1 = "SELECT * FROM futureloan.invest WHERE member_id={} and loan_id={}".format( self.invest_member_id, self.loan_id) # 查询用户余额 sql2 = "SELECT leave_amount FROM futureloan.member where id={}".format( self.invest_member_id) # 查询流水记录 sql3 = "SELECT * FROM futureloan.financelog WHERE pay_member_id={}".format( self.invest_member_id) # 查询 # 用例执行之前投资记录的条数 s_invest = len(db.find_data(sql1)) # 用例执行之前投资用户的余额 s_amount = db.find_data(sql2)[0]["leave_amount"] # 用例执行之前流水记录表用户的的流水记录条数 s_financelog = len(db.find_data(sql3)) # 第二步:请求接口,获取实际结果 response = requests.request(url=url, method=method, headers=headers, json=params) res = response.json() print("预期结果:", expected) print("实际结果:", response.text) # 第三步:断言 try: self.assertEqual(expected["code"], res["code"]) self.assertEqual(expected["msg"], res["msg"]) # 用例执行之前查询sql if item["check_sql"]: # 查询投资表记录 sql1 = "SELECT * FROM futureloan.invest WHERE member_id={} and loan_id={}".format( self.invest_member_id, self.loan_id) # 查询用户余额 sql2 = "SELECT leave_amount FROM futureloan.member where id={}".format( self.invest_member_id) # 查询流水记录 sql3 = "SELECT * FROM futureloan.financelog WHERE pay_member_id={}".format( self.invest_member_id) # 查询 # 用例执行之后投资记录的条数 e_invest = len(db.find_data(sql1)) # 用例执行之后投资用户的余额 e_amount = db.find_data(sql2)[0]["leave_amount"] # 用例执行之后流水记录表用户的的流水记录条数 e_financelog = len(db.find_data(sql3)) # 断言比对 # 1、比对执行前后投资表记录数量是否+1 self.assertEqual(1, e_invest - s_invest) # 2、对比用户余额 self.assertEqual(params["amount"], s_amount - e_amount) # 3、比对执行前后流水记录表记录数量是否+1 self.assertEqual(1, e_financelog - s_financelog) except AssertionError as e: log.error("用例{},执行未通过".format(item["title"])) log.exception(e) raise e else: log.info("用例{},执行通过".format(item["title"]))
# -*- coding:utf-8 -*- import unittest import json from lib.ddt import ddt, data from common.handle_log import Log from common.handle_request import Request from common.handle_excel import Excel from common.handle_dir import CASE_FILE_PATH, CONFIGS_FILE_PATH from common.handle_conf import Config from common.handle_context import Context cf = Config(CONFIGS_FILE_PATH) # 配置文件对象 file = Excel(CASE_FILE_PATH, "group_login") # excel文件 data_list = file.get_cases() # 获取文件中的数据 log = Log().get_logger() # 日志对象 req = Request() # 请求对象 @ddt class Testcase(unittest.TestCase): @classmethod def setUpClass(cls): """ 初始化 :return: """ log.info("{:*^40s}".format("运营商登录开始执行用例")) @classmethod def tearDownClass(cls):
class TestInvestV3(unittest.TestCase): excel = Excel(file_name=os.path.join(DATA_DIR, 'cases.xlsx'), sheet_name='invest') cases = excel.read_excel() @classmethod def setUpClass(cls): # 借款人登录 fixture.setup_login(TestInvestV3) # 投资人登录 fixture.setup_login_invest(TestInvestV3) # 管理员登录 fixture.setup_login_admin(TestInvestV3) # 添加项目 fixture.setup_add(TestInvestV3) # 审核项目 fixture.set_up_audit(TestInvestV3) @myddt.data(*cases) def test_invest(self, item): # 请求数据准备 url = conf.get('env', 'base_url') + item['url'] # 请求头 v2 # headers = eval(conf.get('env', 'headers')) # 请求头v3 headers = eval(conf.get('env', 'headersV3')) headers['Authorization'] = self.invest_token params = eval(replace_data(item['data'], TestInvestV3)) # 请求参数添加timestamp和sign crypt_info = HandleSign.generate_sign(self.invest_token_value) params['timestamp'] = crypt_info['timestamp'] params['sign'] = crypt_info['sign'] method = item['method'] # 预计结果 expected = eval(item['expected']) # 数据库判断逻辑(请求接口之前) if item['check_sql']: # 查询投资表记录 sql1 = "SELECT * FROM futureloan.invest WHERE member_id={} and loan_id={}".format( self.invest_member_id, self.loan_id) # 查询用户余额 sql2 = "SELECT leave_amount FROM futureloan.member where id={}".format( self.invest_member_id) # 查询流水记录 sql3 = "SELECT * FROM futureloan.financelog WHERE pay_member_id={}".format( self.invest_member_id) # 用例执行之前投资记录的条数 s_invest = len(db.find_data(sql1)) # 用例执行之前投资用户的余额 s_amount = db.find_data(sql2)[0]['leave_amount'] # 用例执行之前流水记录表用户的流水记录条数 s_financelog = len(db.find_data(sql3)) # 实际结果 response = requests.request(method=method, url=url, json=params, headers=headers) res = response.json() print('请求参数', params) print('预期结果:', expected) print('实际结果:', res) # 断言 try: self.assertEqual(res['code'], expected['code']) self.assertEqual(res['code'], expected['code']) # 数据库判断逻辑(请求接口之后) if item['check_sql']: # 查询投资表记录 sql1 = "SELECT * FROM futureloan.invest WHERE member_id={} and loan_id={}".format( self.invest_member_id, self.loan_id) # 查询用户余额 sql2 = "SELECT leave_amount FROM futureloan.member where id={}".format( self.invest_member_id) # 查询流水记录 sql3 = "SELECT * FROM futureloan.financelog WHERE pay_member_id={}".format( self.invest_member_id) # 用例执行之后投资记录的条数 e_invest = len(db.find_data(sql1)) # 用例执行之后投资用户的余额 e_amount = db.find_data(sql2)[0]["leave_amount"] # 用例执行之后流水记录表用户的的流水记录条数 e_financelog = len(db.find_data(sql3)) # 断言判断 # 1、对比执行前后投资表记录数量是否+1 self.assertEqual(1, e_invest - s_invest) # 2、对比用户余额 self.assertEqual(params['amount'], s_amount - e_amount) # 3、对比执行前后流水记录表记录数量是否+1 self.assertEqual(1, e_financelog - s_financelog) except AssertionError as e: log.error('用例{},执行失败'.format(item['title'])) log.exception(e) self.excel.write_excel(row=item['case_id'] + 1, column=8, value='未通过') raise e else: log.info('用例{},执行成功'.format(item['title'])) self.excel.write_excel(row=item['case_id'] + 1, column=8, value='通过')