Ejemplo n.º 1
0
    def _find_elements(self,type,value):
        '''
        查找一组元素
        :param type:
        :param value:
        :return:  返回列表的elements
        '''
        selector_list = ["id", "name", "link_text", "partial_link_text", "css", "xpath", "tag_name","class"]

        if type not in selector_list:
            raise IncorrectSelectorType('选择器{type}有误'.format(type=type))

        if type == "id":
            webelements = self.require_driver().find_elements_by_id(value)
        elif type == "css":
            webelements = self.require_driver().find_elements_by_css_selector(value)
        elif type == "link_text":
            webelements = self.require_driver().find_elements_by_link_text(value)
        elif type == "partial_link_text":
            webelements = self.require_driver().find_elements_by_partial_link_text(value)
        elif type == "name":
            webelements = self.require_driver().find_elements_by_name(value)
        elif type == "xpath":
            webelements = self.require_driver().find_elements_by_xpath(value)
        elif type == "tag_name":
            webelements = self.require_driver().find_elements_by_tag_name(value)
        elif type == "class":
            webelements = self.require_driver().find_elements_by_class_name(value)
        else:
            err = '选择器类型不存在'
            logger.error(err)
            raise IncorrectSelectorType(err)
        return  webelements
Ejemplo n.º 2
0
def load_testcases(path):
    '''
    加载测试用例
    '''
    if isinstance(path, (list, set)):
        cases_list = []

        for case in set(path):
            test_case = load_testcases(case)
            if not test_case:
                continue
            cases_list.extend(test_case)

        return cases_list

    if not os.path.exists(path):
        err_msg = "测试用例的文件 {path}不存在".format(path=path)
        logger.error(err_msg)
        raise CaseFileNotFound(err_msg)

    if not os.path.isabs(path):
        path = os.path.join(os.getcwd(), path)

    if os.path.isdir(path):
        files_list = case_folder_list(path)
        testcases_list = load_testcases(files_list)
    elif os.path.isfile(path):
        testcases_list = load_each_file_case(path)

    return testcases_list
Ejemplo n.º 3
0
 def click(self,type,value):
     '''
     元素点击
     '''
     result = None
     start_time = time.time()
     wait_time = lambda : MAXTIME- (time.time()-start_time)
     print (wait_time())
     while result is None:
         try:
             if self.is_element_visible(type,value):
                 element =self._find_element(type,value)
                 element.click()
                 result = True
             if wait_time() < 0:
                 # 触发跳出循环条件
                 break
             else:
                 time.sleep(0.5)
                 logger.error("click元素没有可见,剩余查找时间{:.2f}".format(wait_time()))
         except:
             if wait_time() < 0:
                 # 触发跳出循环条件
                 break
             else:
                 time.sleep(0.5)
                 logger.error("click元素还没有找到,剩余查找时间{:.2f}".format(wait_time()))
     if result is None:
         raise  Exception("元素还没有找到,执行点击失败")
Ejemplo n.º 4
0
def convert_func_list(action,args,varibales=None):
    '''
    这个转换返回                            需要修改
    将关键词 转为 method  e.g
        {"open": "id|kw"}
    返回
        [kw.method,[args]]
    '''
    kw =KeyWord()
    extend_key = parse_extend_module()
    ek = extend_key(_get_global().driver)
    action_list = []

    if hasattr(kw, action):
        action_key = getattr(kw, action)
        new_args = __get_args(args,varibales)
        action_list = [action_key, new_args]

    if hasattr(ek,action):
        action_key = getattr(ek, action)
        new_args = __get_args(args,varibales)
        action_list = [action_key, new_args]

    if not action_list:
        err = "{key}关键字并不存在,请自行添加或者查询关键字添加方法".format(key=action)
        logger.error(err)
        raise KeyNameError(err)
    return action_list
Ejemplo n.º 5
0
 def js(self,script):
     '''
     执行js脚本
     :param script:
     :return:
     '''
     try:
         return self.require_driver().execute_script(script)
     except:
         err = "使用js脚本点击失败"
         logger.error(err)
         raise JsScriptFailed(err)
Ejemplo n.º 6
0
def case_json_data(fileName):
    '''
    加载用例的json文件
    '''
    try:
        with io.open(fileName, encoding='utf8') as data:
            try:
                dict_data = json.load(data)
                # 对load成python 格式的内容进行基本判断
                if not dict_data:
                    err = "重载{file}文件的内容为空".format(file=fileName)
                    logger.error(err)
                    raise FileFormatError(err)
                elif not isinstance(dict_data, (list, dict)):
                    err = "{file}文件格式有误".format(file=fileName)
                    logger.error(err)
                    raise FileFormatError(err)

            except Exception as msg:
                logger.error("加载json文件有误:{err}".format(err=msg))
                raise FileFormatError(err)
            return dict_data
    except Exception as msg:
        logger.error(msg)
        raise FileNotFoundError(msg)
Ejemplo n.º 7
0
 def _find_element(self,type,value,timeout=MAXTIME):
     '''
     寻找页面元素(默认5秒时间)
     :param type:  选择器
     :param value: 选择器值
     :param timeout:  设置等待时间
     :param waitDisplay: 是否设置 元素等待显示
     :return:  返回页面元素
     '''
     selector_list = ["id", "name", "link_text", "partial_link_text", "css", "xpath", "tag_name","class"]
     if type not  in selector_list:
         raise IncorrectSelectorType('选择器{type}有误'.format(type=type))
     element = None
     start_time = time.time()
     wait_time = lambda : timeout - (time.time()-start_time)
     while element is None:
         try:
             if type == 'id':
                 element = self.require_driver().find_element_by_id(value)
             elif type == 'css':
                   element = self.require_driver().find_element_by_css_selector(value)
             elif type == 'link_text':
                 element = self.require_driver().find_element_by_link_text(value)
             elif type == 'partial_link_text':
                 element = self.require_driver().find_element_by_partial_link_text(value)
             elif type == 'name':
                 element = self.require_driver().find_element_by_name(value)
             elif type == 'xpath':
                 element = self.require_driver().find_element_by_xpath(value)
             elif type == 'tag_name':
                 element = self.require_driver().find_element_by_tag_name(value)
             elif type == 'class':
                 element = self.require_driver().find_element_by_class_name(value)
             else:
                 err = "选择器{type}类型有误".format(type=type)
                 logger.error(err)
                 raise  IncorrectSelectorType(err)
             logger.debug('找到页面元素:  {type}{value}'.format(type=type,value=value))
         except:
             if wait_time() < 0:
                 # 触发跳出循环条件
                 break
             else:
                 time.sleep(1)
                 logger.error("页面元素还没有找到,剩余查找时间{:.2f}".format(wait_time()))
     if  not element:
         # raise ElementNotFound("页面元素没有找到,使用{type}选择器".format(type=type))
         return None
     else:
         return element
Ejemplo n.º 8
0
def parse_extend_module():
    '''
    动态加载拓展的关键词
    :return: extend.对象
    '''
    try:
        handler_class = getattr(
            importlib.import_module("extend"),
            "Extend")
        return handler_class
    except:
        err = "拓展关键字模块加载失败"
        logger.error(err)
        raise  NotImplementedError(err)
Ejemplo n.º 9
0
def main():
    """
    python script.py -p ./test_case
    """

    args = list(sys.argv[1:])
    _short_to_long = {}
    options, args = getopt.getopt(sys.argv[1:], 'p:i:')
    try:
        for name, value in options:
            print (value,type(value))
            if name in ('p'):
                serunner = SeRunner(**{})
                serunner.run(value)
                logger.info("测试结果汇总如下'\t\n'{sum}".format(sum=serunner.summary))
    except Exception:
        logger.error("命令行参数有误")
        raise
Ejemplo n.º 10
0
def parse_dynamic_args(arg,variable):
    '''
    获取动态变量
    e.g $url/index/$page
    '''
    variable_regexp = r"\$([\w_]+)"
    try:
        args = re.findall(variable_regexp,arg)
        new_arg = arg
        if args:
            for arg_v in args:
                if  arg_v in variable.keys():
                    dynamic_arg_value = variable[arg_v]
                    new_arg = new_arg.replace("${}".format(arg_v),dynamic_arg_value,1)
                else:
                    err = "该变量[{}]还没定义,请重新定义".format(arg)
                    logger.error(err)
                    raise  NameError(err)
            return new_arg
    except TypeError:
        return None
Ejemplo n.º 11
0
def find_file(filePath,fileName):
    '''
    寻找文件
    '''
    file_abspath = None
    while file_abspath is None:
        if os.path.isfile(filePath):
            file_dir_path = os.path.dirname(filePath)

        elif os.path.isdir(filePath):
            file_dir_path = filePath
        else:
            err = "传入的路径有误"
            logger.error(err)
            raise FileNotFoundError(err)
        file_path = os.path.join(file_dir_path,fileName)

        if os.path.isfile(file_path):
            file_abspath = os.path.abspath(file_path)
        else:
            filePath = os.path.dirname(file_dir_path)

    return file_abspath
Ejemplo n.º 12
0
    def wait_switch_to_alert(self,timeout=MAXTIME):
        '''
        等待切换到弹框
        :return:
        '''
        alert = None
        start_time = time.time()
        wait_time = lambda : timeout - (time.time()-start_time)
        while alert is None:
            try:
                alert = self.require_driver().switch_to.alert
            except NoAlertPresentException:
                if wait_time() < 0:
                    # 触发跳出循环条件
                    break
                else:
                    time.sleep(0.5)
                    logger.error("弹框还没有找到,剩余查找时间{:.2f}".format(wait_time()))

        if not alert:
            raise Exception(" %s 秒后,弹框没有找到 after %s seconds!" % time)
        else:
            return alert
Ejemplo n.º 13
0
def __parse_dynamic_action(dynamic,action):
    '''
    解析动态action
    :param dynamic:  ['open', 'add']
    :param actions:  已经解析好的action(关键词)
    :return:
    '''

    new_value_list = []
    for index in range(len(dynamic)):
        if  dynamic[index] in action.keys():
            method_list = action[dynamic[index]]
            if len(method_list) == 1:
                new_value_list.append(method_list[0])
            if len(method_list) > 1:
                for method in method_list:
                    new_value_list.append(method)
        else:
            err = "{key}关键字并不存在,请自行添加或者查询关键字添加方法".format(key=dynamic[index])
            logger.error(err)
            raise NameError(err)

    return new_value_list
Ejemplo n.º 14
0
    def wait_for_element_visible(self,type,value,timeout=MAXTIME):
        """
        等待元素,如果该元素在页面上存在且可见。返回element

        """
        element = None
        start_time = time.time()
        wait_time = lambda: timeout - (time.time() - start_time)
        while element is None:
            try:
                element = self._find_element(type,value)
                if element.is_displayed():
                    return element
                else:
                    element = None
            except:
                if wait_time() < 0:
                    # 触发跳出循环条件
                    break
                else:
                    time.sleep(0.5)
                    logger.error("元素还没有找到,剩余查找时间{:.2f}".format(wait_time()))
        if not element:
                raise  ElementNotVisibleException("元素等待{time}秒后,依然无法可见".format(time=time))