python+selenium封装UI自动化框架

这篇具有很好参考价值的文章主要介绍了python+selenium封装UI自动化框架。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

seleinum框架

框架的思想:

解决我们测试过程中的问题:大量的重复步骤,用自动化来实现

1)配置和程序的分离

2)测试数据和程序的分离

3)不懂编程的人员可以方便使用:使用的时候不需要写程序

4)有日志功能,实现无人值守

5)自动发报告

6)框架中不要有重复的代码,实现高度的封装和复用

推荐使用关键字驱动、混合驱动

为什么要编写程序呢?

通用性的东西满足不了个性化的需求

测试的工具:python+selenium

接口测试用例:excel

一、搭建自动化测试的目录结构

python+selenium封装UI自动化框架

分层如下:

1、Action包: 放置关键字文件

2、Config目录: 所有配置文件,日志的配置文件;把所有的项目相关的配置均放到这里,用python支持较好的配置文件格式ini进行配置。实现配置与代码的分离

3、Projvar包:项目所有的公共变量,如:目录、自定义变量名称;

4、ScreenCapture目录:存放截屏目录,按照年月日小时来建目录;

5、TestData目录:放测试将数据文件,可以把所有的testcase的参数化相关文件放在这里,一般采用xlsx、xml等格式。实现数据与代码分离;

6、TestScript包:测试脚本,主程序

7、Util包:封装的公共的类,包括读取config的类,写log的类,读取excel、xml

的类、生成报告的类(如HTMLTestRunner)、数据库的连接、发送邮件等类和方法,都在这里

8、ReadMe.txt(加个说明性文件,告诉团队框架需要使用的环境及方法)

二、搭建步骤

  1. 在ProjVar包创建一个var.py用来存放公共变量

import os

#浏览器驱动存放的位置

firefoxDriverFilePath = "e:\\geckodriver"

chromeDriverFilePath = "e:\\chromedriver"

ieDriverFilePath = "e:\\IEDriverServer"

# 当前文件所在目录的父目录的绝对路径

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

test_step_id_col_no = 0

test_step_result_col_no = 8

test_step_error_info_col_no = 9

test_step_capture_pic_path_col_no = 10

test_case_id_col_no= 0

test_case_sheet_name=2

test_case_is_executed_flag_col_no= 3

test_case_is_hybrid_test_data_sheet_col_no=4

test_case_start_time_col_no= 6

test_case_end_time_col_no= 7

test_case_elapsed_time_col_no= 8

test_case_result_col_no = 9

if __name__=="__mian__":

print(ProjDirPath)

2、在Utli包里面创建公共的类、函数

2.1封装excel的类

  1. from openpyxl import *

  1. import os.path

  1. from openpyxl.styles import NamedStyle,Font, colors

  1. from ProjVar.var import *

  1. from Util.FromatTime import *

  1. class Excel:

  1. def __init__(self,excel_file_path):

  1. if os.path.exists(excel_file_path):

  1. self.excel_file_path = excel_file_path

  1. self.wb = load_workbook(self.excel_file_path)

  1. else:

  1. print("%s e文件的路劲不存在,请重新设定!" %excel_file_path)

  1. #通过sheet名字来获取操作的sheet

  1. def set_sheet_by_name(self,sheet_name):

  1. if sheet_name in self.wb.sheetnames:

  1. self.sheet = self.wb[sheet_name]

  1. else:

  1. print("%s sheet不存在,请重新指定!" %sheet_name)

  1. #通过序号来获取操作的sheet

  1. def set_sheet_by_index(self,index):

  1. if isinstance(index,int) and 1<= index <= len(self.get_all_sheet_names()):

  1. sheet_name = self.get_all_sheet_names()[index-1]

  1. self.sheet = self.wb[sheet_name]

  1. else:

  1. print("%s sheet 序号不存在,请重新设定" %index)

  1. #获取当前sheet和title的名称

  1. def get_current_sheet_name(self):

  1. return self.sheet.title

  1. #获取所有sheet的名称

  1. def get_all_sheet_names(self):

  1. return self.wb.sheetnames

  1. #获取sheet的总行数,从0开始,返回list

  1. def get_rows_object(self):

  1. return list(self.sheet.rows)

  1. #获取sheet的总列数,从0开始,返回list

  1. def get_cols_object(self):

  1. return list(self.sheet.columns)

  1. #获取某行的对象,第一行从0开始

  1. def get_row(self,row_no):

  1. return self.get_rows_object()[row_no]

  1. #获取某一列对象,第一列从0开始

  1. def get_col(self,col_no):

  1. return self.get_cols_object()[col_no]

  1. #获取某个单元格对象

  1. def get_cell_value(self,row_no,col_no):

  1. if isinstance(row_no,int) and isinstance(col_no,int) and \

  1. 1<=row_no<=len(self.get_rows_object()) and \

  1. 1 <= row_no <= len(self.get_cols_object()):

  1. return self.sheet.cell(row=row_no, column=col_no).value

  1. else:

  1. print("%s,%s 行号或者列号不存在,请重新设定行号或者列表读取!" % (row_no,col_no))

  1. #给某一个单元格写入指定内容,行号、列号从1开始

  1. #调用此方法时,excel不要处于打开状态

  1. def write_cell_value(self,row_no,col_no,value,color = None):

  1. if isinstance(row_no,int) and isinstance(col_no,int):

  1. if color is None:

  1. font = Font(bold=False, size=10, color=colors.BLACK)

  1. self.sheet.cell(row=row_no, column=col_no).font = font

  1. self.sheet.cell(row=row_no, column=col_no).value = value

  1. elif color == "green":

  1. font = Font(bold=True, size=13, color=colors.GREEN)

  1. self.sheet.cell(row=row_no, column=col_no).font = font

  1. self.sheet.cell(row=row_no, column=col_no).value = value

  1. elif color == "red":

  1. font = Font(bold=True, size=13, color=colors.RED)

  1. self.sheet.cell(row=row_no, column=col_no).font = font

  1. self.sheet.cell(row=row_no, column=col_no).value = value

  1. self.wb.save(self.excel_file_path)

  1. else:

  1. print("%s,%s 行号或者列号不是数字,请重新设定行号或者列表读取!" % (row_no, col_no))

  1. def write_current_time(self,row_no,col_no):

  1. if isinstance(row_no, int) and isinstance(col_no, int):

  1. self.sheet.cell(row=row_no, column=col_no).value = get_current_date_and_time()

  1. self.wb.save(self.excel_file_path)

  1. if __name__ == "__main__":

  1. excel_file_path = ProjDirPath+r"\TestData\126邮箱联系人.xlsx"

  1. #print(excel_file_path )

  1. excel_obj = Excel(excel_file_path)

  1. #Excel("e:\\a.xlsx") #测试路劲不存在的情况

  1. # excel_obj.set_sheet_by_name("测试邮件")

  1. # excel_obj.set_sheet_by_name("测试邮件1111")

  1. excel_obj.set_sheet_by_index(1)

  1. # print(excel_obj.get_current_sheet_name())

  1. #excel_obj.set_sheet_by_index(5)

  1. #print(excel_obj.get_rows_object())

  1. #print(excel_obj.get_cols_object())

  1. #print(excel_obj.get_row(2))

  1. print(excel_obj.get_cell_value(2,2))

  1. print(excel_obj.write_cell_value(5,7,"hello~~"))

  1. print(excel_obj.write_current_time(6,8))

2.2 封装获取页面元素的类

  1. from selenium.webdriver.support.ui import WebDriverWait

  1. import time

  1. #获取单个页面元素对象

  1. def getElement(driver,localtorType,localtorExpression):

  1. try:

  1. element = WebDriverWait(driver,5).until(lambda x:x.find_element(by = localtorType,value=localtorExpression))

  1. return element

  1. except Exception as e:

  1. raise e

  1. #获取多个页面元素对象

  1. def getElement(driver,localtorType,localtorExpression):

  1. try:

  1. elements = WebDriverWait(driver,5).until(lambda x:x.find_elements(by=localtorType,value=localtorExpression))

  1. return elements

  1. except Exception as e:

  1. raise e

  1. if __name__ =="__main__":

  1. from selenium import webdriver

  1. #进行单元测试

  1. driver = webdriver.Firefox(executable_path="e:\\geckodriver")

  1. driver.maximize_window()

  1. driver.get("https://mail.126.com/")

  1. time.sleep(2)

  1. lb = getElement(driver,"id","lbNormal")

  1. print(lb)

  1. driver.quit()

2.3 封装获取当前日期、时间的类

  1. import time

  1. import datetime

  1. import locale

  1. # 获取当前的日期

  1. def get_current_date():

  1. time_tup = time.localtime()

  1. current_date = str(time_tup.tm_year) + "年" + \

  1. str(time_tup.tm_mon) + "月" + str(time_tup.tm_mday)+"日"

  1. return current_date

  1. # 获取当前的时间

  1. def get_current_time():

  1. time_str = datetime.datetime.now()

  1. locale.setlocale(locale.LC_CTYPE, 'chinese')

  1. now_time = time_str.strftime('%H点%M分钟%S秒')

  1. return now_time

  1. # 获取当前的时间

  1. def get_current_hour():

  1. time_str = datetime.datetime.now()

  1. now_hour = time_str.strftime('%H')

  1. return now_hour

  1. def get_current_date_and_time():

  1. return get_current_date()+" "+get_current_time()

  1. if __name__ == "__main__":

  1. print( get_current_date())

  1. print(get_current_time())

  1. print(get_current_hour())

  1. print(get_current_date_and_time())

2.4 封装创建目录的类

  1. import os

  1. from Util.FromatTime import *

  1. from ProjVar.var import *

  1. def make_dir(dir_path):

  1. if not os.path.exists(dir_path):

  1. try:

  1. os.mkdir(dir_path)

  1. except Exception as e:

  1. print("创建%s目录失败" %dir_path)

  1. raise e

  1. def make_current_date_dir(default_dir_path = None):

  1. if default_dir_path is None:

  1. dir_path = get_current_date()

  1. else:

  1. dir_path = os.path.join(default_dir_path,get_current_date())

  1. if not os.path.exists(dir_path):

  1. try:

  1. os.mkdir(dir_path)

  1. except Exception as e:

  1. print("创建%s目录失败" % dir_path)

  1. raise e

  1. return dir_path

  1. def make_current_hour_dir(default_dir_path = None):

  1. if default_dir_path is None:

  1. dir_path = get_current_hour()

  1. else:

  1. dir_path = os.path.join(default_dir_path,get_current_hour())

  1. if not os.path.exists(dir_path):

  1. try:

  1. os.mkdir(dir_path)

  1. except Exception as e:

  1. print("创建%s目录失败" % dir_path)

  1. raise e

  1. return dir_path

  1. if __name__ == "__main__":

  1. make_dir(ProjDirPath+"\\"+"ScreenCapture\\"+"pic")

  1. dir_path = make_current_date_dir(ProjDirPath+"\\"+"ScreenCapture\\")

  1. dir_path=make_current_hour_dir(dir_path+"\\")

  1. print(dir_path)

2.5 封装日志的类

  1. #encoding=utf-8

  1. import logging.config

  1. import logging

  1. from ProjVar.var import ProjDirPath

  1. print(ProjDirPath+"\\Conf\\"+"Logger.conf")

  1. #读取日志配置文件

  1. logging.config.fileConfig(ProjDirPath+"\\Conf\\"+"Logger.conf")

  1. #选择一个日志格式

  1. logger = logging.getLogger("example01")

  1. def debug(message):

  1. print ("debug")

  1. logger.debug(message)

  1. def info(message):

  1. logger.info(message)

  1. def error(message):

  1. print("error")

  1. logger.error(message)

  1. def warning(message):

  1. logger.warning(message)

  1. if __name__=="__main__":

  1. debug("hi")

  1. info("gloryroad")

  1. warning("hello")

  1. error("something error!")

2.6 封装显示等待的类

  1. #encoding=utf-8

  1. from selenium.webdriver.support.ui import WebDriverWait

  1. from selenium.webdriver.common.by import By

  1. from selenium.webdriver.support import expected_conditions as EC

  1. class WaitUtil(object):

  1. def __init__(self,driver):

  1. self.locationTypeDict = {

  1. "xpath":By.XPATH,

  1. "id":By.ID,

  1. "name":By.NAME,

  1. "css_selector":By.CSS_SELECTOR,

  1. "class_name":By.CLASS_NAME,

  1. "tag_name":By.TAG_NAME,

  1. "link_text":By.LINK_TEXT,

  1. "partial_link_text":By.PARTIAL_LINK_TEXT,

  1. }

  1. self.driver = driver

  1. self.wait = WebDriverWait(driver,30)

  1. def presenceOfElementLocated(self,locatorMethod,locatorExpression,*args):

  1. """显式等待页面元素出现在DOM中,但并不一定可见,存在则返回该页面元素"""

  1. try:

  1. #if self.locationTypeDict.has_key(locatorMethod.lower()):

  1. if locatorMethod.lower() in self.locationTypeDict:

  1. self.wait.until(EC.presence_of_element_located((self.locationTypeDict[locatorMethod.lower()],locatorExpression)))

  1. else:

  1. raise Exception(u"未找到定位方式,请确认定位方式是否书写正确")

  1. except Exception as e:

  1. raise e

  1. def frameToBeAvailableAndSwitchToIt(self,locationType,locatorExpression,*args):

  1. """检查frame是否存在,存在则切换进frame控件中"""

  1. try:

  1. self.wait.until(EC.frame_to_be_available_and_switch_to_it((self.locationTypeDict[locationType.lower()],locatorExpression)))

  1. except Exception as e:

  1. raise e

  1. def visibilityOfElementLocated(self,locationMethod,locatorExperssion,*args):

  1. """显式等待页面元素出现在DOM中,并且可见,存在则返回该页面元素对象"""

  1. try:

  1. self.wait.until(EC.visibility_of_element_located((self.locationTypeDict[locationMethod.lower()],locatorExperssion)))

  1. except Exception as e:

  1. raise e

  1. if __name__ == "__main__":

  1. from selenium import webdriver

  1. driver = webdriver.Firefox(executable_path = "e:\\geckodriver")

  1. driver.get("https://mail.126.com/")

  1. waitUtil = WaitUtil(driver)

  1. driver.find_element_by_id("lbNormal").click()

  1. # waitUtil.presenceOfElementLocated("id","lbNormal")

  1. waitUtil.frameToBeAvailableAndSwitchToIt("xpath",'//iframe[contains(@id,"x-URS-iframe")]')

  1. waitUtil.visibilityOfElementLocated("xpath","//input[@name='email']")

  1. waitUtil.presenceOfElementLocated("xpath","//input[@name='email']")

  1. driver.quit()

## 根据需求如果还用其他的类,封装好后放在此目下面 ##

3、在action包里面,创建关键字函数

  1. #encoding=utf-8

  1. from selenium import webdriver

  1. from ProjVar.var import *

  1. from Util.find import *

  1. from Util.KeyBoardUtil import KeyBoardKeys

  1. from Util.ClipboardUtil import Clipboard

  1. from Util.WaitUtil import WaitUtil

  1. from selenium.webdriver.firefox.options import Options

  1. from selenium.webdriver.chrome.options import Options

  1. import time

  1. from Util.FromatTime import *

  1. #定义全局变量driver

  1. driver = None

  1. #定义全局的等待类实例对象

  1. waitUtil = None

  1. def open(browserName):

  1. #打开浏览器

  1. global driver,waitUtil

  1. try:

  1. if browserName.lower() == "ie":

  1. driver = webdriver.Ie(executable_path = ieDriverFilePath)

  1. elif browserName.lower == "chrome":

  1. #创建Chrome浏览器的一个Options实例对象

  1. chrome_options = Options()

  1. #添加屏蔽--ignore--certificate--errors提示信息的设置参数项

  1. chrome_options.add_experimental_option("excludeSwitches",["ignore-certificate-errors"])

  1. driver = webdriver.Chrome(executable_path = chromeDriverFilePath,chrome_options = chrome_options)

  1. else:

  1. driver = webdriver.Firefox(executable_path = firefoxDriverFilePath)

  1. #driver对象创建成功后,创建等待类实例对象

  1. waitUtil = WaitUtil(driver)

  1. except Exception as e:

  1. raise e

  1. def visit(url):

  1. #访问某个网站

  1. global driver

  1. try:

  1. driver.get(url)

  1. except Exception as e:

  1. raise e

  1. def close_browser():

  1. #关闭浏览器

  1. global driver

  1. try:

  1. driver.quit()

  1. except Exception as e:

  1. raise e

  1. def sleep(sleepSeconds):

  1. #强制等待

  1. try:

  1. time.sleep(int(sleepSeconds))

  1. except Exception as e:

  1. raise e

  1. def clear(locationType,locatorExpression):

  1. #清空输入框默认内容

  1. global driver

  1. try:

  1. getElement(driver,locationType,locatorExpression).clear()

  1. except Exception as e:

  1. raise e

  1. def input_string(locationType,locatorExpression,inputContent):

  1. #在页面输入框中输入数据

  1. global driver

  1. try:

  1. getElement(driver,locationType,locatorExpression).send_keys(inputContent)

  1. except Exception as e:

  1. raise e

  1. def click(locationType,locatorExpression,*args):

  1. #点击页面元素

  1. global driver

  1. try:

  1. getElement(driver,locationType,locatorExpression).click()

  1. except Exception as e:

  1. raise e

  1. def assert_string_in_pagesource(assertString,*args):

  1. #断言页面源码是否存在某个关键字或关键字符串

  1. global driver

  1. try:

  1. assert assertString in driver.page_source,u"%s not found in page source!" % assertString

  1. except AssertionError as e:

  1. raise AssertionError(e)

  1. except Exception as e:

  1. raise e

  1. def assert_title(titleStr,*args):

  1. #断言页面标题是否存在给定的关键字符串

  1. global driver

  1. try:

  1. assert titleStr in driver.title,u"%s not found in page title!" % titleStr

  1. except AssertionError as e:

  1. raise AssertionError(e)

  1. except Exception as e:

  1. raise e

  1. def getTitle(*args):

  1. #获取页面标题

  1. global driver

  1. try:

  1. return driver.title

  1. except Exception as e:

  1. raise e

  1. def getPageSource(*args):

  1. #获取页面源码

  1. global driver

  1. try:

  1. return driver.page_source

  1. except Exception as e:

  1. raise e

  1. def switch_to_frame(locationType,frameLocatorExpressoin,*args):

  1. #切换进frame

  1. global driver

  1. try:

  1. driver.switch_to.frame(getElement(driver,locationType,frameLocatorExpressoin))

  1. except Exception as e:

  1. print("frame error!")

  1. raise e

  1. def switch_to_default_content(*args):

  1. #切换妯frame

  1. global driver

  1. try:

  1. driver.switch_to.default_content()

  1. except Exception as e:

  1. raise e

  1. def paste_string(pasteString,*args):

  1. #模拟Ctrl+V操作

  1. try:

  1. Clipboard.setText(pasteString)

  1. #等待2秒,防止代码执行过快,而未成功粘贴内容

  1. time.sleep(2)

  1. KeyBoardKeys.twoKeys("ctrl","v")

  1. except Exception as e:

  1. raise e

  1. def press_tab_key(*args):

  1. #模拟tab键

  1. try:

  1. KeyBoardKeys.oneKey("tab")

  1. except Exception as e:

  1. raise e

  1. def press_enter_key(*args):

  1. #模拟enter键

  1. try:

  1. KeyBoardKeys.oneKey("enter")

  1. except Exception as e:

  1. raise e

  1. def maximize(*args):

  1. #窗口最大化

  1. global driver

  1. try:

  1. driver.maximize_window()

  1. except Exception as e:

  1. raise e

  1. def capture(file_path):

  1. try:

  1. driver.save_screenshot(file_path)

  1. except Exception as e:

  1. raise e

  1. def waitPresenceOfElementLocated(locationType,locatorExpression,*args):

  1. """显式等待页面元素出现在DOM中,但不一定可见,存在则返回该页面元素对象"""

  1. global waitUtil

  1. try:

  1. waitUtil.presenceOfElementLocated(locationType,locatorExpression)

  1. except Exception as e:

  1. raise e

  1. def waitFrameToBeAvailableAndSwitchToIt(locationType,locatorExprssion,*args):

  1. """检查frame是否存在,存在则切换进frame控件中"""

  1. global waitUtil

  1. try:

  1. waitUtil.frameToBeAvailableAndSwitchToIt(locationType,locatorExprssion)

  1. except Exception as e:

  1. raise e

  1. def waitVisibilityOfElementLocated(locationType,locatorExpression,*args):

  1. """显式等待页面元素出现在Dom中,并且可见,存在返回该页面元素对象"""

  1. global waitUtil

  1. try:

  1. waitUtil.visibilityOfElementLocated(locationType,locatorExpression)

  1. except Exception as e:

  1. raise e

4、在Config目录下存放所有配置文件,比如:日志的配置文件;把所有的项目相关的配置均放到这里,实现配置与代码的分离

日志配置文件

  1. [loggers]

  1. keys=root,example01,example02

  1. [logger_root]

  1. level=DEBUG

  1. handlers=hand01,hand02

  1. [logger_example01]

  1. handlers=hand01,hand02

  1. qualname=example01

  1. propagate=0

  1. [logger_example02]

  1. handlers=hand01,hand03

  1. qualname=example02

  1. propagate=0

  1. ###############################################

  1. [handlers]

  1. keys=hand01,hand02,hand03

  1. [handler_hand01]

  1. class=StreamHandler

  1. level=DEBUG

  1. formatter=form01

  1. args=(sys.stderr,)

  1. [handler_hand02]

  1. class=FileHandler

  1. level=DEBUG

  1. formatter=form01

  1. args=('AutoTestLog.log', 'a')

  1. [handler_hand03]

  1. class=handlers.RotatingFileHandler

  1. level=INFO

  1. formatter=form01

  1. args=('AutoTestLog.log', 'a', 10*1024*1024, 5)

  1. ###############################################

  1. [formatters]

  1. keys=form01,form02

  1. [formatter_form01]

  1. format=%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s

  1. datefmt=%Y-%m-%d %H:%M:%S

  1. [formatter_form02]

  1. format=%(name)-12s: %(levelname)-8s %(message)s

  1. datefmt=%Y-%m-%d %H:%M:%S

5、在ProjVar包里面存放项目所有的公共变量,如:目录、自定义变量名称;

  1. import os

  1. #浏览器驱动存放的位置

  1. firefoxDriverFilePath = "e:\\geckodriver"

  1. chromeDriverFilePath = "e:\\chromedriver"

  1. ieDriverFilePath = "e:\\IEDriverServer"

  1. # 当前文件所在目录的父目录的绝对路径

  1. ProjDirPath = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

  1. test_step_id_col_no = 0

  1. test_step_result_col_no = 8

  1. test_step_error_info_col_no = 9

  1. test_step_capture_pic_path_col_no = 10

  1. test_case_id_col_no= 0

  1. test_case_sheet_name=2

  1. test_case_is_executed_flag_col_no= 3

  1. test_case_is_hybrid_test_data_sheet_col_no=4

  1. test_case_start_time_col_no= 6

  1. test_case_end_time_col_no= 7

  1. test_case_elapsed_time_col_no= 8

  1. test_case_result_col_no = 9

  1. if __name__=="__mian__":

  1. print(ProjDirPath)

6、ScreenCapture目录:所有生成的日志、截屏报告均放在这里

python+selenium封装UI自动化框架

7、TestData目录:存放测试文件

126邮箱联系人.xlsx

8、TestScript包用来创建测试脚本,主程序

  1. #encoding=utf-8

  1. import re

  1. from Util.dir_opration import make_current_date_dir, make_current_hour_dir

  1. from Util.Excel import *

  1. from Action.PageAction import *

  1. import traceback

  1. from Util.log import *

  1. def get_test_case_sheet(test_cases_excel_path):

  1. test_case_sheet_names = []

  1. excel_obj = Excel(test_cases_excel_path)

  1. excel_obj.set_sheet_by_index(1)

  1. test_case_rows = excel_obj.get_rows_object()[1:]

  1. for row in test_case_rows:

  1. if row[3].value=='y':

  1. print(row[2].value)

  1. test_case_sheet_names.append((int(row[0].value)+1,row[2].value))

  1. return test_case_sheet_names

  1. #print(get_test_case_sheet(ProjDirPath+"\\TestData\\126邮箱联系人.xlsx"))

  1. def execute(test_cases_excel_path,row_no,test_case_sheet_name):

  1. excel_obj = Excel(test_cases_excel_path)

  1. excel_obj.set_sheet_by_name(test_case_sheet_name)

  1. #获取除第一行之外的所有行对象

  1. test_step_rows = excel_obj.get_rows_object()[1:]

  1. #拼接开始时间:当前年月日+当前时间

  1. start_time = get_current_date_and_time()

  1. #开始计时

  1. start_time_stamp = time.time()

  1. #设置默认用例时执行成功的,如果抛异常则说明用例执行失败

  1. test_result_flag = True

  1. for test_step_row in test_step_rows:

  1. if test_step_row[6].value == "y":

  1. test_action = test_step_row[2].value

  1. locator_method = test_step_row[3].value

  1. locator_exp = test_step_row[4].value

  1. test_value = test_step_row[5].value

  1. print(test_action,locator_method,locator_exp,test_value)

  1. if locator_method is None:

  1. if test_value is None:

  1. command = test_action + "()"

  1. else:

  1. command = test_action + "('%s')" %test_value

  1. else:

  1. if test_value is None:

  1. command = test_action + "('%s','%s')" %(locator_method,locator_exp)

  1. else:

  1. command = test_action + "('%s','%s','%s')" %(locator_method,locator_exp,test_value)

  1. print(command)

  1. eval(command)

  1. #处理异常

  1. try:

  1. info(command)

  1. eval(command)

  1. excel_obj.write_cell_value(int(test_step_row[0].value) + 1, test_step_result_col_no, "执行成功")

  1. excel_obj.write_cell_value(int(test_step_row[0].value) + 1, test_step_error_info_col_no, "")

  1. excel_obj.write_cell_value(int(test_step_row[0].value) + 1, test_step_capture_pic_path_col_no, "")

  1. info("执行成功") # 加入日志信息

  1. except Exception as e:

  1. test_result_flag = False

  1. traceback.print_exc()

  1. error(command + ":" + traceback.format_exc()) # 加入日志信息

  1. excel_obj.write_cell_value(int(test_step_row[0].value) + 1, test_step_result_col_no, "失败", "red")

  1. excel_obj.write_cell_value(int(test_step_row[0].value) + 1, test_step_error_info_col_no, \

  1. command + ":" + traceback.format_exc())

  1. dir_path = make_current_date_dir(ProjDirPath + "\\" + "ScreenCapture\\")

  1. dir_path = make_current_hour_dir(dir_path + "\\")

  1. pic_path = os.path.join(dir_path, get_current_time() + ".png")

  1. capture(pic_path)

  1. excel_obj.write_cell_value(int(test_step_row[0].value) + 1, test_step_capture_pic_path_col_no, pic_path)

  1. # 拼接结束时间:年月日+当前时间

  1. end_time = get_current_date() + " " + get_current_time()

  1. # 计时结束时间

  1. end_time_stamp = time.time()

  1. # 执行用例时间等于结束时间-开始时间;需要转换数据类型int()

  1. elapsed_time = int(end_time_stamp - start_time_stamp)

  1. # 将时间转换成分钟;整除60

  1. elapsed_minutes = int(elapsed_time // 60)

  1. # 将时间转换成秒;除60取余

  1. elapsed_seconds = elapsed_time % 60

  1. # 拼接用例执行时间;分+秒

  1. elapsed_time = str(elapsed_minutes) + "分" + str(elapsed_seconds) + "秒"

  1. # 判断用例是否执行成功

  1. if test_result_flag:

  1. test_case_result = "测试用例执行成功"

  1. else:

  1. test_case_result = "测试用例执行失败"

  1. # 需要写入的时第一个sheet

  1. excel_obj.set_sheet_by_index(1)

  1. # 写入开始时间

  1. excel_obj.write_cell_value(int(row_no), test_case_start_time_col_no, start_time)

  1. # 写入结束时间

  1. excel_obj.write_cell_value(int(row_no), test_case_end_time_col_no, end_time)

  1. # 写入执行时间

  1. excel_obj.write_cell_value(int(row_no), test_case_elapsed_time_col_no, elapsed_time)

  1. # 写入执行结果;

  1. if test_result_flag:

  1. # 用例执行成功,写入执行结果

  1. excel_obj.write_cell_value(int(row_no), test_case_result_col_no, test_case_result)

  1. else:

  1. # 用例执行失败,用red字体写入执行结果

  1. excel_obj.write_cell_value(int(row_no), test_case_result_col_no, test_case_result, "red")

  1. # 清理excel记录的结果数据

  1. def clear_test_data_file_info(test_data_excel_file_path):

  1. excel_obj = Excel(test_data_excel_file_path)

  1. excel_obj.set_sheet_by_index(1)

  1. test_case_rows = excel_obj.get_rows_object()[1:]

  1. for test_step_row in test_case_rows:

  1. excel_obj.set_sheet_by_index(1)

  1. if test_step_row[test_case_is_executed_flag_row_no].value == "y":

  1. excel_obj.write_cell_value(

  1. int(test_step_row[test_case_id_col_no].value) + 1, test_case_start_time_col_no, "")

  1. excel_obj.write_cell_value(

  1. int(test_step_row[test_case_id_col_no].value) + 1, test_case_end_time_col_no, "")

  1. excel_obj.write_cell_value(

  1. int(test_step_row[test_case_id_col_no].value) + 1, test_case_elapsed_time_col_no, "")

  1. excel_obj.write_cell_value(

  1. int(test_step_row[test_case_id_col_no].value) + 1, test_case_result_col_no, "")

  1. excel_obj.set_sheet_by_name(test_step_row[test_case_sheet_name].value)

  1. test_step_rows = excel_obj.get_rows_object()[1:]

  1. for test_step_row in test_step_rows:

  1. if test_step_row[test_step_id_col_no].value is None:

  1. continue

  1. excel_obj.write_cell_value(

  1. int(test_step_row[test_step_id_col_no].value) + 1, test_step_result_col_no, "")

  1. excel_obj.write_cell_value(

  1. int(test_step_row[test_step_id_col_no].value) + 1, test_step_error_info_col_no, "")

  1. excel_obj.write_cell_value(

  1. int(test_step_row[test_step_id_col_no].value) + 1, test_step_capture_pic_path_col_no, "")

  1. if __name__ == "__main__":

  1. test_data_excel_file_path = ProjDirPath + "\\TestData\\126邮箱联系人.xlsx"

  1. print(get_test_case_sheet(test_data_excel_file_path))

  1. execute(test_data_excel_file_path,2,"登录")文章来源地址https://www.toymoban.com/news/detail-487794.html

到了这里,关于python+selenium封装UI自动化框架的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • selenium-基于UI的自动化测试框架

      自动化测试是指软件测试的自动化,在预设状态下运行应用程序或者系统,预设条件包括正常和异常,最后评估运行结果,将人为驱动的测试行为转化为机器执行的过程   自动化测试包括UI自动化、接口自动化、单元测试自动化。按照这个金字塔模型来进行自动化测试

    2024年02月05日
    浏览(42)
  • selenium测试框架快速搭建(UI自动化测试)

    一、介绍         selenium目前主流的web自动化测试框架;支持多种编程语言Java、pythan、go、js等;selenium 提供一系列的api 供我们使用,因此在web测试时我们要点页面中的某一个按钮,那么我们只需要获取页面,然后根据id或者name找到对应的按钮,然后执行click操作就可以完成

    2024年02月02日
    浏览(50)
  • selenium UI自动化PO模式测试框架搭建

    熟悉业务-》确定方案-》选取场景-》了解前端-》定位元素-》编写脚本-》运行优化-》回归报告-》项目汇总 价值意义: 自动化执行需要:模块化 需要可制定化执行 可复用性 PO模式: 将页面定位和业务分开,元素的定位单独处理,执行脚本单独封装。维护方便。 封装BasePag

    2024年02月04日
    浏览(35)
  • 基于Selenium的Web UI自动化测试框架开发实战

    1、自研自动化测试框架 首先进行需求分析。概要设计包括以下三大模块: 公共函数库模块(包括可复用函数库、日志管理、报表管理及发送邮件管理); 测试用例仓库模块(具体用例的相关管理); 可视化页面管理模块(单独针对Web页面进行抽象,封装页面元素和操作方

    2024年01月20日
    浏览(38)
  • Python Selenium UI自动化测试_python 自动化ui测试

    2.2 安装selenium pip install selenium pip install selenium==2.53.0 2.3 下载webdriver驱动 以chrome浏览器为例 查看chrome浏览器版本:在地址栏输入 chrome://version chromedriver下载地址:http://chromedriver.storage.googleapis.com/index.html 下载与浏览器版本对应的chrome driver 将下载好的chrome driver 解压,并放至到

    2024年04月14日
    浏览(54)
  • Web UI 自动化测试框架(Pytest+Selenium+Allure+Loguru)

    本框架主要是基于 Python + pytest + selenium + Allure + loguru + 邮件通知/企业微信通知/钉钉通知 实现的WEB UI自动化框架。 基于PageObject设计模式结合,该平台可实现测试用例的自动化执行及自动化测试报告的生成同时包括自动化测试执行时,用例失败的截图操作。 使用webdriver_manag

    2024年02月04日
    浏览(42)
  • web自动化测试入门篇04——selenium+python基础方法封装

        😏 作者简介:博主是一位测试管理者,同时也是一名对外企业兼职讲师。 📡 主页地址:【Austin_zhai】 🙆 目的与景愿:旨在于能帮助更多的测试行业人员提升软硬技能,分享行业相关最新信息。 💎 声明:博主日常工作较为繁忙,文章会不定期更新,各类行业或职场问

    2024年02月03日
    浏览(36)
  • Python接口自动化 ❀ Request库详解和框架封装

    从招聘需求我们不难看出目前市面上对软件测试人员的要求: 综合型的测试人才、侧重业务能力 代码能力(在自动化框架这一块有一定的建树) 开发思维(代码的封装能力) 而接口测试或者接口自动化是每一个面试环节都必问的,比如: 主流接口测试工具 Postman+Newman+Jen

    2023年04月21日
    浏览(38)
  • 【自动化测试】基于Selenium + Python的web自动化框架

    Selenium是一个基于浏览器的自动化工具,她提供了一种跨平台、跨浏览器的端到端的web自动化解决方案。Selenium主要包括三部分:Selenium IDE、Selenium WebDriver 和Selenium Grid:  1、Selenium IDE:Firefox的一个扩展,它可以进行录制回放,并可以把录制的操作以多种语言(例如java,p

    2024年02月07日
    浏览(49)
  • Python Selenium UI自动化测试_python 自动化ui测试,Kotlin可能带来的一个深坑

    :层级选取,如:#formspaninput 举例:div.entry-sider-panelsection.entry-sider-panel__bddivdiv:nth-child(1) 3.3 元素操作 3.3.1 输入内容 send_keys() 3.3.2 点击元素 click() 3.3.3 清空元素文本内容 clear() 3.3.4 获取元素文本 text 返回的是字符串 3.3.5 获取元素尺寸 size 返回的是字典 3.3.6 获取元素的属性值

    2024年04月25日
    浏览(29)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包