Introduction:data-driven Excel driver, is the data configuration in Excel, the main program calls every time with the data taken from Excel as parameters, to operate,what needs to be mastered is the operation of Excel, the flexibility to find the target datatest data. xlsx:
Path-d:\test\0627
excelutil.py:
#encoding =utf-8
From OPENPYXL import Load_workbook
Class Parseexcel (object):
def __init__ (self, Excelpath, sheetname):
# Load the Excel that will be read into memory
SELF.WB = Load_workbook (Excelpath)
# Get a Sheet object from a worksheet name
Self.sheet = Self.wb.get_sheet_by_name (sheetname)
# Gets the maximum row number of the area where the data exists in the worksheet
Self.maxrownum = Self.sheet.max_row
def getdatasfromsheet (self):
# used to hold data read from the worksheet
DataList = []
# because the first row in the worksheet is the header row, you need to remove
For line in Self.sheet.rows:
# Traverse each row of the data region in the worksheet,
# and the data from each cell in each row is stored in the list tmplist,
# then add a list of rows of data to the final data list DataList
Tmplist = []
Tmplist.append (Line[1].value)
Tmplist.append (Line[2].value)
Datalist.append (Tmplist)
# The Iteration object that gets all the data in the worksheet is returned
Return Datalist[1:]
if __name__ = = ' __main__ ':
Excelpath = U ' e:\\ data driven \ test data. xlsx '
SheetName = u "search data table"
PE = parseexcel (Excelpath, SheetName)
Print Pe.getdatasfromsheet ()
For I in Pe.getdatasfromsheet ():
Print i[0], i[1]
Add print debug log:
#encoding =utf-8
From OPENPYXL import Load_workbook
Class Parseexcel (object):
def __init__ (self,excelpath,sheetname):
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:
Tmplist=[]
Tmplist.append (Line[1].value)
Print "Line[1].value", Line[1].value
Tmplist.append (Line[2].value)
Print "Line[2].value", Line[2].value
Datalist.append (Tmplist)
Print Datalist[1:]
Return Datalist[1:]
If __name__== ' __main__ ':
Excelpath=u "d:\\test\\0627\\ test data. xlsx"
Sheetname=u "Search Data Sheet"
Pe=parseexcel (Excelpath,sheetname)
Print Pe.getdatasfromsheet ()
For I in Pe.getdatasfromsheet ():
Print I[0],i[1]
Run results separately:
D:\test\0627>python excelutil.py
Excelutil.py:7: Deprecationwarning:call to deprecated function get_sheet_by_name (use Wb[sheetname]).
Self.sheet=self.wb.get_sheet_by_name (SheetName)
Line[1].value search terms
Line[2].value expected results
Line[1].value Duncan
Line[2].value Tim
Line[1].value Jordan
Line[2].value Michael
Line[1].value in the library.
Line[2].value Stephen
[u ' \U9093\U80AF ', U ' \u8482\u59c6 '], [u ' \u4e54\u4e39 ', U ' \u8fc8\u514b\u5c14 '], [u ' \u5e93\u91cc ', U ' \u65af\u8482\ U82ac ']
[u ' \U9093\U80AF ', U ' \u8482\u59c6 '], [u ' \u4e54\u4e39 ', U ' \u8fc8\u514b\u5c14 '], [u ' \u5e93\u91cc ', U ' \u65af\u8482\ U82ac ']
Line[1].value search terms
Line[2].value expected results
Line[1].value Duncan
Line[2].value Tim
Line[1].value Jordan
Line[2].value Michael
Line[1].value in the library.
Line[2].value Stephen
[u ' \U9093\U80AF ', U ' \u8482\u59c6 '], [u ' \u4e54\u4e39 ', U ' \u8fc8\u514b\u5c14 '], [u ' \u5e93\u91cc ', U ' \u65af\u8482\ U82ac ']
Duncantim
Jordan Michael
Kuristifen
last script to run:
data_drivern_by_excel.py:
#encoding =utf-8
From selenium import Webdriver
Import Unittest,time
Import Logging,traceback
Import DDT
From Excelutil import Parseexcel
From selenium.common.exceptions import nosuchelementexception
#初始化日志对象
Logging.basicconfig (
#日志级别
Level=logging.info,
#日志格式
#时间, the name of the code, the code line number, the log level name, the log information
format= '% (asctime) s% (filename) s[line:% (lineno) d]% (levelname) s% (message) s ',
#打印日志的时间
datefmt= '%a,%y-%m-%d%h:%m:s ',
#日志文件存放的目录 (directory must exist) and log file name
Filename= ' D:\\test\\0627\\report.log ',
#打开日志文件的方式
Filemode= ' W '
)
Excelpath=u "d:\\test\\0627\\ test data. xlsx"
Sheetname=u "Search Data Sheet"
#创建ParseExcel类的实例对象
Excel=parseexcel (Excelpath,sheetname)
#数据驱动装饰器
@ddt. DDT
Class Testdemo (UnitTest. TestCase):
def setUp (self):
Self.driver=webdriver. Firefox (executable_path= ' c:\\geckodriver ')
@ddt. Data (*excel.getdatasfromsheet ()) #对调用函数返回的含列表的列表进行解包, a list in the list is passed in.
def test_datadrivenbyfile (Self,data):
print "Tuple (data):", tuple (data) #把传过来的一个列表转换成元祖, contains two elements, search values and expectations
Testdata,expectdata=tuple (data)
Print "TestData:", testdata# trial
Print "Expectdata:", expectdata# trial
Url= ' http://www.baidu.com '
#访问百度首页
Self.driver.get (URL)
#讲浏览器窗口最大化
Self.driver.maximize_window ()
#print Testdata,expectdata
#设置隐式等待时间为10秒钟
Self.driver.implicitly_wait (10)
Try
#获取当前的时间戳, used to calculate query time later
Start=time.time ()
#获取当前时间的字符串, indicating the test start time
Starttime=time.strftime ("%y-%m-%d%h:%m:%s", Time.localtime ())
#找到搜索输入框 and enter the test data
self.driver.find_element_by_id (' kw '). Send_keys (TestData)
#找到搜索按钮, and click
self.driver.find_element_by_id (' su '). Click ()
Time.sleep (3)
#断言期望结果是否出现在页面源代码中
Self.asserttrue (Expectdata in Self.driver.page_source)
Print U "search-%s, expect-%s"% (testdata,expectdata)
Except Nosuchelementexception,e:
Logging.error (U "Lookup page element does not exist, exception stack information:" +str (Traceback.format_exc ()))
Except Assertionerror,e:
Logging.info (U ' search-'%s ', expected-'%s ',-failed '% (testdata,expectdata))
Except Exception,e:
Logging.error (U "Unknown error, error message:" +str (Traceback.format_exc ()))
Else
Logging.info (U ' search-'%s ', expected-"%s"-through '% (testdata,expectdata))
def tearDown (self):
Self.driver.quit ()
If __name__== ' __main__ ':
Unittest.main ()
Results:
D:\test\0627>python test.py
D:\test\0627\excelutil.py:11:deprecationwarning:call to deprecated function get_sheet_by_name (use Wb[sheetname]).
Self.sheet=self.wb.get_sheet_by_name (SheetName)
Tuple (data): (U ' \U9093\U80AF ', U ' \u8482\u59c6 ')
TestData: Duncan
Expectdata: Tim
Search-Duncan, expect-Tim
. Tuple (data): (U ' \u4e54\u4e39 ', U ' \u8fc8\u514b\u5c14 ')
TestData: Jordan
Expectdata: Michael
Search-Jordan, expectation-Michael
. Tuple (data): (U ' \u5e93\u91cc ', U ' \u65af\u8482\u82ac ')
TestData: In the Library
Expectdata: Stephen
Search-Library, expectation-Stephen
.
----------------------------------------------------------------------
Ran 3 Tests in 45.614s
Ok
Report.log:
fri,2018-06-29 11:18:s test.py[line:70] INFO search-"Duncan", expectation-"Tim"-by
fri,2018-06-29 11:18:s test.py[line:70] INFO search-"Jordan", Expectation-"Michael"-by
fri,2018-06-29 11:18:s test.py[line:70] INFO search-"In the library", expect-"Stephen"-by
Summarize:
If there is a problem with the log logging part of the writing format, or if the path does not exist, or if there is a problem with the character, the log will be output to the screen, and if there is no problem, it will print to the log file Report.log
Data-driven Excel drive and other methods (TXT, etc.) principle is similar, are to take out the data from the file, with the DDT module to unpack, into the main program, the difficulty is to read different file types may require a special package to deal with, plainly, are the basis of the use of integration, The real project is definitely more complicated than this ...
Python webdriver test framework-how data drives Excel drives