python+selenium封装UI自动化框架

seleinum框架

框架的思想:

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

1)配置和程序的分离

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

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

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

5)自动发报告

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

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

为什么要编写程序呢?

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

测试的工具:python+selenium

接口测试用例:excel

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

分层如下:

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目录:所有生成的日志、截屏报告均放在这里

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,"登录")

  • 2
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值