Selenium3+MySQL數據庫進行數據驅動測試

目錄結構html

一、準備SQL語句 — Sql.pymysql

#建立gloryroad數據庫SQL語句
create_database = 'create database if not exists gloryroad default charset utf8 collate utf8_general_ci;'
#建立testdata表
create_table = """ create table if not exists testdata( id int not null auto_increment comment '主鍵', bookname varchar(40) unique not null comment '書名', author varchar(30) not null comment '做者', primary key(id) )engine = innodb character set utf8 comment '測試數據表'; """

 

二、初始化數據庫腳本 — Databaselnit.pyweb

#初始化數據庫腳本
import pymysql from Sql import *

class DataBaseInit(): #本類用於完成初始化數據庫操做
    #建立數據庫,建立數據表,向表中插入測試數據
    def __init__(self, host, port, dbName, username, password, charset): self.host = host self.port = port self.db = dbName self.user = username self.passwd = password self.charset = charset def create(self): try: #鏈接MySQL數據庫
            conn = pymysql.connect( host = self.host, port = self.port, user = self.user, passwd = self.passwd, charset = self.charset ) #獲取數據庫遊標
            cur = conn.cursor() #建立數據庫
 cur.execute(create_database) #選擇建立好的gloryroad數據庫
            conn.select_db("gloryroad") #建立測試表
 cur.execute(create_table) except pymysql.Error as e: raise e else: #關閉遊標
 cur.close() #提交操做
 conn.commit() #關閉鏈接
 conn.close() print("建立數據庫及表成功") def insertDatas(self): try: #鏈接數據庫中具體某個庫
            conn = pymysql.connect( host=self.host, port=self.port, db = self.db, user=self.user, passwd=self.passwd, charset=self.charset ) cur = conn.cursor() #向測試表中插入測試數據
            sql = "insert into testdata(bookname, author) values(%s, %s);" res = cur.executemany(sql, [('Selenium Data Driven', 'Flutter'), ('Python 基礎教程', 'Magnus Lie Hetland'), ('算法設計與分析', '張德富'), ('計算機網絡', '謝希仁')]) except pymysql.Error as e: raise e else: conn.commit() print("初始數據插入成功") #經過打印,確認數據是否插入成功
            cur.execute("select * from testdata;") for i in cur.fetchall(): print(i[1], i[2]) cur.close() conn.close() if __name__ == '__main__': db = DataBaseInit( host="localhost", port=3306, dbName="gloryroad", username="root", password="root", charset="utf8" ) db.create() db.insertDatas() print("數據庫初始化結束")

 

三、從數據庫中獲取測試數據 — MysqlUtil.py算法

#從數據庫中獲取測試數據
import pymysql from DatabaseInit import DataBaseInit class MyMySQL(): def __init__(self, host, port, dbName, username, password, charset): #進行數據庫初始化
        dbInit = DataBaseInit(host, port, dbName, username, password, charset) dbInit.create() dbInit.insertDatas() self.conn = pymysql.connect( host = host, port = port, db = dbName, user = username, passwd = password, charset = charset ) self.cur = self.conn.cursor() def getDataFromDataBases(self): #從testdata表中獲取須要的測試數據
        #bookname做爲搜索關鍵詞,author做爲預期關鍵詞
        self.cur.execute("select bookname, author from testdata") #從查詢區域取回全部的查詢結果
        datasTuple = self.cur.fetchall() return datasTuple def closeDatabase(self): #數據庫後期清理工做
 self.cur.close() self.conn.commit() self.conn.close() if __name__ == '__main__': #實例化對象
    db = MyMySQL( host="localhost", port=3306, dbName="gloryroad", username="root", password="root", charset="utf8" ) #函數調用
    print(db.getDataFromDataBases()) db.closeDatabase()

 

四、執行數據驅動測試腳本 — DataDrivenByMySQL.pysql

#執行數據驅動測試腳本
from selenium import webdriver import unittest, time import logging, traceback import ddt from MysqlUtil import MyMySQL from selenium.common.exceptions import NoSuchElementException from BSTestRunner import BSTestRunner #初始化日誌對象
logging.basicConfig( #日誌級別
    level=logging.INFO, #日誌格式
    #時間、代碼所在的文件名、代碼行號、日誌級別名字、日誌信息
    format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s', #打印日誌的時間
    datefmt='%a, %Y-%m-%d %H:%M:%S', #日誌文件存放的目錄(目錄必須存在)及日誌文件名
    filename='./dataDrivenReport.log', #打開日誌文件的方式
    filemode='w' )
def getTestDatas(): #對象實例化 db = MyMySQL( host="localhost", port=3306, dbName="gloryroad", username="root", password="root", charset="utf8" ) #從數據庫測試表中獲取測試數據 testData = db.getDataFromDataBases() #關閉數據庫鏈接 db.closeDatabase() #返回數據 return testData @ddt.ddt class TestDemo(unittest.TestCase): def setUp(self): self.driver = webdriver.Chrome() @ddt.data(*getTestDatas()) def test_dataDrivenByDatabase(self, data): #對得到的數據進行解包 testData, expectData = data url = "http://www.baidu.com" #訪問百度首頁 self.driver.get(url) #將瀏覽器窗口最大化 self.driver.maximize_window() print(testData, expectData) #設置隱式等待時間爲10秒 self.driver.implicitly_wait(10) 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: logging.error("查找的頁面元素不存在,異常堆棧信息:" + str(traceback.format_exc())) except AssertionError: logging.info("搜索%s,指望%s,失敗" % (testData, expectData)) except Exception: logging.error("未知錯誤,錯誤信息:" + str(traceback.format_exc())) else: logging.info("搜索%s,指望%s,經過" % (testData, expectData)) def tearDown(self): self.driver.quit() if __name__ == '__main__': # unittest.main() testCase = unittest.TestLoader().loadTestsFromTestCase(TestDemo) # 將多個測試類加載到測試套件中 suite = unittest.TestSuite(testCase) filename = "./test.html" fp = open(filename, 'wb') runner = BSTestRunner(stream=fp, title='數據庫驅動測試', description='測試用例執行狀況:') runner.run(suite) fp.close()
相關文章
相關標籤/搜索