|
| 1 | +# encoding: utf-8 |
| 2 | + |
| 3 | +import twitter |
| 4 | +import time |
| 5 | +import unittest |
| 6 | + |
| 7 | +from apikey import (CONSUMER_KEY, |
| 8 | + CONSUMER_SECRET, |
| 9 | + ACCESS_TOKEN_KEY, |
| 10 | + ACCESS_TOKEN_SECRET) |
| 11 | + |
| 12 | + |
| 13 | +@unittest.skipIf(not CONSUMER_KEY and not CONSUMER_SECRET, "No tokens provided") |
| 14 | +class ApiTest(unittest.TestCase): |
| 15 | + def setUp(self): |
| 16 | + self._urllib = MockUrllib() |
| 17 | + time.sleep(15) |
| 18 | + api = twitter.Api(consumer_key=CONSUMER_SECRET, |
| 19 | + consumer_secret=CONSUMER_SECRET, |
| 20 | + access_token_key=ACCESS_TOKEN_KEY, |
| 21 | + access_token_secret=ACCESS_TOKEN_SECRET, |
| 22 | + cache=None) |
| 23 | + api.SetUrllib(self._urllib) |
| 24 | + self._api = api |
| 25 | + print "Testing the API class. This test is time controlled" |
| 26 | + |
| 27 | + def testTwitterError(self): |
| 28 | + '''Test that twitter responses containing an error message are wrapped.''' |
| 29 | + self._AddHandler('https://api.twitter.com/1.1/statuses/user_timeline.json', |
| 30 | + curry(self._OpenTestData, 'public_timeline_error.json')) |
| 31 | + # Manually try/catch so we can check the exception's value |
| 32 | + try: |
| 33 | + statuses = self._api.GetUserTimeline() |
| 34 | + except twitter.TwitterError, error: |
| 35 | + # If the error message matches, the test passes |
| 36 | + self.assertEqual('test error', error.message) |
| 37 | + else: |
| 38 | + self.fail('TwitterError expected') |
| 39 | + |
| 40 | + def testGetUserTimeline(self): |
| 41 | + '''Test the twitter.Api GetUserTimeline method''' |
| 42 | + time.sleep(8) |
| 43 | + print 'Testing GetUserTimeline' |
| 44 | + self._AddHandler('https://api.twitter.com/1.1/statuses/user_timeline.json?count=1&screen_name=kesuke', |
| 45 | + curry(self._OpenTestData, 'user_timeline-kesuke.json')) |
| 46 | + statuses = self._api.GetUserTimeline(screen_name='kesuke', count=1) |
| 47 | + # This is rather arbitrary, but spot checking is better than nothing |
| 48 | + self.assertEqual(89512102, statuses[0].id) |
| 49 | + self.assertEqual(718443, statuses[0].user.id) |
| 50 | + |
| 51 | + #def testGetFriendsTimeline(self): |
| 52 | + # '''Test the twitter.Api GetFriendsTimeline method''' |
| 53 | + # self._AddHandler('https://api.twitter.com/1.1/statuses/friends_timeline/kesuke.json', |
| 54 | + # curry(self._OpenTestData, 'friends_timeline-kesuke.json')) |
| 55 | + # statuses = self._api.GetFriendsTimeline('kesuke') |
| 56 | + # # This is rather arbitrary, but spot checking is better than nothing |
| 57 | + # self.assertEqual(20, len(statuses)) |
| 58 | + # self.assertEqual(718443, statuses[0].user.id) |
| 59 | + |
| 60 | + def testGetStatus(self): |
| 61 | + '''Test the twitter.Api GetStatus method''' |
| 62 | + time.sleep(8) |
| 63 | + print 'Testing GetStatus' |
| 64 | + self._AddHandler('https://api.twitter.com/1.1/statuses/show.json?include_my_retweet=1&id=89512102', |
| 65 | + curry(self._OpenTestData, 'show-89512102.json')) |
| 66 | + status = self._api.GetStatus(89512102) |
| 67 | + self.assertEqual(89512102, status.id) |
| 68 | + self.assertEqual(718443, status.user.id) |
| 69 | + |
| 70 | + def testDestroyStatus(self): |
| 71 | + '''Test the twitter.Api DestroyStatus method''' |
| 72 | + time.sleep(8) |
| 73 | + print 'Testing DestroyStatus' |
| 74 | + self._AddHandler('https://api.twitter.com/1.1/statuses/destroy/103208352.json', |
| 75 | + curry(self._OpenTestData, 'status-destroy.json')) |
| 76 | + status = self._api.DestroyStatus(103208352) |
| 77 | + self.assertEqual(103208352, status.id) |
| 78 | + |
| 79 | + def testPostUpdate(self): |
| 80 | + '''Test the twitter.Api PostUpdate method''' |
| 81 | + time.sleep(8) |
| 82 | + print 'Testing PostUpdate' |
| 83 | + self._AddHandler('https://api.twitter.com/1.1/statuses/update.json', |
| 84 | + curry(self._OpenTestData, 'update.json')) |
| 85 | + status = self._api.PostUpdate(u'Моё судно на воздушной подушке полно угрей'.encode('utf8')) |
| 86 | + # This is rather arbitrary, but spot checking is better than nothing |
| 87 | + self.assertEqual(u'Моё судно на воздушной подушке полно угрей', status.text) |
| 88 | + |
| 89 | + def testPostRetweet(self): |
| 90 | + '''Test the twitter.Api PostRetweet method''' |
| 91 | + time.sleep(8) |
| 92 | + print 'Testing PostRetweet' |
| 93 | + self._AddHandler('https://api.twitter.com/1.1/statuses/retweet/89512102.json', |
| 94 | + curry(self._OpenTestData, 'retweet.json')) |
| 95 | + status = self._api.PostRetweet(89512102) |
| 96 | + self.assertEqual(89512102, status.id) |
| 97 | + |
| 98 | + def testPostUpdateLatLon(self): |
| 99 | + '''Test the twitter.Api PostUpdate method, when used in conjunction with latitude and longitude''' |
| 100 | + time.sleep(8) |
| 101 | + print 'Testing PostUpdateLatLon' |
| 102 | + self._AddHandler('https://api.twitter.com/1.1/statuses/update.json', |
| 103 | + curry(self._OpenTestData, 'update_latlong.json')) |
| 104 | + #test another update with geo parameters, again test somewhat arbitrary |
| 105 | + status = self._api.PostUpdate(u'Моё судно на воздушной подушке полно угрей'.encode('utf8'), latitude=54.2, |
| 106 | + longitude=-2) |
| 107 | + self.assertEqual(u'Моё судно на воздушной подушке полно угрей', status.text) |
| 108 | + self.assertEqual(u'Point', status.GetGeo()['type']) |
| 109 | + self.assertEqual(26.2, status.GetGeo()['coordinates'][0]) |
| 110 | + self.assertEqual(127.5, status.GetGeo()['coordinates'][1]) |
| 111 | + |
| 112 | + def testGetReplies(self): |
| 113 | + '''Test the twitter.Api GetReplies method''' |
| 114 | + time.sleep(8) |
| 115 | + print 'Testing GetReplies' |
| 116 | + self._AddHandler('https://api.twitter.com/1.1/statuses/user_timeline.json', |
| 117 | + curry(self._OpenTestData, 'replies.json')) |
| 118 | + statuses = self._api.GetReplies() |
| 119 | + self.assertEqual(36657062, statuses[0].id) |
| 120 | + |
| 121 | + def testGetRetweetsOfMe(self): |
| 122 | + '''Test the twitter.API GetRetweetsOfMe method''' |
| 123 | + time.sleep(8) |
| 124 | + print 'Testing GetRetweetsOfMe' |
| 125 | + self._AddHandler('https://api.twitter.com/1.1/statuses/retweets_of_me.json', |
| 126 | + curry(self._OpenTestData, 'retweets_of_me.json')) |
| 127 | + retweets = self._api.GetRetweetsOfMe() |
| 128 | + self.assertEqual(253650670274637824, retweets[0].id) |
| 129 | + |
| 130 | + def testGetFriends(self): |
| 131 | + '''Test the twitter.Api GetFriends method''' |
| 132 | + time.sleep(8) |
| 133 | + print 'Testing GetFriends' |
| 134 | + self._AddHandler('https://api.twitter.com/1.1/friends/list.json?cursor=123', |
| 135 | + curry(self._OpenTestData, 'friends.json')) |
| 136 | + users = self._api.GetFriends(cursor=123) |
| 137 | + buzz = [u.status for u in users if u.screen_name == 'buzz'] |
| 138 | + self.assertEqual(89543882, buzz[0].id) |
| 139 | + |
| 140 | + def testGetFollowers(self): |
| 141 | + '''Test the twitter.Api GetFollowers method''' |
| 142 | + time.sleep(8) |
| 143 | + print 'Testing GetFollowers' |
| 144 | + self._AddHandler('https://api.twitter.com/1.1/followers/list.json?cursor=-1', |
| 145 | + curry(self._OpenTestData, 'followers.json')) |
| 146 | + users = self._api.GetFollowers() |
| 147 | + # This is rather arbitrary, but spot checking is better than nothing |
| 148 | + alexkingorg = [u.status for u in users if u.screen_name == 'alexkingorg'] |
| 149 | + self.assertEqual(89554432, alexkingorg[0].id) |
| 150 | + |
| 151 | + #def testGetFeatured(self): |
| 152 | + # '''Test the twitter.Api GetFeatured method''' |
| 153 | + # self._AddHandler('https://api.twitter.com/1.1/statuses/featured.json', |
| 154 | + # curry(self._OpenTestData, 'featured.json')) |
| 155 | + # users = self._api.GetFeatured() |
| 156 | + # # This is rather arbitrary, but spot checking is better than nothing |
| 157 | + # stevenwright = [u.status for u in users if u.screen_name == 'stevenwright'] |
| 158 | + # self.assertEqual(86991742, stevenwright[0].id) |
| 159 | + |
| 160 | + def testGetDirectMessages(self): |
| 161 | + '''Test the twitter.Api GetDirectMessages method''' |
| 162 | + time.sleep(8) |
| 163 | + print 'Testing GetDirectMessages' |
| 164 | + self._AddHandler('https://api.twitter.com/1.1/direct_messages.json', |
| 165 | + curry(self._OpenTestData, 'direct_messages.json')) |
| 166 | + statuses = self._api.GetDirectMessages() |
| 167 | + self.assertEqual(u'A légpárnás hajóm tele van angolnákkal.', statuses[0].text) |
| 168 | + |
| 169 | + def testPostDirectMessage(self): |
| 170 | + '''Test the twitter.Api PostDirectMessage method''' |
| 171 | + time.sleep(8) |
| 172 | + print 'Testing PostDirectMessage' |
| 173 | + self._AddHandler('https://api.twitter.com/1.1/direct_messages/new.json', |
| 174 | + curry(self._OpenTestData, 'direct_messages-new.json')) |
| 175 | + status = self._api.PostDirectMessage('test', u'Моё судно на воздушной подушке полно угрей'.encode('utf8')) |
| 176 | + # This is rather arbitrary, but spot checking is better than nothing |
| 177 | + self.assertEqual(u'Моё судно на воздушной подушке полно угрей', status.text) |
| 178 | + |
| 179 | + def testDestroyDirectMessage(self): |
| 180 | + '''Test the twitter.Api DestroyDirectMessage method''' |
| 181 | + time.sleep(8) |
| 182 | + print 'Testing DestroyDirectMessage' |
| 183 | + self._AddHandler('https://api.twitter.com/1.1/direct_messages/destroy.json', |
| 184 | + curry(self._OpenTestData, 'direct_message-destroy.json')) |
| 185 | + status = self._api.DestroyDirectMessage(3496342) |
| 186 | + # This is rather arbitrary, but spot checking is better than nothing |
| 187 | + self.assertEqual(673483, status.sender_id) |
| 188 | + |
| 189 | + def testCreateFriendship(self): |
| 190 | + '''Test the twitter.Api CreateFriendship method''' |
| 191 | + time.sleep(8) |
| 192 | + print 'Testing CreateFriendship' |
| 193 | + self._AddHandler('https://api.twitter.com/1.1/friendships/create.json', |
| 194 | + curry(self._OpenTestData, 'friendship-create.json')) |
| 195 | + user = self._api.CreateFriendship('dewitt') |
| 196 | + # This is rather arbitrary, but spot checking is better than nothing |
| 197 | + self.assertEqual(673483, user.id) |
| 198 | + |
| 199 | + def testDestroyFriendship(self): |
| 200 | + '''Test the twitter.Api DestroyFriendship method''' |
| 201 | + time.sleep(8) |
| 202 | + print 'Testing Destroy Friendship' |
| 203 | + self._AddHandler('https://api.twitter.com/1.1/friendships/destroy.json', |
| 204 | + curry(self._OpenTestData, 'friendship-destroy.json')) |
| 205 | + user = self._api.DestroyFriendship('dewitt') |
| 206 | + # This is rather arbitrary, but spot checking is better than nothing |
| 207 | + self.assertEqual(673483, user.id) |
| 208 | + |
| 209 | + def testGetUser(self): |
| 210 | + '''Test the twitter.Api GetUser method''' |
| 211 | + time.sleep(8) |
| 212 | + print 'Testing GetUser' |
| 213 | + self._AddHandler('https://api.twitter.com/1.1/users/show.json?user_id=dewitt', |
| 214 | + curry(self._OpenTestData, 'show-dewitt.json')) |
| 215 | + user = self._api.GetUser('dewitt') |
| 216 | + self.assertEqual('dewitt', user.screen_name) |
| 217 | + self.assertEqual(89586072, user.status.id) |
| 218 | + |
| 219 | + def _AddHandler(self, url, callback): |
| 220 | + self._urllib.AddHandler(url, callback) |
| 221 | + |
| 222 | + def _GetTestDataPath(self, filename): |
| 223 | + directory = os.path.dirname(os.path.abspath(__file__)) |
| 224 | + test_data_dir = os.path.join(directory, 'testdata') |
| 225 | + return os.path.join(test_data_dir, filename) |
| 226 | + |
| 227 | + def _OpenTestData(self, filename): |
| 228 | + f = open(self._GetTestDataPath(filename)) |
| 229 | + # make sure that the returned object contains an .info() method: |
| 230 | + # headers are set to {} |
| 231 | + return urllib.addinfo(f, {}) |
| 232 | + |
| 233 | + |
| 234 | +class MockUrllib(object): |
| 235 | + '''A mock replacement for urllib that hardcodes specific responses.''' |
| 236 | + |
| 237 | + def __init__(self): |
| 238 | + self._handlers = {} |
| 239 | + self.HTTPBasicAuthHandler = MockHTTPBasicAuthHandler |
| 240 | + |
| 241 | + def AddHandler(self, url, callback): |
| 242 | + self._handlers[url] = callback |
| 243 | + |
| 244 | + def build_opener(self, *handlers): |
| 245 | + return MockOpener(self._handlers) |
| 246 | + |
| 247 | + def HTTPHandler(self, *args, **kwargs): |
| 248 | + return None |
| 249 | + |
| 250 | + def HTTPSHandler(self, *args, **kwargs): |
| 251 | + return None |
| 252 | + |
| 253 | + def OpenerDirector(self): |
| 254 | + return self.build_opener() |
| 255 | + |
| 256 | + def ProxyHandler(self, *args, **kwargs): |
| 257 | + return None |
| 258 | + |
| 259 | + |
| 260 | +class MockOpener(object): |
| 261 | + '''A mock opener for urllib''' |
| 262 | + |
| 263 | + def __init__(self, handlers): |
| 264 | + self._handlers = handlers |
| 265 | + self._opened = False |
| 266 | + |
| 267 | + def open(self, url, data=None): |
| 268 | + if self._opened: |
| 269 | + raise Exception('MockOpener already opened.') |
| 270 | + |
| 271 | + # Remove parameters from URL - they're only added by oauth and we |
| 272 | + # don't want to test oauth |
| 273 | + if '?' in url: |
| 274 | + # We split using & and filter on the beginning of each key |
| 275 | + # This is crude but we have to keep the ordering for now |
| 276 | + (url, qs) = url.split('?') |
| 277 | + |
| 278 | + tokens = [token for token in qs.split('&') |
| 279 | + if not token.startswith('oauth')] |
| 280 | + |
| 281 | + if len(tokens) > 0: |
| 282 | + url = "%s?%s" % (url, '&'.join(tokens)) |
| 283 | + |
| 284 | + if url in self._handlers: |
| 285 | + self._opened = True |
| 286 | + return self._handlers[url]() |
| 287 | + else: |
| 288 | + print url |
| 289 | + print self._handlers |
| 290 | + |
| 291 | + raise Exception('Unexpected URL %s (Checked: %s)' % (url, self._handlers)) |
| 292 | + |
| 293 | + def add_handler(self, *args, **kwargs): |
| 294 | + pass |
| 295 | + |
| 296 | + def close(self): |
| 297 | + if not self._opened: |
| 298 | + raise Exception('MockOpener closed before it was opened.') |
| 299 | + self._opened = False |
| 300 | + |
| 301 | + |
| 302 | +class curry(object): |
| 303 | + # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52549 |
| 304 | + |
| 305 | + def __init__(self, fun, *args, **kwargs): |
| 306 | + self.fun = fun |
| 307 | + self.pending = args[:] |
| 308 | + self.kwargs = kwargs.copy() |
| 309 | + |
| 310 | + def __call__(self, *args, **kwargs): |
| 311 | + if kwargs and self.kwargs: |
| 312 | + kw = self.kwargs.copy() |
| 313 | + kw.update(kwargs) |
| 314 | + else: |
| 315 | + kw = kwargs or self.kwargs |
| 316 | + return self.fun(*(self.pending + args), **kw) |
| 317 | + |
| 318 | + |
| 319 | +class MockHTTPBasicAuthHandler(object): |
| 320 | + '''A mock replacement for HTTPBasicAuthHandler''' |
| 321 | + |
| 322 | + def add_password(self, realm, uri, user, passwd): |
| 323 | + # TODO(dewitt): Add verification that the proper args are passed |
| 324 | + pass |
| 325 | + |
0 commit comments