zoukankan      html  css  js  c++  java
  • Python unittest 参数化

    准备工作: pip install  nose_parameterized

    典型场景:用户名、密码参数化

    实例

    1,新建一个ftl.py 文件 ,用来将存在于.txt .xlsx 文件中的参数化数据转换成list 格式

    import os,xlrd
    from MyLog import Logger
    log = Logger(filename='test.log',level='debug')#实例化
    class DataToParam(object):
    @classmethod #类方法不需要实例化
    def text(cls,filename,seq=','): #默认逗号分隔
    cls.file_exist(filename)
    with open(filename,encoding='utf-8') as f:
    res = []
    for line in f:
    res.append(line.strip().split(seq))
    return res

    @classmethod
    def excel(cls,filename):
    cls.file_exist(filename)
    book = xlrd.open_workbook(filename) #打开excel
    sheet = book.sheet_by_index(0) #获取sheet页
    res = []
    for row in range(sheet.nrows): #sheet.nrows excel的行数
    line_list = sheet.row_values(row) #取excel里面的每一行数据,返回的是一个list
    res.append(line_list)
    return res

    @classmethod
    def file_exist(cls,filename):
    if os.path.isfile(filename):#判断文件是否存在
    return True
    log.logger.error('参数化文件不存在 ,文件名为 %s'%filename)
    raise Exception('参数化文件不存在!')
    2,新建 MyLog.py 文件 往日志文件里写日志
    import logging
    from logging import handlers

    class Logger(object):
    level_relations = {
    'debug': logging.DEBUG,
    'info': logging.INFO,
    'warning': logging.WARNING,
    'error': logging.ERROR,
    'crit': logging.CRITICAL
    } # 日志级别关系映射
    def __init__(self,filename,level='info',
    when='D',
    back_count=3,
    fmt='%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s'):
    self.logger = logging.getLogger(filename)
    # 分割日志的单位 S 秒、M 分、 H 小时、 D 天、 W 每星期(interval==0时代表星期一)、midnight 每天凌晨

    format_str = logging.Formatter(fmt) #设置日志格式
    self.logger.setLevel(self.level_relations.get(level)) #设置日志级别
    sh = logging.StreamHandler()
    sh.setFormatter(format_str)
    th = handlers.TimedRotatingFileHandler(filename=filename,when=when,
    backupCount=back_count,encoding='utf-8')
    th.setFormatter(format_str)
    self.logger.addHandler(sh)
    self.logger.addHandler(th)
    3,新建 unittest_1.py 文件 用来执行单元测试
    import unittest
    import nose_parameterized
    from ftl import DataToParam
    from ftl import log

    def calc(a,b):
    a = int(a)
    b = int(b)
    res = round(a/b,2)
    # print(res)
    return res

    class MyTest(unittest.TestCase):
    @nose_parameterized.parameterized.expand(DataToParam.text('case_data.txt'))
    ##使用它提供的装饰器装饰这个函数,传入一个list
    def test_func(self,a,b,e):
    res = calc(a,b)
    try:
    self.assertEqual(res,int(e))
    except Exception as e: #将错误信息写入日志 需加try捕捉异常
    log.logger.error('AssertionError %s' %e)

    if __name__ == '__main__':
    unittest.main()
  • 相关阅读:
    JDE函数--获取当前登录人的描述
    JDE报表开发笔记(R5537011 收货校验统计表)
    JDE函数--GetUDC(B函数)
    JDE隐藏Constant等(Hide Object)
    Oracle “dba_tables”介绍
    word2013设置页面边框
    makefile--#的不正确使用
    CICS定时
    程序的命名
    UE上传到FTP,会多出些字符
  • 原文地址:https://www.cnblogs.com/chendai21/p/8665539.html
Copyright © 2011-2022 走看看