Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python, mock: raise exception [closed]

I'm having issues raising an exception from a function in my test:

### Implemetation
def MethodToTest():
    myVar = StdObject()
    try:
        myVar.raiseError() # <--- here
        return True
    except Exception as e:
        # ... code to test
        return False

### Test file
@patch('stdLib.StdObject', autospec=True)
def test_MethodeToTest(self, mockedObjectConstructor):
    mockedObj = mockedObjectConstructor.return_value
    mockedObj.raiseError.side_effect = Exception('Test') # <--- do not work
    ret = MethodToTest()
    assert ret is False

I would like to raiseError() function to raise an error.

I found several examples on SO, but none that matched my need.

like image 872
user4780495 Avatar asked Nov 22 '16 07:11

user4780495


People also ask

What is Side_effect in mock Python?

side_effect: A function to be called whenever the Mock is called. See the side_effect attribute. Useful for raising exceptions or dynamically changing return values. The function is called with the same arguments as the mock, and unless it returns DEFAULT , the return value of this function is used as the return value.

What is MagicMock?

MagicMock. MagicMock objects provide a simple mocking interface that allows you to set the return value or other behavior of the function or object creation call that you patched. This allows you to fully define the behavior of the call and avoid creating real objects, which can be onerous.


2 Answers

I changed

@patch('stdLib.StdObject', autospec=True)

to

@patch('stdLib.StdObject', **{'return_value.raiseError.side_effect': Exception()})

and removed the # <--- do not work line.

It's now working.

This is a good example.

EDIT:

mockedObj.raiseError.side_effect = Mock(side_effect=Exception('Test'))

also works.

like image 173
user4780495 Avatar answered Oct 17 '22 02:10

user4780495


Ok, your answer you provided is valid, but you changed how you did it (which is fine. To fix your original problem, you need to assign a function to side_effect, not the results or an object:

def my_side_effect():
    raise Exception("Test")

@patch('stdLib.StdObject', autospec=True)
def test_MethodeToTest(self, mockedObjectConstructor):
    mockedObj = mockedObjectConstructor.return_value
    mockedObj.raiseError.side_effect = my_side_effect # <- note no brackets, 
    ret = MethodToTest()
    assert ret is False

Hope that helps. Note, if the target method takes args, the side effect needs to take args as well (I believe).

like image 43
Jmons Avatar answered Oct 17 '22 03:10

Jmons