python assertRaises don't pass test if function with parameters

900 Views Asked by At

assertRaises give an assertion error with the following code. Is there something I'm doing wrong?

class File_too_small(Exception):
    "Check file size"

def foo(a,b):
    if a<b:
        raise File_too_small
class some_Test(unittest.TestCase):

    def test_foo(self):
        self.assertRaises(File_too_small,foo(1,2))

The test seems to pass with the following modification though

def foo:
    raise File_too_small

def test_foo(self):
    self.assertRaises(File_too_small,foo)
2

There are 2 best solutions below

0
On BEST ANSWER

Try like this:

def test_foo(self):
    with self.assertRaises(File_too_small):
        foo(1, 2)

or:

def test_foo(self):
    self.assertRaises(File_too_small, foo, 1, 2):
0
On

You need to pass the callable, not the result, to assertRaises:

self.assertRaises(File_too_small, foo, 1, 2)

Alternatively use it as a context manager:

with self.assertRaises(File_too_small):
    foo(1, 2)