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

后端 未结 2 2051
余生分开走
余生分开走 2021-02-02 07:04

I have the following simplified class I\'m mocking:

class myClass(object):
    @staticmethod
    def A():
        #...

    def check(self):
        #code...
            


        
2条回答
  •  旧时难觅i
    2021-02-02 07:24

    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.

提交回复
热议问题