kurojishi
kurojishi

Reputation: 321

assertRaises doesn't catch errors

I have this script

import unittest,itertools,random

##testclass
class Testcomb(unittest.TestCase):

     def test_input(self):
        self.assertRaises(TypeError,calculate_combinations,dict(comb1), 5)

def calculate_combinations(combin,target):
    counter = 0
    for L in range(0, len(combin)+1):
      for subset in itertools.combinations(combin, L):
        if sum(subset) == target: counter= counter+1
    return counter

comb1=[1,2,3,4]


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

but the self.assertRaises(TypeError,calculate_combinations,dict(comb1), 5) does not intercept the exception giving me this error:

E..
======================================================================
ERROR: test_input (__main__.Testcomb)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "total_combination.py", line 25, in test_input
    self.assertRaises(TypeError,calculate_combinations,dict(comb1), 5)
TypeError: cannot convert dictionary update sequence element #0 to a sequence

----------------------------------------------------------------------
Ran 3 tests in 0.000s

FAILED (errors=1)

Can anyone help?

Upvotes: 2

Views: 715

Answers (1)

mac
mac

Reputation: 43031

The exception that makes your test fail is triggered by the dict(comb1) part of the assertion.

>>> comb1=[1,2,3,4]
>>> dict(comb1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: cannot convert dictionary update sequence element #0 to a sequence

On the contrary, the assertRaises will return True only if it is the callable (in your case calculate_combinations) to trigger it.

HTH!

Upvotes: 3

Related Questions