'''
unittest参数化:从文件和excel中读取
'''
import os
import xlwt,xlrd
class DataToParam(object):
@classmethod
def file_exist(cls,filename):
if os.path.isfile(filename):# 判断文件是否存在
return True
raise Exception('参数化文件不存在') # raise 主动抛出异常
@classmethod # 静态方法不需要实例化就可以调用
def read_text(cls,filename,seq=','):#seq是分隔符
cls.file_exist(filename)
with open(filename,encoding='utf-8') as f:
# f.seek(0)
res = []
for line in f:
res.append(line.strip().split(seq))
return res
# print(DataToParam.read_text('data.txt'))
@classmethod
def read_excel(cls,excelname):
cls.file_exist(excelname)
book =xlrd.open_workbook(excelname) # 打开文件
sheet = book.sheet_by_index(0) # 操作sheet
res=[]
for i in range(sheet.nrows):# 循环 excel 的所有行数
res.append(sheet.row_values(i)) # sheet.row_value(i)取excel里面的每一行数据,返回的是一个list
return res
# print(DataToParam.read_excel('data.xls'))
# print(DataToParam.read_excel(r'C:UsersAdministratorDocumentsdata.xls'))
'''
unittest参数化
'''
import unittest
import nose_parameterized
from eg05 import DataToParam
def calc(a,b):
a=float(a)
b=float(b)
res=round(a/b,2)
print(res)
return res
# case_data = [
# [1,1,1.00],
# [1,0,0],
# [0.5,1,0.50],
# [1,2,0.50],
# [1,3,0.33],
# [1,4,0.25]
#
# ]
class MyTest(unittest.TestCase):
#@nose_parameterized.parameterized.expand(DataToParam.read_text(case_data))
# @nose_parameterized.parameterized.expand(DataToParam.read_text('data.txt'))
@nose_parameterized.parameterized.expand(DataToParam.read_excel(r'C:UsersAdministratorDocumentsdata.xls'))
def test_func(self,a,b,e):
res =calc(a,b)
self.assertEqual(res,float(e))
if __name__ == '__main__':
unittest.main()