• python习题:unittest参数化-数据从文件或excel中读取


    '''
    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()



  • 相关阅读:
    Java自学-集合框架 与数组的区别
    Java自学-I/O 控制台输入流System.in
    Java自学-I/O 对象流
    Java自学-I/O 数据流
    Java自学-I/O 缓存流
    Java自学-I/O 中文问题
    Java自学-I/O 字符流
    Java自学-I/O 关闭流的方式
    Java自学-I/O 字节流
    Java自学-I/O Stream流
  • 原文地址:https://www.cnblogs.com/blackbird0423/p/8543678.html
Copyright © 2020-2023  润新知