]> jfr.im git - z_archive/twitter.git/blob - tests/test_sanity.py
Handle media uploads to upload.twitter.com/1.1/media/upload.json
[z_archive/twitter.git] / tests / test_sanity.py
1 # encoding: utf-8
2 from __future__ import unicode_literals
3
4 import os
5 from random import choice
6 import time
7 import pickle
8 import json
9
10 from twitter import Twitter, NoAuth, OAuth, read_token_file, TwitterHTTPError
11 from twitter.api import TwitterDictResponse, TwitterListResponse, POST_ACTIONS, method_for_uri
12 from twitter.cmdline import CONSUMER_KEY, CONSUMER_SECRET
13
14 noauth = NoAuth()
15 oauth = OAuth(*read_token_file('tests/oauth_creds')
16 + (CONSUMER_KEY, CONSUMER_SECRET))
17
18 twitter11 = Twitter(domain='api.twitter.com',
19 auth=oauth,
20 api_version='1.1')
21
22 twitter_upl = Twitter(domain='upload.twitter.com',
23 auth=oauth)
24
25 twitter11_na = Twitter(domain='api.twitter.com',
26 auth=noauth,
27 api_version='1.1')
28
29 AZaz = "abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ"
30
31
32 def get_random_str():
33 return ''.join(choice(AZaz) for _ in range(10))
34
35
36 def test_API_set_tweet(unicod=False):
37 random_tweet = "A random tweet %s" % \
38 ("with unicode üøπ" if unicod else "") + get_random_str()
39 twitter11.statuses.update(status=random_tweet)
40 time.sleep(5)
41 recent = twitter11.statuses.user_timeline()
42 assert recent
43 assert isinstance(recent.rate_limit_remaining, int)
44 assert isinstance(recent.rate_limit_reset, int)
45 texts = [tweet['text'] for tweet in recent]
46 assert random_tweet in texts
47
48 def test_API_set_unicode_tweet():
49 test_API_set_tweet(unicod=True)
50
51
52 def clean_link(text):
53 pos = text.find(" http://t.co")
54 if pos != -1:
55 return text[:pos]
56 return text
57
58 __location__ = os.path.realpath(
59 os.path.join(os.getcwd(), os.path.dirname(__file__)))
60
61 def _img_data():
62 return open(os.path.join(__location__, "test.png"), "rb").read()
63
64 def test_API_set_unicode_twitpic(base64=False):
65 random_tweet = "A random twitpic from %s with unicode üøπ" % \
66 ("base64" if base64 else "file") + get_random_str()
67 if base64:
68 img = b"iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAIAAACQkWg2AAAAAXNSR0IArs4c6QAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB94JFhMBAJv5kaUAAAAZdEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIEdJTVBXgQ4XAAAA4UlEQVQoz7WSIZLGIAxG6c5OFZjianBcIOfgPkju1DsEBWfAUEcNGGpY8Xe7dDoVFRvHfO8NJGRorZE39UVe1nd/WNfVObcsi3OOEAIASikAmOf5D2q/FWPUWgshKKWfiFIqhNBaxxhPjPQ05/z+Bs557xw9hBC89ymlu5BS8t6HEC5NW2sR8alRRLTWXoRSSinlSejT12M9BAAAgCeoTw9BSimlfBIu6WdYtVZEVErdaaUUItZaL/9wOsaY83YAMMb0dGtt6Jdv3/ec87ZtOWdCCGNsmibG2DiOJzP8+7b+AAOmsiPxyHWCAAAAAElFTkSuQmCC"
69 else:
70 img = _img_data()
71 params = {"status": random_tweet, "media[]": img}
72 if base64:
73 params["_base64"] = True
74 twitter11.statuses.update_with_media(**params)
75 time.sleep(5)
76 recent = twitter11.statuses.user_timeline()
77 assert recent
78 texts = [clean_link(tweet['text']) for tweet in recent]
79 assert random_tweet in texts
80
81 def test_API_set_unicode_twitpic_base64():
82 test_API_set_unicode_twitpic(base64=True)
83
84 def test_upload_media():
85 res = twitter_upl.media.upload(media=_img_data())
86 assert res
87 assert res["media_id"]
88
89 def test_search():
90 # In 1.1, search works on api.twitter.com not search.twitter.com
91 # and requires authorisation
92 results = twitter11.search.tweets(q='foo')
93 assert results
94
95
96 def test_get_trends():
97 # This is one method of inserting parameters, using named
98 # underscore params.
99 world_trends = twitter11.trends.available(_woeid=1)
100 assert world_trends
101
102
103 def test_get_trends_2():
104 # This is a nicer variation of the same call as above.
105 world_trends = twitter11.trends._(1)
106 assert world_trends
107
108
109 def test_get_trends_3():
110 # Of course they broke it all again in 1.1...
111 assert twitter11.trends.place(_id=1)
112
113
114 def test_TwitterHTTPError_raised_for_invalid_oauth():
115 test_passed = False
116 try:
117 twitter11_na.statuses.mentions_timeline()
118 except TwitterHTTPError:
119 # this is the error we are looking for :)
120 test_passed = True
121 assert test_passed
122
123
124 def test_picklability():
125 res = TwitterDictResponse({'a': 'b'})
126 p = pickle.dumps(res)
127 res2 = pickle.loads(p)
128 assert res == res2
129 assert res2['a'] == 'b'
130
131 res = TwitterListResponse([1, 2, 3])
132 p = pickle.dumps(res)
133 res2 = pickle.loads(p)
134 assert res == res2
135 assert res2[2] == 3
136
137
138 def test_jsonifability():
139 res = TwitterDictResponse({'a': 'b'})
140 p = json.dumps(res)
141 res2 = json.loads(p)
142 assert res == res2
143 assert res2['a'] == 'b'
144
145 res = TwitterListResponse([1, 2, 3])
146 p = json.dumps(res)
147 res2 = json.loads(p)
148 assert res == res2
149 assert res2[2] == 3
150
151
152 def test_method_for_uri():
153 for action in POST_ACTIONS:
154 assert method_for_uri(get_random_str() + '/' + action) == 'POST'
155 assert method_for_uri('statuses/timeline') == 'GET'