How to call self in a mock method of an object in Python?

后端 未结 2 1943
自闭症患者
自闭症患者 2020-12-10 01:49

I try to test some codes which don\'t return anything but save the result to the DB. By mocking the save method, I wish to check whether things have been processed correctly

相关标签:
2条回答
  • 2020-12-10 02:15

    Sometime you just want to check that a method has been called, but you have no control over where its class is instantiated or the method called. Here's an approach that could save some time to whoever stumble upon this pattern:

    # first get a reference to the original unbound method we want to mock
    original_save = Item.save
    # then create a wrapper whose main purpose is to record a reference to `self`
    # when it will be passed, then delegates the actual work to the unbound method
    def side_fx(self, *a, **kw):
        side_fx.self = self
        return original_save(self, *a, **kw)
    # you're now ready to play
    with patch.object(Item, 'save', autospec=True, side_effect=side_fx) as mock_save:
        data = "the data"
        # your "system under test"
        instance = SomeClass()
        # the method where your mock is used
        instance.some_method(data) 
    
        # you now want to check if it was indeed called with all the proper arguments
        mock_save.assert_called_once_with(side_fx.self, data) 
    
    0 讨论(0)
  • 2020-12-10 02:25

    You need autospec=True

    def mock_save(self):
        assert self.attr == 'dest_val'
    with mock.patch.object(Item, "save", autospec=True) as save:
        save.side_effect = mock_save
        func_to_call()
    
    0 讨论(0)
提交回复
热议问题