1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
|
from BaseHTTPServer import (
HTTPServer,
BaseHTTPRequestHandler,
)
import httplib
import os
from signal import SIGKILL
import simplejson
from StringIO import StringIO
from unittest import TestCase
from urlparse import urlparse
from urlparse import parse_qs
from testtools import ExpectedException
from grackle.client import (
GrackleClient,
UnsupportedOrder,
)
def threaded_messages(messages):
threads = {}
count = 0
pending = []
for message in messages:
if message.get('in_reply_to') is None:
threads[message['message_id']] = [message]
count += 1
else:
pending.append(message)
for message in pending:
threads[message['in_reply_to']].append(message)
return threads.values()
class ForkedFake:
def __init__(self, port, messages=None):
self.pid = None
self.port = port
self.messages = messages
self.read_end, self.write_end = os.pipe()
def is_ready(self):
os.write(self.write_end, 'asdf')
def __enter__(self):
pid = os.fork()
if pid == 0:
self.start_server()
self.pid = pid
os.read(self.read_end, 1)
return
def start_server(self):
service = HTTPServer(('', self.port), FakeGrackleRequestHandler)
service.messages = self.messages
self.is_ready()
service.serve_forever()
def __exit__(self, exc_type, exc_val, traceback):
os.kill(self.pid, SIGKILL)
SUPPORTED_ORDERS = set(
['date', 'author', 'subject', 'thread_newest', 'thread_oldest',
'thread_subject'])
class FakeGrackleRequestHandler(BaseHTTPRequestHandler):
def do_POST(self):
message = self.rfile.read(int(self.headers['content-length']))
if message == 'This is a message':
self.send_response(httplib.CREATED)
self.end_headers()
self.wfile.close()
else:
self.send_error(httplib.BAD_REQUEST)
def do_GET(self):
scheme, netloc, path, params, query_string, fragments = (
urlparse(self.path))
archive = os.path.split(path)[1]
query = parse_qs(query_string)
parameters = simplejson.loads(query['parameters'][0])
order = parameters.get('order')
messages = self.server.messages[archive]
if order is not None :
if order not in SUPPORTED_ORDERS:
self.send_response(httplib.BAD_REQUEST)
self.wfile.write('Unsupported order')
return
elif order.startswith('thread_'):
threaded = threaded_messages(messages)
messages = []
if order == 'thread_subject':
threaded.sort(key=lambda t: t[0]['subject'])
if order == 'thread_oldest':
threaded.sort(key=lambda t: min(m['date'] for m in t))
if order == 'thread_newest':
threaded.sort(key=lambda t: max(m['date'] for m in t))
for thread in threaded:
messages.extend(thread)
else:
messages.sort(key=lambda m: m[order])
messages = [m for m in messages
if 'message_ids' not in parameters or
m['message_id'] in parameters['message_ids']]
self.send_response(httplib.OK)
self.end_headers()
limit = parameters.get('limit', 100)
memo = parameters.get('memo')
message_id_indices = dict(
(m['message_id'], idx) for idx, m in enumerate(messages))
if memo is None:
start = 0
else:
start = message_id_indices[memo.encode('rot13')]
if start > 0:
previous_memo = messages[start - 1]['message_id'].encode('rot13')
else:
previous_memo = None
end = min(start + limit, len(messages))
if end < len(messages):
next_memo = messages[end]['message_id'].encode('rot13')
else:
next_memo = None
messages = messages[start:end]
response = {
'messages': messages,
'next_memo': next_memo,
'previous_memo': previous_memo
}
self.wfile.write(simplejson.dumps(response))
def fake_grackle_service(client, messages=None):
if messages is None:
messages = {}
return ForkedFake(client.port, messages)
class TestPutMessage(TestCase):
def test_put_message(self):
client = GrackleClient('localhost', 8436)
with fake_grackle_service(client):
client.put_message('arch1', 'asdf', StringIO('This is a message'))
with ExpectedException(Exception, 'wtf'):
client.put_message('arch1', 'asdf',
StringIO('This is not a message'))
class TestGetMessages(TestCase):
def assertIDOrder(self, ids, messages):
self.assertEqual(ids, [m['message_id'] for m in messages])
def assertMessageIDs(self, ids, messages):
self.assertIDOrder(
sorted(ids), sorted(messages, key=lambda m:m['message_id']))
def test_get_messages(self):
client = GrackleClient('localhost', 8435)
with fake_grackle_service(client,
{'baz':
[{'message_id': 'foo'},
{'message_id': 'bar'}]}):
response = client.get_messages('baz')
self.assertEqual(['bar', 'foo'], sorted(m['message_id'] for m in
response['messages']))
self.assertIs(None, response['next_memo'])
self.assertIs(None, response['previous_memo'])
def test_get_messages_by_id(self):
client = GrackleClient('localhost', 8437)
with fake_grackle_service(client,
{'baz':
[{'message_id': 'foo'},
{'message_id': 'bar'}]}):
response = client.get_messages('baz', message_ids=['foo'])
message, = response['messages']
self.assertEqual('foo', message['message_id'])
def test_get_messages_batching(self):
client = GrackleClient('localhost', 8438)
with fake_grackle_service(client,
{'baz':
[{'message_id': 'foo'},
{'message_id': 'bar'}]}):
response = client.get_messages('baz', limit=1)
self.assertEqual(1, len(response['messages']))
messages = response['messages']
response = client.get_messages(
'baz', limit=1, memo=response['next_memo'])
self.assertEqual(1, len(response['messages']))
messages.extend(response['messages'])
self.assertMessageIDs(['foo', 'bar'], messages)
def get_messages_member_order_test(self, key):
client = GrackleClient('localhost', 8439)
with fake_grackle_service(client,
{'baz': [{'message_id': 'foo', key: '2011-03-25'},
{'message_id': 'bar', key: '2011-03-24'}]}):
response = client.get_messages('baz')
self.assertIDOrder(['foo', 'bar'], response['messages'])
response = client.get_messages('baz', order=key)
self.assertIDOrder(['bar', 'foo'], response['messages'])
def test_get_messages_date_order(self):
self.get_messages_member_order_test('date')
def test_get_messages_author_order(self):
self.get_messages_member_order_test('author')
def test_get_messages_subject_order(self):
self.get_messages_member_order_test('subject')
def test_get_messages_thread_subject_order(self):
client = GrackleClient('localhost', 8439)
with fake_grackle_service(client, {'baz': [
{'message_id': 'bar', 'subject': 'y'},
{'message_id': 'qux', 'subject': 'z'},
{'message_id': 'foo', 'subject': 'x', 'in_reply_to': 'qux'},
]}):
response = client.get_messages('baz')
self.assertIDOrder(['bar', 'qux', 'foo'], response['messages'])
response = client.get_messages('baz', order='subject')
self.assertIDOrder(['foo', 'bar', 'qux'], response['messages'])
response = client.get_messages('baz', order='thread_subject')
self.assertIDOrder(['bar', 'qux', 'foo'], response['messages'])
def test_get_messages_thread_oldest_order(self):
client = GrackleClient('localhost', 8439)
with fake_grackle_service(client, {'baz': [
{'message_id': 'bar', 'date': 'x'},
{'message_id': 'qux', 'date': 'z'},
{'message_id': 'foo', 'date': 'y', 'in_reply_to': 'qux'},
]}):
response = client.get_messages('baz')
self.assertIDOrder(['bar', 'qux', 'foo'], response['messages'])
response = client.get_messages('baz', order='date')
self.assertIDOrder(['bar', 'foo', 'qux'], response['messages'])
response = client.get_messages('baz', order='thread_oldest')
self.assertIDOrder(['bar', 'qux', 'foo'], response['messages'])
def test_get_messages_thread_newest_order(self):
client = GrackleClient('localhost', 8439)
with fake_grackle_service(client, {'baz': [
{'message_id': 'bar', 'date': 'x'},
{'message_id': 'qux', 'date': 'w'},
{'message_id': 'foo', 'date': 'y', 'in_reply_to': 'bar'},
{'message_id': 'baz', 'date': 'z', 'in_reply_to': 'qux'},
]}):
response = client.get_messages('baz', order='date')
self.assertIDOrder(
['qux', 'bar', 'foo', 'baz'], response['messages'])
response = client.get_messages('baz', order='thread_newest')
self.assertIDOrder(
['bar', 'foo', 'qux', 'baz'], response['messages'])
def test_get_messages_unsupported_order(self):
client = GrackleClient('localhost', 8439)
with fake_grackle_service(client,
{'baz': [{'message_id': 'foo', 'date': '2011-03-25'},
{'message_id': 'bar', 'date': '2011-03-24'}]}):
with ExpectedException(UnsupportedOrder):
client.get_messages('baz', order='nonsense')
|