關鍵字驅動測試框架搭建(2)

二、練習:使用excel,使用關鍵字驅動,實現一個搜狗搜索
4個關鍵字:訪問某個網站、輸入文字、點擊搜索按鈕、斷言
普通腳本以下:
test_no_keyword.pyweb

#encoding=utf-8
from selenium import webdriver
import time

driver = webdriver.Firefox(executable_path = "D:\\geckodriver")
driver.maximize_window()
driver.get("http://www.sogou.com")
search_box = driver.find_element_by_id("query")
search_box.send_keys(u"光榮之路 吳老師")
button = driver.find_element_by_id("stb")
button.click()
time.sleep(3)

assert u"財富自由" in driver.page_source

driver.quit()

關鍵字驅動以下:
Excel數據列
動做(方法名),定位方式,定位表達式,操做值,執行結果
browser,,,firefox
visit_url,,,http://www.sogou.com
input,id,query,光榮之路 吳老師
click,id,stb
sleep,,,2
assert_word,,,財富自由
quit,,,

須要將以上數據經過框架拼接成可執行函數調用,再經過eval執行
browser("firefox")
visit_url("http://www.sogou.com")
input("id","query",u"光榮之路 吳老師")
click("id","stb")
sleep(2)
assert_word(u"財富自由")
quit()


建立一個工程sogou_search_keyword_driven
工程下建立一個包Util,項下放解析Excel的模塊
ParseExcel.py,解析Excel類,內容以下:express

# encoding=utf-8
import openpyxl
from openpyxl.styles import Border, Side, Font
import time


class ParseExcel(object):

    def __init__(self):
        self.workbook = None
        self.excelFile = None
        self.font = Font(color = None) #設置字體的顏色
        #顏色對應的RGB值
        self.RGBDict = {"red":"FFFF0303","green":"FF008B00"}

    def loadWorkbook(self,excelPathAndName):
        #將excel文件加載到內存,並獲取其workbook對象
        try:
            self.workbook = openpyxl.load_workbook(excelPathAndName)
        except Exception,e:
            raise e
        self.excelFile = excelPathAndName
        return self.workbook

    def getSheetByName(self,sheetName):
        #根據sheet名獲取該sheet對象
        try:
            sheet = self.workbook.get_sheet_by_name(sheetName)
            return sheet
        except Exception,e:
            raise e

    def getSheetByIndex(self,sheetIndex):
        #根據sheet的索引號獲取該sheet對象
        try:
            sheetName = self.workbook.get_sheet_names()[sheetIndex]
        except Exception,e:
            raise e
        sheet = self.workbook.get_sheet_by_name(sheetName)
        return sheet

    def getRowsNumber(self,sheet):
        #獲取sheet中有數據區域的結束行號
        return sheet.max_row

    def getColsNumber(self,sheet):
        #獲取sheet中有數據區域的結束列號
        return sheet.max_column

    def getStartRowNumber(self,sheet):
        #獲取sheet中有數據區域的開始行號
        return sheet.min_row

    def getStartColNumber(self,sheet):
        #獲取sheet中有數據區域的開始列號
        return sheet.min_column

    def getRow(self,sheet,rowNo):
        #獲取sheet中某一行,返回的是這一行全部的數據內容組成的tuple
        #下標從1開始,sheet.rows[1]表示第一行
        try:
            rows = []
            for row in sheet.iter_rows():
                rows.append(row)
            return rows[rowNo - 1]
        except Exception , e:
            raise e

    def getColumn(self,sheet,colNo):
        #獲取sheet中某一列,返回的是這一列全部數據內容組成的tuple
        #下標從1開始,sheet,columns[1]表示第一列
        try:
            cols = []
            for col in sheet.iter_cols():
                cols.append(col)
            return cols[colNo - 1]
        except Exception,e:
            raise e

    def getAllRows(self,sheet):
        #獲取sheet中全部行
        try:
            rows = []
            for row in sheet.iter_rows():
                rows.append(row)
            return rows
        except Exception , e:
            raise e

    def getAllColumns(self,sheet):
        #獲取sheet中全部列
        try:
            cols = []
            for col in sheet.iter_cols():
                cols.append(col)
            return cols
        except Exception,e:
            raise e

    def getCellOfValue(self,sheet,coordinate = None,rowNo = None,colNo = None):
        #根據單元格所在的位置索引獲取該單元格的值,座標從1開始
        #sheet.cell(row = 1,column = 1).value 表示excel中第一行第一列的值
        if coordinate != None:
            try:
                return sheet.cell(coordinate = coordinate).value
            except Exception,e:
                raise e
        elif coordinate is None and rowNo is not None and colNo is not None:
            try:
                return sheet.cell(row = rowNo,column = colNo).value
            except Exception,e:
                raise e
        else:
            raise Exception("Insufficient Coordinates of Cell !!!")

    def getCellOfObject(self,sheet,coordinate = None,rowNo = None,colNo = None):
        #獲取某個單元格的對象,能夠根據單元格所在位置的數字索引,
        #也能夠直接根據excel中單元格的編碼及座標
        #如getCellOfObject(sheet,corrdinate = "A1") 或者
        #getCellOfObject(sheet,rowNo = 1,colNo = 1)
        if coordinate != None:
            try:
                return sheet.cell(coordinate = coordinate)
            except Exception,e:
                raise e
        elif coordinate == None and rowNo is not None and colNo is not None:
            try:
                return sheet.cell(row = rowNo,column = colNo)
            except Exception,e:
                raise e
        else:
            raise Exception("Insufficient Coordinates of Cell !!!")

    def writeCell(self,sheet,content,coordinate = None,rowNo = None,colNo = None,style = None):
        #根據單元格在excel中的編碼位置或者數字索引座標向單元格中寫入數據
        #下標從1開始,參數style表示字體顏色的名稱,好比,red , green
        if coordinate != None:
            try:
                sheet.cell(coordinate = coordinate).value = content
                if style is not None:
                    sheet.cell(coordinate=coordinate).font = Font(color = self.RGBDict[style])
                self.workbook.save(self.excelFile)
            except Exception,e:
                raise e
        elif coordinate == None and rowNo is not None and colNo is not None:
            try:
                sheet.cell(row = rowNo,column = colNo).value = content
                if style is not None:
                     sheet.cell(coordinate=coordinate).font = Font(color=self.RGBDict[style])
                self.workbook.save(self.excelFile)
            except Exception,e:
                raise e
        else:
            raise Exception("Insufficient Coordinates of Cell !!!")

    def writeCelCurrentTime(self,sheet,coordinate = None,rowNo = None,colNo = None,style = None):
        #寫入當前時間,下標從1開始
        now = int(time.time()) #顯示爲時間戳
        timeArray = time.localtime(now)
        currentTime = time.strftime("%Y-%m-%d %H:%M:%S",timeArray)
        if coordinate != None:
            try:
                sheet.cell(coordinate = coordinate).value = currentTime
                self.workbook.save(self.excelFile)
            except Exception,e:
                raise e
        elif coordinate == None and rowNo is not None and colNo is not None:
            try:
                sheet.cell(row = rowNo,column = colNo).value = currentTime
                self.workbook.save(self.excelFile)
            except Exception,e:
                raise e
        else:
            raise Exception("Insufficient Coordinates of Cell !!!")


if __name__ == "__main__":
    pe = ParseExcel()
    pe.loadWorkbook("D:\\PythonProject\\keyword_driven_frame\\sogou_search_keyword_driven\\test_data_test.xlsx")
    print u"經過名稱獲取sheet對象的名字:",pe.getSheetByName(u"測試步驟").title
    print u"經過index獲取sheet對象的名字:", pe.getSheetByIndex(0).title
    sheet = pe.getSheetByIndex(0)
    print type(sheet)
    print "max row number:",pe.getRowsNumber(sheet)
    print "max column Number:",pe.getColsNumber(sheet)
    row = pe.getRow(sheet,1) #獲取第一行
    for i in row:
        print i.value
    #獲取第一行第一列單元格內容
    print "*" * 50
    print pe.getCellOfValue(sheet,rowNo = 1,colNo = 1)
    pe.writeCell(sheet,u"我愛中國",rowNo = 10,colNo = 10)
    pe.writeCelCurrentTime(sheet,rowNo = 10,colNo = 11)

測試數據文件直接存放在工程目錄下:
test_data.xslx中的「測試步驟」sheet數據以下:
動做                 定位方式                定位表達式                      操做值                             執行結果
broswer                                                                                  firefox    
visit_url                                                                                   http://www.sogou.com    
input                  id                             query                             光榮之路 吳老師    
click                  xpath                       //*[@id='stb']        
sleep                                                                                       2    
assert_word                                                                            自由    
quit

再建立一個包Action,存放關鍵字方法:
PageAction.py內容以下:app

#encoding=utf-8
from selenium import webdriver
import time

driver = ""
#定義函數
def browser(browser_name):
    global driver #聲明全局變量
    try:
        if browser_name.lower() == "firefox":
            driver = webdriver.Firefox(executable_path = "D:\\geckodriver")
    except Exception,e:
        raise e

def visit_url(url):
    global driver  # 聲明全局變量
    try:
        driver.get(url)
    except Exception, e:
        raise e

def input(locate_method,locate_expression,content):
    global driver  # 聲明全局變量
    try:
        # 添加顯式等待
        driver.find_element(locate_method,locate_expression).send_keys(content)
    except Exception, e:
        raise e

def click(locate_method,locate_expression):
    global driver  # 聲明全局變量
    try:
        # 添加顯式等待
        driver.find_element(locate_method,locate_expression).click()
    except Exception, e:
        raise e

def sleep(sleep_time):
    global driver  # 聲明全局變量
    try:
        time.sleep(int(sleep_time))
    except Exception, e:
        raise e

def quit():
    global driver  # 聲明全局變量
    try:
        driver.quit()
    except Exception, e:
        raise e

def assert_word(word):
    global driver  # 聲明全局變量
    try:
        assert word in driver.page_source
    except Exception, e:
        raise e
        

在工程目錄下建立測試腳本:
run.py內容以下:框架

#encoding=utf-8
from Util import ParseExcel
from Action.PageAction import *
import sys
reload(sys)
sys.setdefaultencoding("utf-8")

test_data_excel = ParseExcel.ParseExcel()
test_data_excel.loadWorkbook("test_data.xlsx")
#測試解析Excel,能夠刪除
print u"經過名稱獲取sheet對象的名字:",test_data_excel.getSheetByName(u"測試步驟").title
test_data_sheet = test_data_excel.getSheetByName(u"測試步驟")

row_num = test_data_excel.getRowsNumber(test_data_sheet)
print "Total Rows:",row_num
for i in range(1,row_num+1):
    print test_data_excel.getRow(test_data_sheet,i)

print "=" * 50
col_num = test_data_excel.getColsNumber(test_data_sheet)
print "Total Columns:",col_num
for j in range(1,col_num+1):
    print test_data_excel.getColumn(test_data_sheet,j)

print "*" * 50

#遍歷文件,開始進行測試
for i in range(1,row_num):
    # for j in range(col_num-1): #行號是固定的,而後按列號遍歷,獲取每一行,結果列不須要讀取
    #     print test_data_excel.getRow(test_data_sheet,i)[j].value
    row = test_data_excel.getAllRows(test_data_sheet)[i]
    print "-" * 50
    print u"行號:",row[0].value
    action =  row[1].value
    locate_method = row[2].value
    locate_expression = row[3].value
    operate_value = row[4].value

    print action,locate_method,locate_expression,operate_value

    print "+" * 50
    #拼接字符串
    #excel中組合狀況有四種,即:(定位方式+定位表達式)和操做值爲空或不空的組合狀況
    #定位方式和定位表達式只能同時存在或同時爲空,因此能夠看成是一個字段
    #遍歷組合狀況,拼接不一樣形式的字符串
    #將定位表達式中的單引號替換成雙引號,因在後面拼接字符串時須要用單引號去包括參數
    #因此須要進行替換,或者用雙引號包括參數,則excel中的定位表達式須要用單引號
    #兩種狀況取一種
    test_step = ""
    if action and locate_method is None and operate_value:
        test_step = action + "('" + str(operate_value) + "')"
        print test_step
    elif action and locate_method and locate_expression and operate_value:
        #加u後拼接會報錯,須要使用sys.setdefaultencoding("utf-8")
        test_step = action + "('" + locate_method + "','" + locate_expression.replace("\'","\"") + "',u'" + str(operate_value) + "')"
        print test_step
    elif action and locate_method and locate_expression and operate_value is None:
        test_step = action + "('" + locate_method + "','" + locate_expression.replace("\'","\"") + "')"
        print test_step
    elif action and locate_method is None and locate_expression is None and operate_value is None:
        test_step = action + "()"
        print test_step
    try:
        eval(test_step)
        #執行成功,在結果列中寫入「Success」
        test_data_excel.writeCell(test_data_sheet,"Success",rowNo = i+1,colNo = 6)
    except Exception,e:
        #執行失敗,在結果列中寫入「Fail」
        test_data_excel.writeCell(test_data_sheet, "Fail", rowNo= i+1, colNo=6)

以上內容爲一個簡單的關鍵字驅動框架,真正的框架核心思想也是如此,經過拼接字符串,拼接出想要的函數調,再用eval執行每一步,只不過真正的框架中封裝了更多的方法ide

相關文章
相關標籤/搜索