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