【问题标题】:How to catch "TypeError" with assertRaises()如何用 assertRaises() 捕获“TypeError”
【发布时间】:2014-04-03 16:15:22
【问题描述】:

我想捕捉代码产生的 TypeError,但不幸的是,unittest 失败了:

代码如下:

import unittest                                                                 

class _Foo(object):                                                             
    def __init__(self):                                                         
        self.bar = ['AAA']                                                      

    def _validate_bar(self, bar):                                               
        if not isinstance(bar, list):                                           
            raise TypeError                                                     
        return True                                                             

class Foo(_Foo):                                                                
    def __init__(self, bar=None):                                               
        super(Foo, self).__init__()                                             
        if bar and self._validate_bar(bar):                                     
            self.bar = bar                                                      

class FooTest(unittest.TestCase):                                               

    def test_bar_as_string(self):                                               
        self.assertRaises("TypeError", Foo("a"))                                

    #def test_a(self):                                                          
    #    try:                                                                   
    #        Foo('a')                                                           
    #    except Exception as exc:                                               
    #        self.assertEqual('TypeError', exc.__class__.__name__)              

    #def test_bar_as_string(self):                                              
    #    with self.assertRaises("TypeError"):                                   
    #        Foo("a")                                                           

if __name__ == "__main__":                            

这是错误:

test_bar_as_string (__main__.FooTest) ... ERROR

======================================================================
ERROR: test_bar_as_string (__main__.FooTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "test.py", line 21, in test_bar_as_string
    self.assertRaises("TypeError", Foo("a"))
  File "test.py", line 15, in __init__
    if bar and self._validate_bar(bar):
  File "test.py", line 9, in _validate_bar
    raise TypeError
TypeError

----------------------------------------------------------------------
Ran 1 test in 0.000s

FAILED (errors=1)



    unittest.main(verbosity=2)   

【问题讨论】:

    标签: python unit-testing assert


    【解决方案1】:

    取消引用TypeError,不要直接调用Foo,而是传递函数(Foo 类)和参数。

    def test_bar_as_string(self):                                               
        self.assertRaises(TypeError, Foo, "a")
    

    或者,您可以使用assertRaises 作为上下文管理器:

    def test_bar_as_string(self):                                               
        with self.assertRaises(TypeError):
            Foo("a")                                
    

    【讨论】:

    • 看了你的例子后,我意识到,我把"放在TypeError周围,这就是我注释掉的代码不起作用的原因。
    【解决方案2】:

    你可以这样做:

    with self.assertRaises(TypeError):
        Foo("a")
    

    self.assertRaises(TypeError, Foo, "a")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-02
      • 2021-01-30
      • 2012-01-30
      • 1970-01-01
      • 2019-04-20
      • 2017-01-19
      • 2010-11-19
      • 1970-01-01
      相关资源
      最近更新 更多