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
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
|
from BaseHTTPServer import (
HTTPServer,
BaseHTTPRequestHandler,
)
from email.message import Message
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import httplib
import logging
import os
from signal import SIGKILL
import simplejson
from StringIO import StringIO
import sys
from unittest import TestCase
from urlparse import urlparse
from urlparse import parse_qs
from testtools import ExpectedException
from grackle.client import (
GrackleClient,
UnsupportedDisplayType,
UnsupportedOrder,
)
def make_message(message_id, body='body', headers=None, hidden=False):
if headers is None:
headers = {}
headers['Message-Id'] = message_id
message = {
'message_id': message_id,
'headers': headers,
'thread_id': message_id,
'date': headers.get('date', '2005-01-01'),
'subject': headers.get('subject', 'subject'),
'author': headers.get('author', 'author'),
'hidden': hidden,
'attachments': [],
'body': body,
'replies': [],
}
if 'in-reply-to' in headers:
message['in_reply_to'] = headers['in-reply-to']
return message
def make_mime_message(message_id, text, headers=None, hidden=False,
attachment_type=None):
message = MIMEMultipart()
message.attach(MIMEText(text))
message['Message-Id'] = message_id
if headers is not None:
for k, v in headers.items():
message[k] = v
if attachment_type is not None:
attachment = Message()
attachment.set_payload('attactment data.')
attachment['Content-Type'] = attachment_type
attachment['Content-Disposition'] = (
'attachment; filename="file.ext"')
message.attach(attachment)
dict_message = {
'message_id': message_id,
'headers': dict(message.items()),
'body': message.get_payload(),
}
return dict_message
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 GrackleStore:
"""A memory-backed message store."""
def __init__(self, messages):
"""Constructor."""
self.messages = messages
def get_messages(self, archive_id, query_string):
"""Return matching messages.
:param archive_id: The archive to retrieve from.
:param query_string: Contains 'parameters', which is a JSON-format
string describing parameters.
"""
query = parse_qs(query_string)
parameters = simplejson.loads(query['parameters'][0])
order = parameters.get('order')
messages = self.messages[archive_id]
if order is not None:
if order not in SUPPORTED_ORDERS:
raise UnsupportedOrder
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])
display_type = parameters.get('display_type', 'all')
if display_type not in SUPPORTED_DISPLAY_TYPES:
raise UnsupportedDisplayType
new_messages = []
for message in messages:
if (not parameters['include_hidden']
and message.get('hidden', False)):
continue
if ('message_ids' in parameters
and message['message_id'] not in parameters['message_ids']):
continue
message = dict(message)
if 'headers' in parameters:
headers = dict(
(k, v) for k, v in message['headers'].iteritems()
if k in parameters['headers'])
message['headers'] = headers
max_body = parameters.get('max_body_length')
if display_type == 'headers-only':
del message['body']
elif (display_type == 'text-only'
and isinstance(message['body'], list)):
text_parts = [
part.get_payload() for part in message['body']
if part.get_content_type() == 'text/plain']
message['body'] = '\n\n'.join(text_parts)
elif (display_type == 'all'
and 'body' in message
and isinstance(message['body'], list)):
parts = [str(part.get_payload()) for part in message['body']]
message['body'] = '\n\n'.join(parts)
if max_body is not None and display_type != 'headers-only':
message['body'] = message['body'][:max_body]
new_messages.append(message)
messages = new_messages
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
}
return response
class ForkedFakeService:
"""A Grackle service fake, as a ContextManager."""
def __init__(self, port, messages=None, write_logs=False):
"""Constructor.
:param port: The tcp port to use.
:param messages: A dict of lists of dicts representing messages. The
outer dict represents the archive, the list represents the list of
messages for that archive.
:param write_logs: If true, log messages will be written to stdout.
"""
self.pid = None
self.port = port
if messages is None:
self.messages = {}
else:
self.messages = messages
self.read_end, self.write_end = os.pipe()
self.write_logs = write_logs
@staticmethod
def from_client(client, messages=None):
"""Instantiate a ForkedFakeService from the client.
:param port: The client to provide service for.
:param messages: A dict of lists of dicts representing messages. The
outer dict represents the archive, the list represents the list of
messages for that archive.
"""
return ForkedFakeService(client.port, messages)
def is_ready(self):
"""Tell the parent process that the server is ready for writes."""
os.write(self.write_end, 'asdf')
def __enter__(self):
"""Run the service.
Fork and start a server in the child. Return when the server is ready
for use."""
pid = os.fork()
if pid == 0:
self.start_server()
self.pid = pid
os.read(self.read_end, 1)
return
def start_server(self):
"""Start the HTTP server."""
service = HTTPServer(('', self.port), FakeGrackleRequestHandler)
service.store = GrackleStore(self.messages)
for archive_id, messages in service.store.messages.iteritems():
for message in messages:
message.setdefault('headers', {})
self.is_ready()
if self.write_logs:
logging.basicConfig(
stream=sys.stderr, level=logging.INFO)
service.serve_forever()
def __exit__(self, exc_type, exc_val, traceback):
os.kill(self.pid, SIGKILL)
SUPPORTED_DISPLAY_TYPES = set(['all', 'text-only', 'headers-only'])
SUPPORTED_ORDERS = set(
['date', 'author', 'subject', 'thread_newest', 'thread_oldest',
'thread_subject'])
class FakeGrackleRequestHandler(BaseHTTPRequestHandler):
"""A request handler that forwards to server.store."""
def __init__(self, *args, **kwargs):
"""Constructor. Sets up logging."""
self.logger = logging.getLogger('http')
BaseHTTPRequestHandler.__init__(self, *args, **kwargs)
def do_POST(self):
"""Create a message on POST."""
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):
"""Retrieve a list of messages on GET."""
scheme, netloc, path, params, query_string, fragments = (
urlparse(self.path))
parts = path.split('/')
if parts[1] == 'archive':
try:
response = self.server.store.get_messages(
parts[2], query_string)
self.send_response(httplib.OK)
self.end_headers()
self.wfile.write(simplejson.dumps(response))
except UnsupportedOrder:
self.send_response(
httplib.BAD_REQUEST, UnsupportedOrder.__doc__)
return
except UnsupportedDisplayType:
self.send_response(
httplib.BAD_REQUEST, UnsupportedDisplayType.__doc__)
return
def log_message(self, format, *args):
"""Override log_message to use standard Python logging."""
message = "%s - - [%s] %s\n" % (
self.address_string(), self.log_date_time_string(), format % args)
self.logger.info(message)
class TestPutMessage(TestCase):
def test_put_message(self):
client = GrackleClient('localhost', 8436)
with ForkedFakeService.from_client(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)
archive = {
'baz': [make_message('foo'), make_message('bar')]}
with ForkedFakeService.from_client(client, archive):
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)
archive = {
'baz': [make_message('foo'), make_message('bar')]}
with ForkedFakeService.from_client(client, archive):
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)
archive = {'baz': [make_message('foo'), make_message('bar')]}
with ForkedFakeService.from_client(client, archive):
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)
archive = {
'baz': [
make_message('foo', headers={key: '2011-03-25'}),
make_message('bar', headers={key: '2011-03-24'}),
]}
with ForkedFakeService.from_client(client, archive):
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):
archive = {
'baz': [
make_message('bar', headers={'subject': 'y'}),
make_message('qux', headers={'subject': 'z'}),
make_message('foo', headers={'subject': 'x',
'in-reply-to': 'qux'}),
]}
client = GrackleClient('localhost', 8439)
with ForkedFakeService.from_client(client, archive):
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)
archive = {
'baz': [
make_message('bar', headers={'date': 'x'}),
make_message('qux', headers={'date': 'z'}),
make_message('foo', headers={'date': 'y',
'in-reply-to': 'qux'}),
]}
with ForkedFakeService.from_client(client, archive):
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)
archive = {
'baz': [
make_message('bar', headers={'date': 'x'}),
make_message('qux', headers={'date': 'w'}),
make_message('foo', headers={'date': 'y',
'in-reply-to': 'bar'}),
make_message('baz', headers={'date': 'z',
'in-reply-to': 'qux'}),
]}
with ForkedFakeService.from_client(client, archive):
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)
archive = {
'baz': [
make_message('foo', headers={'date': '2011-03-25'}),
make_message('foo', headers={'date': '2011-03-24'}),
]}
with ForkedFakeService.from_client(client, archive):
with ExpectedException(UnsupportedOrder, ''):
client.get_messages('baz', order='nonsense')
def test_get_messages_headers_no_headers(self):
client = GrackleClient('localhost', 8440)
archive = {'baz': [make_message('foo')]}
with ForkedFakeService.from_client(client, archive):
response = client.get_messages('baz', headers=[
'Subject', 'Date', 'X-Launchpad-Message-Rationale'])
first_message = response['messages'][0]
self.assertEqual('foo', first_message['message_id'])
self.assertEqual({}, first_message['headers'])
def test_get_messages_headers_exclude_headers(self):
client = GrackleClient('localhost', 8441)
archive = {
'baz': [make_message('foo', headers={'From': 'me'})]}
with ForkedFakeService.from_client(client, archive):
response = client.get_messages('baz', headers=[
'Subject', 'Date', 'X-Launchpad-Message-Rationale'])
first_message = response['messages'][0]
self.assertEqual('foo', first_message['message_id'])
self.assertEqual({}, first_message['headers'])
def test_get_messages_headers_include_headers(self):
client = GrackleClient('localhost', 8442)
archive = {
'baz': [
make_message('foo', headers={'From': 'me', 'To': 'you'})]}
with ForkedFakeService.from_client(client, archive):
response = client.get_messages('baz', headers=[
'From', 'To'])
first_message = response['messages'][0]
self.assertEqual('foo', first_message['message_id'])
self.assertEqual({'From': 'me', 'To': 'you'}, first_message['headers'])
def test_get_messages_max_body_length(self):
client = GrackleClient('localhost', 8443)
archive = {'baz': [make_message('foo', body=u'abcdefghi')]}
with ForkedFakeService.from_client(client, archive):
response = client.get_messages('baz', max_body_length=3)
first_message = response['messages'][0]
self.assertEqual('abc', first_message['body'])
def test_include_hidden(self):
client = GrackleClient('localhost', 8444)
archive = {
'baz': [
make_message('foo', hidden=True),
make_message('bar', hidden=False),
]}
with ForkedFakeService.from_client(client, archive):
response = client.get_messages('baz', include_hidden=True)
self.assertMessageIDs(['bar', 'foo'], response['messages'])
response = client.get_messages('baz', include_hidden=False)
self.assertMessageIDs(['bar'], response['messages'])
def test_display_type_unknown_value(self):
client = GrackleClient('localhost', 8445)
archive = {'baz': [make_message('foo', body=u'abcdefghi')]}
with ForkedFakeService.from_client(client, archive):
with ExpectedException(UnsupportedDisplayType, ''):
client.get_messages('baz', display_type='unknown')
def test_display_type_headers_only(self):
client = GrackleClient('localhost', 8446)
archive = {
'baz': [
make_message('foo', body=u'abcdefghi',
headers={'From': 'me', 'To': 'you'})]}
with ForkedFakeService.from_client(client, archive):
response = client.get_messages('baz', display_type='headers-only')
first_message = response['messages'][0]
self.assertEqual('foo', first_message['message_id'])
self.assertEqual(
{'From': 'me', 'Message-Id': 'foo', 'To': 'you'},
first_message['headers'])
self.assertNotIn('body', first_message)
def test_display_type_text_only(self):
client = GrackleClient('localhost', 8446)
archive = {
'baz': [
make_mime_message(
'foo', 'abcdefghi',
headers={'From': 'me', 'To': 'you'},
attachment_type='text/x-diff')]}
with ForkedFakeService.from_client(client, archive):
response = client.get_messages('baz', display_type='text-only')
first_message = response['messages'][0]
self.assertEqual('foo', first_message['message_id'])
self.assertEqual('me', first_message['headers']['From'])
self.assertEqual('you', first_message['headers']['To'])
self.assertEqual('abcdefghi', first_message['body'])
def test_display_type_all(self):
client = GrackleClient('localhost', 8447)
archive = {
'baz': [
make_mime_message(
'foo', 'abcdefghi',
headers={'From': 'me', 'To': 'you'},
attachment_type='text/x-diff')]}
with ForkedFakeService.from_client(client, archive):
response = client.get_messages('baz', display_type='all')
first_message = response['messages'][0]
self.assertEqual('foo', first_message['message_id'])
self.assertEqual('me', first_message['headers']['From'])
self.assertEqual('you', first_message['headers']['To'])
self.assertEqual(
'abcdefghi\n\nattactment data.', first_message['body'])
|