【问题标题】:Testing `__init__` attributes测试 __init__ 属性
【发布时间】:2023-02-06 10:01:53
【问题描述】:

我知道 __init__ 总是返回 None,那么如何有效地测试 __init__ 属性,这样如果属性未通过测试,初始化可以返回 False

我可以做这样的事情,但我怀疑从 number_of_lines 的角度来看这是非常低效的。

#
#### test.py
#
class Foo():
    def __init__(self, word):
        if word == 'foo':
            raise ValueError(f'{word} invalid for attribute') 

def test():
    try:
        f = Foo('foo')
    except ValueError:
        return False

test()

# test.py
False

【问题讨论】:

  • 这将取决于有效值是什么。如果它只能是“bar”,那么测试它不能成为的所有东西将是非常低效的。但是,如果它可以不是“foo”,那么这很好。
  • 如果使用 unittest 模块,则可以使用 assertRaises 来测试无效值。
  • “这样如果属性未通过测试,初始化可能会返回 False”——这将是一种非常奇怪的类设计方式,通常比仅仅引发异常更糟糕。

标签: python


【解决方案1】:

使用 unittest 模块,它有很多方便的助手来处理这种事情:

class Foo():
    def __init__(self, word):
        if word == 'foo':
            raise ValueError(f'{word} invalid for attribute') 


from unittest import TestCase

class FooTest(TestCase):
    def test_init(self):
        """Test that Foo.__init__ only raises on 'foo'"""
        Foo('bar')
        with self.assertRaises(ValueError):
            Foo('foo')

使用 pytest 工具自动运行所有测试并向您报告是否有任何失败:

>pytest test.py
================================================ test session starts =================================================
platform win32 -- Python 3.10.5, pytest-7.1.2, pluggy-1.0.0
plugins: cov-3.0.0, dotenv-0.5.2
collected 1 item

test.py .                                                                                                       [100%]

================================================= 1 passed in 0.18s ==================================================

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-15
    • 1970-01-01
    • 1970-01-01
    • 2019-04-07
    • 2017-11-28
    • 2018-02-23
    • 2019-03-02
    相关资源
    最近更新 更多