I have a file say twitter.py in which I have two global objects: user and tweet. I have another file say twitter_utils.py in which I have imported module twitter and have written few methods using global objects as following:
twitter_utils.py:
import twitter
def __get_user_date_of_birth(user_id):
return twitter.user.get_date_of_birth(userId=user_id)
def __get_tweet_likes_count(user_id, tweet_id):
return twitter.tweet.getLikesCount(user_id, tweet_id)
I created a file test_twitter_utils.py and tried writing tests for above methods. Following is an attempt:
import twitter
import twitter_utils
@patch('twitter_utils.twitter.user')
def test_get_user_date_of_birth(mock_user):
mock_get_date_of_birth = Mock(
return_value='18 Aug 1989')
mock_user.attach_mock(mock_get_date_of_birth,
'get_date_of_birth')
twitter_utils.__get_user_date_of_birth('test')
assert mock_user.mock_get_date_of_birth.call_count == 1
Above test fails with an assertion error saying, assert 0 == 1. Essentially saying that mock_user.mock_get_date_of_birth.call_count = 0. What am I doing wrong ? Am I importing things in wrong fashion ?
I believe you need to mock using the path that your module imports. twitter_utils.py
imports twitter
, so your patch
should be patching twitter
.
@patch('twitter_utils.twitter')
.
You can then mock functions from there.
Had you been doing an import like:
from twitter import user as twitter_user
Then your patch would be @patch("twitter_utils.twitter_user")
Also, not sure if you are aware, but when writing tests it's good to use unittest
framework. https://docs.python.org/2/library/unittest.html
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.