Any way to reset a mocked method to its original state? – Python Mock – mock 1.0b1

You can use mock.patch as a decorator or a context manager:

from mock import patch, MagicMock

@patch('myClass.A', MagicMock(return_value="CPU"))
def test(self):
    pass

or:

def test(self):
    with patch('myClass.A', MagicMock(return_value="CPU")):
        pass

If you don’t supply a mock object to patch then it will provide an autospecced mock that you can modify:

@patch('myClass.A')
def test(self, mock_A):
    mock_A.return_value="CPU"
    pass

or:

def test(self):
    with patch('myClass.A') as mock_A:
        mock_A.return_value="CPU"
        pass

In all cases the original value will be restored when the decorated test function or context manager finishes.

Leave a Comment