I'm using http://ift.tt/SHBj91 lib for Twiitter's API integration in Python. I have tw.py file with some Twitter's API usages and a tests.py file with some unit tests. Why my test: test_third does not pass? What am I doing wrong with patching tweepy.API class?
# tw.py
import tweepy
import settings
def get_tweepy_api():
"""
Constructs twitter api object with all required keys, tokens.
@return: tweepy API object
@rtype: tweepy.api.API
"""
oauth = tweepy.auth.OAuthHandler(
consumer_key=settings.TWITTER_CONSUMER_KEY_ENGINE,
consumer_secret=settings.TWITTER_CONSUMER_SECRET_KEY_ENGINE,
callback=None)
oauth.set_access_token(settings.TWITTER_ACCESS_KEY_ENGINE,
settings.TWITTER_ACCESS_SECRET_ENGINE)
api = tweepy.API(oauth)
return api
class TwitterAccount(object):
@staticmethod
def validate(user_id):
try:
api = get_tweepy_api()
print('object api', api)
tuser = api.get_user(user_id)
print('method', api.get_user)
print('tuser', tuser)
if tuser.protected:
return False
except tweepy.TweepError:
return False
return True
# tw.py
import unittest
from unittest.mock import create_autospec, MagicMock, ANY, patch
import tweepy
from tw import TwitterAccount
class MockedUser(object):
protected = False
class TwitterTestCase(unittest.TestCase):
def test_first(self):
api = create_autospec(tweepy.API, name='FirstAPI')
api.get_user = MagicMock(return_value=MockedUser)
tweepy.API = MagicMock(return_value=api)
self.assertTrue(TwitterAccount.validate('123'))
api.get_user.assert_called_once_with('123')
@patch.object(tweepy.API, 'get_user', return_value=MockedUser)
def test_second(self, tweepy_api):
self.assertTrue(TwitterAccount.validate('123'))
tweepy_api.assert_called_once_with(ANY)
@patch('tw.tweepy.API', autospec=True)
def test_third(self, tweepy_api):
tweepy_api.get_user = MagicMock(return_value=MockedUser)
self.assertTrue(TwitterAccount.validate('123'))
Aucun commentaire:
Enregistrer un commentaire