思路:
1)设计测试数据
2)读取excel
3) 编写测试脚本
数据
excel读取
# encoding = utf-8
from openpyxl import load_workbook
class ParseExcel(object):
def __init__(self,excelPath,SheetName):
# 将要读取的excel加载到内存
self.wb = load_workbook(excelPath)
# 通过工作表名称获取工作表对象
self.sheet = self.wb.get_sheet_by_name(SheetName)
self.maxRowNum = self.sheet.max_row
def getDatasFromSheet(self):
# 用于存放从工作表中读出来的数据
dataList=[]
for line in self.sheet.rows[1:]:
print(line[0].value)
tmpList = []
tmpList.append(line[1].value)
tmpList.append(line[2].value)
# tmpList.append(line[3].value)
dataList.append(tmpList)
return dataList
if __name__ == '__main__':
excelPath = "/Users/doudou/Desktop/搜索数据表.xlsx"
SheetName = "工作表1"
pe = ParseExcel(excelPath,SheetName)
for i in pe.getDatasFromSheet():
print(i[0],i[1])
脚本
# encoding = utf-8
from selenium import webdriver
import unittest,time
import ddt,traceback
from excel.readExcel import ParseExcel
from selenium.common.exceptions import NoSuchElementException
excelPath = '/Users/doudou/Desktop/搜索数据表.xlsx'
SheetName = "工作表1"
# 创建ParseExcel类的实例对象
excel = ParseExcel(excelPath,SheetName)
@ddt.ddt
class TestDemo(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Firefox()
@ddt.data(*excel.getDatasFromSheet())
def test_dataDrivenByFile(self,data):
testData,expectData = tuple(data)
url = "http://www.baidu.com"
self.driver.get(url)
self.driver.maximize_window()
time.sleep(5)
print(testData, expectData)
try:
self.driver.find_element_by_id("kw").send_keys(testData)
self.driver.find_element_by_id("su").click()
time.sleep(3)
self.assertTrue(expectData in self.driver.page_source)
except NoSuchElementException as e:
print("查找的网页元素不存在:"+str(traceback.format_exc()))
except AssertionError as e:
print("搜索'%s',期望'%s',失败"%(testData,expectData))
except Exception as e:
print("未知错误信息:"+str(traceback.format_exc()))
else:
print("搜索'%s'期望'%s通过" %(testData,expectData))
def tearDown(self):
self.driver.quit()
if __name__ == '__main__':
unittest.main()