def in_web(): common() yield driver #函数后置 MyLog().info("关闭浏览器") MyLog().info("############################") driver.quit()
def send_email(email_info: EmailInfo): ret = False message = MIMEMultipart() message['From'] = email_info.sender.get_formataddr() message['To'] = email_info.receivers.get_formataddr() message['Subject'] = email_info.message message.attach(MIMEText(email_info.title, email_info.message_type, 'utf-8')) for item in email_info.files: message.attach(item.get_attr()) try: server = smtplib.SMTP_SSL(EmailSMTPServer.host, EmailSMTPServer.port) server.login(EmailSMTPServer.user, EmailSMTPServer.pwd) server.sendmail(EmailSMTPServer.user, email_info.receivers.get_address_list(), message.as_string()) server.quit() MyLog.logcat('发送成功') ret = True except smtplib.SMTPException as e: MyLog.logcat('Error,无法发送邮件! \n ' + str(e)) return ret
def do_sql(self, sql, state='all', mode='query'): ''' :param sql: :param state: 返回多条还是单挑 :param mode: 查询还是其他操作,查询不需要commit,其他操作需要 :return: ''' #创建游标 cursor = self.connect_mysql().cursor() #写sql语句 MyLog().info(f"执行sql语句:{sql}") cursor.execute(sql) res = None if state == 'all': res = cursor.fetchall() #返回列表嵌套元组,多条数据 if state == 1: res = cursor.fetchone() if mode is not 'query': self.connect_mysql().commit() #关闭游标 cursor.close() #关闭连接 self.connect_mysql().close() MyLog().info(f"执行完成sql语句,返回为:{res}") if res is not None: res = res[0] return res
def login(): common() LoginPage(driver).login("yang", "123456", "abcd") yield driver # 类后置 MyLog().info("关闭浏览器") MyLog().info("############################") driver.quit()
def common(): global driver url = ReadConfig().read_config(test_config_path, "project", "url") # 启动浏览器前置 MyLog().info("###########################") MyLog().info("启动浏览器") driver = webdriver.Chrome() MyLog().info(f"driver.get({url})") MyLog().info(type(url)) driver.get(url) driver.maximize_window()
def send_keys(self, loc, para): ''' :param loc: 位置 :param para: 从数据库读的可能为空,读出来为None :return: ''' MyLog().info(f"清空{loc}的值") self.find_element(loc).clear() if (para == None): MyLog().info("从数据库读的值为空") self.find_element(loc).send_keys(" ") else: self.find_element(loc).send_keys(para)
def test_api(self, item): global Actual MyLog().my_log("INFO", "————————现在执行的用例是:{0}————————".format(item["title"])) MyLog().my_log( "INFO", "*********此条用例不需要数据库校验:{}*********".format(item["title"])) MyLog().my_log("INFO", "————————开始http 接口请求————————") MyLog().my_log("INFO", "请求url为:{}".format(item["url"])) MyLog().my_log("INFO", "请求参数为:{}".format(item["data"])) res = HttpRequests().http_requests(item["url"], eval(item["data"]), item["method"], getattr(GetData, "Cookie")) MyLog().my_log("INFO", "请求结果为:{}".format(res.json())) MyLog().my_log("INFO", "————————完成http 接口请求————————") if res.cookies: setattr(GetData, "Cookie", res.cookies) try: self.assertEqual(item["ExpectedResult"], res.json()["status"]) Actual = "Pass" except AssertionError as e: MyLog().my_log("ERROR", "*****************出错啦!错误为:{}*********".format(e)) Actual = "Fail" raise e finally: res_code_massage = res.json() if "data" in res_code_massage: res_code_massage.pop("data") ReadExcel().write_back(item["sheet_name"], item["id"] + 1, 9, str(res_code_massage)) ReadExcel().write_back(item["sheet_name"], item["id"] + 1, 10, Actual)
def test_api(self,item): res=HttpRequest.http_request(item['method'],item['url'],eval(item['data']),getattr(GetCookie,'Cookie')) if res.cookies: #利用反射存储cookie值 setattr(GetCookie,'Cookie',res.cookies) try: self.assertEqual(str(item['expected']),res.json()['resultcode']) TestResult='PASS' except AssertionError as e: TestResult='Failed' MyLog.error("执行用例出错:{0}".format(e)) raise e finally: DoExcel.write_back(test_case_path,item['sheet_name'],item['case_id']+1,res.text,TestResult) MyLog.info("获取到的结果是:{0}".format(res.text))
def switch_frame(self, loc): # MyLog().info(f"等待元素{loc}") # # WebDriverWait(self.driver, 10).until(EC.frame_to_be_available_and_switch_to_it(loc)) # WebDriverWait(self.driver, 10).until(EC.visibility_of_element_located(loc)) MyLog().info(f"准备进入iframe:{loc}") #括号里面应该是一个对象,不用再次等待 self.driver.switch_to.frame(self.find_element(loc))
def find_element(self, loc): try: MyLog().info(f"查找元素{loc}") WebDriverWait(self.driver, 10).until(EC.visibility_of_element_located(loc)) MyLog().info(f"查找元素{loc}成功") ele = self.driver.find_element(*loc) except Exception as e: MyLog().error(u"出现的异常是%s" % e) #异常截图 nowTime = time.strftime("%Y%m%d-%H-%M-%S") t = self.driver.get_screenshot_as_file(img_path + u'%s.jpg' % nowTime) #异常截图的路径 MyLog().info(u"截图结果为:%s" % t) else: return ele
def http_request(method,url,data,cookie=None): try: if method.upper()=='GET': res=requests.get(url,data,cookies=cookie) elif method.upper() == 'POST': res=requests.post(url,data,cookies=cookie) else: MyLog.info("请求的方法不对") except Exception as e: MyLog.error("请求报错了:{0}".format(e)) raise e return res
def http_request(url, data, method, cookies=None, headers=None): requests.packages.urllib3.disable_warnings() # headers = {"Content-Type": "application/json"} # data = json.dumps(data) if method == "get": MyLog().info("接口{0}的请求参数是:{1}".format(url, data)) try: r = requests.get(url=url, data=data, headers=headers, cookies=cookies, verify=False) response = r.text print("get请求结果为:{}".format(response)) MyLog().info("接口{0}的请求结果是:{1}".format(url, response)) return r except BaseException as e: print("get请求错误,错误原因:{}".format(e)) MyLog().info("get请求错误,错误原因:{}".format(e)) elif method == "post": MyLog().info("接口{0}的请求参数是:{1}".format(url, data)) try: r = requests.post(url=url, data=data, headers=headers, cookies=cookies, verify=False) response = r.text print("post请求结果为:{}".format(response)) MyLog().info("接口{0}的请求结果是:{1}".format(url, response)) return r except BaseException as e: print("post请求错误,错误原因:{}".format(e)) MyLog().info("post请求错误,错误原因:{}".format(e)) elif method == "put": MyLog().info("接口{0}的请求参数是:{1}".format(url, data)) try: r = requests.put(url=url, data=data, headers=headers, cookies=cookies, verify=False) response = r.text print("put请求结果为:{}".format(response)) MyLog().info("接口{0}的请求结果是:{1}".format(url, response)) return r except BaseException as e: print("put请求错误,错误原因:{}".format(e)) MyLog().info("put请求错误,错误原因:{}".format(e))
def http_requests( self, url, data, method, cookie=None, ): try: res = None if method == "get": res = requests.get(url, params=data, cookies=cookie) elif method == "post": res = requests.post(url, json=data, cookies=cookie) elif method == "put": res = requests.put( url, json=data, cookies=cookie, ) elif method == "delete": res = requests.delete(url, cookies=cookie) return res except Exception as e: MyLog().my_log("ERROR", "出错啦!错误为:{}".format(e))
# run(test_data) # test_data=DoExcel().get_data("test_data/test_data.xlsx","register") # run(test_data) # test_data=DoExcel().get_data("test_data/test_data.xlsx","recharge") # run_recharge(test_data,"recharge") import unittest import HTMLTestRunner from tools.project_path import * from tools.test_http_request import TestHttpRequest from tools.my_log import MyLog from tools.send_email import sendEmail my_logger = MyLog() suite = unittest.TestSuite() # suite.addTest(TestHttpRequest("test_api"))#测试类实例 loader = unittest.TestLoader() #并行多个用例方法一 # suite.addTest(loader.loadTestsFromModule(test_login)) # suite.addTest(loader.loadTestsFromModule(test_recharge)) suite.addTest(loader.loadTestsFromTestCase(TestHttpRequest)) with open(test_report_path, 'wb') as file: #执行用例 my_logger.info("开始执行用例") runner = HTMLTestRunner.HTMLTestRunner(stream=file, verbosity=2,
def tearDown(self): MyLog().my_log("INFO", "————————测试执行结束————————")
def init_app(): MyLog.set_status(MyLog.status_debug) EmailSMTPServer.init("server_info.json")
def init_app(): MyLog.set_status(0)
def refresh(self): MyLog().info("#########刷新##########") self.driver.refresh()
def refuse_alert(self): MyLog().info("进入取消alert") self.driver.switch_to.alert.dismiss()
def accept_alert(self): MyLog().info("进入确认alert") self.driver.switch_to.alert.accept()
def setUp(self): MyLog().my_log("INFO", "————————《开始测试》————————")
# -*- conding: utf-8 -*- # @Time :2019/7/26 10:10 # Author :chengjin # @Email :[email protected] # @File :http_request.py import requests from tools.my_log import MyLog my_logger = MyLog() class HttpRequest: @staticmethod def http_request(url, data, http_method, cookie=None): try: if http_method == "get": res = requests.get(url, data, cookies=cookie) elif http_method == "post": res = requests.post(url, data, cookies=cookie) else: my_logger.info("输入请求方法不对") except Exception as e: my_logger.error("请求报错了:{}".format(e)) raise e return res if __name__ == '__main__': #注册 register_url = "https://www.ketangpai.com/UserApi/login" register_data = { "email": "*****@*****.**",
def delete_menu(self): self.b.refresh() #刷新 self.in_menu_manage() MyLog().info(f"按钮位置:{menu.dele_menu_but}") self.b.click(menu().dele_menu_but) self.b.accept_alert()
def test_usedCar_collection(self, item): print("用例名称:{}".format(item["title"])) # print("car_id:{}".format(getattr(GetData,'car_id'))) if item['url'].find('#{car_id}') != -1: '''从反射里拿到car_id替换#{car_id}''' item['url'] = item['url'].replace('#{car_id}', getattr(GetData, 'car_id')) if item['url'].find('#{car_info_id}') != -1: '''从反射里拿到{car_info_id}替换#{car_info_id}''' item['url'] = item['url'].replace('#{car_info_id}', getattr(GetData, 'car_info_id')) if item['data'].find('${car_num}') != -1: '''从反射里拿到车牌号替换${car_num}''' item['data'] = item['data'].replace('${car_num}', getattr(GetData, 'car_num')) else: pass d = eval(item["data"]) print("url:{}".format(item['url'])) # 如果参数类型是json,要在header里加上“Content-Type:application/json”,并且要对data进行处理 if item['contentType'] == 'json': headers["Content-Type"] = "application/json" d = json.dumps(eval(item["data"])) res = HttpResuest.http_request(url=item['url'], data=d, method=item['method'], headers=headers, cookies=cookies) # 请求结束后删除headers里面的Content-Type,因为后续接口的传参格式不一定是json del headers["Content-Type"] else: res = HttpResuest.http_request(url=item['url'], data=d, method=item['method'], headers=headers, cookies=cookies) r = json.loads(res.text) # 将response格式转化为python字典格式 print("code:{}".format(r["code"]), "message:{}".format(r["message"])) if item['title'] == '新建线索': '''将新建线索生成的车辆id保存,用于下一个接口查询car_id''' car_id = r["data"]["id"] setattr(GetData, 'car_id', str(car_id)) # MyLog().info('存储car_id为{0}'.format(car_id)) print('存储car_id为{0}'.format(car_id)) elif item['title'] == '获取car_info_id': '''将新建线索生成的车辆的car_info_id获取到并储存起来,用于后续接口''' car_info_id = r["data"]["car_info_id"] setattr(GetData, 'car_info_id', str(car_info_id)) # MyLog().info('存储car_id为{0}'.format(car_id)) print('存储car_info_id为{0}'.format(car_info_id)) try: self.assertEqual(str(r["code"]), str(item['excepted'])) test_result = 'pass' except AssertionError as e: test_result = 'fail' MyLog().error("执行用例出错:{0}".format(e)) print(e) raise finally: '''结果写回excel''' DoExcle(test_data_path).write_back(item['sheetname'], int(item['case_id']) + 1, 9, str(r)) DoExcle(test_data_path).write_back(item['sheetname'], int(item['case_id']) + 1, 10, test_result)
#作者:HP #日期:2020-03-20 20:48 #文件:test_http_request import unittest from tools.http_request import HttpRequest from tools.get_data import GetData from ddt import ddt, data # from tools.do_excel import DoExcel from tools.project_path import * from tools.my_log import MyLog my_logger = MyLog() test_data = DoExcel.get_data(test_case_path) #执行所有用例 @ddt #对数据进行分离 class TestHttpRequest(unittest.TestCase): def setUp(self): pass @data(*test_data) def test_api(self, item): res = HttpRequest.http_request(item['url'], eval(item['data']), item['http_method'], getattr(GetData, 'Cookie')) if res.cookies: #利用反射存取cookies setattr(GetData, 'Cookie', res.cookies) try: self.assertEqual(item['expected'], res.json()['stat'])
def click(self, loc): MyLog().info(f"点击元素{loc}") self.find_element(loc).click()
def get_text(self, loc): MyLog().info(f"获取元素{loc}的值") text = self.find_element(loc).text MyLog().info(f"值为{text}") return text
def test_usedCar_collection(self, item): print("用例名称:{}".format(item["title"])) # print("car_id:{}".format(getattr(GetData,'car_id'))) if item['url'].find('#{car_id}') != -1: '''从反射里拿到car_id替换${car_id}''' item['url'] = item['url'].replace('#{car_id}', getattr(GetData, 'car_id')) if item['url'].find('#{car_info_id}') != -1: '''从反射里拿到{car_info_id}替换#{car_info_id}''' item['url'] = item['url'].replace('#{car_info_id}', getattr(GetData, 'car_info_id')) if item['data'].find('${car_num}') != -1: '''从反射里拿到车牌号替换${car_num}''' item['data'] = item['data'].replace('${car_num}', getattr(GetData, 'car_num')) else: pass if item['data'].find('${car_num}') != -1: '''从反射拿到生成的car_num,替换${car_num}''' item['data'] = item['data'].replace( '${car_num}', str(getattr(GetData, 'car_num'))) else: pass #对参数中的的嵌套字典进行处理 d = eval(item["data"]) if "inspection" in d.keys(): d["inspection"] = json.dumps(d["inspection"]) elif "info" in d.keys(): d["info"] = json.dumps(d["info"]) print("url:{}".format(item['url'])) MyLog().info("请求的参数是:{0}".format(d)) res = HttpResuest.http_request(url=item['url'], data=d, method=item['method'], headers=headers, cookies=cookies) r = json.loads(res.text) # 将response格式转化为python字典格式 print("code:{}".format(r["code"]), "message:{}".format(r["message"])) if item['title'] == '新建线索': '''将新建线索生成的车辆id保存,用于下一个接口查询car_id''' car_id = r["data"]["id"] setattr(GetData, 'car_id', str(car_id)) # MyLog().info('存储car_id为{0}'.format(car_id)) print('存储car_id为{0}'.format(car_id)) elif item['title'] == '获取car_info_id': '''将新建线索生成的车辆的car_info_id获取到并储存起来,用于后续接口''' car_info_id = r["data"]["car_info_id"] setattr(GetData, 'car_info_id', str(car_info_id)) #MyLog().info('存储car_id为{0}'.format(car_id)) print('存储car_info_id为{0}'.format(car_info_id)) try: self.assertEqual(str(r["code"]), str(item['excepted'])) test_result = 'pass' except AssertionError as e: test_result = 'fail' MyLog().error("执行用例出错:{0}".format(e)) print(e) raise finally: '''结果写回excel''' DoExcle(test_data_path).write_back(item['sheetname'], int(item['case_id']) + 1, 8, str(r)) DoExcle(test_data_path).write_back(item['sheetname'], int(item['case_id']) + 1, 9, test_result) MyLog().error("获取到的结果是:{0}".format(res))