Home > OS >  Why does this Python Try not catch an exception when the return value is assigned to a variable?
Why does this Python Try not catch an exception when the return value is assigned to a variable?

Time:02-02

I've got a try block like so:

try:
   result = api.call_to_api(arg1, ar2)
except: ValueError

Which gets called via a unit test where api.call_to_api() is patched as following:

@patch('api.call_to_api')
def myTest(self, mock):
   mock.side_effect = [DEFAULT, ValueError]
   # test logic

In the test it does not catch the error. Rather, what happens is result gets assigned

However, when I change the try block to the following it does catch the error:

try:
   result = api.call_to_api(arg1, ar2)
   api.call_to_api(arg1, ar2)
except: ValueError

When the api.call_to_api() gets its own line there is no issue with the test. It successfully catches the error I have mocked and sends it down the exception path. When I inspect the values result is still receiving the '' value, and it does trigger the try on the specific line without the assignment.

Why does this Python Try not catch an exception when the return value is assigned to a variable?

CodePudding user response:

Your first block of code does not catch an exception because no exception is raised. When you write mock.side_effect = [DEFAULT, ValueError], you tell the mock to return DEFAULT the first time it is called and ValueError the second time (see docs). In your second block of code, you call api.call_to_api twice. This means that result will get the value of the first element in side_effect (i.e., DEFAULT), and the second line is an expression which equates to ValueError.

  • Related