【问题标题】:How to use unittest to assert an assert?如何使用 unittest 断言断言?
【发布时间】:2019-04-08 17:36:43
【问题描述】:

假设我有这个功能:

def to_upper(var):
    assert type(var) is str, 'The input for to_upper should be a string'
    return var.upper()

还有一个使用unittest进行单元测试的文件:

class Test(unittest.TestCase):

    def test_1(self):
        -- Code here --


if __name__ == '__main__':
    unittest.main()

如何测试如果我调用 to_upper(9) 会引发断言错误?

【问题讨论】:

  • 附带说明,您可能希望将type(var) is str 更改为isinstance(var, str) 以更符合习惯并处理str 的子类
  • 鉴于可以在运行时禁用断言,这似乎是一个无用的测试。
  • @chepner 可能是对的。随它去吧。如果var 不是strto_upper 将自动提升AttributeError(假设它没有实现upper

标签: python testing assert python-unittest


【解决方案1】:

您可以使用assertRaises(AssertionError) 断言断言:

def test_1(self):
    with self.assertRaises(AssertionError):
        to_upper(9)

【讨论】:

    【解决方案2】:

    断言用于调试。如果有一些足够重要的前提条件可以通过单元测试进行验证,请明确检查它,如果失败,请酌情提出ValueErrorTypeError

    不过,在这种情况下,您实际上并不关心 varstr;你只需要它有一个upper 方法。

    def to_upper(var):
        try:
            return var.upper()
        except AttributeError:
            raise TypeError("Argument has no method 'upper'")
    

    【讨论】:

    • 也许TypeErrorValueError 更合适?
    • 是的,会的。
    猜你喜欢
    • 1970-01-01
    • 2015-02-02
    • 1970-01-01
    • 2013-09-16
    • 2013-01-07
    • 1970-01-01
    • 1970-01-01
    • 2022-11-17
    • 2011-05-12
    相关资源
    最近更新 更多