DDT(Data Driver Tests)数据驱动测试。
1、DDT里读取csv文件
使用python的 csv模块来处理csv文件
结合pytest的参数化处理方法来实现ddt
实例:
import pytest
import csv
def get_data():
with open('test.csv') as f:
lst = csv.reader(f)
my_data = []
for row in lst:
#print(row)
my_data.extend(row)
return my_data
@pytest.mark.parametrize('name',get_data())
def test01(name):
print(name)
if __name__ == '__main__':
#print(get_data())
pytest.main(['-sv','test_csv.py'])
2、DDT里读取json文件
import pytest
import json
def get_data():
with open("test.json") as j:
lst=[]
data = json.load(j)
lst.extend(data["keys"])
#print(data["keys"])
return lst
@pytest.mark.parametrize("name",get_data())
def test(name):
print(name)
if __name__ == '__main__':
#print(get_data())
pytest.main(["-sv","test_json.py"])
3、使用xlrd模块读取excel文件,使用pytest参数化实现DDT
import pytest
import xlrd
def get_data():
filename='data.xlsx'
wb = xlrd.open_workbook(filename)
sheet = wb.sheet_by_index(0)
rows = sheet.nrows
cols = sheet.ncols
lst=[]
for row in range(rows):
for col in range(cols):
cell_data = sheet.cell_value(row,col)
lst.append(cell_data)
return lst
@pytest.mark.parametrize("name",get_data())
def test1(name):
print(name)
if __name__ == '__main__':
pytest.main(["-sv","test_excel.py"])
4、selenium读取数据库数据,将数据保存到数据库,实现数据驱动的测试
(1)安装mysqlclient模块:pip install mysqlclient
(2) 获得数据库连接
(3)查询数据
(4) 代码
数据库语句:
create database testing_db;
use testing_db;
create table user_tbl(id int primary_key auto_increment,username varchar(20),pwd varchar(20));
insert into user_tbl(username,pwd)values('sophia','123');
insert into user_tbl(username,pwd)values('kite','456');
insert into user_tbl(username,pwd)values('tom','789');
import MySQLdb
import pytest
conn=MySQLdb.connect(
user='root',
passwd='root',
host='localhost',
port=3306,
db='testing_db'
)
def get_data():
query_sql = 'select id,username,pwd from user_tbl'
lst=[]
try:
cursor = conn.cursor()
cursor.execute(query_sql)
r = cursor.fetchall()
for x in r:
u=(x[0],x[1],x[2])
lst.append(u)
print('11111',lst)
return lst
finally:
cursor.close()
conn.close()
@pytest.mark.parametrize('id,name,pwd',get_data())
def test1(id,name,pwd):
print(id,name,pwd)
if __name__ == '__main__':
pytest.main(['-sv'])