【Appium_python】利用Template生成对象模板_appium_元素定位/操作

UI自动化中用PageObject设计模式就会发现page元素定位代码基本重复,复制黏贴,修改,所以就想到运用模板方式,批量生成page,同理也能批量生成handle。

有模板,利用配置文件ini获取类名,方法名,模板套用,生成文件。

1、编写模板文件:

文件名:template_handle_head.tmpl,template_page_body.tmpl

2、利用配置文件:

LocalElement.ini

3、用configparser 读取配置文件,替换class_name、fun_name以及option,批量生成多个page文件:

from string import Template
import configparser


# 用ini里的文件获取元素生成的类--->后面再升级直接读取excel生成page跟handle下的页面
class GeneratePage:
    def __init__(self):
        # 元素文件
        self.config_file = '..\\config\\LocalElement.ini'
        # 类模板文件,模板文件最下面要空2行
        self.template_path_head = '../config/template_page_head.tmpl'
        self.template_path_body = '../config/template_page_body.tmpl'
        # 生成文件后的地址
        self.package_path = '../page/'

    # 自动生成类文件_page_package下的元素定位
    def generate_class_file(self, class_name, list_func_name):
        my_code = []
        template_file_head = open(self.template_path_head, 'r')
        template_file_body = open(self.template_path_body, 'r')
        tmpl_head = Template(template_file_head.read())
        tmpl_body = Template(template_file_body.read())
        my_code.append(tmpl_head.substitute(class_name=class_name))
        for func_name in list_func_name:
            my_code.append(tmpl_body.substitute(func_name=func_name, option="\'" + func_name + "\'"))
        return my_code

    # 生成文件
    def write_to_file(self, file_name, code):
        file_path = self.package_path + file_name + '_page.py'
        class_file = open(file_path, 'w')
        class_file.writelines(code)
        class_file.close()

    # 用configparser 读取配置文件,替换class_name、fun_name以及option
    def loop_generate_class_file(self):
        config = configparser.ConfigParser()
        config.read(self.config_file, encoding='utf-8')
        list_section = config.sections()
        for section in list_section:
            # 文件名
            file_name = section[0:section.rfind('_')]
            # 类名
            list_file = file_name.split('_')
            class_name = "".join([name.capitalize() for name in list_file])
            # 方法名集合里就是func_name以及option_name
            list_func_name = config.options(section)
            code = self.generate_class_file(class_name, list_func_name)
            self.write_to_file(file_name, code)
        print('ok')


if __name__ == '__main__':
    generate_code = GeneratePage()
    generate_code.loop_generate_class_file()

4.查看效果图:

5、其他:handel格式也是类似,可以同样自动生成,配置文件也可以用excel等。

 

posted @ 2023-02-06 18:33  ninarMing  阅读(31)  评论(0编辑  收藏  举报