Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AssertionError "not called" on simple mock in Python

Tags:

python

mocking

I'm trying to use the Python mock module (downloaded using pip) for the first time. I'm having problems setting an assert, I've narrowed it down to this code:

class TestUsingMock(unittest.TestCase):

    def setUp(self):
        self.fake_client = mock.Mock()

    def test_mock(self):
        self.fake_client.copy = mock.Mock()
        self.fake_client.copy("123")
        self.fake_client.assert_called_with("123")

if __name__ == "__main__":
    unittest.main()

This is the error I get:

F
======================================================================
FAIL: test_mock (__main__.TestVCSDriver)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "./mock_test.py", line 17, in test_mock
    self.fake_client.assert_called_with("123")
  File "/Library/Python/2.6/site-packages/mock.py", line 859, in assert_called_with
    raise AssertionError('Expected call: %s\nNot called' % (expected,))
AssertionError: Expected call: mock('123')
Not called

Without the assertion, everything works fine. What am I doing wrong?

like image 676
seanhodges Avatar asked Jun 06 '26 19:06

seanhodges


1 Answers

You are calling the object self.fake_client.copy, but test whether another one, self.fake_client has been called.

Either call the "correct" object:

self.fake_client("123")
self.fake_client.assert_called_with("123")

or test the copy:

self.fake_client.copy("123")
self.fake_client.copy.assert_called_with("123")
like image 145
Ferdinand Beyer Avatar answered Jun 09 '26 07:06

Ferdinand Beyer