[ddt02篇]十年测试老鸟帮您解析:ddt结合txt,excel,csv实现自动化测试数据驱动
上一篇 / 下一篇 2020-04-24 18:51:07 / 个人分类:接口自动化
阅读此文之前请先阅读:
[ddt01篇]十年测试老鸟帮您解析:ddt数据驱动入门基础应用:
二、ddt数据驱动框架结合txt文件实现数据驱动
test_demo.py代码如下:
importunittestfromddtimportddt, data, unpack#读取txt文件中的内容,strip()方法去掉首位的指定字符。defread_txt():list = []
file = open('param.txt','r',encoding='utf-8')forlineinfile.readlines():
list.append(line.strip('\n').split(','))returnlist@ddtclassaaa(unittest.TestCase):defsetUp(self):pass@data(*read_txt())deftest1_data(self,args1):print(args1)deftearDown(self):passif__name__ =='__main__':
unittest.main()
param.txt文件中内容如下:
诸葛,司马
马超,关羽
三、使用ddt结合excel(.csv格式也可以)文件实现数据驱动
test_demo.py代码如下:
importtimeimportunittestimportddtfromseleniumimportwebdriverfromselenium.webdriver.common.byimportByfroma.excel_utilimportExcelUtil@ddt.ddtclassTestDemo(unittest.TestCase):eu = ExcelUtil()defsetUp(self)->None:self.driver = webdriver.Chrome()
self.driver.get("https://www.baidu.com")
self.driver.maximize_window()
self.driver.implicitly_wait(10)@ddt.data(*eu.read_excel("D:\\testdata.xlsx","Sheet1"))deftest_data_driver_by_jsonfile(self,value):try:
testData,expectData = tuple(value)
self.driver.find_element(By.ID,"kw").send_keys(testData)
time.sleep(3)
self.driver.find_element(By.ID,"su").click()
time.sleep(5)
self.assertTrue(expectDatainself.driver.page_source)except:
print("搜索:%s,期望:%s,失败"%(testData,expectData))passelse:
print("搜索:%s,期望:%s,通过"%(testData,expectData))passdeftearDown(self)->None:self.driver.quit()if__name__ =='__main__':
unittest.main()
excel_util.py读取excel(csv)数据文件如下:
importxlrdclassExcelUtil:#读取excel数据defread_excel(self,excel_path,sheet_name):xls = xlrd.open_workbook(excel_path)
sheet = xls.sheet_by_name(sheet_name)
dataList=[]forlineinrange(1,sheet.nrows):
tempList = []
tempList.append(sheet.cell_value(line,1))
tempList.append(sheet.cell_value(line,2))
dataList.append(tempList)returndataListif__name__ =='__main__':
data = ExcelUtil().read_excel("d:\\testdata.xlsx","Sheet1")
print(data)
D:\\testdata.xlsx文件中Sheet1的工作表内容如下:
实例讲解:@ddt.data()从eu.read_excel("D:\\testdata.xlsx","Sheet1")方法中接收一个可迭代的数组对象,以此来判断需要执行的次数。如果@ddt.data()括号中传的是一个方法,方法前需要加星号(*)修饰。*表示出掉最外层的括号。
四、使用ddt结合mysql数据库进行数据驱动
1.在dos窗口安装pymysql模块来操作数据库。命令:pip install pymysql
2.安装mysql数据库(安装过程省略),创建database.py文件,使用pymysql创建数据库datadriver,创建表testdata,并向testdata表中插入三条数据。
database.py代码如下:
importtimeimportpymysqlaspymysqlclassDataBase:#删除datadriver数据库的SQL语句drop_database =" drop database if exists datadriver;"#创建datadriver的SQL语句:create_database ="create database datadriver default charset utf8 COLLATE utf8_general_ci;"#创建testdata表的SQL语句:create_table ="""
create table testdata(
id int not null auto_increment comment '主键',
searchContent varchar(40) unique not null comment '百度搜索的内容',
assertContent varchar(30) not null comment '断言的内容',
primary key(id)
);
"""def__init__(self,host,port,username,password,db):self.host = host
self.port = port
self.username = username
self.password = password
self.db = db#连接数据库创建数据库和表defcreate_databse_and_table(self):try:#连接Mysql数据库。conn = pymysql.connect(host=self.host,port=self.port,user=self.username,password=self.password)#获取数据库游标cur = conn.cursor()#删除数据库cur.execute(self.drop_database)
time.sleep(3)#执行创建数据库的SQL语句cur.execute(self.create_database)
time.sleep(3)#选中创建好的datadriver数据库。conn.select_db("datadriver")#执行创建表的SQL语句cur.execute(self.create_table)# 提交操作conn.commit()exceptException:raiseelse:
cur.close()#关闭游标conn.close()#关闭连接print("创建数据库和表成功!")#插入数据definsert_data(self):try:# 连接Mysql数据库。conn = pymysql.connect(host=self.host, port=self.port, user=self.username, password=self.password,db=self.db)# 获得数据库游标cur = conn.cursor()# 执行插入数据的SQL语句sql ="insert into testdata(searchContent,assertContent) values(%s,%s)"cur.executemany(sql,[('神奇动物在哪里','叶茨'),('疯狂动物城','霍华德'),('杜兰特','凯文')])# 提交操作conn.commit()exceptException:raiseelse:
cur.close()# 关闭游标conn.close()# 关闭连接print("数据插入成功!")#查询数据defselect_data(self):result =""try:
conn = pymysql.connect(host=self.host,port=self.port,user=self.username,password=self.password,db=self.db)
cur = conn.cursor()
cur.execute("select searchContent,assertContent from testdata;")
result=cur.fetchall()exceptException:raiseelse:
cur.close()# 关闭游标conn.close()# 关闭连接print("数据查询成功!")returnresultif__name__ =='__main__':
db = DataBase("localhost",3306,"root","admin","datadriver")
db.create_databse_and_table()
db.insert_data()
print(db.select_data())
注意事项:
# 以下代码连接Mysql数据库。最好使用关键字传参,否则可能会出现参数顺序问题,关键字包括:host,port,user,password,db
conn = pymysql.connect(host=self.host, port=self.port, user=self.username, password=self.password,db="datadriver")
#以下代码在传值时3306必须传数字类型,不能传入"3306"这种字符串类型。
db = DataBase("localhost",3306,"root","admin")
3.使用ddt结合mysql数据库进行数据驱动
test_demo.py文件内容如下:
importtimeimportunittestimportwarningsimportddtfromseleniumimportwebdriverfromselenium.webdriver.common.byimportByfroma.databaseimportDataBasedefget_data():db = DataBase("localhost",3306,"root","admin","datadriver")
data = db.select_data()returndata@ddt.ddtclassTestDemo(unittest.TestCase):defsetUp(self)->None:warnings.simplefilter('ignore',ResourceWarning)#处理资源警告。self.driver = webdriver.Chrome()
self.driver.get("https://www.baidu.com")
self.driver.maximize_window()
self.driver.implicitly_wait(10)@ddt.data(*get_data())deftest_data_driver_by_jsonfile(self,data):try:
testData,expectData = data
self.driver.find_element(By.ID,"kw").send_keys(testData)
time.sleep(3)
self.driver.find_element(By.ID,"su").click()
time.sleep(5)
self.assertTrue(expectDatainself.driver.page_source)except:
print("搜索:%s,期望:%s,失败"%(testData,expectData))passelse:
print("搜索:%s,期望:%s,通过"%(testData,expectData))passdeftearDown(self)->None:self.driver.quit()if__name__ =='__main__':
unittest.main()
案例讲解:get_data()方法用于调用database.py中的select_data()查询数据库中数据的方法。warnings.simplefilter('ignore',ResourceWarning)代码用于处理警告信息。
五、使用ddt中读取json/yaml文件实现数据驱动。
因内容太多,这里就先说到这里,请继续关注!
TAG:
如果你对软件测试、面试经验交流感兴趣欢迎加入软件测试技术群:695458161,群里发放的免费资料都是笔者十多年测试生涯的精华。还有同行大神一起交流技术哦。
标题搜索
日历
|
|||||||||
日 | 一 | 二 | 三 | 四 | 五 | 六 | |||
1 | 2 | 3 | 4 | 5 | 6 | ||||
7 | 8 | 9 | 10 | 11 | 12 | 13 | |||
14 | 15 | 16 | 17 | 18 | 19 | 20 | |||
21 | 22 | 23 | 24 | 25 | 26 | 27 | |||
28 | 29 | 30 |
数据统计
- 访问量: 22073
- 日志数: 38
- 建立时间: 2020-04-01
- 更新时间: 2020-06-29