xitiomet is sharing code with you

Bitbucket is a code hosting site. Unlimited public and private repositories. Free for small teams.

Don't show this again

xitiomet / python-twitter (fork of saiyr / python-twitter)

Mostly the same, but i added support for Mentions http://apiwiki.twitter.com/Twitter-REST-API-Met...

Clone this repository (size: 393.3 KB): HTTPS / SSH
hg clone https://bitbucket.org/xitiomet/python-twitter
hg clone ssh://hg@bitbucket.org/xitiomet/python-twitter

python-twitter / twitter_test.py

commit
82aae45f64f2
parent
a58f4a7ad991
branch
default

Added GetMentions to twitter.py

1
fc159c49c080
#!/usr/bin/python2.4
2
c42880b017af
# -*- coding: utf-8 -*-#
3
4805aee792f0
#
4
4805aee792f0
# Copyright 2007 Google Inc. All Rights Reserved.
5
fceb5d2374d2
#
6
fceb5d2374d2
# Licensed under the Apache License, Version 2.0 (the "License");
7
fceb5d2374d2
# you may not use this file except in compliance with the License.
8
fceb5d2374d2
# You may obtain a copy of the License at
9
fceb5d2374d2
#
10
fceb5d2374d2
#     http://www.apache.org/licenses/LICENSE-2.0
11
fceb5d2374d2
#
12
fceb5d2374d2
# Unless required by applicable law or agreed to in writing, software
13
fceb5d2374d2
# distributed under the License is distributed on an "AS IS" BASIS,
14
fceb5d2374d2
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
fceb5d2374d2
# See the License for the specific language governing permissions and
16
fceb5d2374d2
# limitations under the License.
17
4805aee792f0
18
4805aee792f0
'''Unit tests for the twitter.py library'''
19
4805aee792f0
20
4805aee792f0
__author__ = 'dewitt@google.com'
21
4805aee792f0
22
4805aee792f0
import os
23
4805aee792f0
import simplejson
24
4805aee792f0
import time
25
c68ef9d563c3
import calendar
26
4805aee792f0
import unittest
27
4805aee792f0
28
4805aee792f0
import twitter
29
4805aee792f0
30
4805aee792f0
class StatusTest(unittest.TestCase):
31
4805aee792f0
32
07b822ba13ca
  SAMPLE_JSON = '''{"created_at": "Fri Jan 26 23:17:14 +0000 2007", "id": 4391023, "text": "A l\u00e9gp\u00e1rn\u00e1s haj\u00f3m tele van angoln\u00e1kkal.", "user": {"description": "Canvas. JC Penny. Three ninety-eight.", "id": 718443, "location": "Okinawa, Japan", "name": "Kesuke Miyagi", "profile_image_url": "http://twitter.com/system/user/profile_image/718443/normal/kesuke.png", "screen_name": "kesuke", "url": "http://twitter.com/kesuke"}}'''
33
4805aee792f0
34
4805aee792f0
  def _GetSampleUser(self):
35
4805aee792f0
    return twitter.User(id=718443,
36
4805aee792f0
                        name='Kesuke Miyagi',
37
4805aee792f0
                        screen_name='kesuke',
38
4805aee792f0
                        description=u'Canvas. JC Penny. Three ninety-eight.',
39
4805aee792f0
                        location='Okinawa, Japan',
40
4805aee792f0
                        url='http://twitter.com/kesuke',
41
4805aee792f0
                        profile_image_url='http://twitter.com/system/user/pro'
42
4805aee792f0
                                          'file_image/718443/normal/kesuke.pn'
43
4805aee792f0
                                          'g')
44
4805aee792f0
45
4805aee792f0
  def _GetSampleStatus(self):
46
4805aee792f0
    return twitter.Status(created_at='Fri Jan 26 23:17:14 +0000 2007',
47
4805aee792f0
                          id=4391023,
48
dbe3b23bfd08
                          text=u'A légpárnás hajóm tele van angolnákkal.',
49
4805aee792f0
                          user=self._GetSampleUser())
50
17f566981b41
51
4805aee792f0
  def testInit(self):
52
4805aee792f0
    '''Test the twitter.Status constructor'''
53
4805aee792f0
    status = twitter.Status(created_at='Fri Jan 26 23:17:14 +0000 2007',
54
4805aee792f0
                            id=4391023,
55
dbe3b23bfd08
                            text=u'A légpárnás hajóm tele van angolnákkal.',
56
4805aee792f0
                            user=self._GetSampleUser())
57
4805aee792f0
58
4805aee792f0
  def testGettersAndSetters(self):
59
4805aee792f0
    '''Test all of the twitter.Status getters and setters'''
60
4805aee792f0
    status = twitter.Status()
61
4805aee792f0
    status.SetId(4391023)
62
4805aee792f0
    self.assertEqual(4391023, status.GetId())
63
c68ef9d563c3
    created_at = calendar.timegm((2007, 1, 26, 23, 17, 14, -1, -1, -1))
64
4805aee792f0
    status.SetCreatedAt('Fri Jan 26 23:17:14 +0000 2007')
65
4805aee792f0
    self.assertEqual('Fri Jan 26 23:17:14 +0000 2007', status.GetCreatedAt())
66
589da64c5e64
    self.assertEqual(created_at, status.GetCreatedAtInSeconds())
67
589da64c5e64
    status.SetNow(created_at + 10)
68
3c401eb136ea
    self.assertEqual("about 10 seconds ago", status.GetRelativeCreatedAt())
69
dbe3b23bfd08
    status.SetText(u'A légpárnás hajóm tele van angolnákkal.')
70
dbe3b23bfd08
    self.assertEqual(u'A légpárnás hajóm tele van angolnákkal.',
71
4805aee792f0
                     status.GetText())
72
4805aee792f0
    status.SetUser(self._GetSampleUser())
73
4805aee792f0
    self.assertEqual(718443, status.GetUser().id)
74
4805aee792f0
75
4805aee792f0
  def testProperties(self):
76
4805aee792f0
    '''Test all of the twitter.Status properties'''
77
4805aee792f0
    status = twitter.Status()
78
4805aee792f0
    status.id = 1
79
4805aee792f0
    self.assertEqual(1, status.id)
80
c68ef9d563c3
    created_at = calendar.timegm((2007, 1, 26, 23, 17, 14, -1, -1, -1))
81
4805aee792f0
    status.created_at = 'Fri Jan 26 23:17:14 +0000 2007'
82
4805aee792f0
    self.assertEqual('Fri Jan 26 23:17:14 +0000 2007', status.created_at)
83
589da64c5e64
    self.assertEqual(created_at, status.created_at_in_seconds)
84
589da64c5e64
    status.now = created_at + 10
85
3c401eb136ea
    self.assertEqual('about 10 seconds ago', status.relative_created_at)
86
4805aee792f0
    status.user = self._GetSampleUser()
87
4805aee792f0
    self.assertEqual(718443, status.user.id)
88
4805aee792f0
89
3c401eb136ea
  def _ParseDate(self, string):
90
c68ef9d563c3
    return calendar.timegm(time.strptime(string, '%b %d %H:%M:%S %Y'))
91
3c401eb136ea
92
3c401eb136ea
  def testRelativeCreatedAt(self):
93
8218c3572da9
    '''Test various permutations of Status relative_created_at'''
94
3c401eb136ea
    status = twitter.Status(created_at='Fri Jan 01 12:00:00 +0000 2007')
95
3c401eb136ea
    status.now = self._ParseDate('Jan 01 12:00:00 2007')
96
3c401eb136ea
    self.assertEqual('about a second ago', status.relative_created_at)
97
3c401eb136ea
    status.now = self._ParseDate('Jan 01 12:00:01 2007')
98
3c401eb136ea
    self.assertEqual('about a second ago', status.relative_created_at)
99
3c401eb136ea
    status.now = self._ParseDate('Jan 01 12:00:02 2007')
100
3c401eb136ea
    self.assertEqual('about 2 seconds ago', status.relative_created_at)
101
3c401eb136ea
    status.now = self._ParseDate('Jan 01 12:00:05 2007')
102
3c401eb136ea
    self.assertEqual('about 5 seconds ago', status.relative_created_at)
103
3c401eb136ea
    status.now = self._ParseDate('Jan 01 12:00:50 2007')
104
3c401eb136ea
    self.assertEqual('about a minute ago', status.relative_created_at)
105
3c401eb136ea
    status.now = self._ParseDate('Jan 01 12:01:00 2007')
106
3c401eb136ea
    self.assertEqual('about a minute ago', status.relative_created_at)
107
3c401eb136ea
    status.now = self._ParseDate('Jan 01 12:01:10 2007')
108
3c401eb136ea
    self.assertEqual('about a minute ago', status.relative_created_at)
109
3c401eb136ea
    status.now = self._ParseDate('Jan 01 12:02:00 2007')
110
3c401eb136ea
    self.assertEqual('about 2 minutes ago', status.relative_created_at)
111
3c401eb136ea
    status.now = self._ParseDate('Jan 01 12:31:50 2007')
112
3c401eb136ea
    self.assertEqual('about 31 minutes ago', status.relative_created_at)
113
3c401eb136ea
    status.now = self._ParseDate('Jan 01 12:50:00 2007')
114
3c401eb136ea
    self.assertEqual('about an hour ago', status.relative_created_at)
115
3c401eb136ea
    status.now = self._ParseDate('Jan 01 13:00:00 2007')
116
3c401eb136ea
    self.assertEqual('about an hour ago', status.relative_created_at)
117
3c401eb136ea
    status.now = self._ParseDate('Jan 01 13:10:00 2007')
118
3c401eb136ea
    self.assertEqual('about an hour ago', status.relative_created_at)
119
3c401eb136ea
    status.now = self._ParseDate('Jan 01 14:00:00 2007')
120
3c401eb136ea
    self.assertEqual('about 2 hours ago', status.relative_created_at)
121
3c401eb136ea
    status.now = self._ParseDate('Jan 01 19:00:00 2007')
122
3c401eb136ea
    self.assertEqual('about 7 hours ago', status.relative_created_at)
123
3c401eb136ea
    status.now = self._ParseDate('Jan 02 11:30:00 2007')
124
3c401eb136ea
    self.assertEqual('about a day ago', status.relative_created_at)
125
3c401eb136ea
    status.now = self._ParseDate('Jan 04 12:00:00 2007')
126
3c401eb136ea
    self.assertEqual('about 3 days ago', status.relative_created_at)
127
3c401eb136ea
    status.now = self._ParseDate('Feb 04 12:00:00 2007')
128
3c401eb136ea
    self.assertEqual('about 34 days ago', status.relative_created_at)
129
dbe3b23bfd08
130
4805aee792f0
  def testAsJsonString(self):
131
4805aee792f0
    '''Test the twitter.Status AsJsonString method'''
132
4805aee792f0
    self.assertEqual(StatusTest.SAMPLE_JSON,
133
4805aee792f0
                     self._GetSampleStatus().AsJsonString())
134
4805aee792f0
135
4805aee792f0
  def testAsDict(self):
136
4805aee792f0
    '''Test the twitter.Status AsDict method'''
137
4805aee792f0
    status = self._GetSampleStatus()
138
4805aee792f0
    data = status.AsDict()
139
4805aee792f0
    self.assertEqual(4391023, data['id'])
140
17f566981b41
    self.assertEqual('Fri Jan 26 23:17:14 +0000 2007', data['created_at'])
141
dbe3b23bfd08
    self.assertEqual(u'A légpárnás hajóm tele van angolnákkal.', data['text'])
142
4805aee792f0
    self.assertEqual(718443, data['user']['id'])
143
4805aee792f0
144
4805aee792f0
  def testEq(self):
145
4805aee792f0
    '''Test the twitter.Status __eq__ method'''
146
4805aee792f0
    status = twitter.Status()
147
4805aee792f0
    status.created_at = 'Fri Jan 26 23:17:14 +0000 2007'
148
4805aee792f0
    status.id = 4391023
149
dbe3b23bfd08
    status.text = u'A légpárnás hajóm tele van angolnákkal.'
150
4805aee792f0
    status.user = self._GetSampleUser()
151
4805aee792f0
    self.assertEqual(status, self._GetSampleStatus())
152
17f566981b41
153
4805aee792f0
  def testNewFromJsonDict(self):
154
4805aee792f0
    '''Test the twitter.Status NewFromJsonDict method'''
155
4805aee792f0
    data = simplejson.loads(StatusTest.SAMPLE_JSON)
156
4805aee792f0
    status = twitter.Status.NewFromJsonDict(data)
157
4805aee792f0
    self.assertEqual(self._GetSampleStatus(), status)
158
4805aee792f0
159
4805aee792f0
class UserTest(unittest.TestCase):
160
4805aee792f0
161
07b822ba13ca
  SAMPLE_JSON = '''{"description": "Indeterminate things", "id": 673483, "location": "San Francisco, CA", "name": "DeWitt", "profile_image_url": "http://twitter.com/system/user/profile_image/673483/normal/me.jpg", "screen_name": "dewitt", "status": {"created_at": "Fri Jan 26 17:28:19 +0000 2007", "id": 4212713, "text": "\\"Select all\\" and archive your Gmail inbox.  The page loads so much faster!"}, "url": "http://unto.net/"}'''
162
4805aee792f0
163
4805aee792f0
  def _GetSampleStatus(self):
164
4805aee792f0
    return twitter.Status(created_at='Fri Jan 26 17:28:19 +0000 2007',
165
4805aee792f0
                          id=4212713,
166
4805aee792f0
                          text='"Select all" and archive your Gmail inbox. '
167
17f566981b41
                               ' The page loads so much faster!')
168
4805aee792f0
169
4805aee792f0
  def _GetSampleUser(self):
170
4805aee792f0
    return twitter.User(id=673483,
171
4805aee792f0
                        name='DeWitt',
172
4805aee792f0
                        screen_name='dewitt',
173
4805aee792f0
                        description=u'Indeterminate things',
174
4805aee792f0
                        location='San Francisco, CA',
175
4805aee792f0
                        url='http://unto.net/',
176
4805aee792f0
                        profile_image_url='http://twitter.com/system/user/prof'
177
4805aee792f0
                                          'ile_image/673483/normal/me.jpg',
178
4805aee792f0
                        status=self._GetSampleStatus())
179
4805aee792f0
180
4805aee792f0
181
17f566981b41
182
4805aee792f0
  def testInit(self):
183
4805aee792f0
    '''Test the twitter.User constructor'''
184
4805aee792f0
    user = twitter.User(id=673483,
185
4805aee792f0
                        name='DeWitt',
186
4805aee792f0
                        screen_name='dewitt',
187
4805aee792f0
                        description=u'Indeterminate things',
188
4805aee792f0
                        url='http://twitter.com/dewitt',
189
4805aee792f0
                        profile_image_url='http://twitter.com/system/user/prof'
190
4805aee792f0
                                          'ile_image/673483/normal/me.jpg',
191
4805aee792f0
                        status=self._GetSampleStatus())
192
4805aee792f0
193
4805aee792f0
  def testGettersAndSetters(self):
194
4805aee792f0
    '''Test all of the twitter.User getters and setters'''
195
4805aee792f0
    user = twitter.User()
196
4805aee792f0
    user.SetId(673483)
197
4805aee792f0
    self.assertEqual(673483, user.GetId())
198
4805aee792f0
    user.SetName('DeWitt')
199
4805aee792f0
    self.assertEqual('DeWitt', user.GetName())
200
4805aee792f0
    user.SetScreenName('dewitt')
201
4805aee792f0
    self.assertEqual('dewitt', user.GetScreenName())
202
4805aee792f0
    user.SetDescription('Indeterminate things')
203
4805aee792f0
    self.assertEqual('Indeterminate things', user.GetDescription())
204
4805aee792f0
    user.SetLocation('San Francisco, CA')
205
4805aee792f0
    self.assertEqual('San Francisco, CA', user.GetLocation())
206
4805aee792f0
    user.SetProfileImageUrl('http://twitter.com/system/user/profile_im'
207
4805aee792f0
                            'age/673483/normal/me.jpg')
208
4805aee792f0
    self.assertEqual('http://twitter.com/system/user/profile_image/673'
209
4805aee792f0
                     '483/normal/me.jpg', user.GetProfileImageUrl())
210
4805aee792f0
    user.SetStatus(self._GetSampleStatus())
211
4805aee792f0
    self.assertEqual(4212713, user.GetStatus().id)
212
4805aee792f0
213
4805aee792f0
  def testProperties(self):
214
4805aee792f0
    '''Test all of the twitter.User properties'''
215
4805aee792f0
    user = twitter.User()
216
4805aee792f0
    user.id = 673483
217
4805aee792f0
    self.assertEqual(673483, user.id)
218
4805aee792f0
    user.name = 'DeWitt'
219
4805aee792f0
    self.assertEqual('DeWitt', user.name)
220
4805aee792f0
    user.screen_name = 'dewitt'
221
4805aee792f0
    self.assertEqual('dewitt', user.screen_name)
222
4805aee792f0
    user.description = 'Indeterminate things'
223
4805aee792f0
    self.assertEqual('Indeterminate things', user.description)
224
4805aee792f0
    user.location = 'San Francisco, CA'
225
4805aee792f0
    self.assertEqual('San Francisco, CA', user.location)
226
4805aee792f0
    user.profile_image_url = 'http://twitter.com/system/user/profile_i' \
227
4805aee792f0
                             'mage/673483/normal/me.jpg'
228
4805aee792f0
    self.assertEqual('http://twitter.com/system/user/profile_image/6734'
229
4805aee792f0
                     '83/normal/me.jpg', user.profile_image_url)
230
4805aee792f0
    self.status = self._GetSampleStatus()
231
4805aee792f0
    self.assertEqual(4212713, self.status.id)
232
4805aee792f0
233
4805aee792f0
  def testAsJsonString(self):
234
4805aee792f0
    '''Test the twitter.User AsJsonString method'''
235
4805aee792f0
    self.assertEqual(UserTest.SAMPLE_JSON,
236
4805aee792f0
                     self._GetSampleUser().AsJsonString())
237
4805aee792f0
238
4805aee792f0
  def testAsDict(self):
239
4805aee792f0
    '''Test the twitter.User AsDict method'''
240
4805aee792f0
    user = self._GetSampleUser()
241
4805aee792f0
    data = user.AsDict()
242
4805aee792f0
    self.assertEqual(673483, data['id'])
243
4805aee792f0
    self.assertEqual('DeWitt', data['name'])
244
4805aee792f0
    self.assertEqual('dewitt', data['screen_name'])
245
4805aee792f0
    self.assertEqual('Indeterminate things', data['description'])
246
4805aee792f0
    self.assertEqual('San Francisco, CA', data['location'])
247
4805aee792f0
    self.assertEqual('http://twitter.com/system/user/profile_image/6734'
248
4805aee792f0
                     '83/normal/me.jpg', data['profile_image_url'])
249
4805aee792f0
    self.assertEqual('http://unto.net/', data['url'])
250
4805aee792f0
    self.assertEqual(4212713, data['status']['id'])
251
4805aee792f0
252
4805aee792f0
  def testEq(self):
253
4805aee792f0
    '''Test the twitter.User __eq__ method'''
254
4805aee792f0
    user = twitter.User()
255
4805aee792f0
    user.id = 673483
256
4805aee792f0
    user.name = 'DeWitt'
257
4805aee792f0
    user.screen_name = 'dewitt'
258
4805aee792f0
    user.description = 'Indeterminate things'
259
4805aee792f0
    user.location = 'San Francisco, CA'
260
4805aee792f0
    user.profile_image_url = 'http://twitter.com/system/user/profile_image/67' \
261
4805aee792f0
                             '3483/normal/me.jpg'
262
4805aee792f0
    user.url = 'http://unto.net/'
263
4805aee792f0
    user.status = self._GetSampleStatus()
264
4805aee792f0
    self.assertEqual(user, self._GetSampleUser())
265
17f566981b41
266
4805aee792f0
  def testNewFromJsonDict(self):
267
4805aee792f0
    '''Test the twitter.User NewFromJsonDict method'''
268
4805aee792f0
    data = simplejson.loads(UserTest.SAMPLE_JSON)
269
4805aee792f0
    user = twitter.User.NewFromJsonDict(data)
270
4805aee792f0
    self.assertEqual(self._GetSampleUser(), user)
271
17f566981b41
272
17f566981b41
273
4805aee792f0
class FileCacheTest(unittest.TestCase):
274
4805aee792f0
275
4805aee792f0
  def testInit(self):
276
4805aee792f0
    """Test the twitter._FileCache constructor"""
277
4805aee792f0
    cache = twitter._FileCache()
278
4805aee792f0
    self.assert_(cache is not None, 'cache is None')
279
4805aee792f0
280
4805aee792f0
  def testSet(self):
281
4805aee792f0
    """Test the twitter._FileCache.Set method"""
282
4805aee792f0
    cache = twitter._FileCache()
283
4805aee792f0
    cache.Set("foo",'Hello World!')
284
4805aee792f0
    cache.Remove("foo")
285
4805aee792f0
286
4805aee792f0
  def testRemove(self):
287
4805aee792f0
    """Test the twitter._FileCache.Remove method"""
288
4805aee792f0
    cache = twitter._FileCache()
289
4805aee792f0
    cache.Set("foo",'Hello World!')
290
4805aee792f0
    cache.Remove("foo")
291
4805aee792f0
    data = cache.Get("foo")
292
4805aee792f0
    self.assertEqual(data, None, 'data is not None')
293
4805aee792f0
294
4805aee792f0
  def testGet(self):
295
4805aee792f0
    """Test the twitter._FileCache.Get method"""
296
4805aee792f0
    cache = twitter._FileCache()
297
4805aee792f0
    cache.Set("foo",'Hello World!')
298
4805aee792f0
    data = cache.Get("foo")
299
4805aee792f0
    self.assertEqual('Hello World!', data)
300
4805aee792f0
    cache.Remove("foo")
301
4805aee792f0
302
4805aee792f0
  def testGetCachedTime(self):
303
4805aee792f0
    """Test the twitter._FileCache.GetCachedTime method"""
304
4805aee792f0
    now = time.time()
305
4805aee792f0
    cache = twitter._FileCache()
306
4805aee792f0
    cache.Set("foo",'Hello World!')
307
4805aee792f0
    cached_time = cache.GetCachedTime("foo")
308
4805aee792f0
    delta = cached_time - now
309
4805aee792f0
    self.assert_(delta <= 1,
310
4805aee792f0
                 'Cached time differs from clock time by more than 1 second.')
311
4805aee792f0
    cache.Remove("foo")
312
4805aee792f0
313
4805aee792f0
class ApiTest(unittest.TestCase):
314
ee84714ea665
315
4805aee792f0
  def setUp(self):
316
4805aee792f0
    self._urllib = MockUrllib()
317
ee84714ea665
    api = twitter.Api(username='test', password='test')
318
4805aee792f0
    api.SetCache(NullCache())
319
4805aee792f0
    api.SetUrllib(self._urllib)
320
4805aee792f0
    self._api = api
321
4805aee792f0
322
265fcf2a1e01
  def testTwitterError(self):
323
265fcf2a1e01
    '''Test that twitter responses containing an error message are wrapped.'''
324
265fcf2a1e01
    self._AddHandler('http://twitter.com/statuses/public_timeline.json',
325
265fcf2a1e01
                     curry(self._OpenTestData, 'public_timeline_error.json'))
326
265fcf2a1e01
    # Manually try/catch so we can check the exception's value
327
265fcf2a1e01
    try:
328
265fcf2a1e01
      statuses = self._api.GetPublicTimeline()
329
265fcf2a1e01
    except twitter.TwitterError, error:
330
265fcf2a1e01
      # If the error message matches, the test passes
331
265fcf2a1e01
      self.assertEqual('test error', error.message)
332
265fcf2a1e01
    else:
333
265fcf2a1e01
      self.fail('TwitterError expected')
334
265fcf2a1e01
335
4805aee792f0
  def testGetPublicTimeline(self):
336
4805aee792f0
    '''Test the twitter.Api GetPublicTimeline method'''
337
ee84714ea665
    self._AddHandler('http://twitter.com/statuses/public_timeline.json?since_id=12345',
338
4805aee792f0
                     curry(self._OpenTestData, 'public_timeline.json'))
339
ee84714ea665
    statuses = self._api.GetPublicTimeline(since_id=12345)
340
4805aee792f0
    # This is rather arbitrary, but spot checking is better than nothing
341
ee84714ea665
    self.assertEqual(20, len(statuses))
342
ee84714ea665
    self.assertEqual(89497702, statuses[0].id)
343
4805aee792f0
344
4805aee792f0
  def testGetUserTimeline(self):
345
4805aee792f0
    '''Test the twitter.Api GetUserTimeline method'''
346
ee84714ea665
    self._AddHandler('http://twitter.com/statuses/user_timeline/kesuke.json?count=1&since=Tue%2C+27+Mar+2007+22%3A55%3A48+GMT',
347
ee84714ea665
                     curry(self._OpenTestData, 'user_timeline-kesuke.json'))
348
ee84714ea665
    statuses = self._api.GetUserTimeline('kesuke', count=1, since='Tue, 27 Mar 2007 22:55:48 GMT')
349
4805aee792f0
    # This is rather arbitrary, but spot checking is better than nothing
350
ee84714ea665
    self.assertEqual(89512102, statuses[0].id)
351
ee84714ea665
    self.assertEqual(718443, statuses[0].user.id)
352
4805aee792f0
353
4805aee792f0
  def testGetFriendsTimeline(self):
354
4805aee792f0
    '''Test the twitter.Api GetFriendsTimeline method'''
355
ee84714ea665
    self._AddHandler('http://twitter.com/statuses/friends_timeline/kesuke.json',
356
ee84714ea665
                     curry(self._OpenTestData, 'friends_timeline-kesuke.json'))
357
ee84714ea665
    statuses = self._api.GetFriendsTimeline('kesuke')
358
4805aee792f0
    # This is rather arbitrary, but spot checking is better than nothing
359
ee84714ea665
    self.assertEqual(20, len(statuses))
360
ee84714ea665
    self.assertEqual(718443, statuses[0].user.id)
361
ee84714ea665
362
ee84714ea665
  def testGetStatus(self):
363
ee84714ea665
    '''Test the twitter.Api GetStatus method'''
364
ee84714ea665
    self._AddHandler('http://twitter.com/statuses/show/89512102.json',
365
ee84714ea665
                     curry(self._OpenTestData, 'show-89512102.json'))
366
ee84714ea665
    status = self._api.GetStatus(89512102)
367
ee84714ea665
    self.assertEqual(89512102, status.id)
368
ee84714ea665
    self.assertEqual(718443, status.user.id)
369
32a0266e88a8
370
4da5ec4d173a
  def testDestroyStatus(self):
371
4da5ec4d173a
    '''Test the twitter.Api DestroyStatus method'''
372
4da5ec4d173a
    self._AddHandler('http://twitter.com/statuses/destroy/103208352.json',
373
4da5ec4d173a
                     curry(self._OpenTestData, 'status-destroy.json'))
374
4da5ec4d173a
    status = self._api.DestroyStatus(103208352)
375
4da5ec4d173a
    self.assertEqual(103208352, status.id)
376
4da5ec4d173a
377
ee84714ea665
  def testPostUpdate(self):
378
ee84714ea665
    '''Test the twitter.Api PostUpdate method'''
379
ee84714ea665
    self._AddHandler('http://twitter.com/statuses/update.json',
380
ee84714ea665
                     curry(self._OpenTestData, 'update.json'))
381
ee84714ea665
    status = self._api.PostUpdate(u'Моё судно на воздушной подушке полно угрей')
382
ee84714ea665
    # This is rather arbitrary, but spot checking is better than nothing
383
ee84714ea665
    self.assertEqual(u'Моё судно на воздушной подушке полно угрей', status.text)
384
ee84714ea665
385
ee84714ea665
  def testGetReplies(self):
386
ee84714ea665
    '''Test the twitter.Api GetReplies method'''
387
8202aa019ee2
    self._AddHandler('http://twitter.com/statuses/replies.json?page=1',
388
ee84714ea665
                     curry(self._OpenTestData, 'replies.json'))
389
8202aa019ee2
    statuses = self._api.GetReplies(page=1)
390
ee84714ea665
    self.assertEqual(36657062, statuses[0].id)
391
4805aee792f0
392
4805aee792f0
  def testGetFriends(self):
393
4805aee792f0
    '''Test the twitter.Api GetFriends method'''
394
8202aa019ee2
    self._AddHandler('http://twitter.com/statuses/friends.json?page=1',
395
4805aee792f0
                     curry(self._OpenTestData, 'friends.json'))
396
8202aa019ee2
    users = self._api.GetFriends(page=1)
397
ee84714ea665
    buzz = [u.status for u in users if u.screen_name == 'buzz']
398
ee84714ea665
    self.assertEqual(89543882, buzz[0].id)
399
4805aee792f0
400
4805aee792f0
  def testGetFollowers(self):
401
4805aee792f0
    '''Test the twitter.Api GetFollowers method'''
402
8202aa019ee2
    self._AddHandler('http://twitter.com/statuses/followers.json?page=1',
403
4805aee792f0
                     curry(self._OpenTestData, 'followers.json'))
404
8202aa019ee2
    users = self._api.GetFollowers(page=1)
405
4805aee792f0
    # This is rather arbitrary, but spot checking is better than nothing
406
ee84714ea665
    alexkingorg = [u.status for u in users if u.screen_name == 'alexkingorg']
407
ee84714ea665
    self.assertEqual(89554432, alexkingorg[0].id)
408
4805aee792f0
409
e3638dafb13c
  def testGetFeatured(self):
410
e3638dafb13c
    '''Test the twitter.Api GetFeatured method'''
411
e3638dafb13c
    self._AddHandler('http://twitter.com/statuses/featured.json',
412
e3638dafb13c
                     curry(self._OpenTestData, 'featured.json'))
413
e3638dafb13c
    users = self._api.GetFeatured()
414
e3638dafb13c
    # This is rather arbitrary, but spot checking is better than nothing
415
e3638dafb13c
    stevenwright = [u.status for u in users if u.screen_name == 'stevenwright']
416
e3638dafb13c
    self.assertEqual(86991742, stevenwright[0].id)
417
90377483d9fa
418
90377483d9fa
  def testGetDirectMessages(self):
419
90377483d9fa
    '''Test the twitter.Api GetDirectMessages method'''
420
8202aa019ee2
    self._AddHandler('http://twitter.com/direct_messages.json?page=1',
421
90377483d9fa
                     curry(self._OpenTestData, 'direct_messages.json'))
422
8202aa019ee2
    statuses = self._api.GetDirectMessages(page=1)
423
90377483d9fa
    self.assertEqual(u'A légpárnás hajóm tele van angolnákkal.', statuses[0].text)
424
c42880b017af
425
c42880b017af
  def testPostDirectMessage(self):
426
c42880b017af
    '''Test the twitter.Api PostDirectMessage method'''
427
c42880b017af
    self._AddHandler('http://twitter.com/direct_messages/new.json',
428
c42880b017af
                     curry(self._OpenTestData, 'direct_messages-new.json'))
429
c42880b017af
    status = self._api.PostDirectMessage('test', u'Моё судно на воздушной подушке полно угрей')
430
c42880b017af
    # This is rather arbitrary, but spot checking is better than nothing
431
c42880b017af
    self.assertEqual(u'Моё судно на воздушной подушке полно угрей', status.text)
432
32a0266e88a8
433
32a0266e88a8
  def testDestroyDirectMessage(self):
434
32a0266e88a8
    '''Test the twitter.Api DestroyDirectMessage method'''
435
32a0266e88a8
    self._AddHandler('http://twitter.com/direct_messages/destroy/3496342.json',
436
32a0266e88a8
                     curry(self._OpenTestData, 'direct_message-destroy.json'))
437
32a0266e88a8
    status = self._api.DestroyDirectMessage(3496342)
438
32a0266e88a8
    # This is rather arbitrary, but spot checking is better than nothing
439
32a0266e88a8
    self.assertEqual(673483, status.sender_id)
440
32a0266e88a8
441
79429eb1b54d
  def testCreateFriendship(self):
442
79429eb1b54d
    '''Test the twitter.Api CreateFriendship method'''
443
79429eb1b54d
    self._AddHandler('http://twitter.com/friendships/create/dewitt.json',
444
79429eb1b54d
                     curry(self._OpenTestData, 'friendship-create.json'))
445
79429eb1b54d
    user = self._api.CreateFriendship('dewitt')
446
79429eb1b54d
    # This is rather arbitrary, but spot checking is better than nothing
447
79429eb1b54d
    self.assertEqual(673483, user.id)
448
79429eb1b54d
449
79429eb1b54d
  def testDestroyFriendship(self):
450
79429eb1b54d
    '''Test the twitter.Api DestroyFriendship method'''
451
79429eb1b54d
    self._AddHandler('http://twitter.com/friendships/destroy/dewitt.json',
452
79429eb1b54d
                     curry(self._OpenTestData, 'friendship-destroy.json'))
453
79429eb1b54d
    user = self._api.DestroyFriendship('dewitt')
454
79429eb1b54d
    # This is rather arbitrary, but spot checking is better than nothing
455
79429eb1b54d
    self.assertEqual(673483, user.id)
456
79429eb1b54d
457
ee84714ea665
  def testGetUser(self):
458
ee84714ea665
    '''Test the twitter.Api GetUser method'''
459
ee84714ea665
    self._AddHandler('http://twitter.com/users/show/dewitt.json',
460
ee84714ea665
                     curry(self._OpenTestData, 'show-dewitt.json'))
461
ee84714ea665
    user = self._api.GetUser('dewitt')
462
ee84714ea665
    self.assertEqual('dewitt', user.screen_name)
463
ee84714ea665
    self.assertEqual(89586072, user.status.id)
464
4805aee792f0
465
4805aee792f0
  def _AddHandler(self, url, callback):
466
4805aee792f0
    self._urllib.AddHandler(url, callback)
467
4805aee792f0
468
4805aee792f0
  def _GetTestDataPath(self, filename):
469
4805aee792f0
    directory = os.path.dirname(os.path.abspath(__file__))
470
4805aee792f0
    test_data_dir = os.path.join(directory, 'testdata')
471
4805aee792f0
    return os.path.join(test_data_dir, filename)
472
17f566981b41
473
4805aee792f0
  def _OpenTestData(self, filename):
474
4805aee792f0
    return open(self._GetTestDataPath(filename))
475
4805aee792f0
476
4805aee792f0
class MockUrllib(object):
477
4805aee792f0
  '''A mock replacement for urllib that hardcodes specific responses.'''
478
4805aee792f0
479
4805aee792f0
  def __init__(self):
480
4805aee792f0
    self._handlers = {}
481
4805aee792f0
    self.HTTPBasicAuthHandler = MockHTTPBasicAuthHandler
482
17f566981b41
483
4805aee792f0
  def AddHandler(self, url, callback):
484
4805aee792f0
    self._handlers[url] = callback
485
17f566981b41
486
4805aee792f0
  def build_opener(self, *handlers):
487
4805aee792f0
    return MockOpener(self._handlers)
488
4805aee792f0
489
4805aee792f0
class MockOpener(object):
490
4805aee792f0
  '''A mock opener for urllib'''
491
4805aee792f0
492
4805aee792f0
  def __init__(self, handlers):
493
4805aee792f0
    self._handlers = handlers
494
c1d12896a51f
    self._opened = False
495
4805aee792f0
496
4805aee792f0
  def open(self, url, data=None):
497
c1d12896a51f
    if self._opened:
498
c1d12896a51f
      raise Exception('MockOpener already opened.')
499
4805aee792f0
    if url in self._handlers:
500
c1d12896a51f
      self._opened = True
501
4805aee792f0
      return self._handlers[url]()
502
4805aee792f0
    else:
503
4805aee792f0
      raise Exception('Unexpected URL %s' % url)
504
4805aee792f0
505
c1d12896a51f
  def close(self):
506
c1d12896a51f
    if not self._opened:
507
c1d12896a51f
      raise Exception('MockOpener closed before it was opened.')
508
c1d12896a51f
    self._opened = False
509
c1d12896a51f
510
4805aee792f0
class MockHTTPBasicAuthHandler(object):
511
4805aee792f0
  '''A mock replacement for HTTPBasicAuthHandler'''
512
4805aee792f0
513
4805aee792f0
  def add_password(self, realm, uri, user, passwd):
514
4805aee792f0
    # TODO(dewitt): Add verification that the proper args are passed
515
4805aee792f0
    pass
516
4805aee792f0
517
4805aee792f0
518
4805aee792f0
class NullCache(object):
519
4805aee792f0
  '''A no-op replacement for the cache class'''
520
4805aee792f0
521
4805aee792f0
  def Get(self, key):
522
4805aee792f0
    return None
523
4805aee792f0
524
4805aee792f0
  def Set(self, key, data):
525
4805aee792f0
    pass
526
4805aee792f0
527
4805aee792f0
  def Remove(self, key):
528
4805aee792f0
    pass
529
4805aee792f0
530
4805aee792f0
  def GetCachedTime(self, key):
531
4805aee792f0
    return None
532
4805aee792f0
533
4805aee792f0
534
4805aee792f0
class curry:
535
4805aee792f0
  # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52549
536
4805aee792f0
537
4805aee792f0
  def __init__(self, fun, *args, **kwargs):
538
4805aee792f0
    self.fun = fun
539
4805aee792f0
    self.pending = args[:]
540
4805aee792f0
    self.kwargs = kwargs.copy()
541
4805aee792f0
542
4805aee792f0
  def __call__(self, *args, **kwargs):
543
4805aee792f0
    if kwargs and self.kwargs:
544
4805aee792f0
      kw = self.kwargs.copy()
545
4805aee792f0
      kw.update(kwargs)
546
4805aee792f0
    else:
547
4805aee792f0
      kw = kwargs or self.kwargs
548
4805aee792f0
    return self.fun(*(self.pending + args), **kw)
549
4805aee792f0
550
4805aee792f0
551
4805aee792f0
def suite():
552
4805aee792f0
  suite = unittest.TestSuite()
553
4805aee792f0
  suite.addTests(unittest.makeSuite(FileCacheTest))
554
4805aee792f0
  suite.addTests(unittest.makeSuite(StatusTest))
555
4805aee792f0
  suite.addTests(unittest.makeSuite(UserTest))
556
4805aee792f0
  suite.addTests(unittest.makeSuite(ApiTest))
557
4805aee792f0
  return suite
558
4805aee792f0
559
4805aee792f0
if __name__ == '__main__':
560
4805aee792f0
  unittest.main()