自動化測試框架的搭建

自動化測試框架的搭建
一、自動化測試框架
(1)概述:
自動化測試框架是應用於自動化測試的程序框架。它提供了可重用的自動化測試模塊,提供最基礎的自動化測試功能(如:打開瀏覽器、單擊連接等功能),或提供自動化測試執行和管理功能的架構模塊(如TestNG)。它是由一個或多個自動化測試基礎模塊、自動化測試管理模塊、自動化測試統計模塊等組成的工具集合。
(2)常見模式
>數據驅動測試框架:使用數據數組、測試數據文件或者數據庫等方式做爲測試過程輸入的自動化測試框架
>關鍵字驅動測試框架:使用被操做的元素對象、操做的方法和操做的數據值做爲測試過程輸入的自動化測試框架
>混合型測試框架:在關鍵字驅動測試框架中加入了數據驅動
>行爲驅動測試框架:支持天然語言做爲測試用例描述的自動化測試框架
(3)做用:
>可以有效組織和管理測試腳本
>進行數據驅動或關鍵字驅動的測試
>將基礎的測試代碼進行封裝,下降測試腳本編寫的複雜性和重複性
>提升測試腳本維護和修改的效率
>自動執行測試腳本,並自動發佈測試報告,爲持續集成的開發方式提供腳本支持
>讓不具有編程能力的測試工程師開展自動化測試工做
(4)自動化測試框架的設計核心思想
將經常使用的腳本代碼或者測試邏輯進行抽象和總結,而後將這些代碼進行面向對象設計,將須要重複的代碼封裝到可公用的類方法中。經過調用公用的類立法,測試類中的腳本複雜度會被大大下降,讓更多腳本能力不強的測試人員來實施自動化測試。
建立和實施Web自動化測試框架的步驟以下:
1)根據測試業務的手工測試用例,選出須要可自動化執行的測試用例
2)根據可自動化執行的測試用例,分析出測試框架須要模擬的手工操做和重複高的測試流程或邏輯
3)將手工操做和重複高的測試邏輯在代碼中實現,並在類中進行封裝方法的編寫
4)根據測試業務的類型和自己技術能力,選擇數據驅動框架、關鍵字驅動框架、混合型框架仍是行爲驅動框架
5)肯定框架模型後,將框架中經常使用的瀏覽器選擇、測試數據處理、文件操做、數據庫操做、頁面元素的原始操做、日誌和報告等功能進行類方法的封裝實現
6)對框架代碼進行集成測試和系統測試,採用PageObject模式和TestNG框架(或JUnit)編寫測試腳本,使用框架進行自動化測試,驗證框架的功能能夠知足自動化測試的需求
7)編寫自動化測試框架的經常使用 Api文檔,以供他人蔘閱
8)在測試組內部進行培訓和推廣
9)不斷收集測試過程當中的框架使用問題和反饋意見,不斷增長和優化自動化框架的功能,不斷加強框架中複雜操做的封裝效果,儘可能下降測試腳本的編寫複雜性。
10)按期評估測試框架的使用效果,評估自動化測試的投入產出比,再逐推廣自動化框架的應用範圍python

二、數據驅動框架及實踐
(1)框架大致包含目錄:
新建一個工程,下面包含如下部分
1)Util包:封裝經常使用的函數和功能(複用的)
Excel、時間、取元素、寫日誌、mapobject程序、解析ini文件,可選(截屏、建目錄、文件操做、數據庫操做等)
2)工程變量包
存放全部通用的變量或配置相關的變量
3)PageObject 包:一個頁面一個類,裏面有不少方法,方法是用於獲取頁面中的一個元素
如:login類 get_frame get_username get_password 等 返回頁面元素對象
4)conf配置目錄:存放全部的配置文件(日誌的配置文件、定位元素的配置文件)
5)Action包:
login函數:全部登陸的腳本邏輯
addContact : 添加聯繫人爲腳本邏輯
6)可選的(截屏目錄)
出錯的截屏web

(2)框架搭建步驟:
1)在PyCharm中新建一個工程:my_datadriven_frame
2)在工程my_datadriven_frame下新建一個包:Util
a、在Util下新增一個模塊,即python模塊:Excel.py 內容以下:數據庫

#encoding=utf-8
from openpyxl import *
from openpyxl.styles import Font
from FormatTime import data_time_chinese

class ParseExcel(object):
    def __init__(self,excel_file_path):
        self.excel_file_path=excel_file_path
        self.workbook=load_workbook(excel_file_path)
        self.font=Font(color=None)
        self.colorDict={"red":'FFFF3030',"green":'FF008B00'}
        self.sheet=self.get_sheet_by_index(0)

    # 經過序號設置當前要操做的sheet,使用index來獲取相應的sheet
    def set_sheet_by_index(self,sheet_index):
        self.sheet = self.get_sheet_by_index(sheet_index)

    # 經過名字設置操做的sheet
    def set_sheet_by_name(self,sheet_name):
        self.sheet = self.workbook.get_sheet_by_name(sheet_name)

    # 獲取當前操做的sheet和title名字
    def get_default_name(self):
        return self.sheet.title

    # 經過名字獲取要操做的sheet
    def get_sheet_by_name(self,sheet_name):
        self.sheet = self.workbook.get_sheet_by_name(sheet_name)
        return self.sheet

    # 經過序號獲取要操做的sheet
    def get_sheet_by_index(self, sheet_index):
        sheet_name = self.workbook.get_sheet_names()[sheet_index]
        self.sheet = self.get_sheet_by_name(sheet_name)
        return self.sheet

    #獲取sheet中的最大行號,從0開始
    def get_max_row_no(self):
        return self.sheet.max_row

    # 獲取sheet中的最大列號,從0開始
    def get_max_col_no(self):
        return self.sheet.max_column

    #獲取默認sheet中的最小行號
    def get_min_row_no(self):
        return self.sheet.min_row

    # 獲取默認sheet中的最小列號
    def get_min_col_no(self):
        return self.sheet.min_column

    #獲取正在操做的sheet中的全部行對象
    def get_all_rows(self):
        # rows = []
        # for row in self.sheet.iter_rows():
        #     rows.append(row)
        # return rows
        #也可用以上方法
        return list(self.sheet.iter_rows())

    #獲取正在操做的sheet中的全部列對象
    def get_all_cols(self):
        # cols = []
        # for col in self.sheet.iter_cols():
        #     cols.append(col)
        # return cols
        #也可用以上方法
        return list(self.sheet.iter_cols())

    #獲取某一個行對象,第一行從0開始
    def get_single_row(self,row_no):
        return self.get_all_rows()[row_no]

    # 獲取某一個列對象,第一列從0開始
    def get_single_col(self, col_no):
        return self.get_all_cols()[col_no]

    #獲取某一個單元格對象,行號和列號從1開始
    def get_cell(self,row_no,col_no):
        return self.sheet.cell(row = row_no,column = col_no)

    # 獲取某一個單元格內容
    def get_cell_content(self, row_no, col_no):
        return self.sheet.cell(row = row_no,column = col_no).value

    # 給某一個單元格寫入指定內容,行號和列號從1開始
    #調用此方法時,excel不要處於打開狀態
    def write_cell_content(self, row_no, col_no,content,font=None):
        self.sheet.cell(row=row_no,column=col_no).value = content
        self.workbook.save(self.excel_file_path)

    #給某個單元格寫入當前時間,行號和列號從1開始
    #調用此方法時,excel不要處於打開狀態
    def write_cell_current_time(self,row_no,col_no):
        self.sheet.cell(row=row_no,column=col_no).value = data_time_chinese()
        self.workbook.save(self.excel_file_path)

    def save_excel_file(self):
        self.workbook.save(self.excel_file_path)
    #保存全部對單元格的修改

if __name__ == "__main__":
    #測試全部的方法
    pe = ParseExcel("D:\\test\\test.xlsx")
    pe.set_sheet_by_index(0)
    print pe.get_default_name()
    pe.set_sheet_by_name("2")
    print pe.get_default_name()
    print pe.get_sheet_by_name("2")
    print pe.get_sheet_by_index(0)

    print "max rows:",pe.get_max_row_no()
    print "min row",pe.get_min_row_no()
    print pe.get_all_rows() #獲取全部行對象
    print pe.get_all_rows()[2] #獲取某一行
    print pe.get_all_rows()[0][2] #獲取某一個單元格
    print pe.get_all_rows()[2][1].value #獲取某一單元格的值

    print "max cols:",pe.get_max_col_no()
    print "min col",pe.get_min_col_no()
    print pe.get_all_cols() #獲取全部行對象
    print pe.get_all_cols()[2] #獲取某一行
    print pe.get_all_cols()[0][2] #獲取某一個單元格
    print pe.get_all_cols()[2][1].value #獲取某一單元格的值

    print len(pe.get_all_rows())
    for cell in pe.get_all_rows()[1]:
        print cell.value

    print len(pe.get_all_cols())
    for cell in pe.get_all_cols()[2]:
        print cell.value

    print "================================"

    for cell in pe.get_single_col(0):
        print cell.value

    for cell in pe.get_single_row(0):
        print cell.value

    print "--------------------"
    print pe.get_cell(1,2)
    print pe.get_cell_content(1,1)

    pe.write_cell_content(5,6,"hello")
    print pe.get_cell_content(5,6)
    pe.write_cell_current_time(7,7)
    print pe.get_cell_content(7,7)

b、封裝時間模塊,FormatTime.py,內容以下:編程

#encoding=utf-8
import time

#返回中文的年月日時分秒
def data_time_chinese():
    return time.strftime("%Y年%m月%d日 %H時%M分%S秒",time.localtime())

#返回中文的時分秒
def time_chinese():
    return time.strftime("%H時%M分%S秒", time.localtime())

# 返回英文的年月日時分秒
def data_time_english():
    return time.strftime("%Y-%m-%d %H:%M:%S秒", time.localtime())

# 返回英文的時分秒
def time_english():
    return time.strftime("%H:%M:%S秒", time.localtime())

if __name__ == "__main__":
    print data_time_chinese()
    print time_chinese()
    print data_time_english()
    print time_english()

c、封裝日誌模塊,Log.py,內容以下:數組

#encoding=utf-8
import logging
import logging.config
from ProjectVar.var import *

#讀取日誌的配置文件
logging.config.fileConfig(log_config_file_path)
#選擇一個日誌格式
logger = logging.getLogger("example02")


def info(message):
    #打印info級別的信息
    logging.info(message)

def error(message):
    #打印error級別的信息
    logging.error(message)

def warning(message):
    #打印warning級別的信息
    logging.warning(message)

if __name__ == "__main__":
    error("---ERROR---")
    info("===Test===")
    warning("````Wang`````")

d、封裝獲取頁面元素模塊,ObjectMap.py,內容以下:瀏覽器

#encoding=utf-8
from selenium.webdriver.support.ui import WebDriverWait
import time

#獲取單個頁面元素對象
def getElement(driver,locateType,locateExpression):
    try:
        element = WebDriverWait(driver,5).until(lambda x: x.find_element(by = locateType,value = locateExpression))
        return element
    except Exception,e:
        raise e

#獲取多個相同頁面元素對象,以list返回
def getElements(driver,locateType,locateExpression):
    try:
        element = WebDriverWait(driver,5).until(lambda x: x.find_elements(by = locateType,value = locateExpression))
        return element
    except Exception,e:
        raise e

if __name__ == "__main__":
    from selenium import webdriver
    #進行單元測試
    driver = webdriver.Firefox(executable_path = "D:\\geckodriver")
    driver.maximize_window()
    driver.get("https://mail.126.com/")
    time.sleep(2)
    lb = getElement(driver,"id","lbNormal")
    print lb
    driver.quit()    
    

e、封裝解析配置文件的模塊,ParsePageObjectRepository.py,內容以下:架構

#encoding=utf-8
from ConfigParser import ConfigParser
from ProjectVar.var import page_object_repository_path

class ParsePageObjectRepositoryConfig(object):
    def __init__(self):
        self.cf = ConfigParser()
        self.cf.read(page_object_repository_path)

    #獲取某個section,全部的key和value,用字典方式返回
    def getItemsFromSection(self,sectionName):
        print self.cf.items(sectionName)
        return dict(self.cf.items(sectionName))

    #獲取某一個具體的選項對應的value
    def getOptionValue(self,sectionName,optionName):
        return self.cf.get(sectionName,optionName)

3)新建一個包,ProjectVar
在ProjectVar下新增一個模塊,var.py,內容以下:app

#encoding=utf-8
import os

#獲取工程所在目錄的絕對路徑
project_path = os.path.dirname(os.path.dirname(__file__))
#日誌配置文件的絕對路徑
log_config_file_path = project_path + "/Conf/logger.conf"
#測試數據excel文件的絕對路徑
test_data_excel_path = project_path.decode("utf-8") + u"/TestData/126郵箱聯繫人.xlsx"
#
page_object_repository_path = project_path.decode("utf-8") + "/Conf/PageProjectRepository.ini"

username_col_no=1
password_col_no=2
is_executed_col_no=4
test_result_col_no=6
exception_info_col_no=7
assert_keyword_col_no = 6
firefox_driver_path= 'D:\\geckodriver'

if __name__ == "__main__":
    print os.path.dirname(__file__)
    print os.path.dirname(os.path.dirname(__file__))
    print os.path.dirname(project_path+"/Conf/logger.conf") #路徑斜槓向左向右均可以
    print log_config_file_path
    print test_data_excel_path

4)新建一個目錄 Conf
在Conf下新建一個log配置文件, logger.conf內容以下:框架

#logger.conf
###############################################
[loggers]
keys=root,example01,example02
[logger_root]
level=DEBUG
handlers=hand01,hand02

[logger_example01]
handlers=hand01,hand02
qualname=example01
propagate=0

[logger_example02]
handlers=hand01,hand03
qualname=example02
propagate=0

###############################################
[handlers]
keys=hand01,hand02,hand03

[handler_hand01]
class=StreamHandler
level=INFO
formatter=form01
args=(sys.stderr,)

[handler_hand02]
class=FileHandler
level=DEBUG
formatter=form01
args=('DataDrivenFrameWork.log', 'a')

[handler_hand03]
class=handlers.RotatingFileHandler
level=INFO
formatter=form01
args=('DataDrivenFrameWork.log', 'a', 10*1024*1024, 5)

###############################################
[formatters]
keys=form01,form02

[formatter_form01]
format=%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s
datefmt=%Y-%m-%d %H:%M:%S

[formatter_form02]
format=%(name)-12s: %(levelname)-8s %(message)s
datefmt=%Y-%m-%d %H:%M:%S

在Conf目錄下新建一個PageProjectRepository配置文件,PageProjectRepository.ini內容以下:函數

[126mail_login]
login_page.lbnormalbutton=id>lbNormal
login_page.frame=xpath>//iframe[contains(@id,"x-URS-iframe")]
login_page.username=xpath>//input[@name='email']
login_page.password=xpath>//input[@name='password']
login_page.loginbutton=id>dologin

[126mail_homepage]
home_page.addressbook=xpath>//div[text()='通信錄']

[126mail_addcontactspage]
addcontacts_page.createcontactsbtn=xpath>//span[text()='新建聯繫人']
addcontacts_page.contactpersonname=xpath>//a[@title='編輯詳細姓名']/preceding-sibling::div/input
addcontacts_page.contactpersonemail=xpath>//*[@id='iaddress_MAIL_wrap']//input
addcontacts_page.starcontacts=xpath>//span[text()='設爲星標聯繫人']/preceding-sibling::span/b
addcontacts_page.contactpersonmobile=xpath>//*[@id='iaddress_TEL_wrap']//dd//input
addcontacts_page.contactpersoncomment=xpath>//textarea
addcontacts_page.savecontaceperson=xpath>//span[.='確 定']

5)新建一個目錄TestData,存放測試數據: 126郵箱聯繫人.xlsx

sheet1數據:
序號   用戶名    密碼       數據表      是否執行    測試結果
1          xxx        xxx          聯繫人        y
2          xxx        xxx          聯繫人        y

sheet2數據(聯繫人):
序號    聯繫人姓名   聯繫人郵箱    是否設爲星標聯繫人   聯繫人手機號    聯繫人備註信息   驗證頁面包含的關鍵字   是否執行   執行時間   測試結果
1     lily       lily@qq.com        是         13512319865      lily      lily@qq.com          y
2      張三      zhangsan@qq.com    否         15812316893      忽略     zhangsan@qq.com         n
3          amy      am y@qq.com     是            13901902408     lily       amy                n
4      李四       lisi@qq.com         否         15796356569      lily       李四                  y

 

6)新建一個包,PageProject(一個頁面一個類,裏面有不少方法,方法是用於獲取頁面中的一個元素)
新建login_page(登陸頁面)模塊,login_page.py,內容以下:

#ecoding=utf-8
import time
from Util.ObjectMap import *
from Util.ParsePageObjectRepository import ParsePageObjectRepositoryConfig

class LoginPage(object):
    def __init__(self,driver):
        self.driver = driver
        self.parse_config_file = ParsePageObjectRepositoryConfig()
        self.login_page_items = self.parse_config_file.getItemsFromSection("126mail_login")
        print self.login_page_items

    #獲取元素
    def lbnormalbutton(self):
        locateType, locateExpression = self.login_page_items['login_page.lbnormalbutton'].split(">")
        print locateType, locateExpression
        return getElement(self.driver, locateType, locateExpression)

    def frame(self):
        locateType, locateExpression = self.login_page_items['login_page.frame'].split(">")
        print locateType, locateExpression
        return getElement(self.driver, locateType, locateExpression)

    def username(self):
        locateType, locateExpression = self.login_page_items['login_page.username'].split(">")
        print locateType, locateExpression
        return getElement(self.driver, locateType, locateExpression)

    def password(self):
        locateType, locateExpression = self.login_page_items['login_page.password'].split(">")
        print locateType, locateExpression
        return getElement(self.driver, locateType, locateExpression)

    def loginbutton(self):
        locateType, locateExpression = self.login_page_items['login_page.loginbutton'].split(">")
        print locateType, locateExpression
        return getElement(self.driver, locateType, locateExpression)

    #操做元素
    def lbnormalbutton_click(self):
        self.lbnormalbutton().click()

    def switch_to_frame(self):
        self.driver.switch_to.frame(self.frame())

    def input_username(self,username):
        self.username().send_keys(username)

    def input_password(self,password):
        self.password().send_keys(password)

    def loginbutton_click(self):
        self.loginbutton().click()


if __name__ == "__main__":
    from selenium import webdriver
    driver = webdriver.Firefox(executable_path = "D:\\geckodriver")
    driver.maximize_window()
    driver.get("https://mail.126.com")
    lp = LoginPage(driver)
    # lp.lbnormalbutton().click()
    lp.lbnormalbutton_click()
    time.sleep(1)
    # driver.switch_to.frame(lp.frame())
    lp.switch_to_frame()
    time.sleep(3)
    # lp.username().send_keys("xxx")
    lp.input_username("xxx")
    # lp.password().send_keys("xxx")
    lp.input_password("xxx")
    lp.loginbutton_click()
    time.sleep(5)
    driver.quit()

新建home_page(郵箱首頁)模塊,home_page.py,內容以下:

#encoding=utf-8
import time
from Util.ObjectMap import *
from Util.ParsePageObjectRepository import ParsePageObjectRepositoryConfig
from Action.login import *

class HomePage(object):
    def __init__(self,driver):
        self.driver = driver
        self.parse_config_file = ParsePageObjectRepositoryConfig()
        self.home_page_items = self.parse_config_file.getItemsFromSection("126mail_homepage")
        print self.home_page_items

    def address_book_page_link(self):
        locateType, locateExpression = self.home_page_items['home_page.addressbook'].split(">")
        print locateType, locateExpression
        return getElement(self.driver, locateType, locateExpression)

if __name__ == "__main__":
    from selenium import webdriver
    driver = webdriver.Firefox(executable_path = "D:\\geckodriver")
    driver.maximize_window()
    login(driver,"xxx","xxx")
    hp = HomePage(driver)
    hp.address_book_page_link().click()
    time.sleep(5)
    driver.quit()

新建addressBook(通信錄)模塊,addressBook.py,內容以下:

#encoding=utf-8
import time
from Util.ObjectMap import *
from Util.ParsePageObjectRepository import ParsePageObjectRepositoryConfig
from Action.login import *
from Action.visit_address_page import *

class AddressPage(object):
    def __init__(self,driver):
        self.driver = driver
        self.parse_config_file = ParsePageObjectRepositoryConfig()
        self.address_page_items = self.parse_config_file.getItemsFromSection("126mail_addcontactspage")
        print self.address_page_items

    def add_contact_button(self):
        locateType, locateExpression = self.address_page_items['addcontacts_page.createcontactsbtn'].split(">")
        print locateType, locateExpression
        return getElement(self.driver, locateType, locateExpression)

    def contact_name(self):
        locateType, locateExpression = self.address_page_items['addcontacts_page.contactpersonname'].split(">")
        print locateType, locateExpression
        return getElement(self.driver, locateType, locateExpression)

    def contact_email(self):
        locateType, locateExpression = self.address_page_items['addcontacts_page.contactpersonemail'].split(">")
        print locateType, locateExpression
        return getElement(self.driver, locateType, locateExpression)

    def contact_is_star(self):
        locateType, locateExpression = self.address_page_items['addcontacts_page.starcontacts'].split(">")
        print locateType, locateExpression
        return getElement(self.driver, locateType, locateExpression)

    def contact_mobile(self):
        locateType, locateExpression = self.address_page_items['addcontacts_page.contactpersonmobile'].split(">")
        print locateType, locateExpression
        return getElement(self.driver, locateType, locateExpression)

    def contact_other_info(self):
        locateType, locateExpression = self.address_page_items['addcontacts_page.contactpersoncomment'].split(">")
        print locateType, locateExpression
        return getElement(self.driver, locateType, locateExpression)

    def contact_save_button(self):
        locateType, locateExpression = self.address_page_items['addcontacts_page.savecontaceperson'].split(">")
        print locateType, locateExpression
        return getElement(self.driver, locateType, locateExpression)

if __name__ == "__main__":
    from selenium import webdriver
    driver = webdriver.Firefox(executable_path="D:\\geckodriver")
    login(driver, "xxx", "xxx")
    hp=HomePage(driver)
    hp.address_book_page_link().click()
    time.sleep(5)
    ap=AddressPage(driver)
    ap.add_contact_button().click()
    time.sleep(2)
    ap.contact_name().send_keys("gloryroad")
    ap.contact_email().send_keys("87393932@qq.com")
    ap.contact_is_star().click()
    ap.contact_mobile().send_keys("1322222222")
    ap.contact_other_info().send_keys(u"光榮之路")
    ap.contact_save_button().click()

7)新建一個包,Action ,封裝各類方法

新建一個模塊,login.py,內容以下:

#encoding=utf-8
import time
from selenium import webdriver
from Util.Log import *
from Util.FormatTime import data_time_chinese
from PageProject.login_page import *

def login(driver,username,password):
    driver.get("https://mail.126.com")
    time.sleep(2)
    lp = LoginPage(driver)
    lp.lbnormalbutton_click()
    lp.switch_to_frame()
    time.sleep(2)
    lp.input_username(username)
    lp.input_password(password)
    lp.loginbutton_click()
    time.sleep(2)
    info("Login Successfully!")
    print data_time_chinese()

if __name__ == "__main__":
    driver = webdriver.Firefox(executable_path = "D:\\geckodriver")
    login(driver,"xxx","xxx")

新建一個模塊,visit_address_page.py,內容以下:

#encoding=utf-8
from selenium import webdriver
from Util.Log import *
import time
from PageObject.login_page import *
from PageObject.home_page import *
from login import *

def visit_address_page(driver):
    hp = HomePage(driver)
    hp.address_book_page_link().click()
    time.sleep(5)

if __name__ == "__main__":
    driver = webdriver.Firefox(executable_path = "D:\\geckodriver")
    login(driver,"xxx","xxx")
    visit_address_page(driver)

新建一個模塊,add_contact.py,內容以下:

#encoding=utf-8
from selenium import webdriver
from Util.Log import *
from Util.FormatTime import *
import time
from PageObject.login_page import *
from PageObject.home_page import *
from PageObject.addressBook import *
from Util.Excel import *
from ProjectVar.var import *

def add_contact(driver,name="",email="",is_star=True,mobile="",other_info=""):
    ap = AddressPage(driver)
    ap.add_contact_button().click()
    time.sleep(2)
    ap.contact_name().send_keys(name)
    ap.contact_email().send_keys(email)
    if is_star == "True":
        ap.contact_is_star().click()
    ap.contact_mobile().send_keys(mobile)
    ap.contact_other_info().send_keys(other_info)
    ap.add_contact_button().click()
    time.sleep(3)

if __name__ == "__main__":
    driver = webdriver.Firefox(executable_path = "D:\\geckodriver")
    login(driver,"xxx","xxx")
    visit_address_page(driver)
    add_contact(driver,"Tom","1234@qq.com","True","18702235965",u"本身")
    driver.quit()
    

8)新建一個目錄TestScript,存放測試腳本
新建一個python文件,testContact.py,內容以下:

#encoding=utf-8
from selenium import webdriver
from Util.Log import *
from Util.Excel import *
from Util.FormatTime import *
import time
from Action.add_contact import *
from Action.visit_address_page import *
from Action.login import *
from ProjectVar.var import *
import sys
reload(sys)
sys.setdefaultencoding("utf8")

#取出全部行,使用切片取非第一行的全部行,由於第一行是標題,因此不用取
#遍歷每一行,而後使用讀取單元格的方法,將用戶名和密碼讀取到兩個變量裏面,而後傳到login方法中,調用便可
pe = ParseExcel(test_data_excel_path)
pe.set_sheet_by_index(0)
print pe.get_default_name()
rows = pe.get_all_rows()[1:]
for id,row in enumerate(rows):
    if row[is_executed_col_no].value.lower() == "y":
        username = row[username_col_no].value
        password = row[password_col_no].value
        print "username:",row[username_col_no].value
        print "password:",row[password_col_no].value
        driver = webdriver.Firefox(executable_path = firefox_driver_path)

        try:
            login(driver,username,password)
            visit_address_page(driver)
            time.sleep(3)
            pe.set_sheet_by_index(1)
            print pe.get_default_name()
            print pe.get_all_rows()
            test_data_result_flag = True #新建聯繫人都成功纔是True,有一個失敗就是False
            for id2,row in enumerate(pe.get_all_rows()[1:]):
                if row[7].value == "y":
                    try:
                        print "log:",row[1],row[1].value
                        print "log:",type(row[1])
                        add_contact(driver,row[1].value,row[2].value,row[3].value,row[4].value,row[5].value)
                        pe.write_cell_content(id2 + 2,9,data_time_chinese())
                        print "assert word:",row[assert_keyword_col_no].value
                        assert row[assert_keyword_col_no].value in driver.page_source
                        pe.write_cell_content(id2 + 2,10,"pass")
                    except Exception,e:
                        print u"異常信息:",e.message
                        error(u"異常信息:" + e.message)
                        pe.write_cell_content(id2 + 2,9,data_time_chinese())
                        pe.write_cell_content(id2 + 2,10,"fail")
                        test_data_result_flag = False
                else:
                    pe.write_cell_content(id2 + 2,10,u"忽略")
                    continue
            if test_data_result_flag == True:
                pe.set_sheet_by_index(0)
                pe.write_cell_content(id + 2,test_result_col_no,u"成功")
            else:
                pe.set_sheet_by_index(0)
                pe.write_cell_content(id + 2, test_result_col_no, u"失敗")
        except Exception,e:
            print u"異常信息:",e.message
            info(u"異常信息:" + e.message)

        driver.quit()
    else:
        print u"" + str(id+1) + u"行數據不執行"
        pe.set_sheet_by_index(0)
        pe.write_cell_content(id+2,test_result_col_no,u"忽略")
        continue
相關文章
相關標籤/搜索