Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to catch "TypeError" with assertRaises()

I want to catch a TypeError produced by the code, but unfortunately, unittest fails:

Here is the code:

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__":                            

Here is the error:

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)   
like image 867
Vor Avatar asked Dec 12 '22 06:12

Vor


2 Answers

Unquote the TypeError and don't call Foo directly, but pass the function (class Foo) and arguments.

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

Or, you can use assertRaises as context manager:

def test_bar_as_string(self):                                               
    with self.assertRaises(TypeError):
        Foo("a")                                
like image 108
falsetru Avatar answered Dec 13 '22 20:12

falsetru


You could do it as:

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

or

self.assertRaises(TypeError, Foo, "a")
like image 20
aneroid Avatar answered Dec 13 '22 20:12

aneroid