Ejemplo n.º 1
0
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
Ejemplo n.º 2
0
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
Ejemplo n.º 3
0
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 = '******')
Ejemplo n.º 4
0
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
Ejemplo n.º 5
0
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