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?
-
I've only found the need to do this when testing legacy code and putting up a bunch of sanity tests. These are tests without any Asserts (basically verifying that the code block executes without blowing up). Any unexpected exceptions fail the test anyway - not sure if the Python frameworks works similarly to the xUnit family.– GishuJun 1, 2011 at 5:16
-
2Possible duplicate of: stackoverflow.com/questions/4319825/…– user2443147Nov 13, 2014 at 1:53
-
Does this answer your question? Python unittest - opposite of assertRaises?– user9876Aug 22, 2021 at 21:28
4 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.
-
4IMHO something like this should be part of the unittest.TestCase class, it's an awkward thing to want, but I can't be the only person who wants it. May 30, 2011 at 23:50
-
@Levi Campbell: I agree, an
assertDoesNotRaise()
method would be neater. N.B: I have edited my answer since you accepted. May 30, 2011 at 23:57 -
14Why bother to first catch an exception and then raise a different one? Just call
do_something()
, and if an exception gets raised, the test automatically fails. This is also the reason whyassertDoesNotRaise()
does not exist. May 31, 2011 at 2:16 -
@Sven Marnach: You are correct and I have updated my answer accordingly. I initially answered the question as posed without giving due consideration as to the nature of the underlying problem. May 31, 2011 at 2:51
-
No @SvenMarnach is not correct: There is a difference between raising an error and failing a test. If do_something() raises an error in your last version, then the test will exit with an error instead of registering a test failure, which is what you actually want.– AlexMay 10, 2021 at 19:54
Many of the comments on this page treat errors and failures as equivalent, which they are not. The right solution in my opinion is to explicitly fail the test if the exception is raised. E.g.:
def test_does_not_error(self):
try:
code_under_test()
except ThatException:
self.fail("code_under_test raised ThatException")
-
3Agree -- while the console output for errors and failures parses comparably by a human read, most automated unit testing tools treat the two quite differently, right?– hBy2PyOct 8, 2015 at 2:17
-
It's the default assumption that code does not error out. Tests should test for desired behaviour. I don't see what value the try/except block adds. In fact, it decreases the usefulness of the test, since the output won't include the traceback, which it would if you just let the code fail. May 10, 2021 at 20:44
-
One value the try/except block adds is that it gives the OP what they were asking for. I understand it's a matter of preference; this style is my preference over unhandled exceptions. By catching a specific exception that indicates a known problem, the failure can be understood faster than if one has to scan screenfuls of traceback output. If this were a real test and not an example, and the traceback or other details of the exception were important, they could be reported in the
self.fail
as well. May 12, 2021 at 0:55
Simply call your functionality, e.g. do_something()
. If an unhandled exception gets raised, the test automatically fails! There is really no reason to do anything else. This is also the reason why assertDoesNotRaise()
does not exist.
Credit: comment by Sven
-
5That is not true, As if the method raises an error, then the test cases will be marked as an
error
not afailure
Nov 13, 2019 at 10:59 -
1@IslamTaha What difference does it make? Either way it has to be fixed. Nov 13, 2019 at 13:20
-
4@Acumenus the point isn't to just fix the test, you could in principle fix the test by cheating it. The point is that the purpose of the test is to exactly have you understand what is happening in the code and distinguishing between exceptions, sheer code bugs and failures is fundamental.– gentedDec 11, 2019 at 10:40
-
If you cheat with your test, you have bigger problems. For example, if I were to put one foot on the floor when I am checking my weight, then it's not the weighing scale that is to blame. Dec 3, 2020 at 13:40
I stumbled upon this question while looking for an answer to this obvious problem. Whilst the suggested solutions with try/except are fine, I found that I ended up with uncovered lines of code in coverage and that doesn't sit well with me. So I have come up with another solution, whilst not perfect, works for functions that only throw exceptions.
def check_raises(obj):
if obj.condition is True:
raise Exception('Condition is true')
In order to successfully test this function, I have resorted to using assertIsNone
. The below code covers both cases.
import unittest
class Object:
def __init__(self):
self.condition = None
class TestCheckRaises(unittest.TestCase):
def test_check_raises_exception(self):
obj = Object()
obj.condition = True
self.assertRaises(Exception, check_raises, obj)
def test_check_raises_no_exception(self):
obj = Object()
obj.condition = False
self.assertIsNone(check_raises(obj))
I am with the original poster that a assertNotRaises
would be nice, but failing that, assertIsNone
is perfectly acceptable for functions that do not return a value.