为类的 __init__ 方法编写单元测试

Omi*_*nus 5 python unit-testing nose

我对单元测试和编写/使用异常很陌生。我目前正在努力学习最佳实践并将它们集成到我的项目中。为了测试我一直在阅读的一些内容,我编写了一个简单的 Contracts 模块。下面是合约类的初始化,它有几个相互依赖的参数。

我将/应该如何根据其参数依赖性为 init 方法编写测试。

提前致谢!

def __init__(self, code, description ,contract_type,
             start_date ,end_date ,reminder_date, 
             customer=None, isgroup=False, vendor=None, 
             discount_perc=None):

    contract_types = ['item','vendor']
    self.code = code
    self.description = description
    self.contract_type = contract_type
    self.start_date = start_date
    self.end_date = end_date
    self.reminder_date = reminder_date
    if contract_type not in contract_types:
        raise AttributeError("Valid contract types are 'item' & 'vendor'")
    if isgroup:
        if customer:
            raise AttributeError("Group contracts should not have 'customer' passed in")
        self.is_group_contract = True
    else:
        if customer:
            self.add_customer(customer)
        else:
            raise AttributeError('Customer required for non group contracts.')
    if contract_type == 'vendor':
        if vendor and discount_perc:
            self.vendor = vendor
            self.discount_perc = discount_perc
        else:
            if not vendor:
                raise AttributeError('Vendor contracts require vendor to be passed in')
            if not discount_perc:
                raise AttributeError('Vendor contracts require discount_perc(Decimal)')
Run Code Online (Sandbox Code Playgroud)

如果这类问题不适合 SO,我去哪里比较好?

Mis*_*sev 3

我会__init__像任何其他(不是类或静态)方法 \xe2\x80\x93 一样对待基于各种输入组合的预期输出。但除此之外,我还会测试它是否返回(或不返回,具体取决于您的要求)单例对象。
\n然而,人们可能更愿意提取单例测试作为__new__相关测试用例。

\n\n

最终您将进行以下测试:

\n\n
    \n
  1. 无效参数的类型处理(空/非空字符串、整数、元组、字典等)。
  2. \n
  3. 无效的参数组合处理(在您的情况下它会引发异常)。
  4. \n
  5. 可选参数存在/不存在处理(默认值有效,自定义值也有效,等等)。
  6. \n
  7. 有效参数组合处理(正流有效)。
  8. \n
  9. 结果对象的属性存在/不存在及其值(大多数情况下您在其他方法中依赖它们)。
  10. \n
  11. 生成的对象是单例(或不是)。
  12. \n
  13. ???
  14. \n
\n\n

另一个提示:提取contract_types = ['item','vendor']到类属性将有助于业务逻辑测试组织。

\n