Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python unit test for a function that has try/except

I have a function that has try/except as follows:

def func_A():
  try:
       # do some stuff
  except Exception as e:
     log.error("there was an exception %s", str(e))

I want to write a unit test for this func_A() More importantly, I want to ensure that

  • No exception was caught inside A

I have try/except just for safety. Unless there is a bug, there should be no exception thrown inside A (although it will be caught with try/except) and that's what I want to validate with my unit test.

What is the best way for unit test to catch the case where there was an exception thrown and caught?

like image 699
leopoodle Avatar asked Oct 28 '16 21:10

leopoodle


People also ask

How do you test try and except in Python?

The try block lets you test a block of code for errors. The except block lets you handle the error. The else block lets you execute code when there is no error. The finally block lets you execute code, regardless of the result of the try- and except blocks.

How do you write a unit test case for exception in 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.

What is assertRaises?

assertraises is a function that fails unless an exception is raised by an object of a class. It is mostly used in testing scenarios to prevent our code from malfunctioning. Let's work with a detailed example to see the working of assertRaises .

How do I run a unit test in Python?

If you're using the PyCharm IDE, you can run unittest or pytest by following these steps: In the Project tool window, select the tests directory. On the context menu, choose the run command for unittest . For example, choose Run 'Unittests in my Tests…'.


1 Answers

If you really need this, one possible way is to mock out the log.error object. After invoking the func_A function, you can make an assertion that your mock wasn't called.

Note that you should not catch exceptions at all if you don't intend to actually handle them. For proper test coverage, you should provide 2 tests here - one which checks each branching of the try/except.

like image 198
wim Avatar answered Sep 22 '22 03:09

wim