Selenium3+MySQL数据库进行数据驱动测试
生活随笔
收集整理的這篇文章主要介紹了
Selenium3+MySQL数据库进行数据驱动测试
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
目錄結(jié)構(gòu)
1、準(zhǔn)備SQL語(yǔ)句 — Sql.py
#創(chuàng)建gloryroad數(shù)據(jù)庫(kù)SQL語(yǔ)句 create_database = 'create database if not exists gloryroad default charset utf8 collate utf8_general_ci;' #創(chuàng)建testdata表 create_table = """create table if not exists testdata(id int not null auto_increment comment '主鍵',bookname varchar(40) unique not null comment '書(shū)名',author varchar(30) not null comment '作者',primary key(id))engine = innodb character set utf8 comment '測(cè)試數(shù)據(jù)表'; """?
2、初始化數(shù)據(jù)庫(kù)腳本 — Databaselnit.py
#初始化數(shù)據(jù)庫(kù)腳本 import pymysql from Sql import *class DataBaseInit():#本類用于完成初始化數(shù)據(jù)庫(kù)操作#創(chuàng)建數(shù)據(jù)庫(kù),創(chuàng)建數(shù)據(jù)表,向表中插入測(cè)試數(shù)據(jù)def __init__(self, host, port, dbName, username, password, charset):self.host = hostself.port = portself.db = dbNameself.user = usernameself.passwd = passwordself.charset = charsetdef create(self):try:#連接MySQL數(shù)據(jù)庫(kù)conn = pymysql.connect(host = self.host,port = self.port,user = self.user,passwd = self.passwd,charset = self.charset)#獲取數(shù)據(jù)庫(kù)游標(biāo)cur = conn.cursor()#創(chuàng)建數(shù)據(jù)庫(kù) cur.execute(create_database)#選擇創(chuàng)建好的gloryroad數(shù)據(jù)庫(kù)conn.select_db("gloryroad")#創(chuàng)建測(cè)試表 cur.execute(create_table)except pymysql.Error as e:raise eelse:#關(guān)閉游標(biāo) cur.close()#提交操作 conn.commit()#關(guān)閉連接 conn.close()print("創(chuàng)建數(shù)據(jù)庫(kù)及表成功")def insertDatas(self):try:#連接數(shù)據(jù)庫(kù)中具體某個(gè)庫(kù)conn = pymysql.connect(host=self.host,port=self.port,db = self.db,user=self.user,passwd=self.passwd,charset=self.charset)cur = conn.cursor()#向測(cè)試表中插入測(cè)試數(shù)據(jù)sql = "insert into testdata(bookname, author) values(%s, %s);"res = cur.executemany(sql, [('Selenium Data Driven', 'Flutter'),('Python 基礎(chǔ)教程', 'Magnus Lie Hetland'),('算法設(shè)計(jì)與分析', '張德富'),('計(jì)算機(jī)網(wǎng)絡(luò)', '謝希仁')])except pymysql.Error as e:raise eelse:conn.commit()print("初始數(shù)據(jù)插入成功")#通過(guò)打印,確認(rèn)數(shù)據(jù)是否插入成功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("數(shù)據(jù)庫(kù)初始化結(jié)束")?
3、從數(shù)據(jù)庫(kù)中獲取測(cè)試數(shù)據(jù) — MysqlUtil.py
#從數(shù)據(jù)庫(kù)中獲取測(cè)試數(shù)據(jù) import pymysql from DatabaseInit import DataBaseInitclass MyMySQL():def __init__(self, host, port, dbName, username, password, charset):#進(jìn)行數(shù)據(jù)庫(kù)初始化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表中獲取需要的測(cè)試數(shù)據(jù)#bookname作為搜索關(guān)鍵詞,author作為預(yù)期關(guān)鍵詞self.cur.execute("select bookname, author from testdata")#從查詢區(qū)域取回所有的查詢結(jié)果datasTuple = self.cur.fetchall()return datasTupledef closeDatabase(self):#數(shù)據(jù)庫(kù)后期清理工作 self.cur.close()self.conn.commit()self.conn.close()if __name__ == '__main__':#實(shí)例化對(duì)象db = MyMySQL(host="localhost",port=3306,dbName="gloryroad",username="root",password="root",charset="utf8")#函數(shù)調(diào)用print(db.getDataFromDataBases())db.closeDatabase()?
4、執(zhí)行數(shù)據(jù)驅(qū)動(dòng)測(cè)試腳本 — DataDrivenByMySQL.py
#執(zhí)行數(shù)據(jù)驅(qū)動(dòng)測(cè)試腳本 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#初始化日志對(duì)象 logging.basicConfig(#日志級(jí)別level=logging.INFO,#日志格式#時(shí)間、代碼所在的文件名、代碼行號(hào)、日志級(jí)別名字、日志信息format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',#打印日志的時(shí)間datefmt='%a, %Y-%m-%d %H:%M:%S',#日志文件存放的目錄(目錄必須存在)及日志文件名filename='./dataDrivenReport.log',#打開(kāi)日志文件的方式filemode='w' )def getTestDatas():#對(duì)象實(shí)例化db = MyMySQL(host="localhost",port=3306,dbName="gloryroad",username="root",password="root",charset="utf8")#從數(shù)據(jù)庫(kù)測(cè)試表中獲取測(cè)試數(shù)據(jù)testData = db.getDataFromDataBases()#關(guān)閉數(shù)據(jù)庫(kù)連接 db.closeDatabase()#返回?cái)?shù)據(jù)return testData@ddt.ddt class TestDemo(unittest.TestCase):def setUp(self):self.driver = webdriver.Chrome()@ddt.data(*getTestDatas())def test_dataDrivenByDatabase(self, data):#對(duì)獲得的數(shù)據(jù)進(jìn)行解包testData, expectData = dataurl = "http://www.baidu.com"#訪問(wèn)百度首頁(yè) self.driver.get(url)#將瀏覽器窗口最大化 self.driver.maximize_window()print(testData, expectData)#設(shè)置隱式等待時(shí)間為10秒self.driver.implicitly_wait(10)try:# 找到搜索輸入框,并輸入測(cè)試數(shù)據(jù)self.driver.find_element_by_id("kw").send_keys(testData)# 找到搜索按鈕,并單擊self.driver.find_element_by_id("su").click()time.sleep(3)#斷言期望結(jié)果是否出現(xiàn)在頁(yè)面源代碼中self.assertTrue(expectData in self.driver.page_source)except NoSuchElementException:logging.error("查找的頁(yè)面元素不存在,異常堆棧信息:" + str(traceback.format_exc()))except AssertionError:logging.info("搜索%s,期望%s,失敗" % (testData, expectData))except Exception:logging.error("未知錯(cuò)誤,錯(cuò)誤信息:" + str(traceback.format_exc()))else:logging.info("搜索%s,期望%s,通過(guò)" % (testData, expectData))def tearDown(self):self.driver.quit()if __name__ == '__main__':# unittest.main()testCase = unittest.TestLoader().loadTestsFromTestCase(TestDemo)# 將多個(gè)測(cè)試類加載到測(cè)試套件中suite = unittest.TestSuite(testCase)filename = "./test.html"fp = open(filename, 'wb')runner = BSTestRunner(stream=fp,title='數(shù)據(jù)庫(kù)驅(qū)動(dòng)測(cè)試',description='測(cè)試用例執(zhí)行情況:')runner.run(suite)fp.close()
轉(zhuǎn)載于:https://www.cnblogs.com/test-postman/p/10131467.html
總結(jié)
以上是生活随笔為你收集整理的Selenium3+MySQL数据库进行数据驱动测试的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 挂式空调滤芯怎么安装?
- 下一篇: tcpdump软件使用