jack
jack

Reputation: 923

In python 3.4.1, how can I assert an error in unittest like this?

For example, I define a function like

def f(n): return 1+'1'

and in the unittest, I define test_error:

assertRaises(TypeError,f(1))

But it just showed that this is a error. But when I define f with no argument like

def f(): return 1+'1'

and in unittest

assertRaises(TypeError,f)

it worked just fine. Why is that? How can I deal with function with arguments?

Upvotes: 0

Views: 565

Answers (2)

alecxe
alecxe

Reputation: 473863

This is because you should pass function arguments alongside with it's arguments:

self.assertRaises(TypeError, f, 1)

FYI, according to the documentation, this is the assertRaises() contract:

assertRaises(exception, callable, *args, **kwds)

where callable is your f function, *args and **kwds are positional and keyword arguments that you are passing in.

Upvotes: 0

Martijn Pieters
Martijn Pieters

Reputation: 1121834

You called the first function before handing it to the assertRaises() method. You can give the method additional arguments that it'll then pass on to the function-under-test:

self.assertRaises(TypeError, f, 1)

The better option would be to use self.assertRaises() as a context manager:

with self.assertRaises(TypeError):
    f(1)

You call the method 'normally' in that case, which reads a lot more natural.

See the TestCase.assertRaises() documentation:

Test that an exception is raised when callable is called with any positional or keyword arguments that are also passed to assertRaises().

and

If only the exception and possibly the msg arguments are given, return a context manager so that the code under test can be written inline rather than as a function:

with self.assertRaises(SomeException):
    do_something()

Upvotes: 1

Related Questions