def put(header, address, request_parameter_type, data=None, timeout=8, files=None): """ put 请求 :param header: 请求头 :param address: host地址 :param request_parameter_type: 接口请求参数格式 (form-data, raw, Restful) :param data: 请求参数 :param timeout: 超时时间 :param files: 文件路径 :return: """ if request_parameter_type == 'raw': data = json.dumps(data) response = requests.put(url=address, data=data, headers=header, timeout=timeout, files=files) try: return response.status_code, response.json() except json.decoder.JSONDecodeError: return response.status_code, '' except simplejson.errors.JSONDecodeError: return response.status_code, '' except Exception as e: logging.exception('ERROR') logging.error(e) raise
def get(header, address, data, timeout=8): """ get 请求 :param header: 请求头 :param address: host地址 :param data: 请求参数 :param timeout: 超时时间 :return: """ response = requests.get(url=address, params=data, headers=header, timeout=timeout) if response.status_code == 301: response = requests.get(url=response.headers["location"]) try: return response.status_code, response.json() except json.decoder.JSONDecodeError: return response.status_code, '' except simplejson.errors.JSONDecodeError: return response.status_code, '' except Exception as e: logging.exception('ERROR') logging.error(e) raise
def get_Browser_Type(self,Browser_type): self.Browser = None if Browser_type : try: if Browser_type == 'Chrome': self.Browser = webdriver.Chrome() self.log.debug('get_Browser {type}'.format(type='Chrome')) self.type_name = 'Chrome' if Browser_type == 'Firefox': self.Browser = webdriver.Firefox() self.log.debug('get_Browser {type}'.format(type='Firefox')) self.type_name = 'Firefox' if Browser_type == 'Ie': self.Browser = webdriver.Ie() self.log.debug('get_Browser {type}'.format(type='Ie')) self.type_name = 'Ie' if Browser_type == 'headless': opt = Options() opt.add_argument('headless') self.Browser = webdriver.Chrome(options=opt) except Exception as e: MyLog.error(str(e)) return None return self.Browser else: return None
def _func(*args, **kwargs): r= func(*args, **kwargs) request = "---------------请求-----------------\n{0}\n{1}\n{2}".format(r.url,dic_to_str(r.request.headers),r.request.body) MyLog.info(request) response = "---------------响应----------------\n{0}\n{1}\n{2}".format(r.status_code,dic_to_str(r.headers),r.text) MyLog.info(response) allure.attach(request,'请求',allure.attachment_type.TEXT) allure.attach(response, '响应', allure.attachment_type.TEXT) return r
def get_relevance(data, relevance_list, relevance): """ 从返回结果中获取关联键的值 :param data: 返回结果 :param relevance_list: 关联键列表 :param relevance: 关联对象 :return: """ # 关联键是否时list if not relevance_list: return relevance logging.debug("从返回结果中根据关联键%s提取值" % relevance_list) if isinstance(relevance_list, list): # 遍历关联键 for j in relevance_list: # 从结果中提取关联键的值 relevance_value = get_value(data, j) if relevance_value: # 考虑到一个关联键,多个值 if j in relevance: if isinstance(relevance[j], list): a = relevance[j] a.append(relevance_value) relevance[j] = a else: a = relevance[j] b = list() b.append(a) b.append(relevance_value) relevance[j] = b else: relevance[j] = relevance_value else: return False else: relevance_value = get_value(data, relevance_list) if relevance_value: # 考虑到一个关联键,多个值 if relevance_list in relevance: if isinstance(relevance_list, list): a = relevance[relevance_list] a.append(relevance_value) relevance[relevance_list] = a else: a = relevance[relevance_list] b = list() b.append(a) b.append(relevance_value) relevance[relevance_list] = a else: relevance[relevance_list] = relevance_value logging.debug("提取后,关联键对象\n%s" % relevance) return relevance
def post(header, address, request_parameter_type, timeout=8, data=None, files=None): """ post请求 :param header: 请求头 :param address: 请求地址 :param request_parameter_type: 请求参数格式(form_data,raw) :param timeout: 超时时间 :param data: 请求参数 :param files: 文件路径 :return: """ if 'form_data' in request_parameter_type: for i in files: value = files[i] if '/' in value: file_parm = i files[file_parm] = (os.path.basename(value), open(value, 'rb')) enc = MultipartEncoder(fields=files, boundary='--------------' + str(random.randint(1e28, 1e29 - 1))) header['Content-Type'] = enc.content_type response = requests.post(url=address, data=enc, headers=header, timeout=timeout) else: response = requests.post(url=address, data=data, headers=header, timeout=timeout, files=files) try: if response.status_code != 200: return response.status_code, response.text else: return response.status_code, response.json() except json.decoder.JSONDecodeError: return response.status_code, '' except simplejson.errors.JSONDecodeError: return response.status_code, '' except Exception as e: logging.exception('ERROR') logging.error(e) raise
def testBankValid(self): """绑定银行卡""" self.cls = common.getXls("testCase.xlsx", "test1") self.log = log.get_log() self.readConfig = ReadConfig.ReadConfig() self.logger = self.log.getLogger() self.Http = configHttp.ConfigHttp() self.HttpUrl = self.Http.setUrl(self.cls.get(9).get("url")) self.logger.info(self.HttpUrl) TempParams = json.loads(self.cls.get(9).get("params")) self.readConfig.setReslConfig("channelId", common.getChannelId()) #TempParams["channelId"] = self.readConfig.getReslConfig("channelId") TempParams["mobile"] = self.readConfig.getReslConfig("mobile") TempParams["idCard"] = self.readConfig.getReslConfig("idnum") TempParams["name"] = self.readConfig.getReslConfig("realname") self.params = json.dumps(TempParams) self.logger.info(self.params) self.Http.setParams(self.params) self.Http.setHeaders("jwt", self.readConfig.getReslConfig("jwt")) self.r = self.Http.post() self.r.status_code self.r.encoding = 'utf-8' self.logger.info("result-----------", self.r.json().get("errorCode")) assert self.r.status_code == 200, "请求失败" assert self.r.json().get("errorCode") == "0000000", "响应失败"
def __init__(self): self.caseListPath = os.path.join(readConfig.rootDir, "caseList") self.caseList = [] self.log = log.get_log() self.logger = self.log.getLogger() self.reportPath = self.log.getReprotPath() self.email = MyEmail.getEmail() self.onOff = self.email.onOff
def __init__(self): global log, logger, reportPath log = Log.get_log() logger = log.get_logger() reportPath = log.get_report_path() self.caseListFile = os.path.join(proDir, "testFile", "caseList.txt") # 测试用例文件夹 self.caseFile = os.path.join(readConfig.proDir, "testCase") print(self.caseFile) # 测试用例名称 self.caseList = []
def save_cookie(header, address, timeout=8, data=None, files=None): """ 保存cookie信息 :param header: 请求头 :param address: 请求地址 :param timeout: 超时时间 :param data: 请求参数 :param files: 文件路径 :return: """ cookie_path = setupMain.PATH + '/aff/data/cookie.txt' response = requests.post(url=address, data=data, headers=header, timeout=timeout, files=files) try: cookie = response.cookies.get_dict() for i in cookie: values = cookie[i] with open(cookie_path, 'w+', encoding='utf-8') as f: f.write(i + "=" + values) logging.debug("cookies已保存,结果为:%s" % (i + "=" + values)) except json.decoder.JSONDecodeError: return response.status_code, '' except simplejson.errors.JSONDecodeError: return response.status_code, '' except Exception as e: logging.exception('ERROR') logging.error(e) raise
def __init__(self): global host, port, timeOut host = localReadConfig.getHttpConfig("host") port = localReadConfig.getHttpConfig("port") #timeout:设置接口连接的最大时间(超过该时间会抛出超时错误) timeOut = localReadConfig.getHttpConfig("timeOut") self.log = log.get_log() self.logger = self.log.getLogger() #headers:定制请求头(headers),例如:content-type = application/x-www-form-urlencoded self.headers = eval(localReadConfig.getHttpConfig("header")) #params:用于传递测试接口所要用的参数,这里我们用python中的字典形式(key:value)进行参数的传递。 self.params = {} self.data = {} #url:显而易见,就是接口的地址url啦 self.url = None self.files = {}
def testImg1(self): """获取图形验证码""" self.cls = common.getXls("testCase.xlsx", "test1") self.log = log.get_log() self.logger = self.log.getLogger() self.Http = configHttp.ConfigHttp() self.HttpUrl = self.Http.setUrl(self.cls.get(0).get("url")) self.logger.info(self.HttpUrl) self.Http.setParams(self.cls.get(0).get("params")) self.r = self.Http.get() self.r.status_code self.r.encoding = 'utf-8' self.r.text self.logger.info(self.r.text) self.logger.info(self.r.status_code) self.imgCodeId = self.r.json().get("data").get("imgCodeId") self.confige.setReslConfig("imgCodeId", self.imgCodeId)
def testImg(self): """获取图形验证码""" self.cls = common.getXls("testCase.xlsx", "test1") self.log = log.get_log() self.logger = self.log.getLogger() self.Http = configHttp.ConfigHttp() self.HttpUrl = self.Http.setUrl(self.cls.get(0).get("url")) self.logger.info(self.HttpUrl) self.Http.setParams(self.cls.get(0).get("params")) self.r = self.Http.get() self.r.status_code self.r.encoding = 'utf-8' self.logger.info("result-----------", self.r.json().get("errorCode")) assert self.r.status_code == 200, "请求失败" assert self.r.json().get("errorCode") == "0000000", "响应失败" self.imgCodeId = self.r.json().get("data").get("imgCodeId") self.confige.setReslConfig("imgCodeId", self.imgCodeId)
def ini_request(case_dict, relevance, _path, result): """ 用例前提条件执行,提取关联键 :param case_dict: 用例对象 :param relevance: 关联对象 :param _path: case路径 :param result: 全局结果 :return: """ if isinstance(case_dict["premise"], list): logging.info("执行测试用例前置接口") with allure.step("接口关联请求"): for i in case_dict["premise"]: relevance_list = relevance.copy() for j in range(0, 3): # 获取前置接口关联数据失败 code, data = send_request(i, case_dict["testinfo"].get("host"), case_dict["testinfo"].get("address"), relevance_list, _path, result) if not data: with allure.step("接口请求失败!等待三秒后重试!"): pass logging.info("接口请求失败!等待三秒后重试!") continue if i["relevance"]: if len(i["relevance"]): relevance = get_relevance(data, i["relevance"], relevance) if isinstance(relevance, bool): with allure.step("从结果中提取关联键的值失败!等待3秒后重试!"): pass logging.info("从结果中提取关联键的值失败!等待3秒后重试!") time.sleep(3) continue else: break else: break else: break if isinstance(relevance, bool): logging.info("从结果中提取关联键的值失败!重试三次失败") result["result"] = False raise failureException("获取前置接口关联数据失败") return relevance
def testLogin(self): """登陆""" self.cls = common.getXls("testCase.xlsx","test1") self.log = log.get_log() self.logger = self.log.getLogger() self.Http = configHttp.ConfigHttp() self.HttpUrl = self.Http.setUrl(self.cls.get(4).get("url")) self.logger.info(self.HttpUrl) TempParams = json.loads(self.cls.get(4).get("params")) self.readConfig = readConfig() TempParams["mobile"] = self.readConfig.getReslConfig("mobile") self.params =json.dumps(TempParams) self.logger.info(self.params) self.Http.setParams(self.params) self.r = self.Http.post() self.r.encoding = 'utf-8' self.logger.info("result-----------",self.r.json().get("errorCode")) assert self.r.status_code == 200,"请求失败" assert self.r.json().get("errorCode") == "0000000","响应失败" assert self.r.status_code == 200
def getChannelId(): log = Log.get_log() logger = log.getLogger() #链接数据库 db = ConfigDB.MyDB() db.connectDB() getChannelIdSql = get_sql("dzjk_user1", "usr_channel", "2") db.executeSQL(getChannelIdSql) ChannelId = db.getOne() if ChannelId: db.closeDB() return ChannelId[0] else: logger.info("获取ChannelId 报错!!!") db.closeDB() # if __name__ == "__main__": # mobielIsExistSql = getChannelId() # print(mobielIsExistSql)
def MobileIsNotExist(): log = Log.get_log() logger = log.getLogger() #链接数据库 db = ConfigDB.MyDB() db.connectDB() mobielIsNotExist = False #获取sql mobielIsExistSql = get_sql("dzjk_user", "usr_info", "1") if mobielIsExistSql is not None: mobielIsExistSql = mobielIsExistSql.strip() #创建moblie c = CreateMobile.CreateMobile() mobile = c.create() mobielIsExistSql = mobielIsExistSql.replace("${mobile}", mobile) db.executeSQL(mobielIsExistSql) if not db.getOne(): mobielIsNotExist = True else: mobielIsNotExist = False db.closeDB() return mobielIsNotExist
def testApply(self): """身份认证""" self.cls = common.getXls("testCase.xlsx", "test1") self.log = log.get_log() self.logger = self.log.getLogger() self.Http = configHttp.ConfigHttp() self.HttpUrl = self.Http.setUrl(self.cls.get(5).get("url")) self.logger.info(self.HttpUrl) TempParams = json.loads(self.cls.get(5).get("params")) self.readConfig = readConfig() TempParams["idNum"] = self.readConfig.getReslConfig("idnum") TempParams["realName"] = self.readConfig.getReslConfig("realname") self.params = json.dumps(TempParams) self.logger.info(self.params) self.Http.setParams(self.params) self.Http.setHeaders("jwt", self.readConfig.getReslConfig("jwt")) self.r = self.Http.post() self.r.status_code self.r.encoding = 'utf-8' self.logger.info("result-----------", self.r.json().get("errorCode")) assert self.r.status_code == 200, "请求失败" assert self.r.json().get("errorCode") == "0000000", "响应失败"
def __init__(self): global host, user, password, port, sender, title, content host = localReadConfig.getEmailConfig("mailHost") user = localReadConfig.getEmailConfig("mailUser") password = localReadConfig.getEmailConfig("mailPass") port = int(localReadConfig.getEmailConfig("port")) sender = localReadConfig.getEmailConfig("sender") title = localReadConfig.getEmailConfig("subject") content = localReadConfig.getEmailConfig("content") self.receiverValue = localReadConfig.getEmailConfig("receiver") self.onOff = localReadConfig.getEmailConfig("onOff") self.receiverList = [] #获取收件人列表 for receiver in str(self.receiverValue).split("/"): self.receiverList.append(receiver) #定义邮件发送时间 date = datetime.now().strftime("%Y-%m-%d %H:%M:%S") self.subject = title + " " + date self.log = log.get_log() self.logger = self.log.getLogger() self.msg = MIMEMultipart("mixed")
from Common import ReadConfig from Common.Log import MyLog as Log from Common import ConfigHttp from Common import ConfigDB from Common import CreateMobile global rootPath rootPath = ReadConfig.rootDir localConfigHttp = ConfigHttp.ConfigHttp() log = Log.get_log() logger = log.getLogger() #从excel文件中读取测试用例 def getXls(xlsName, sheetName): xlsNameValues = {} cls = [] xlsPath = os.path.join(rootPath, "testFile", xlsName) file = open_workbook(xlsPath) sheet = file.sheet_by_name(sheetName) nRows = sheet.nrows clsTitileName = sheet.row_values(0) for i in range(nRows):
def __init__(self): logging.info("初始化关联文件") self.data = ConfRelevance(CONF_PATH, "env").get_relevance_conf()
def send_request(data, host, address,port ,relevance, _path, success): """ 再次封装请求 :param data: 测试用例 :param host: 测试地址 :param address: 接口地址 :param relevance: 关联对象 :param port: 端口地址 :param _path: case路径 :param success: 全局结果 :return: """ # logging = Log.MyLog() config = Config.Config() logging.info("="*100) header = ReadParam.read_param(data["test_name"], data["headers"], relevance, _path, success) # 处理请求头 logging.debug("请求头处理结果: %s" % header) parameter = ReadParam.read_param(data["test_name"], data["parameter"], relevance, _path, success) # 处理请求参数 logging.debug("请求参数处理结果: %s" % header) try: # 如果用例中写了host和address,则使用用例中的host和address,若没有则使用全局的 host = data["host"] except KeyError: pass try: address = data["address"] except KeyError: pass host = config.host # host处理,读取配置文件中的host address = ParamManage.manage(address, relevance) logging.debug("host处理结果: %s" % host) if not host: raise failureException("接口请求地址为空 %s" % data["headers"]) logging.info("请求接口:%s" % str(data["test_name"])) logging.info("请求地址:%s" % data["http_type"] + "://" + host + ":"+ port+address) logging.info("请求头: %s" % str(header)) logging.info("请求参数: %s" % str(parameter)) if data["request_type"].lower() == 'post': if data["file"]: with allure.step("POST上传文件"): allure.attach("请求接口:", str(data["test_name"])) allure.attach("请求地址", data["http_type"] + "://" + host + ":"+ port+address) allure.attach("请求头", str(header)) allure.attach("请求参数", str(parameter)) result = confighttp.post(header=header, address=data["http_type"] + "://" + host + ":"+ port+address, request_parameter_type=data["parameter_type"], files=parameter, timeout=data["timeout"]) else: with allure.step("POST请求接口"): allure.attach("请求接口:", str(data["test_name"])) allure.attach("请求地址", data["http_type"] + "://" + host + ":"+ port+address) allure.attach("请求头", str(header)) allure.attach("请求参数", str(parameter)) logging.info("POST请求接口") result = confighttp.post(header=header, address=data["http_type"] + "://" + host + ":"+ port+address, request_parameter_type=data["parameter_type"], data=parameter, timeout=data["timeout"]) elif data["request_type"].lower() == 'get': with allure.step("GET请求接口"): allure.attach("请求接口:", str(data["test_name"])) allure.attach("请求地址", data["http_type"] + "://" + host + ":"+ port+address) allure.attach("请求头", str(header)) allure.attach("请求参数", str(parameter)) logging.info("GET请求接口") result = confighttp.get(header=header, address=data["http_type"] + "://" + host + ":"+ port+address, data=parameter, timeout=data["timeout"]) elif data["request_type"].lower() == "put": if data["file"]: with allure.step("PUT上传文件"): allure.attach("请求接口:", str(data["test_name"])) allure.attach("请求地址", data["http_type"] + "://" + host + ":"+ port+address) allure.attach("请求头", str(header)) allure.attach("请求参数", str(parameter)) logging.info("PUT上传文件") result = confighttp.put(header=header, address=data["http_type"] + "://" + host + ":"+ port+address, request_parameter_type=data["parameter_type"], files=parameter, timeout=data["timeout"]) else: with allure.step("PUT请求接口"): allure.attach("请求接口:", str(data["test_name"])) allure.attach("请求地址", data["http_type"] + "://" + host + ":"+ port+address) allure.attach("请求头", str(header)) allure.attach("请求参数", str(parameter)) logging.info("PUT请求接口") result = confighttp.put(header=header, address=data["http_type"] + "://" + host + ":"+ port+address, request_parameter_type=data["parameter_type"], data=parameter, timeout=data["timeout"]) elif data["request_type"].lower() == "delete": with allure.step("DELETE请求接口"): allure.attach("请求接口:", str(data["test_name"])) allure.attach("请求地址", data["http_type"] + "://" + host + ":"+ port+address) allure.attach("请求头", str(header)) allure.attach("请求参数", str(parameter)) logging.info("DELETE请求接口") result = confighttp.delete(header=header, address=data["http_type"] + "://" + host + ":"+ port+address, data=parameter, timeout=data["timeout"]) else: result = {"code": False, "data": False} logging.info("接口请求结果:\n %s" % str(result)) return result
def __init__(self): self.log = log.get_log() self.logger = self.log.getLogger() self.db = None self.cursor = None
def __init__(self,Browser_type): self.log = MyLog() self.webdriver = self.get_Browser_Type(Browser_type) self.set_Browser_size() self.conf = Config() self.Browser_type = Browser_type
class PageBase(object): def __init__(self,Browser_type): self.log = MyLog() self.webdriver = self.get_Browser_Type(Browser_type) self.set_Browser_size() self.conf = Config() self.Browser_type = Browser_type def get_Browser_Type(self,Browser_type): self.Browser = None if Browser_type : try: if Browser_type == 'Chrome': self.Browser = webdriver.Chrome() self.log.debug('get_Browser {type}'.format(type='Chrome')) self.type_name = 'Chrome' if Browser_type == 'Firefox': self.Browser = webdriver.Firefox() self.log.debug('get_Browser {type}'.format(type='Firefox')) self.type_name = 'Firefox' if Browser_type == 'Ie': self.Browser = webdriver.Ie() self.log.debug('get_Browser {type}'.format(type='Ie')) self.type_name = 'Ie' if Browser_type == 'headless': opt = Options() opt.add_argument('headless') self.Browser = webdriver.Chrome(options=opt) except Exception as e: MyLog.error(str(e)) return None return self.Browser else: return None def set_Browser_size(self): #默认全屏显示 try: self.webdriver.maximize_window() except Exception as e: self.log.error(e) return None def close_Browser(self): try: self.webdriver.quit() self.log.debug('close_Browser {Browser_type}'.format(Browser_type=self.type_name)) except Exception as e: self.log.error(e) return None def getUrl(self,url): try: self.webdriver.get(url) self.log.debug('Browser get {url}'.format(url=url)) except Exception as e: self.log.error(e) self.allure_pic_report() return None def get_screenshot_as_file(self): '''在本地截图函数''' try: pic_pth = self.conf.pic_path filename = pic_pth +str(time.time()).split('.')[0]+'.png' filename = filename.replace('\\','/') self.webdriver.get_screenshot_as_file(filename) self.log.debug('get_screenshot_as_file {filename}'.format(filename=filename)) return filename except Exception as e: self.log.error(e) return None def allure_pic_report(self,msg = None): '''在allure-report报告中保存截图''' f = self.get_screenshot_as_file() self.log.error('失败的用例,已在异常处截图 :{filename} {msg}'.format(filename = f,msg =msg )) allure.attach.file(f,'失败的用例,已在异常处截图 :{filename} {msg}'.format(filename = f,msg =msg ),allure.attachment_type.PNG) def find_element(self,locator,timeout = 10): ''' 定位元素,参数locator是元祖类型 Usage: locator = ("id","xxx") locator = () driver.find_element(locator) ''' try: element = WebDriverWait(self.webdriver, timeout).until(EC.presence_of_element_located(locator)) return element except Exception as e: self.log.error("not find element by '{way}' ,element name is '{name}'".format(way=locator[0],name=locator[1])) self.allure_pic_report(msg = '没有找到元素 by {way},element name is {name}'.format(way=locator[0],name=locator[1])) self.restart() self.log.error("restar Login") return None raise e def find_elements(self, locator, timeout=10): '''定位一组元素''' try: elements = WebDriverWait(self.webdriver, timeout, 1).until(EC.presence_of_all_elements_located(locator)) return elements except Exception as e: self.log.error("not find elements by '{way}' ,elements name is '{name}'".format(way=locator[0],name=locator[1])) self.allure_pic_report(msg = '没有找到元素 by {way},elements name is {name}'.format(way=locator[0],name=locator[1])) self.restart() self.log.error("restar Login") return [] raise e def click(self, locator): ''' 点击操作 Usage: locator = ("id","xxx") driver.click(locator) ''' element = self.find_element(locator) if element is not None: try: element.click() self.log.debug('click by locator {locator}'.format(locator = locator)) time.sleep(1) except Exception as e: self.log.error(e) self.allure_pic_report() return else: return def clear(self,locator,timeout): try: _element = self.find_element(locator, timeout) # _element.clear() _element.send_keys(Keys.CONTROL+'a') _element.send_keys(Keys.BACKSPACE) except Exception as e: self.log.error(e) return else: return def click_By_element(self,element): if element: try: element.click() self.log.debug('click {element}'.format(element = element.__dict__)) allure.attach('click {element}'.format(element = element.__dict__)) time.sleep(1) except Exception as e: self.log.error(e) allure.attach('click {element}'.format(element = element.__dict__)) return def refresh(self): '''刷新界面''' self.webdriver.refresh() self.log.debug('刷新界面') def is_text_in_element(self, locator, text, timeout=10): ''' 判断文本在元素里,没定位到元素返回False,查找到返回True result = driver.text_in_element(locator, text) ''' try: result = WebDriverWait(self.webdriver, timeout, 1).until(EC.text_to_be_present_in_element(locator, text)) except TimeoutException: self.log.error("元素没定位到:"+str(locator)) return False else: return result def is_text_in_value(self, locator, value, timeout=10): ''' 判断元素的value值,没定位到元素返回false,定位到返回判断结果布尔值 result = driver.text_in_element(locator, text) ''' try: result = WebDriverWait(self.webdriver, timeout, 1).until(EC.text_to_be_present_in_element_value(locator, value)) except TimeoutException: self.log.error("元素没定位到:"+str(locator)) self.allure_pic_report() return False else: return result def is_title(self, title, timeout=10): '''判断title完全等于''' result = WebDriverWait(self.webdriver, timeout, 1).until(EC.title_is(title)) return result def is_alert_present(self, timeout=10): '''判断页面是否有alert,有返回alert(注意这里是返回alert,不是True)没有返回False''' result = WebDriverWait(self.webdriver, timeout, 1).until(EC.alert_is_present()) return result def Select_by_value(self,locator,value,timeout=10): _element = self.find_element(locator) try: s = Select(_element) s.select_by_value(value) self.log.debug('select {value}'.format(value = value)) time.sleep(1) except Exception as e: self.log.error(e) self.allure_pic_report() return def get_text(self, locator,timeout = 3): '''获取文本''' try: element = WebDriverWait(self.webdriver, timeout, 0.5).until(EC.presence_of_element_located(locator)) return element.text except TimeoutException : self.log.debug('元素 {element} 没有找到'.format(element = locator)) self.allure_pic_report() return '' def get_attribute(self, locator, name): '''获取属性''' element = self.find_element(locator) return element.get_attribute(name) def get_element_attribute(self,element,name): '''获取某个元素的属性值''' return element.get_attribute(name) def get_login_url(self): '''获取登陆url''' return str(self.conf.login_url_debug) def login(self,username,password): '''用户登陆''' if self.webdriver: self.webdriver.delete_all_cookies() self.getUrl(self.get_login_url()) self.send_keys(locator = ('id','userName'),text = username) self.send_keys(locator = ('id','password'),text = password) self.click(locator = ('xpath','//*[@id="root"]/div/div/article/form/div[4]/div/div/span/button')) if self.is_text_in_element(locator=('id','login'), text=username) == True: self.log.debug('success login by user {name}'.format(name=username)) return self.webdriver else: return None def send_keys(self,locator,text): element = self.find_element(locator) if element is not None: try: element.clear() self.log.debug('clear') element.send_keys(text) self.log.debug('send {text}'.format(text = text)) except WebDriverException: self.log.debug('元素 {element}不可编辑'.format(element = locator)) self.allure_pic_report() return def restart(self): ''' 关闭浏览器重新打开 ''' allure.attach('重新打开浏览器') self.webdriver.delete_all_cookies() self.webdriver.close() self.webdriver = self.get_Browser_Type(self.Browser_type) self.webdriver.maximize_window() self.get_login_url() self.login(username = '******', password = '******')
def send_request(data, host, address, _path, relevance=None): """ 封装请求 :param data: 测试用例 :param host: 测试host :param address: 接口地址 :param relevance: 关联对象 :param _path: case路径 :return: """ logging.info("=" * 100) header = readParameter.read_param(data["test_name"], data["headers"], _path, relevance) if data["cookies"] is True: header["Cookie"] = initializeCookie.ini_cookie() logging.debug("请求头处理结果:%s" % header) parameter = readParameter.read_param(data["test_name"], data["parameter"], _path, relevance) logging.debug("请求参数处理结果:%s" % parameter) try: host = data["host"] except KeyError: pass try: address = data["address"] except KeyError: pass host = confManage.host_manage(host) address = replaceRelevance.replace(address, relevance) logging.debug("host处理结果: %s" % host) if not host: raise Exception("接口请求地址为空 %s" % data["headers"]) logging.info("请求接口:%s" % str(data["test_name"])) logging.info("请求地址:%s" % data["http_type"] + "://" + host + address) logging.info("请求头: %s" % str(header)) logging.info("请求参数: %s" % str(parameter)) if data["test_name"] == 'password正确': with allure.step("保存cookie信息"): allure.attach("请求接口:", str(data["test_name"])) allure.attach("请求地址", data["http_type"] + "://" + host + address) allure.attach("请求头", str(header)) allure.attach("请求参数", str(parameter)) apiMethod.save_cookie(header=header, address=data["http_type"] + "://" + host + address, data=parameter) if data["request_type"].lower() == 'post': logging.info("请求方法: POST") if data["file"]: with allure.step("POST上传文件"): allure.attach("请求接口:", str(data["test_name"])) allure.attach("请求地址", data["http_type"] + "://" + host + address) allure.attach("请求头", str(header)) allure.attach("请求参数", str(parameter)) result = apiMethod.post( header=header, address=data["http_type"] + "://" + host + address, request_parameter_type=data["parameter_type"], files=parameter, timeout=data["timeout"]) else: with allure.step("POST请求接口"): allure.attach("请求接口:", str(data["test_name"])) allure.attach("请求地址", data["http_type"] + "://" + host + address) allure.attach("请求头", str(header)) allure.attach("请求参数", str(parameter)) result = apiMethod.post( header=header, address=data["http_type"] + "://" + host + address, request_parameter_type=data["parameter_type"], data=parameter, timeout=data["timeout"]) elif data["request_type"].lower() == 'get': with allure.step("GET请求接口"): allure.attach("请求接口:", str(data["test_name"])) allure.attach("请求地址", data["http_type"] + "://" + host + address) allure.attach("请求头", str(header)) allure.attach("请求参数", str(parameter)) logging.info("请求方法: GET") result = apiMethod.get(header=header, address=data["http_type"] + "://" + host + address, data=parameter, timeout=data["timeout"]) elif data["request_type"].lower() == 'put': logging.info("请求方法: PUT") if data["file"]: with allure.step("PUT上传文件"): allure.attach("请求接口:", str(data["test_name"])) allure.attach("请求地址", data["http_type"] + "://" + host + address) allure.attach("请求头", str(header)) allure.attach("请求参数", str(parameter)) result = apiMethod.post( header=header, address=data["http_type"] + "://" + host + address, request_parameter_type=data["parameter_type"], files=parameter, timeout=data["timeout"]) else: with allure.step("PUT请求接口"): allure.attach("请求接口:", str(data["test_name"])) allure.attach("请求地址", data["http_type"] + "://" + host + address) allure.attach("请求头", str(header)) allure.attach("请求参数", str(parameter)) result = apiMethod.post( header=header, address=data["http_type"] + "://" + host + address, request_parameter_type=data["parameter_type"], data=parameter, timeout=data["timeout"]) elif data["request_type"].lower() == 'delete': with allure.step("DELETE请求接口"): allure.attach("请求接口:", str(data["test_name"])) allure.attach("请求地址", data["http_type"] + "://" + host + address) allure.attach("请求头", str(header)) allure.attach("请求参数", str(parameter)) logging.info("请求方法: DELETE") result = apiMethod.get(header=header, address=data["http_type"] + "://" + host + address, data=parameter, timeout=data["timeout"]) else: result = {"code": False, "data": False} logging.info("请求接口结果:\n %s" % str(result)) return result