X Tutup
Skip to content

Commit 955f771

Browse files
author
James Salter
committed
fix tests that weren't already broken on py3
1 parent b3ad682 commit 955f771

File tree

5 files changed

+55
-33
lines changed

5 files changed

+55
-33
lines changed

twitter/_file_cache.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,8 @@ def __init__(self, root_directory=None):
1919
def Get(self, key):
2020
path = self._GetPath(key)
2121
if os.path.exists(path):
22-
return open(path).read()
22+
with open(path) as f:
23+
return f.read()
2324
else:
2425
return None
2526

@@ -85,7 +86,7 @@ def _InitializeRootDirectory(self, root_directory):
8586

8687
def _GetPath(self, key):
8788
try:
88-
hashed_key = md5(key).hexdigest()
89+
hashed_key = md5(key.encode('utf-8')).hexdigest()
8990
except TypeError:
9091
hashed_key = md5.new(key).hexdigest()
9192

twitter/api.py

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,13 @@
4646
from twitter import (__version__, _FileCache, simplejson, DirectMessage, List,
4747
Status, Trend, TwitterError, User, UserStatus)
4848

49+
try:
50+
# python 3
51+
urllib_version = urllib.request.__version__
52+
except AttributeError:
53+
# python 2
54+
urllib_version = urllib.__version__
55+
4956
CHARACTER_LIMIT = 140
5057

5158
# A singleton representing a lazily instantiated FileCache.
@@ -3468,7 +3475,7 @@ def _InitializeRequestHeaders(self, request_headers):
34683475

34693476
def _InitializeUserAgent(self):
34703477
user_agent = 'Python-urllib/%s (python-twitter/%s)' % \
3471-
(urllib.__version__, __version__)
3478+
(urllib_version, __version__)
34723479
self.SetUserAgent(user_agent)
34733480

34743481
def _InitializeDefaultParameters(self):

twitter/direct_message.py

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,13 @@
1-
from builtins import object
21
#!/usr/bin/env python
32

3+
from builtins import object
4+
45
from calendar import timegm
5-
import rfc822
6+
7+
try:
8+
from rfc822 import parsedate
9+
except ImportError:
10+
from email.utils import parsedate
611

712
from twitter import simplejson, TwitterError
813

@@ -107,7 +112,7 @@ def GetCreatedAtInSeconds(self):
107112
Returns:
108113
The time this direct message was posted, in seconds since the epoch.
109114
"""
110-
return timegm(rfc822.parsedate(self.created_at))
115+
return timegm(parsedate(self.created_at))
111116

112117
created_at_in_seconds = property(GetCreatedAtInSeconds,
113118
doc="The time this direct message was "

twitter/status.py

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,12 @@
44
from builtins import object
55
from past.utils import old_div
66
from calendar import timegm
7-
import rfc822
7+
8+
try:
9+
from rfc822 import parsedate
10+
except ImportError:
11+
from email.utils import parsedate
12+
813
import time
914

1015
from twitter import simplejson, Hashtag, TwitterError, Url
@@ -152,7 +157,7 @@ def GetCreatedAtInSeconds(self):
152157
Returns:
153158
The time this status message was posted, in seconds since the epoch.
154159
"""
155-
return timegm(rfc822.parsedate(self.created_at))
160+
return timegm(parsedate(self.created_at))
156161

157162
created_at_in_seconds = property(GetCreatedAtInSeconds,
158163
doc="The time this status message was "

twitter_test.py

Lines changed: 29 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -20,18 +20,22 @@
2020

2121
__author__ = 'python-twitter@googlegroups.com'
2222

23+
from future import standard_library
24+
standard_library.install_aliases()
25+
2326
import os
2427
import json as simplejson
2528
import time
2629
import calendar
2730
import unittest
28-
import urllib
31+
import urllib.request, urllib.parse, urllib.error
2932

3033
import twitter
3134

3235
class StatusTest(unittest.TestCase):
3336

34-
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": "https://twitter.com/system/user/profile_image/718443/normal/kesuke.png", "screen_name": "kesuke", "url": "https://twitter.com/kesuke"}}'''
37+
# this is aiming to test escaped text passes through okay - the python interpreter will ignore the \u because this is a raw literal
38+
SAMPLE_JSON = r'''{"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": "https://twitter.com/system/user/profile_image/718443/normal/kesuke.png", "screen_name": "kesuke", "url": "https://twitter.com/kesuke"}}'''
3539

3640
def _GetSampleUser(self):
3741
return twitter.User(id=718443,
@@ -315,7 +319,7 @@ class FileCacheTest(unittest.TestCase):
315319
def testInit(self):
316320
"""Test the twitter._FileCache constructor"""
317321
cache = twitter._FileCache()
318-
self.assert_(cache is not None, 'cache is None')
322+
self.assertTrue(cache is not None, 'cache is None')
319323

320324
def testSet(self):
321325
"""Test the twitter._FileCache.Set method"""
@@ -346,7 +350,7 @@ def testGetCachedTime(self):
346350
cache.Set("foo",'Hello World!')
347351
cached_time = cache.GetCachedTime("foo")
348352
delta = cached_time - now
349-
self.assert_(delta <= 1,
353+
self.assertTrue(delta <= 1,
350354
'Cached time differs from clock time by more than 1 second.')
351355
cache.Remove("foo")
352356

@@ -362,7 +366,7 @@ def setUp(self):
362366
cache=None)
363367
api.SetUrllib(self._urllib)
364368
self._api = api
365-
print "Testing the API class. This test is time controlled"
369+
print("Testing the API class. This test is time controlled")
366370

367371
def testTwitterError(self):
368372
'''Test that twitter responses containing an error message are wrapped.'''
@@ -371,7 +375,7 @@ def testTwitterError(self):
371375
# Manually try/catch so we can check the exception's value
372376
try:
373377
statuses = self._api.GetUserTimeline()
374-
except twitter.TwitterError, error:
378+
except twitter.TwitterError as error:
375379
# If the error message matches, the test passes
376380
self.assertEqual('test error', error.message)
377381
else:
@@ -380,7 +384,7 @@ def testTwitterError(self):
380384
def testGetUserTimeline(self):
381385
'''Test the twitter.Api GetUserTimeline method'''
382386
time.sleep(8)
383-
print 'Testing GetUserTimeline'
387+
print('Testing GetUserTimeline')
384388
self._AddHandler('https://api.twitter.com/1.1/statuses/user_timeline.json?count=1&screen_name=kesuke',
385389
curry(self._OpenTestData, 'user_timeline-kesuke.json'))
386390
statuses = self._api.GetUserTimeline(screen_name='kesuke', count=1)
@@ -400,7 +404,7 @@ def testGetUserTimeline(self):
400404
def testGetStatus(self):
401405
'''Test the twitter.Api GetStatus method'''
402406
time.sleep(8)
403-
print 'Testing GetStatus'
407+
print('Testing GetStatus')
404408
self._AddHandler('https://api.twitter.com/1.1/statuses/show.json?include_my_retweet=1&id=89512102',
405409
curry(self._OpenTestData, 'show-89512102.json'))
406410
status = self._api.GetStatus(89512102)
@@ -410,7 +414,7 @@ def testGetStatus(self):
410414
def testDestroyStatus(self):
411415
'''Test the twitter.Api DestroyStatus method'''
412416
time.sleep(8)
413-
print 'Testing DestroyStatus'
417+
print('Testing DestroyStatus')
414418
self._AddHandler('https://api.twitter.com/1.1/statuses/destroy/103208352.json',
415419
curry(self._OpenTestData, 'status-destroy.json'))
416420
status = self._api.DestroyStatus(103208352)
@@ -419,7 +423,7 @@ def testDestroyStatus(self):
419423
def testPostUpdate(self):
420424
'''Test the twitter.Api PostUpdate method'''
421425
time.sleep(8)
422-
print 'Testing PostUpdate'
426+
print('Testing PostUpdate')
423427
self._AddHandler('https://api.twitter.com/1.1/statuses/update.json',
424428
curry(self._OpenTestData, 'update.json'))
425429
status = self._api.PostUpdate(u'Моё судно на воздушной подушке полно угрей'.encode('utf8'))
@@ -429,7 +433,7 @@ def testPostUpdate(self):
429433
def testPostRetweet(self):
430434
'''Test the twitter.Api PostRetweet method'''
431435
time.sleep(8)
432-
print 'Testing PostRetweet'
436+
print('Testing PostRetweet')
433437
self._AddHandler('https://api.twitter.com/1.1/statuses/retweet/89512102.json',
434438
curry(self._OpenTestData, 'retweet.json'))
435439
status = self._api.PostRetweet(89512102)
@@ -438,20 +442,20 @@ def testPostRetweet(self):
438442
def testPostUpdateLatLon(self):
439443
'''Test the twitter.Api PostUpdate method, when used in conjunction with latitude and longitude'''
440444
time.sleep(8)
441-
print 'Testing PostUpdateLatLon'
445+
print('Testing PostUpdateLatLon')
442446
self._AddHandler('https://api.twitter.com/1.1/statuses/update.json',
443447
curry(self._OpenTestData, 'update_latlong.json'))
444448
#test another update with geo parameters, again test somewhat arbitrary
445449
status = self._api.PostUpdate(u'Моё судно на воздушной подушке полно угрей'.encode('utf8'), latitude=54.2, longitude=-2)
446450
self.assertEqual(u'Моё судно на воздушной подушке полно угрей', status.text)
447-
self.assertEqual(u'Point',status.GetGeo()['type'])
451+
self.assertEqual('Point',status.GetGeo()['type'])
448452
self.assertEqual(26.2,status.GetGeo()['coordinates'][0])
449453
self.assertEqual(127.5,status.GetGeo()['coordinates'][1])
450454

451455
def testGetReplies(self):
452456
'''Test the twitter.Api GetReplies method'''
453457
time.sleep(8)
454-
print 'Testing GetReplies'
458+
print('Testing GetReplies')
455459
self._AddHandler('https://api.twitter.com/1.1/statuses/user_timeline.json',
456460
curry(self._OpenTestData, 'replies.json'))
457461
statuses = self._api.GetReplies()
@@ -460,7 +464,7 @@ def testGetReplies(self):
460464
def testGetRetweetsOfMe(self):
461465
'''Test the twitter.API GetRetweetsOfMe method'''
462466
time.sleep(8)
463-
print 'Testing GetRetweetsOfMe'
467+
print('Testing GetRetweetsOfMe')
464468
self._AddHandler('https://api.twitter.com/1.1/statuses/retweets_of_me.json',
465469
curry(self._OpenTestData, 'retweets_of_me.json'))
466470
retweets = self._api.GetRetweetsOfMe()
@@ -469,7 +473,7 @@ def testGetRetweetsOfMe(self):
469473
def testGetFriends(self):
470474
'''Test the twitter.Api GetFriends method'''
471475
time.sleep(8)
472-
print 'Testing GetFriends'
476+
print('Testing GetFriends')
473477
self._AddHandler('https://api.twitter.com/1.1/friends/list.json?cursor=123',
474478
curry(self._OpenTestData, 'friends.json'))
475479
users = self._api.GetFriends(cursor=123)
@@ -479,7 +483,7 @@ def testGetFriends(self):
479483
def testGetFollowers(self):
480484
'''Test the twitter.Api GetFollowers method'''
481485
time.sleep(8)
482-
print 'Testing GetFollowers'
486+
print('Testing GetFollowers')
483487
self._AddHandler('https://api.twitter.com/1.1/followers/list.json?cursor=-1',
484488
curry(self._OpenTestData, 'followers.json'))
485489
users = self._api.GetFollowers()
@@ -499,7 +503,7 @@ def testGetFollowers(self):
499503
def testGetDirectMessages(self):
500504
'''Test the twitter.Api GetDirectMessages method'''
501505
time.sleep(8)
502-
print 'Testing GetDirectMessages'
506+
print('Testing GetDirectMessages')
503507
self._AddHandler('https://api.twitter.com/1.1/direct_messages.json',
504508
curry(self._OpenTestData, 'direct_messages.json'))
505509
statuses = self._api.GetDirectMessages()
@@ -508,7 +512,7 @@ def testGetDirectMessages(self):
508512
def testPostDirectMessage(self):
509513
'''Test the twitter.Api PostDirectMessage method'''
510514
time.sleep(8)
511-
print 'Testing PostDirectMessage'
515+
print('Testing PostDirectMessage')
512516
self._AddHandler('https://api.twitter.com/1.1/direct_messages/new.json',
513517
curry(self._OpenTestData, 'direct_messages-new.json'))
514518
status = self._api.PostDirectMessage('test', u'Моё судно на воздушной подушке полно угрей'.encode('utf8'))
@@ -518,7 +522,7 @@ def testPostDirectMessage(self):
518522
def testDestroyDirectMessage(self):
519523
'''Test the twitter.Api DestroyDirectMessage method'''
520524
time.sleep(8)
521-
print 'Testing DestroyDirectMessage'
525+
print('Testing DestroyDirectMessage')
522526
self._AddHandler('https://api.twitter.com/1.1/direct_messages/destroy.json',
523527
curry(self._OpenTestData, 'direct_message-destroy.json'))
524528
status = self._api.DestroyDirectMessage(3496342)
@@ -528,7 +532,7 @@ def testDestroyDirectMessage(self):
528532
def testCreateFriendship(self):
529533
'''Test the twitter.Api CreateFriendship method'''
530534
time.sleep(8)
531-
print 'Testing CreateFriendship'
535+
print('Testing CreateFriendship')
532536
self._AddHandler('https://api.twitter.com/1.1/friendships/create.json',
533537
curry(self._OpenTestData, 'friendship-create.json'))
534538
user = self._api.CreateFriendship('dewitt')
@@ -538,7 +542,7 @@ def testCreateFriendship(self):
538542
def testDestroyFriendship(self):
539543
'''Test the twitter.Api DestroyFriendship method'''
540544
time.sleep(8)
541-
print 'Testing Destroy Friendship'
545+
print('Testing Destroy Friendship')
542546
self._AddHandler('https://api.twitter.com/1.1/friendships/destroy.json',
543547
curry(self._OpenTestData, 'friendship-destroy.json'))
544548
user = self._api.DestroyFriendship('dewitt')
@@ -548,7 +552,7 @@ def testDestroyFriendship(self):
548552
def testGetUser(self):
549553
'''Test the twitter.Api GetUser method'''
550554
time.sleep(8)
551-
print 'Testing GetUser'
555+
print('Testing GetUser')
552556
self._AddHandler('https://api.twitter.com/1.1/users/show.json?user_id=dewitt',
553557
curry(self._OpenTestData, 'show-dewitt.json'))
554558
user = self._api.GetUser('dewitt')
@@ -622,8 +626,8 @@ def open(self, url, data=None):
622626
self._opened = True
623627
return self._handlers[url]()
624628
else:
625-
print url
626-
print self._handlers
629+
print(url)
630+
print(self._handlers)
627631

628632
raise Exception('Unexpected URL %s (Checked: %s)' % (url, self._handlers))
629633

0 commit comments

Comments
 (0)
X Tutup