测试数据分离
unittest+文件存放测试数据
数据驱动装饰圈 ddt.ddt ddt.data() unpack ddt.file_data()
文件读取 txt readlines strip split
json json.load
excel xlrd.open_workbook book.sheet_by_name sheet.nrows sheet.row_values
yaml 不用写读取方法 ddt.file_data()可自动解包 yaml中用列表套字典方式传递
文件类容解析为 [{"user": "admin","pwd": 123},{"user": "wang","pwd": 234}]
import json
import unittest
import ddt
import xlrd
# 读取txt文件
def read_file_txt(file):
li = []
with open(file, 'r', encoding='utf-8') as f:
for line in f.readlines():
lis = line.strip().split(',')
dic = {
'user': lis[0],
'pwd': lis[1]
}
li.append(dic)
return li
# 读取json文件
def read_file_json(file):
li = json.load(open(file))
return li
#读取excel文件
def read_file_excel(file, sheet="Sheet1"):
book = xlrd.open_workbook(file)
sheet = book.sheet_by_name(sheet)
title = sheet.row_values(0)
li = []
for i in range(1, sheet.nrows):
value = sheet.row_values(i)
li.append(dict(zip(title, value)))
return li
@ddt.ddt
class MyTestCase(unittest.TestCase):
# @ddt.data({'user':'admin','pwd':'123'},{'user':'wning','pwd':'456'})
# @ddt.data(*read_file_txt('data.txt'))
# @ddt.data(*read_file_json("data.json"))
@ddt.data(*read_file_excel("data.xls"))
@ddt.unpack
def test_01(self, user, pwd):
"""
登录测试
:param user: 用户名
:param pwd: 密码
:return:
"""
print(f'测试数据{user},{pwd}')
self.assertTrue(True)
if __name__ == '__main__':
unittest.main()
unitest框架基础
执行流程
setUpClass->setUp--用例--tearDown-->tearDownClass
class MyTestCase(unittest.TestCase):
@classmethod
def setUpClass(cls) -> None:
print("测试结束")
@classmethod
def tearDownClass(cls) -> None:
print("测试开始")
def setUp(self) -> None:
print("用例执行前")
def tearDown(self) -> None:
print("用例执行后")
变量传递
用类变量中list或dict可以传递参数
class MyTestCase(unittest.TestCase):
dic = {}
def test_case1(self):
self.dic["session"] = "ABCD"
def test_case2(self):
print(self.dic)
标签:sheet,读取,data,unittest,ddt,file,li,数据,def
From: https://www.cnblogs.com/wn-garden/p/17124993.html