DDT思想
一、先了解一下几种数据取值方式
csv文件取值
def test_file():
with open('test_csv.csv') as f:
lst_f = csv.reader(f)
data = []
for r in lst_f:
data.extend(r)
# print(data)
return data
print(test_file())
# @pytest.mark.skip
@pytest.mark.parametrize('name',test_file())
def test01(name):
print(name)
json格式取值
# json数据处理
def test_json():
with open('test_json.json') as tj:
lst = []
data = json.load(tj)
print(data)
lst.extend(data)
return lst
@pytest.mark.parametrize('name',test_json())
def test02(name):
print(name)
Excel文件处理
def test_xlrd():
filename = 'test1.xlsx'
w_data = xlrd.open_workbook(filename)
sheet = w_data.sheet_by_index(0)
rows = sheet.nrows
cols = sheet.ncols
lst = []
for row in range(rows):
for col in range(cols):
c_data = sheet.cell_value(row, col)
lst.append(c_data)
return lst
@pytest.mark.parametrize('name',test_xlrd())
def test03(name):
print(name)
操作数据库
conn = pymysql.connect(
user='root',
passwd='123456',
host='localhost',
port=3306,
db='my_test'
)
def test_db():
qs = 'select uid,uname,pwd from test_user'
lst = []
try:
cursor = conn.cursor()
cursor.execute(qs)
# 获取所有的数据
r = cursor.fetchall()
for x in r:
# x 表示列
u = (x[0],x[1],x[2])
lst.append(u)
return lst
finally:
cursor.close()
conn.close()
@pytest.mark.parametrize('uid,uname,pwd',test_db())
def test04(uid,uname,pwd):
print(uid,uname,pwd)
if __name__ == '__main__':
# pytest.main(['-vs', 'test_file.py'])
print(test04())
二、认识ddt :Data Driver Test
通过使用数据驱动测试的方法,可以在需要验证多组数据测试场景中,使用外部数据源实现对输入输出与期望值的参数化,避免在测试中使用硬编码的数据。 包括四个模块,@ddt、@data、@unpack 解包 @ file_data
# 安装
pip install ddt
code示例
from ddt import ddt,data,unpack,file_data
import pytest
import os
import unittest
def get_data():
testdata = [{'name': 'tom', 'age': 20}, {'name': 'kite', 'age': 30}]
return testdata
@ddt
class MyTestCase(unittest.TestCase):
# 读取元组数据-单组元素
@data(1, 2, 3)
def test1(self, value):
print(value)
# 读取元组数据-多组元素
@data((1, 2, 3), (4, 5, 6))
def test2(self, value):
print(value)
# 读取元组数据-拆分数据
@data((1, 2, 3), (4, 5, 6))
@unpack # 拆分数据
def test3(self, value1, value2, value3):
print(value1, value2, value3)
# 列表
@data([{'name': 'tom', 'age': 20}, {'name': 'kite', 'age': 30}])
def test4(self, value):
print(value)
# 字典
@data({'name': 'tom', 'age': '20'}, {'name': 'kite', 'age': '30'})
def test5(self, value):
print(value)
# 字典-拆分
@data({'name': 'tom', 'age': '20'}, {'name': 'kite', 'age': '30'})
@unpack
def test6(self, name, age):
print(name, age)
# 变量或者方法调用
testdata = [{'name': 'tom', 'age': 20}, {'name': 'kite', 'age': 30}]
# @data(*testdata)
@data(get_data())
def test7(self, value):
print(value)
# 读文件
@file_data(os.getcwd() + '/test_json.json')
def test8(self, value2):
print(value2)
if __name__ == '__main__':
unittest.main()