【问题标题】:python unittest combine assertions with context managerpython unittest 将断言与上下文管理器结合起来
【发布时间】:2021-04-27 11:31:24
【问题描述】:

为了测试一个函数,当第一个参数不是整数类型时我会引发异常:

def magicWithInteger(integerA):
    if not isinstance(integerA, int):
        raise TypeError("argument should be integer type")

我使用 unittest assertRaises AND assertEqual,所以我可以检查参数错误的函数是否引发 TypeError 以及 TypeError 是否真的吐出“参数应该是整数类型”

class test(unittest.TestCase):

    def test_magicWithInteger(self):
        self.assertRaises(TypeError, MagicWithInteger, "TEST")
        try:
            MagicWithInteger("TEST")
        except TypeError as error:
            self.assertEqual(str(error), "argument should be integer type")

两次调用函数看起来有点傻,第一次检查是否引发异常,第二次检查哪个TypeError异常?
经过一番研究,我知道应该可以使用上下文管理器一次性完成这两个测试,但我似乎无法维持生计......

【问题讨论】:

    标签: python unit-testing libreoffice soffice


    【解决方案1】:

    您可以使用with self.assertRaises(ExceptionType) 上下文管理器来捕获异常。根据assertRaises manual,您可以查看with 块之后的异常:如果您使用as <name> 语法为其命名,它似乎仍在范围内:

    with self.assertRaises(SomeException) as cm:
        do_something()
    
    the_exception = cm.exception
    self.assertEqual(the_exception.error_code, 3)
    

    来源:docs.python.org

    所以你的代码会变成:

    class test(unittest.TestCase):
        def test_magicWithInteger(self):
            with self.assertRaises(TypeError) as cm:
                MagicWithInteger("TEST")
            self.assertEqual(str(cm.exception), "argument should be integer type")
    

    PS:我不知道这一点,但是with 语句并没有在 Python 中引入新的作用域。在with 中定义的变量与with 语句本身在同一范围内。关于这一点,请参阅 https://stackoverflow.com/a/45100308/3216427,对于实际创建范围的内容,请参阅 https://stackoverflow.com/a/52992404/3216427

    【讨论】:

      猜你喜欢
      • 2020-06-10
      • 1970-01-01
      • 2015-02-02
      • 2020-11-08
      • 2016-10-21
      • 2019-05-30
      • 1970-01-01
      • 1970-01-01
      • 2013-09-16
      相关资源
      最近更新 更多