Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass a Python unittest if an exception isn't raised

Tags:

In the Python unittest framework, is there a way to pass a unit test if an exception wasn't raised, and fail with an AssertRaise otherwise?

like image 306
Levi Campbell Avatar asked May 30 '11 23:05

Levi Campbell


People also ask

How do you handle exceptions in unit test Python?

There are two ways you can use assertRaises: using keyword arguments. Just pass the exception, the callable function and the parameters of the callable function as keyword arguments that will elicit the exception. Make a function call that should raise the exception with a context.

Which item in Python will stop a unit test abruptly?

An exception object is created when a Python script raises an exception. If the script explicitly doesn't handle the exception, the program will be forced to terminate abruptly.

How do you assert false in Python?

assertFalse() in Python is a unittest library function that is used in unit testing to compare test value with false. This function will take two parameters as input and return a boolean value depending upon the assert condition. If test value is false then assertFalse() will return true else return false.


1 Answers

If I understand your question correctly, you could do something like this:

def test_does_not_raise_on_valid_input(self):     raised = False     try:         do_something(42)     except:         raised = True     self.assertFalse(raised, 'Exception raised') 

...assuming that you have a corresponding test that the correct Exception gets raised on invalid input, of course:

def test_does_raise_on_invalid_input(self):     self.assertRaises(OutOfCheese, do_something, 43) 

However, as pointed out in the comments, you need to consider what it is that you are actually testing. It's likely that a test like...

def test_what_is_42(self):     self.assertEquals(do_something(42), 'Meaning of life') 

...is better because it tests the desired behaviour of the system and will fail if an exception is raised.

like image 91
Johnsyweb Avatar answered Sep 20 '22 12:09

Johnsyweb