ProjVar.py:
# -*-coding:utf-8 -*-
_author_ = 'kongsh'
__date__ = '2019/3/3 22:55'
import os
#工程路径
proj_path = os.path.dirname(os.path.dirname(__file__))
#测试用例名称
test_file_path = os.path.join(proj_path, "TestData", "测试用例.xlsx")
#测试case的sheet名称
test_case_sheet_name = "测试用例"
#测试用例是否执行所在的列
is_execute_col = 4
#测试步骤sheet中,动作,定位方法,定位表达式和操作值所在的列号
action_col = 2
locate_method_col =3
locate_expression_col = 4
oprate_value_col = 5
log_file_path = os.path.join(proj_path, "Log")
conf_path = os.path.join(proj_path, "Config", "Logger.conf")
ie_driver = "f:\\IEDriverServer"
chrome_driver = "f:\\chromedriver"
firefox_driver = "f:\\geckodriver"
if __name__=="__main__":
print(proj_path)
print(test_file_path)
print(log_file_path)
Test.py:
# -*-coding:utf-8 -*-
_author_ = 'kongsh'
__date__ = '2019/3/4 23:01'
from Utils.Excel import *
from Config.ProjVar import *
from Utils.Log import *
from Action.WebElementAction import *
successful_case_num = 0
#获取测试用例的excel文件对象
test_file_wb = ParseExcel(test_file_path)
#根据test_case_sheet_name切换到要操作的sheet
test_file_wb.set_sheet_by_name(test_case_sheet_name)
#获取测试用例是否需要执行的列
case_cols = test_file_wb.get_col(is_execute_col)
# print(case_cols)
for row_no, cell in enumerate(case_cols[1:],start=2):#去掉标题行
#如果是y的话说明需要执行
if cell.value.strip().lower() =="y":
#找到测试用例sheet的名称
test_step_sheet = test_file_wb.get_cell_value(row_no,is_execute_col-1)
#切换到test_step_sheet
test_file_wb.set_sheet_by_name(test_step_sheet)
#遍历测试步骤中所有的行,从2开始,忽略标题行
for i in range(2,test_file_wb.get_max_row()+1):
#获取动作
action = test_file_wb.get_cell_value(i, action_col)
#获取定位方法
locate_method = test_file_wb.get_cell_value(i, locate_method_col)
#获取定位表达式
locate_expression = test_file_wb.get_cell_value(i, locate_expression_col)
#获取操作值
value = test_file_wb.get_cell_value(i, oprate_value_col)
# print(action, locate_method, locate_expression, value)
#将动作,定位方法,
#没有参数
if action is not None and locate_method is None and locate_expression \
is None and value is None:
command = "%s()"%action
#只有操作值
elif action is not None and locate_method is None and locate_expression \
is None and value is not None:
command = "%s('%s')"%(action,value)
# 有定位方法和定位表达式
elif action is not None and locate_method is not None and locate_expression \
is not None and value is None:
command = "%s('%s','%s')" % (action, locate_method, locate_expression)
# 有定位方法、定位表达式和操作值
elif action is not None and locate_method is not None and locate_expression \
is not None and value is not None:
command = "%s('%s','%s','%s')" % (action, locate_method, locate_expression, value)
# print(command)
#执行拼接好的命令
try:
eval(command)
except Exception as e:
info("测试用例:%s执行失败,错误信息为:%s"%(action, str(traceback.format_exc())))
#写入执行时间
test_file_wb.write_cell_time(i,oprate_value_col+1)
# 写入执行结果
test_file_wb.write_cell(i, oprate_value_col + 2, "fail")
test_file_wb.set_cell_style(i, oprate_value_col + 2, font=Font(color=colors.RED))
#写入异常信息
test_file_wb.write_cell(i, oprate_value_col + 3, str(traceback.format_exc()))
else:
info("测试用例:%s执行成功" %action)
# 写入执行时间
test_file_wb.write_cell_time(i, oprate_value_col + 1)
# 写入执行结果
test_file_wb.write_cell(i, oprate_value_col + 2, "pass")
test_file_wb.set_cell_style(i, oprate_value_col + 2, font=Font(color=colors.GREEN))
# 写入异常信息
successful_case_num += 1
#切换到test_case_sheet_name中,写入整体的测试结果
result = "pass"
if successful_case_num != test_file_wb.get_max_row()-1:
result = "fail"
test_file_wb.set_sheet_by_name(test_case_sheet_name)
# 写入执行日期和时间
test_file_wb.write_cell_datetime(row_no, is_execute_col + 1)
# 写入测试执行结果
test_file_wb.write_cell(row_no, is_execute_col + 2, result)
ClipboardUtil.py:
# -*-coding:utf-8 -*-
_author_ = 'kongsh'
__date__ = '2019/3/4 13:59'
import win32clipboard as w
import win32con
class Clipboard(object):
'''模拟windows设置和读取剪贴板'''
@staticmethod
def setText(content):
'''设置剪贴板'''
#打开剪贴板
w.OpenClipboard()
#清空剪贴板
w.EmptyClipboard()
#设置指定的内容
w.SetClipboardData(win32con.CF_UNICODETEXT, content)
#关闭剪贴板
w.CloseClipboard()
def getText():
'''获取剪贴板中指定的内容'''
#打开剪贴板
w.OpenClipboard()
#读取剪贴板中的内容
content = w.GetClipboardData(win32con.CF_TEXT)
#关闭剪贴板
w.CloseClipboard()
#返回从剪贴板获取的数据
return content
Dir.py
# -*-coding:utf-8 -*-
_author_ = 'kongsh'
__date__ = '2019/3/4 11:31'
import time
import os
from Utils.GenTime import *
from Config.ProjVar import *
def make_date_dir(dir_path=log_file_path):
'''在dir_path下创建日期目录'''
if os.path.exists(dir_path):
path = os.path.join(dir_path, get_current_date())
if not os.path.exists(path):
os.mkdir(path)
else:
raise Exception("make_date_dir创建目录失败!")
def make_time_dir(dir_path=log_file_path):
'''在dir_path下创建时间目录'''
if os.path.exists(dir_path):
path = os.path.join(dir_path, get_current_time())
if not os.path.exists(path):
os.mkdir(path)
else:
raise Exception("make_time_dir创建目录失败!")
if __name__=="__main__":
make_date_dir()
make_time_dir()
Excel.py:
# -*-coding:utf-8 -*-
_author_ = 'kongsh'
__date__ = '2019/3/3 22:37'
import os
import time
import traceback
from openpyxl import load_workbook
from openpyxl.styles import Font, Border, Side, PatternFill, Alignment, colors
class ParseExcel(object):
'''excel操作类'''
def __init__(self,file_path):
if not os.path.exists(file_path):
self.wb = None
self.file_path = file_path
self.wb = load_workbook(file_path)
self.sheet = self.wb[self.wb.sheetnames[0]]
def get_excel_file_path(self):
'''获取excel文件命名'''
return self.file_path
def set_sheet_by_name(self, name):
'''切换到name指定的sheet'''
self.sheet = None
if name in self.wb.sheetnames:
self.sheet = self.wb[name]
return self.sheet
def get_current_sheet_name(self):
'''获取当前sheet的名称'''
if self.sheet:
return self.sheet.title
def get_min_row(self):
'''获取最小行号,从1开始'''
try:
return self.sheet.min_row
except:
traceback.print_exc()
return None
def get_max_row(self):
'''获取最大行号'''
try:
return self.sheet.max_row
except:
traceback.print_exc()
return None
def get_min_col(self):
'''获取最小列号,从1开始'''
try:
return self.sheet.min_column
except:
traceback.print_exc()
return None
def get_max_col(self):
'''获取最大列号'''
try:
return self.sheet.max_column
except:
traceback.print_exc()
return None
def get_row(self, row_no):
'''按索引获取指定的行'''
if not isinstance(row_no, int):
return None
try:
return list(self.sheet.rows)[row_no - 1]
except:
traceback.print_exc()
def get_col(self, col_no):
'''按索引获取指定的列'''
if not isinstance(col_no, int):
return None
try:
return list(self.sheet.columns)[col_no - 1]
except:
traceback.print_exc()
def get_cell_value(self, row_no, col_no):
'''获取指定单元格的内容'''
if isinstance(row_no, int) and isinstance(col_no, int):
try:
return self.sheet.cell(row=row_no, column=col_no).value
except:
traceback.print_exc()
def write_cell(self, row_no, col_no, value):
'''设置指定单元格的内容'''
if isinstance(row_no, int) and isinstance(col_no, int):
try:
self.sheet.cell(row=row_no, column=col_no).value = value
self.save()
except:
traceback.print_exc()
def write_cell_date(self, row_no, col_no):
'''向指定单元格写入日期字符串'''
timeTup = time.localtime()
currentDate = str(timeTup.tm_year)+'年'+str(timeTup.tm_mon)+'月'+ \
str(timeTup.tm_mday) + '日'
self.write_cell(row_no, col_no, currentDate)
def write_cell_time(self, row_no, col_no):
'''向指定单元格写入时间字符串'''
timeTup = time.localtime()
currentTime = str(timeTup.tm_hour) + "时" + \
str(timeTup.tm_min) + "分" + str(timeTup.tm_sec) + "秒"
self.write_cell(row_no, col_no, currentTime)
def write_cell_datetime(self, row_no, col_no):
'''向指定单元格写入日期和时间字符串'''
timeTup = time.localtime()
currentDate = str(timeTup.tm_year) + "年" + \
str(timeTup.tm_mon) + "月" + str(timeTup.tm_mday) + "日"
currentTime = str(timeTup.tm_hour) + "时" + \
str(timeTup.tm_min) + "分" + str(timeTup.tm_sec) + "秒"
self.write_cell(row_no, col_no, currentDate+" "+currentTime)
def merge_cells(self, range_string=None, start_row=None, start_column=None, end_row=None, end_column=None):
'''合并单元格'''
try:
self.sheet.merge_cells(range_string, start_row, start_column, end_row, end_column)
except:
traceback.print_exc()
else:
self.save()
def set_cell_style(self, row_no, col_no, border=None, fill=None,
font=None, alignment=None):
'''设定单元格的字体,颜色,边框,大小和边框背景色'''
try:
cell = self.sheet.cell(row=row_no, column=col_no)
if border:
cell.border = border
if font:
cell.font = font
if fill:
cell.fill = fill
if alignment:
cell.alignment = alignment
except:
traceback.print_exc()
else:
self.save()
def save(self):
'''保存单元格'''
self.wb.save(self.file_path)
if __name__=="__main__":
ws = ParseExcel("126邮箱联系人.xlsx")
print(ws.get_current_sheet_name())
print(ws.get_excel_file_path())
print(ws.get_min_row())
print(ws.get_max_row())
print(ws.get_min_col())
print(ws.get_max_col())
print(ws.get_row(3))
print(ws.get_col(4))
ws.write_cell_date(1, 1)
ws.write_cell_time(1, 2)
ws.write_cell_datetime(1, 3)
ws.merge_cells("A1:A3")
ws.set_cell_style(3, 3, font=Font(color=colors.RED))
GenTime.py:
# -*-coding:utf-8 -*-
_author_ = 'kongsh'
__date__ = '2019/3/4 11:36'
import time
def get_current_date():
'''生成日期字符串,格式为xxxx年xx月xx日'''
timeTup = time.localtime()
currentDate = str(timeTup.tm_year) + "年" + \
str(timeTup.tm_mon) + "月" + str(timeTup.tm_mday) + "日"
return currentDate
def get_current_time():
'''生成时间字符串,格式为xx时xx分xx秒'''
timeTup = time.localtime()
currentTime = str(timeTup.tm_hour) + "时" + \
str(timeTup.tm_min) + "分" + str(timeTup.tm_sec) + "秒"
return currentTime
def get_current_datetime():
'''生成日期+日期字符串,格式为xxxx年xx月xx日 xx时xx分xx秒'''
return get_current_date() + " " + get_current_time()
if __name__ == "__main__":
print(get_current_date())
print(get_current_datetime())
print(get_current_time())
KeyboardUtil.py:
# -*-coding:utf-8 -*-
_author_ = 'kongsh'
__date__ = '2019/3/4 14:06'
import win32api
import win32con
class Keyboard(object):
'''模拟键盘操作类'''
VK_CODE = {
'enter':0x0D,
"ctrl": 0x11,
'a':0x41,
'v': 0x56,
'x': 0x58,
'z': 0x5A,
'tab': 0x09
}
@staticmethod
def keyDown(keyName):
'''按下'''
win32api.keybd_event(Keyboard.VK_CODE[keyName], 0, 0, 0)
@staticmethod
def keyUp(keyName):
'''抬起'''
win32api.keybd_event(Keyboard.VK_CODE[keyName], 0, win32con.KEYEVENTF_KEYUP, 0)
@staticmethod
def oneKey(keyName):
'''单个按键的按下和抬起'''
Keyboard.keyDown(keyName)
Keyboard.keyUp(keyName)
@staticmethod
def twoKey(keyName1, keyName2):
'''两个按键的按下和抬起'''
Keyboard.keyDown(keyName1)
Keyboard.keyDown(keyName2)
Keyboard.keyUp(keyName2)
Keyboard.keyUp(keyName1)
WaitUtil.py:
# -*-coding:utf-8 -*-
_author_ = 'kongsh'
__date__ = '2019/3/4 14:47'
import traceback
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
class WaitUtil(object):
def __init__(self, driver):
self.driver = driver
self.wait = WebDriverWait(self.driver, 10)
self.locate_method = {
'id':By.ID,
'name':By.NAME,
'xpath':By.XPATH,
'link_text':By.LINK_TEXT,
'partial_link_text':By.PARTIAL_LINK_TEXT
}
def presenceOfElement(self, locateMethod, locateExpression):
'''显示等待判断元素是否存在'''
try:
return self.wait.until\
(lambda x:x.find_element(self.locate_method[locateMethod],
locateExpression))
except TimeoutException:
traceback.print_exc()
raise TimeoutException
def visibleOfElement(self, locateMethod, locateExpression):
'''显示等待判断元素是否可见'''
try:
return self.wait.until\
(EC.visibility_of_element_located((self.locate_method[locateMethod],
locateExpression)))
except TimeoutException:
traceback.print_exc()
raise TimeoutException
def clickbleOfElement(self, locateMethod, locateExpression):
'''显示等待判断元素是否点击'''
try:
return self.wait.until\
(EC.element_to_be_clickable((self.locate_method[locateMethod],
locateExpression)))
except TimeoutException:
traceback.print_exc()
raise TimeoutException
def switchToFrame(self, locateMethod, locateExpression):
'''切换到指定的frame'''
try:
return self.wait.until\
(EC.frame_to_be_available_and_switch_to_it((self.locate_method[locateMethod],
locateExpression)))
except Exception as e:
traceback.print_exc()
raise e
def beSelectedOfElement(self, locateMethod, locateExpression):
'''显示等待判断元素是否被选中'''
try:
return self.wait.until \
(EC.element_located_to_be_selected((self.locate_method[locateMethod],
locateExpression)))
except TimeoutException:
traceback.print_exc()
raise TimeoutException
if __name__ == "__main__":
driver = webdriver.Chrome(executable_path="f:\\chromedriver")
wait_object = WaitUtil(driver)
driver.get("http://mail.126.com")
try:
element = wait_object.switchToFrame("xpath", "//iframe[contains(@id,'x-URS-iframe')]")
import time
time.sleep(3)
except TimeoutException:
print("元素未定位!")