tests.py 13.4 KB
Newer Older
1
2
import unittest
import random
3
from time import sleep
Josh Roesslein's avatar
Josh Roesslein committed
4
import os
5

Joshua Roesslein's avatar
Joshua Roesslein committed
6
7
from nose import SkipTest

Joshua Roesslein's avatar
Joshua Roesslein committed
8
from tweepy import (API, OAuthHandler, Friendship, Cursor,
9
                    MemoryCache, FileCache)
10

Josh Roesslein's avatar
Josh Roesslein committed
11
12
"""Configurations"""
# Must supply twitter account credentials for tests
13
14
15
16
17
username = os.environ.get('TWITTER_USERNAME', '')
oauth_consumer_key = os.environ.get('CONSUMER_KEY', '')
oauth_consumer_secret = os.environ.get('CONSUMER_SECRET', '')
oauth_token = os.environ.get('ACCESS_KEY', '')
oauth_token_secret = os.environ.get('ACCESS_SECRET', '')
Josh Roesslein's avatar
Josh Roesslein committed
18

19
20
test_tweet_id = '266367358078169089'

21
22
"""Unit tests"""

23
24
25
26
27
28
29
30
31
32
33
34
class TweepyErrorTests(unittest.TestCase):

    def testpickle(self):
        """Verify exceptions can be pickled and unpickled."""
        import pickle
        from tweepy.error import TweepError

        e = TweepError('no reason', {'status': 200})
        e2 = pickle.loads(pickle.dumps(e))

        self.assertEqual(e.reason, e2.reason)
        self.assertEqual(e.response, e2.response)
Josh Roesslein's avatar
Josh Roesslein committed
35

36
37
class TweepyAPITests(unittest.TestCase):

Josh Roesslein's avatar
Josh Roesslein committed
38
    def setUp(self):
39
40
41
        auth = OAuthHandler(oauth_consumer_key, oauth_consumer_secret)
        auth.set_access_token(oauth_token, oauth_token_secret)
        self.api = API(auth)
Josh Roesslein's avatar
Josh Roesslein committed
42
43
        self.api.retry_count = 2
        self.api.retry_delay = 5
Josh Roesslein's avatar
Josh Roesslein committed
44

45
46
47
    def testhometimeline(self):
        self.api.home_timeline()

Josh Roesslein's avatar
Josh Roesslein committed
48
    def testusertimeline(self):
49
50
        self.api.user_timeline()
        self.api.user_timeline('twitter')
Josh Roesslein's avatar
Josh Roesslein committed
51

Joshua Roesslein's avatar
Joshua Roesslein committed
52
53
    def testmentionstimeline(self):
        self.api.mentions_timeline()
54
55
56
57
58

    def testretweetsofme(self):
        self.api.retweets_of_me()

    def testretweet(self):
Joshua Roesslein's avatar
Joshua Roesslein committed
59
60
        # TODO(josh): Need a way to get random tweets to retweet.
        raise SkipTest()
61
62

    def testretweets(self):
63
        self.api.retweets(test_tweet_id)
64

Josh Roesslein's avatar
Josh Roesslein committed
65
    def testgetstatus(self):
66
        self.api.get_status(id=test_tweet_id)
Josh Roesslein's avatar
Josh Roesslein committed
67
68
69
70
71
72
73
74
75
76
77
78

    def testupdateanddestroystatus(self):
        # test update
        text = 'testing %i' % random.randint(0, 1000)
        update = self.api.update_status(status=text)
        self.assertEqual(update.text, text)

        # test destroy
        deleted = self.api.destroy_status(id=update.id)
        self.assertEqual(deleted.id, update.id)

    def testgetuser(self):
79
80
81
82
        u = self.api.get_user('twitter')
        self.assertEqual(u.screen_name, 'twitter')

        u = self.api.get_user(783214)
Josh Roesslein's avatar
Josh Roesslein committed
83
84
        self.assertEqual(u.screen_name, 'twitter')

85
86
87
    def testsearchusers(self):
        self.api.search_users('twitter')

88
89
90
    def testsuggestedcategories(self):
        self.api.suggested_categories()

91
92
93
94
95
96
97
98
99
    def testsuggestedusers(self):
        categories = self.api.suggested_categories()
        if len(categories) != 0:
            self.api.suggested_users(categories[0].slug)

    def testsuggesteduserstweets(self):
        categories = self.api.suggested_categories()
        if len(categories) != 0:
            self.api.suggested_users_tweets(categories[0].slug)
100

Josh Roesslein's avatar
Josh Roesslein committed
101
102
103
104
105
    def testme(self):
        me = self.api.me()
        self.assertEqual(me.screen_name, username)

    def testdirectmessages(self):
106
107
108
109
        self.api.direct_messages()

    def testsentdirectmessages(self):
        self.api.sent_direct_messages()
Josh Roesslein's avatar
Josh Roesslein committed
110
111
112

    def testsendanddestroydirectmessage(self):
        # send
Joshua Roesslein's avatar
Joshua Roesslein committed
113
        sent_dm = self.api.send_direct_message(username, text='test message')
Josh Roesslein's avatar
Josh Roesslein committed
114
115
116
117
118
119
120
121
122
123
124
        self.assertEqual(sent_dm.text, 'test message')
        self.assertEqual(sent_dm.sender.screen_name, username)
        self.assertEqual(sent_dm.recipient.screen_name, username)

        # destroy
        destroyed_dm = self.api.destroy_direct_message(sent_dm.id)
        self.assertEqual(destroyed_dm.text, sent_dm.text)
        self.assertEqual(destroyed_dm.id, sent_dm.id)
        self.assertEqual(destroyed_dm.sender.screen_name, username)
        self.assertEqual(destroyed_dm.recipient.screen_name, username)

125
    def testcreatedestroyfriendship(self):
Josh Roesslein's avatar
Josh Roesslein committed
126
127
128
        enemy = self.api.destroy_friendship('twitter')
        self.assertEqual(enemy.screen_name, 'twitter')

129
130
131
132
        # Wait 5 seconds to allow Twitter time
        # to process the friendship destroy request.
        sleep(5)

133
134
135
        friend = self.api.create_friendship('twitter')
        self.assertEqual(friend.screen_name, 'twitter')

Josh Roesslein's avatar
Josh Roesslein committed
136
137
138
139
140
    def testshowfriendship(self):
        source, target = self.api.show_friendship(target_screen_name='twtiter')
        self.assert_(isinstance(source, Friendship))
        self.assert_(isinstance(target, Friendship))

141
142
143
144
145
146
147
    def testfriendsids(self):
        self.api.friends_ids(username)

    def testfollowersids(self):
        self.api.followers_ids(username)

    def testverifycredentials(self):
148
        self.assertNotEqual(self.api.verify_credentials(), False)
149

150
151
152
153
154
155
156
157
        # make sure that `me.status.entities` is not an empty dict
        me = self.api.verify_credentials(include_entities=True)
        self.assertTrue(me.status.entities)

        # `status` shouldn't be included
        me = self.api.verify_credentials(skip_status=True)
        self.assertFalse(hasattr(me, 'status'))

158
159
160
    def testratelimitstatus(self):
        self.api.rate_limit_status()

161
    """ TODO(josh): Remove once this deprecated API is gone.
162
163
164
    def testsetdeliverydevice(self):
        self.api.set_delivery_device('im')
        self.api.set_delivery_device('none')
165
    """
166
167
168

    def testupdateprofilecolors(self):
        original = self.api.me()
Josh Roesslein's avatar
Josh Roesslein committed
169
        updated = self.api.update_profile_colors('000', '000', '000', '000', '000')
170
171
172
173
174
175
176
177
178
179

        # restore colors
        self.api.update_profile_colors(
            original.profile_background_color,
            original.profile_text_color,
            original.profile_link_color,
            original.profile_sidebar_fill_color,
            original.profile_sidebar_border_color
        )

Joshua Roesslein's avatar
Joshua Roesslein committed
180
181
182
183
184
        self.assertEqual(updated.profile_background_color, '000000')
        self.assertEqual(updated.profile_text_color, '000000')
        self.assertEqual(updated.profile_link_color, '000000')
        self.assertEqual(updated.profile_sidebar_fill_color, '000000')
        self.assertEqual(updated.profile_sidebar_border_color, '000000')
185

186
    """
187
188
189
190
191
    def testupateprofileimage(self):
        self.api.update_profile_image('examples/profile.png')

    def testupdateprofilebg(self):
        self.api.update_profile_background_image('examples/bg.png')
192
    """
193
194
195
196
197
198
199
200
201
202
203

    def testupdateprofile(self):
        original = self.api.me()
        profile = {
            'name': 'Tweepy test 123',
            'url': 'http://www.example.com',
            'location': 'pytopia',
            'description': 'just testing things out'
        }
        updated = self.api.update_profile(**profile)
        self.api.update_profile(
204
            name = original.name, url = original.url,
205
206
207
208
            location = original.location, description = original.description
        )

        for k,v in profile.items():
Josh Roesslein's avatar
Josh Roesslein committed
209
            if k == 'email': continue
210
211
212
213
214
215
            self.assertEqual(getattr(updated, k), v)

    def testfavorites(self):
        self.api.favorites()

    def testcreatedestroyfavorite(self):
Josh Roesslein's avatar
Josh Roesslein committed
216
217
        self.api.create_favorite(4901062372)
        self.api.destroy_favorite(4901062372)
218
219
220
221

    def testcreatedestroyblock(self):
        self.api.create_block('twitter')
        self.api.destroy_block('twitter')
Josh Roesslein's avatar
Josh Roesslein committed
222
        self.api.create_friendship('twitter') # restore
223
224
225
226
227
228
229

    def testblocks(self):
        self.api.blocks()

    def testblocksids(self):
        self.api.blocks_ids()

Josh Roesslein's avatar
Josh Roesslein committed
230
    def testcreateupdatedestroylist(self):
231
232
233
234
        params = {
            'owner_screen_name': username,
            'slug': 'tweeps'
        }
Joshua Roesslein's avatar
Joshua Roesslein committed
235
236
        l = self.api.create_list(name=params['slug'], **params)
        l = self.api.update_list(list_id=l.id, description='updated!')
237
        self.assertEqual(l.description, 'updated!')
Joshua Roesslein's avatar
Joshua Roesslein committed
238
        self.api.destroy_list(list_id=l.id)
Josh Roesslein's avatar
Josh Roesslein committed
239

Joshua Roesslein's avatar
Joshua Roesslein committed
240
241
    def testlistsall(self):
        self.api.lists_all()
Josh Roesslein's avatar
Josh Roesslein committed
242
243
244
245
246
247
248
249

    def testlistsmemberships(self):
        self.api.lists_memberships()

    def testlistssubscriptions(self):
        self.api.lists_subscriptions()

    def testlisttimeline(self):
Joshua's avatar
Joshua committed
250
        self.api.list_timeline('applepie', 'stars')
Josh Roesslein's avatar
Josh Roesslein committed
251
252

    def testgetlist(self):
Joshua Roesslein's avatar
Joshua Roesslein committed
253
        self.api.get_list(owner_screen_name='applepie', slug='stars')
Josh Roesslein's avatar
Josh Roesslein committed
254
255

    def testaddremovelistmember(self):
256
257
258
259
260
261
262
263
264
265
266
        params = {
            'slug': 'test',
            'owner_screen_name': username,
            'screen_name': 'twitter'
        }

        def assert_list(l):
            self.assertEqual(l.name, params['slug'])

        assert_list(self.api.add_list_member(**params))
        assert_list(self.api.remove_list_member(**params))
Josh Roesslein's avatar
Josh Roesslein committed
267
268

    def testlistmembers(self):
Joshua's avatar
Joshua committed
269
        self.api.list_members('applepie', 'stars')
Josh Roesslein's avatar
Josh Roesslein committed
270

Joshua Roesslein's avatar
Joshua Roesslein committed
271
272
    def testshowlistmember(self):
        self.assertTrue(self.api.show_list_member(owner_screen_name='applepie', slug='stars', screen_name='NathanFillion'))
Josh Roesslein's avatar
Josh Roesslein committed
273
274

    def testsubscribeunsubscribelist(self):
Joshua Roesslein's avatar
Joshua Roesslein committed
275
276
277
278
279
280
        params = {
            'owner_screen_name': 'applepie',
            'slug': 'stars'
        }
        self.api.subscribe_list(**params)
        self.api.unsubscribe_list(**params)
Josh Roesslein's avatar
Josh Roesslein committed
281
282

    def testlistsubscribers(self):
Joshua's avatar
Joshua committed
283
        self.api.list_subscribers('applepie', 'stars')
Josh Roesslein's avatar
Josh Roesslein committed
284

Joshua Roesslein's avatar
Joshua Roesslein committed
285
286
    def testshowlistsubscriber(self):
        self.assertTrue(self.api.show_list_subscriber('applepie', 'stars', username))
Josh Roesslein's avatar
Josh Roesslein committed
287

288
289
290
    def testsavedsearches(self):
        s = self.api.create_saved_search('test')
        self.api.saved_searches()
Josh Roesslein's avatar
Josh Roesslein committed
291
        self.assertEqual(self.api.get_saved_search(s.id).query, 'test')
292
293
294
        self.api.destroy_saved_search(s.id)

    def testsearch(self):
Josh Roesslein's avatar
Josh Roesslein committed
295
        self.api.search('tweepy')
296

297
    def testgeoapis(self):
298
299
300
301
302
303
304
305
306
307
308
        def place_name_in_list(place_name, place_list):
            """Return True if a given place_name is in place_list."""
            return any([x.full_name.lower() == place_name.lower() for x in place_list])

        twitter_hq = self.api.geo_similar_places(lat=37, long= -122, name='Twitter HQ')
        # Assumes that twitter_hq is first Place returned...
        self.assertEqual(twitter_hq[0].id, '3bdf30ed8b201f31')
        # Test various API functions using Austin, TX, USA
        self.assertEqual(self.api.geo_id(id='c3f37afa9efcf94b').full_name, 'Austin, TX')
        self.assertTrue(place_name_in_list('Austin, TX',
            self.api.reverse_geocode(lat=30.267370168467806, long= -97.74261474609375))) # Austin, TX, USA
309

Josh Roesslein's avatar
Josh Roesslein committed
310
311
312
class TweepyCursorTests(unittest.TestCase):

    def setUp(self):
313
314
315
        auth = OAuthHandler(oauth_consumer_key, oauth_consumer_secret)
        auth.set_access_token(oauth_token, oauth_token_secret)
        self.api = API(auth)
Josh Roesslein's avatar
Josh Roesslein committed
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
        self.api.retry_count = 2
        self.api.retry_delay = 5

    def testpagecursoritems(self):
        items = list(Cursor(self.api.user_timeline).items())
        self.assert_(len(items) > 0)

        items = list(Cursor(self.api.user_timeline, 'twitter').items(30))
        self.assert_(len(items) == 30)

    def testpagecursorpages(self):
        pages = list(Cursor(self.api.user_timeline).pages())
        self.assert_(len(pages) > 0)

        pages = list(Cursor(self.api.user_timeline, 'twitter').pages(5))
        self.assert_(len(pages) == 5)

    def testcursorcursoritems(self):
Joshua Roesslein's avatar
Joshua Roesslein committed
334
        items = list(Cursor(self.api.friends_ids).items())
Josh Roesslein's avatar
Josh Roesslein committed
335
336
        self.assert_(len(items) > 0)

Joshua Roesslein's avatar
Joshua Roesslein committed
337
        items = list(Cursor(self.api.followers_ids, 'twitter').items(30))
Josh Roesslein's avatar
Josh Roesslein committed
338
339
340
        self.assert_(len(items) == 30)

    def testcursorcursorpages(self):
Joshua Roesslein's avatar
Joshua Roesslein committed
341
        pages = list(Cursor(self.api.friends_ids).pages())
Josh Roesslein's avatar
Josh Roesslein committed
342
343
        self.assert_(len(pages) > 0)

Joshua Roesslein's avatar
Joshua Roesslein committed
344
        pages = list(Cursor(self.api.followers_ids, 'twitter').pages(5))
Josh Roesslein's avatar
Josh Roesslein committed
345
        self.assert_(len(pages) == 5)
Josh Roesslein's avatar
Josh Roesslein committed
346

Josh Roesslein's avatar
Josh Roesslein committed
347
348
class TweepyAuthTests(unittest.TestCase):

Josh Roesslein's avatar
Josh Roesslein committed
349
    def testoauth(self):
350
        auth = OAuthHandler(oauth_consumer_key, oauth_consumer_secret)
Josh Roesslein's avatar
Josh Roesslein committed
351

Josh Roesslein's avatar
Josh Roesslein committed
352
353
354
355
356
357
358
        # test getting access token
        auth_url = auth.get_authorization_url()
        print 'Please authorize: ' + auth_url
        verifier = raw_input('PIN: ').strip()
        self.assert_(len(verifier) > 0)
        access_token = auth.get_access_token(verifier)
        self.assert_(access_token is not None)
Josh Roesslein's avatar
Josh Roesslein committed
359

Josh Roesslein's avatar
Josh Roesslein committed
360
361
        # build api object test using oauth
        api = API(auth)
Josh Roesslein's avatar
Josh Roesslein committed
362
363
        s = api.update_status('test %i' % random.randint(0, 1000))
        api.destroy_status(s.id)
Josh Roesslein's avatar
Josh Roesslein committed
364

365
366
367

class TweepyCacheTests(unittest.TestCase):

Josh Roesslein's avatar
Josh Roesslein committed
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
    timeout = 2.0
    memcache_servers = ['127.0.0.1:11211']  # must be running for test to pass

    def _run_tests(self, do_cleanup=True):
        # test store and get
        self.cache.store('testkey', 'testvalue')
        self.assertEqual(self.cache.get('testkey'), 'testvalue',
            'Stored value does not match retrieved value')

        # test timeout
        sleep(self.timeout)
        self.assertEqual(self.cache.get('testkey'), None,
            'Cache entry should have expired')

        # test cleanup
        if do_cleanup:
            self.cache.store('testkey', 'testvalue')
            sleep(self.timeout)
            self.cache.cleanup()
            self.assertEqual(self.cache.count(), 0, 'Cache cleanup failed')

        # test count
        for i in range(0, 20):
            self.cache.store('testkey%i' % i, 'testvalue')
        self.assertEqual(self.cache.count(), 20, 'Count is wrong')

        # test flush
        self.cache.flush()
        self.assertEqual(self.cache.count(), 0, 'Cache failed to flush')

    def testmemorycache(self):
        self.cache = MemoryCache(timeout=self.timeout)
        self._run_tests()

    def testfilecache(self):
        os.mkdir('cache_test_dir')
        self.cache = FileCache('cache_test_dir', self.timeout)
        self._run_tests()
        self.cache.flush()
        os.rmdir('cache_test_dir')
408

409
if __name__ == '__main__':
Josh Roesslein's avatar
Josh Roesslein committed
410
    unittest.main()