关键字框架补充2

1、增加清除结果

2、增加定位方式、定位路径配置文件

3、增加ObjectMap工具类

4、修改测试脚本兼容测试数据定位方式和定位表达式为配置文件中的section、option名字;

LocateInfo.ini

[baidu]

SearchPage.SearchBox=id>kw

SearchPage.SearchButton=xpath>//*[@id="su"]

[sogou]

searchPage.SearchBox=id>query

searchPage.SearchButton=xpath>//*[@id="stb"]

ProjectVar.py

# -*- coding : utf-8 -*-

# Time  : 2019/3/3 22:12

# Author : huhongqiang

# File  : ProjectVar.py

import os

#工程根目录

project_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

#测试数据文件目录

excel_file_path =  os.path.join(project_path,"TestData","126测试用例.xlsx")

#日志配置文件目录

log_conf_file = os.path.join(project_path,"Config","Logger.conf")

#定位方式配置文件路径

locate_info_config_file_path = os.path.join(project_path,"Config","LocateInfo.ini")

#浏览器驱动文件路径

ie_driver_path = "d:\\IDServerDriver"

chrome_driver_path = "d:\\chromedriver"

firefox_driver_path = "d:\\geckodriver"

#测试用例列号字段

#这两个是遍历所有行时候用,因为sheet.rows()返回一个列表,索引从0开始

testcase_name  = 1

testcase_test_data_sheet_col = 2

testcase_is_execute_col = 3

#这两个是写结果用,因为用cell(row=no,column=no)都是从1开始

testcase_execute_time_col = 5

testcase_result_col = 6

#测试步骤列号字段

#遍历所有行时候用,因为sheet.rows()返回一个列表,索引从0开始

teststep_stepname_col = 1

teststep_action_col = 2

teststep_locate_type_col = 3

teststep_locate_expression_col = 4

teststep_operate_value_col = 5

#写结果用,因为用cell(row=no,column=no)索引都是从1开始

teststep_execute_time_col= 7

teststep_result_col = 8

teststep_error_screen_col = 9

teststep_exception_message_col = 10

if __name__ == "__main__":

    # print(project_path)

    # print(log_conf_file)

    # print(excel_file_path)

    print(locate_info_config_file_path)

GetConfigInfo.py

# -*- coding : utf-8 -*-

'''

根据配置Config.LocateInfo.ini的配置文件内容

获取对应option的内容

'''

import  configparser

class GetConfigInfo(object):

    def __init__(self,config_path):

        self.cf = configparser.ConfigParser()

        self.cf.read(config_path)

    #获取section下option的值

    def get_option_value(self,section_name,option_name):

        return self.cf.get(section_name,option_name)

    #获取所有的section

    def get_all_section(self):

        return self.cf.sections()

    #获取某section下的所有option

    def get_all_option(self,section_name):

        return  self.cf.options(section_name)

    #获取section下所有option的键值对

    def get_section_items(self,section_name):

        items = self.cf.items(section_name)

        #把option的选项名和值作为键值对返回

        return dict(items)

if __name__ == "__main__":

    from Config.ProjectVar import *

    g = GetConfigInfo(locate_info_config_file_path)

    print(g.get_all_section())

    print(g.get_all_option("baidu"))

    print(g.get_option_value("baidu","SearchPage.SearchBox"))

    print(g.get_section_items("baidu"))

ObjectMap.py

# -*- coding : utf-8 -*-

'''.

此文件主要用于根据Config.LocateInfo.ini中的定位表达式

获取页面元素对象;

当excel测试数据文件中的定位方式、定位表达式列指定为Config.LocateInfo.ini

中section和option时候用于获取页面元素;

'''

from Util.GetConfigInfo import GetConfigInfo

from selenium.webdriver.support.ui import  WebDriverWait

from Config.ProjectVar import *

import traceback

class ObjectMap(object):

    def __init__(self):

        self.get_config_info = GetConfigInfo(locate_info_config_file_path)

    #根据配置文件中section和option获取对应的定位方式和定位表达式

    #并获取页面元素

    #参数section_name,option_name对应excel表测试数据中的定位方式和定位表达式列的值

    #excel表测试数据中的定位方式和定位表达式列分别可写真正的定位方式和定位表达式

    #也可以写配置文件中对应的section和option

    def get_element(self,driver,section_name,option_name):

        try:

            #获取section下option的值

            option_value = self.get_config_info.get_option_value(section_name,option_name).strip()

            #查分求出定位方式和定位表达式

            locate_type,locate_expression = option_value.split(">")

            # print(type(locate_type),locate_expression)

            #显式等待获取页面元素

            element = WebDriverWait(driver,10,0.2).until(\

                lambda x : x.find_element(locate_type,locate_expression))

            return element

        except Exception as e:

            traceback.print_exc()

            raise e

    #获取配置文件中section下option的值

    def get_locateType_locateExpression(self,section_name,option_name):

        # 获取section下option的值

        option_value = self.get_config_info.get_option_value(section_name, option_name).strip()

        # 查分求出定位方式和定位表达式

        locate_type, locate_expression = option_value.split(">")

        return locate_type,locate_expression

if __name__ == "__main__":

    from selenium import webdriver

    import time

    driver = webdriver.Chrome(executable_path = "d:\\chromedriver")

    driver.get("http://www.baidu.com")

    # element = ObjectMap().get_element(driver,"baidu","SearchPage.SearchBox")

    # element.send_keys("yoursel")

    print(ObjectMap().get_locateType_locateExpression("baidu","SearchPage.SearchBox"))

    time.sleep(3)

    # print(element)

    driver.quit()

TestScrip.py

# -*- coding : utf-8 -*-

from Util.ParseExcel import ParseExcel

from Config.ProjectVar import *

import traceback

from Action.PageAction import *

from Util.Log import *

from Util.ClearTestResult import clear_test_result

from Util.ObjectMap import ObjectMap

"""

此脚本兼容测试数据中定位方式和定位表达式总中的值

1、定位方式和定位表达式

2、配置文件section名和option名

"""

def run():

    try:

        #首先清空测试数据中的测试结果列

        clear_test_result()

        #创建ParseExcel对象,用于处理excel数据

        pe = ParseExcel(excel_file_path)

        #切换到测试用例sheet

        pe.set_sheet_by_name("测试用例")

        #获取测试用例sheet的所有行

        testCaseRows = pe.get_all_rows()

        #遍历测试用例sheet的所有行,去除标题行

        for case_index,case_row in enumerate(testCaseRows[1:]):

            testCaseName = case_row[testcase_name].value

            testDataSheet = case_row[testcase_test_data_sheet_col].value

            isExecute = case_row[testcase_is_execute_col].value

            # print(testDataSheet,isExecute)

            #如果此行用例需要执行,切换到对应的sheet

            if isExecute.lower() == "y":

                pe.set_sheet_by_name(testDataSheet)

                #获取所有的测试步骤行

                testStepRows = pe.get_all_rows()

                #遍历所有的步骤行,去除标题行

                #测试用例是否执行成功标志

                sucess_flag = True

                for step_index,step_row in enumerate(testStepRows[1:]):

                    #获取每行的单元格值

                    stepName = step_row[teststep_stepname_col].value

                    action = step_row[teststep_action_col].value

                    locteType = step_row[teststep_locate_type_col].value

                    locateExpression = step_row[teststep_locate_expression_col].value

                    operatorValue = step_row[teststep_operate_value_col].value

                    # print("first",stepName,action,locteType,locateExpression,operatorValue)

                    #判断测试数据文件中定位表达式列是否为配置文件中的option名

                    #如果是的话,需要从配置文件中读取定位方式和定位表达式的值

                    #需要判断locateExpression不能为空

                    if locateExpression and "Page." in locateExpression:

                        #返回一个元组,此根据locteType、locateExpression获取配置文件中的的

                        #定位方式和定位表达式

                        locteType,locateExpression= ObjectMap().get_locateType_locateExpression(\

                            locteType,locateExpression)

                        print("second",stepName,action,locteType,locateExpression,operatorValue)

                    #拼接需要执行的关键字命令

                    if locteType is None and locateExpression is None and \

                            operatorValue is not None:

                        command = "%s('%s')" %(action,operatorValue)

                    elif locteType is None and locateExpression is None and \

                            operatorValue is  None:

                        command = "%s()" %action

                    elif locteType is not None and locateExpression is not None and \

                            operatorValue is  None:

                        command = "%s('%s','%s')" %(action,locteType,locateExpression)

                    elif locteType is not None and locateExpression is not None and \

                            operatorValue is not None:

                        command = "%s('%s','%s','%s')" %(action,locteType,locateExpression,operatorValue)

                    # print(command)

                    try:

                        #执行关键字命令

                        eval(command)

                    except Exception as e:

                        #打印异常信息

                        traceback.print_exc()

                        #执行关键字命令发生异常,sucess_flag赋值False

                        sucess_flag = False

                        #写异常日志

                        error("测试步骤: [%s] 执行失败!" %(stepName) + str(traceback.format_exc()))

                        #写失败的测试结果,因为step_index从0开始,测试数据行从去除标题行的

                        #第二行开始

                        pe.write_cell_value(step_index + 2,teststep_result_col,"Failed")

                        #写执行时间

                        pe.write_cell_time(step_index + 2,teststep_execute_time_col)

                        #发生异常截取当前屏幕,并返回截图保存路径

                        pic_path = capture_screen()

                        #写截图路径

                        pe.write_cell_value(step_index + 2,teststep_error_screen_col,pic_path)

                        #写异常信息到excel

                        pe.write_cell_value(step_index + 2,teststep_exception_message_col,str(traceback.format_exc()))

                    else:

                        #写日志

                        info("测试步骤: [%s] 执行成功!" %(stepName))

                        #写成功的测试结果,因为step_index从0开始,测试数据行从去除标题行的

                        #第二行开始

                        pe.write_cell_value(step_index + 2,teststep_result_col,"PASS")

                        #写执行时间

                        pe.write_cell_time(step_index + 2,teststep_execute_time_col)

                #切换到测试用例sheet

                pe.set_sheet_by_name("测试用例")

                #写测试用例执行结果

                if sucess_flag == True:

                    pe.write_cell_value(case_index + 2,testcase_result_col,"PASS")

                    info("测试用例: [%s] 执行成功!" %testCaseName)

                else:

                    pe.write_cell_value(case_index + 2, testcase_result_col, "Failed")

                    error("测试用例: [%s] 执行失败!" % testCaseName)

                ##写测试用例执行时间

                pe.write_cell_time(case_index + 2,testcase_execute_time_col)

    except Exception as e:

        traceback.print_exc()

if __name__ == "__main__":

    run()

你可能感兴趣的:(关键字框架补充2)