4

I am trying to mock an instance method in Python with a side_effect. I want/expect my side effect to be called with an initial 'self' argument that I can use to determine the return value.

So I have something like this:

import mock

class TestCases(unittest.TestCase):

  @mock.patch('Item.exists')
  def test_foo(self, mock_item_exists):

    def item_exists_side_effect(*args, **kwargs):
      # I expect args[0] here to be supplied and to refer to the item
      _self = args[0]
      return _self.name == 'bar'

    mock_item_exists.side_effect = item_exists_side_effect

    ...

However, when Item.exists() gets called I end up in my side-effect function but with an empty args list.

Is this expected? Am I doing something wrong?

Graham Wheeler
  • 2,734
  • 1
  • 19
  • 23

1 Answers1

2

Looks like this is the reason:

Why does mock ignore the instance/object passed to a mocked out method when it is called?

I.e. by calling mock.patch I turned the instance method into a class method.

Community
  • 1
  • 1
Graham Wheeler
  • 2,734
  • 1
  • 19
  • 23
  • It is correct,. But in this case is better delete your question or mark it as duplicate. BTW you could upvote the linked answer if you find it useful :). One more thing: `mock_item_exists` is a *staticmethod* and not a *classmethod*. – Michele d'Amico Sep 12 '15 at 12:29