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

后端 未结 2 2030
余生分开走
余生分开走 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条回答
  •  臣服心动
    2021-02-02 07:23

    You can stash the function away on self and put it back when you're done.

    import unittest
    
    from mock import MagicMock
    from MyClass import MyClass
    
    class FirstTest(unittest.TestCase):
    
        def setUp(self):
            self.A = MyClass.A
            MyClass.A = MagicMock(name='mocked A', return_value='CPU')
    
    
        def tearDown(self):
            MyClass.A = self.A
    
        def test_mocked_static_method(self):
            print 'First Test'
            print MyClass.check
            print MyClass.A
    
    
    class SecondTest(unittest.TestCase):
    
        def setUp(self):
            MyClass.check = MagicMock(name='mocked check', return_value=object)
    
        def test_check_mocked_check_method(self):
            print 'Second Test'
            print MyClass.check
            print MyClass.A
    
    
    if __name__ == '__main__':
        unittest.main()
    

    Running this file gives the following output:

    First Test
     
    
    Second Test
    
    
    

    I found myself using the patch decorator a lot more than setUp and tearDown now. In this case you could do

    from mock import patch
    
    @patch('MyClass.A')
    def test_mocked_static_method(self, mocked_A)
        mocked_A.return_value = 'CPU'
        # This mock will expire when the test method is finished
    

提交回复
热议问题