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"]))
def test_login(self, item): # 1. 准备测试数据 url = conf.get("env", "base_url") + item["url"] method = item["method"] params = eval(item["data"]) expected = eval(item["expected"]) # 2. 请求接口,获取实际结果 res = requests.request(method, url, json=params).json() print("-------当前执行的用例是:{}----------".format(item["title"])) print("请求参数:", params) print("预期结果:", expected) print("实际结果:", res) print("===============执行结束===============\n") # 3. 断言 try: assert_dict_item(expected, res) except AssertionError as e: log.exception(e) log.error("--测试用例:{}--执行失败".format(item["title"])) raise e else: log.info("--测试用例:{}--执行通过".format(item["title"]))
def wait_element_presence(self, locator, img_info, timeout=15, poll_frequency=0.5): start_time = time.time() try: # 等待元素被加载 ele = WebDriverWait(self.driver, timeout, poll_frequency).until( EC.presence_of_element_located(locator)) except Exception as e: # 输出日志 log.error("元素--{}--等待可见超时".format(locator)) log.exception(e) # 对当前页面进行截图,格式:时间_页面_操作.png file_name = "{}_{}.png".format(start_time, img_info) file_path = os.path.join(ERROR_IMAGE, file_name) self.driver.save_screenshot(file_path) log.info("错误页面截图成功,图片保存的路径:{}".format(file_path)) raise e else: # 元素等待之后获取时间 end_time = time.time() log.info("元素--{}--等待成功,等待时间是{}秒".format(locator, end_time - start_time)) return ele
def test_info(self, item): # 请求接口 url = conf.get('env', 'base_url') + replace_data(item['url'], TestInfo) # 请求方法 method = item['method'] # 请求头 headers = eval(conf.get('env', 'headers')) 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='通过')
def wait_ele_be_clickable(self, loc, loc_desc='', timeout=20, poll_time=0.5): """ 等待元素可点击 :param loc: 元素定位器 ——> :(BY.xxx,'表达式') :param loc_desc: 元素文本的描述(记录日志时使用) :param timeout: 最大等待时间 :param poll_time: 等待的轮询间隔 :return: 定位到的element """ try: ele = WebDriverWait(self.driver, timeout=timeout, poll_frequency=poll_time).until( EC.element_to_be_clickable(loc)) except Exception as e: log.error('等待元素-【{}】-可点击超时'.format(loc_desc)) log.exception(e) self.page_save_screenshot(loc_desc) raise e else: log.info('等待元素-【{}】-可点击成功'.format(loc_desc)) return ele
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))
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='通过')
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))
def test_register(self, item): """测试注册的测试用例方法""" # 请求数据 """参数化开始""" # 判断请求参数中是否有手机号,需要替换 if "*phone*" in item['data']: phone = self.random_phone() # 将参数中的*phone*替换为随机生成的手机号 item['data'] = item['data'].replace('*phone*', phone) """参数化结束""" params = eval(item['data']) # 请求头 headers = eval(conf.get('env', 'headers')) # 请求接口 register_url = conf.get('env', 'base_url') + item['url'] # 预期结果 expected = eval(item['expected']) # 请求方式 method = item['method'] # 实际结果 response = requests.request(method=method, json=params, url=register_url, headers=headers) res = response.json() print('预期结果:', expected) print('请求参数:', params) print('实际结果:', res) # 断言判断 try: self.assertEqual(expected['code'], res['code']) self.assertEqual(expected['msg'], res['msg']) # 获取测试数据中的 check_sql 判断注册的信息在数据库中是否存在 check_sql = item['check_sql'] if check_sql: # params['mobile_phone'] 请求参数中的 mobile_phone 的值 res = db.find_data(check_sql.format(params['mobile_phone'])) # 判断res结果是否为空,为空则断言失败,用例执行不通过 self.assertTrue(res) 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='通过')
def generate_phone(self): '''生成随机的手机号码''' phone = "135" num = random.randint(100000000, 999999999) phone += str(num)[1:] # 随机生成的手机号码后,先查询下数据库当中是否这个手机号码,要是存在就不用 query_sql = "SELECT * FROM futureloan.member WHERE mobile_phone={}".format( phone) query_result = self.mysql.get_count(query_sql) if query_result == 0: return phone else: log.info("该随机生成的手机号码{}已经存在!".format(phone))
def test_login_invalid_user(self, test_info, init_web): driver = init_web expected = test_info['expected'] LoginPage(driver).login(test_info["mobile"], test_info["pwd"]) invalid_msg = LoginPage(driver).get_invalid_msg() try: assert invalid_msg == expected except AssertionError as e: log.error("断言失败") log.exception(e) raise e else: log.info("用例执行通过")
def test_add(self, item): # 请求接口的url url = conf.get('env', 'base_url') + item['url'] # 请求参数 params = eval(replace_data(item['data'], TestAddV3)) # 请求参数中添加 timestamp 和sign crypt_info = HandleSign.generate_sign(self.token_value) params['timestamp'] = crypt_info['timestamp'] params['sign'] = crypt_info['sign'] # 请求头 # headers = eval(conf.get('env', 'headers')) # 请求头 V3 headers = eval(conf.get('env', 'headersV3')) 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='通过')
def test_login_success_user(self, test_info, init_web): driver = init_web expected = test_info['expected'] LoginPage(driver).login(test_info["mobile"], test_info["pwd"]) time.sleep(0.5) # 此处发生页面跳转,建议强制等待0.5秒 account_msg = HomePage(driver).get_user_info() try: assert account_msg == expected except AssertionError as e: log.error("断言失败") log.exception(e) raise e else: log.info("用例执行通过")
def test_audit(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.admin_token # 替换用例参数 item["data"] = replace_data(item["data"], TestAuditV3) params = eval(item["data"]) # 请求参数添加timestamp和sign crypt_info = HandleSign.generate_sign(self.admin_token_value) params['timestamp'] = crypt_info['timestamp'] params['sign'] = crypt_info['sign'] # 请求方法 method = item["method"] # 预期结果 expected = eval(item["expected"]) # 第二步:请求接口,获取实际返回的结果 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 item["title"] == "审核通过": TestAuditV3.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='通过')
def click_element(self, loc, loc_desc=''): """ 点击元素 :param loc:元素定位器 ——> :(BY.xxx,'表达式') :param loc_desc:元素文本的描述(记录日志时使用) """ try: self.driver.find_element(*loc).click() except Exception as e: log.error('点击元素-【{}】-失败'.format(loc_desc)) log.exception(e) self.page_save_screenshot(loc_desc) raise e else: log.info('点击元素-【{}】-成功'.format(loc_desc))
def click_element(self, locator, img_info): try: self.driver.find_element(*locator).click() except Exception as e: # 输出日志 log.error("元素--{}--点击元素失败".format(locator)) log.exception(e) # 对当前页面进行截图,格式:时间_页面_操作.png file_name = "{}_{}.png".format(img_info) file_path = os.path.join(ERROR_IMAGE, file_name) self.driver.save_screenshot(file_path) log.info("错误属性截图成功,图片保存的路径:{}".format(file_path)) raise e else: log.info("元素--{}--元素点击成功,".format(locator))
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='通过')
def test_login_username_is_empty(self, test_info, init_web): driver = init_web # 预期结果 expected = test_info["expected"] # 实际结果 LoginPage(driver).login(test_info["mobile"], test_info["pwd"]) # 断言 error_msg = LoginPage(driver).get_error_msg() try: assert error_msg == expected except AssertionError as e: log.error("断言失败") log.exception(e) raise e else: log.info("用例执行通过")
def input_text(self, locator, text_value, img_info): # 文本内容输入 try: self.driver.find_element(*locator).send_keys(text_value) except Exception as e: # 输出日志 log.error("输入文本-{}--失败".format(locator)) log.exception(e) # 对当前页面进行截图,格式:时间_页面_操作.png file_name = "{}_{}.png".format(img_info) file_path = os.path.join(ERROR_IMAGE, file_name) self.driver.save_screenshot(file_path) log.info("错误属性截图成功,图片保存的路径:{}".format(file_path)) raise e else: log.info("输入文本内容--{}--成功,".format(locator))
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="通过")
def get_element(self, loc, loc_desc=''): """ 查找元素 :param loc: 元素定位器 ——> :(BY.xxx,'表达式') :param loc_desc: 元素文本的描述(记录日志时使用) :return: 查找到的元素 """ try: ele = self.driver.find_element(*loc) except Exception as e: log.error('查找元素-【{}】-失败'.format(loc_desc)) log.exception(e) self.page_save_screenshot(loc_desc) raise e else: log.info('查找元素-【{}】-成功'.format(loc_desc)) return ele
def page_save_screenshot(self, loc_desc): """ 页面截图 :param loc_desc: 操作的描述 """ try: # 获取当前时间,并转换为指定格式的字符串 date_desc = time.strftime('%Y-%m-%d %H_%M_%S') filename = date_desc + loc_desc + '.png' file_path = os.path.join(ERROR_IMAGE, filename) self.driver.save_screenshot(file_path) except Exception as e: log.error("对-【{}】--这个操作进行页面截图失败".format(loc_desc)) log.exception(e) raise e else: log.info("对-【{}】--这个操作进行页面截图成功,图片保存为{}".format(loc_desc, filename))
def get_element_text(self, loc, loc_desc=''): """ 获取元素的文本 :param loc: 元素定位器 ——> :(BY.xxx,'表达式') :param loc_desc: 元素文本的描述(记录日志时使用) :return: 元素的text """ try: text = self.driver.find_element(*loc).text except Exception as e: log.error('获取元素-【{}】-文本失败'.format(loc_desc)) log.exception(e) self.page_save_screenshot(loc_desc) raise e else: log.info('获取元素-【{}】-文本成功'.format(loc_desc)) return text
def test_login(self, item): # 准备测试数据 params = eval(item['params']) expected = eval(item['expected']) rows = item['case_id'] + 1 # 请求功能函数 res = login_check(**params) # 断言 try: self.assertEqual(expected, res) except AssertionError as e: self.excel.write_excel(row=rows, column=5, value='未通过') log.error('用例---【{}】----执行失败'.format(item['title'])) log.exception(e) raise e else: self.excel.write_excel(row=rows, column=5, value='通过') log.info('用例---【{}】----执行通过'.format(item['title']))
def get_element_attr(self, loc, attr, loc_desc=''): """ 获取元素的属性 :param loc: 元素定位器 ——> :(BY.xxx,'表达式') :param attr: 元素的属性 :param loc_desc: 元素文本的描述(记录日志时使用) :return: 元素的属性 """ try: text = self.driver.find_element(*loc).get_attribute(attr) except Exception as e: log.error('获取元素-【{}】-属性失败'.format(loc_desc)) log.exception(e) self.page_save_screenshot(loc_desc) raise e else: log.info('获取元素-【{}】-属性成功'.format(loc_desc)) return text
def input_send_keys(self, loc, value, loc_desc=''): """ 向input框中输入数据 :param loc: 元素定位器 ——> :(BY.xxx,'表达式') :param value: 输入的内容 :param loc_desc: 元素文本的描述(记录日志时使用) """ try: ele = self.driver.find_element(*loc) ele.clear() ele.send_keys(value) except Exception as e: log.error('向input元素-【{}】-输入值失败'.format(loc_desc)) log.exception(e) self.page_save_screenshot(loc_desc) raise e else: log.info('向input元素-【{}】-输入值成功'.format(loc_desc))
def switch_to_window(self, locator, img_info): try: self.driver.find_element(*locator).click() except Exception as e: # 输出日志 log.error("获取元素-{}--失败".format(locator)) log.exception(e) # 对当前页面进行截图,格式:时间_页面_操作.png file_name = "{}_{}.png".format(img_info) file_path = os.path.join(ERROR_IMAGE, file_name) self.driver.save_screenshot(file_path) log.info("错误属性截图成功,图片保存的路径:{}".format(file_path)) raise e else: # 获取所有的窗口句柄 e_handles = self.driver.window_handles # 切换到新的窗口 self.driver.switch_to.window(e_handles[-1])
def get_element_attribute(self, locator, attr_name, img_info): # "获取元素的文本" try: ele = self.driver.find_element(*locator) attr_value = ele.get_attribute(attr_name) except Exception as e: # 输出日志 log.error("元素--{}--获取属性失败".format(locator)) log.exception(e) # 对当前页面进行截图,格式:时间_页面_操作.png file_name = "{}_{}.png".format(img_info) file_path = os.path.join(ERROR_IMAGE, file_name) self.driver.save_screenshot(file_path) log.info("错误属性截图成功,图片保存的路径:{}".format(file_path)) raise e else: log.info("元素--{}--获取属性成功".format(locator)) return attr_value
def test_recharge(self, item): case_id = item["case_id"] # 第一步:准备数据 url = conf.get("env", "base_url") + item["url"] # 请求参数 item["data"] = replace_data(item["data"],TestRecharge) 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(e_money - s_money), params["amount"]) except AssertionError as e: log.error("用例{},执行未通过".format(item["title"])) self.excel.write_data(row=case_id +1,column=8,value="失败") log.exception(e) raise e else: log.info("用例{},执行通过".format(item["title"])) self.excel.write_data(row=case_id + 1, column=8, value="通过")
def get_element_text(self, locator, img_info): # "获取元素的文本" start_time = time.time() try: text = self.driver.find_element(*locator).text except Exception as e: # 输出日志 log.error("元素--{}--获取文本失败".format(locator)) log.exception(e) # 对当前页面进行截图,格式:时间_页面_操作.png file_name = "{}_{}.png".format(start_time, img_info) file_path = os.path.join(ERROR_IMAGE, file_name) self.driver.save_screenshot(file_path) log.info("错误页面截图成功,图片保存的路径:{}".format(file_path)) raise e else: log.info("元素--{}--获取文本成功".format(locator)) return text