17

I'm trying to understand the assert_called_with within mock but the code I wrote throws some error.

import os
import twitter

URL = "http://test.com"

def tweet(api, message):
    if len(message) > 40:
        message = message.strip("?.,.,.")

    status = api.PostUpdate(message)
    return status

def main():
    api = twitter.Api(consumer_key=''
                    ,consumer_secret='')
    msg = 'This is test message'
    tweet(api, msg)

if __name__ == '__main__':
    main()

unittest

import unittest
from mock import Mock
import test

class TweetTest(unittest.TestCase):
    def test_example(self):
        mock_twitter = Mock()        
        test.tweet(mock_twitter,'msg')        
        mock_twitter.PostUpdate.assert_called_with('message')        

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

I'm trying to understand what assert_called_with does here?

damon
  • 14,485
  • 14
  • 56
  • 75
user1050619
  • 19,822
  • 85
  • 237
  • 413
  • That test has no value for you. All it does is fail when api.PostUpdate is not called with 'message'. Based on the code it will fail every time. A better test is to lookup the twitter api test credentials and actually hit the external api. – Dan Dec 01 '17 at 17:02
  • 1
    @Dan I agree there's limited use in this particular code snippet but I don't agree with looking up the API test credentials and hitting the external API. Isn't the whole point of introducing mocks here so that you can make assertions about how the code will interact w/ an external system without actually HAVING to call/mutate that external system? Otherwise we are venturing into the territory of E2E / integration testing? – Yu Chen Aug 07 '21 at 17:01

1 Answers1

21

According to the python documentation https://docs.python.org/3/library/unittest.mock.html#unittest.mock.Mock.assert_called_with

'This method is a convenient way of asserting that calls are made in a particular way'

so it tests whether the parameters are being used in the correct way.

About the errors that you are receiving, I think the parameter you're passing is wrong. Its have to be something like this:

mock_twitter.PostUpdate.assert_called_with(message='msg')