~didrocks/unity/altf10

4 by Aaron Bentley
Initial test.
1
from BaseHTTPServer import (
2
    HTTPServer,
3
    BaseHTTPRequestHandler,
4
    )
6 by Aaron Bentley
Use constants.
5
import httplib
4 by Aaron Bentley
Initial test.
6
import os
5 by Aaron Bentley
Actual fake service working.
7
from signal import SIGKILL
13 by Aaron Bentley
Retrieve messages.
8
import simplejson
4 by Aaron Bentley
Initial test.
9
from StringIO import StringIO
3 by Aaron Bentley
Add test framework.
10
from unittest import TestCase
13 by Aaron Bentley
Retrieve messages.
11
from urlparse import urlparse
15 by Aaron Bentley
Test filtering by message-id.
12
from urlparse import parse_qs
3 by Aaron Bentley
Add test framework.
13
5 by Aaron Bentley
Actual fake service working.
14
from testtools import ExpectedException
15
8 by Aaron Bentley
Test message path.
16
from grackle.client import (
17
    GrackleClient,
21 by Aaron Bentley
Test unsupported orders.
18
    UnsupportedOrder,
8 by Aaron Bentley
Test message path.
19
    )
4 by Aaron Bentley
Initial test.
20
21
22 by Aaron Bentley
Order by thread subject.
22
def threaded_messages(messages):
23
    threads = {}
24
    count = 0
25
    pending = []
26
    for message in messages:
27
        if message.get('in_reply_to') is None:
28
            threads[message['message_id']] = [message]
29
            count += 1
30
        else:
31
            pending.append(message)
32
    for message in pending:
33
        threads[message['in_reply_to']].append(message)
34
    return threads.values()
35
36
28 by Aaron Bentley
Extract GrackleStore.
37
class GrackleStore:
5 by Aaron Bentley
Actual fake service working.
38
28 by Aaron Bentley
Extract GrackleStore.
39
    def __init__(self, messages):
12 by Aaron Bentley
Use pipe to ensure we only use HTTP once it's running.
40
        self.messages = messages
26 by Aaron Bentley
Implement an archive namespace.
41
42
    def get_messages(self, archive_id, query_string):
15 by Aaron Bentley
Test filtering by message-id.
43
        query = parse_qs(query_string)
44
        parameters = simplejson.loads(query['parameters'][0])
22 by Aaron Bentley
Order by thread subject.
45
        order = parameters.get('order')
28 by Aaron Bentley
Extract GrackleStore.
46
        messages = self.messages[archive_id]
22 by Aaron Bentley
Order by thread subject.
47
        if order is not None :
48
            if order not in SUPPORTED_ORDERS:
28 by Aaron Bentley
Extract GrackleStore.
49
                raise UnsupportedOrder
23 by Aaron Bentley
Support thread_oldest order.
50
            elif order.startswith('thread_'):
22 by Aaron Bentley
Order by thread subject.
51
                threaded = threaded_messages(messages)
52
                messages = []
23 by Aaron Bentley
Support thread_oldest order.
53
                if order == 'thread_subject':
54
                    threaded.sort(key=lambda t: t[0]['subject'])
55
                if order == 'thread_oldest':
56
                    threaded.sort(key=lambda t: min(m['date'] for m in t))
24 by Aaron Bentley
Support thread_newest threading.
57
                if order == 'thread_newest':
58
                    threaded.sort(key=lambda t: max(m['date'] for m in t))
22 by Aaron Bentley
Order by thread subject.
59
                for thread in threaded:
60
                    messages.extend(thread)
61
            else:
23 by Aaron Bentley
Support thread_oldest order.
62
                messages.sort(key=lambda m: m[order])
22 by Aaron Bentley
Order by thread subject.
63
        messages = [m for m in messages
64
                    if 'message_ids' not in parameters or
65
                    m['message_id'] in parameters['message_ids']]
19 by Aaron Bentley
Implement memo/limit support.
66
        limit = parameters.get('limit', 100)
67
        memo = parameters.get('memo')
68
        message_id_indices = dict(
69
            (m['message_id'], idx) for idx, m in enumerate(messages))
70
        if memo is None:
71
            start = 0
72
        else:
73
            start = message_id_indices[memo.encode('rot13')]
74
        if start > 0:
75
            previous_memo = messages[start - 1]['message_id'].encode('rot13')
76
        else:
77
            previous_memo = None
78
        end = min(start + limit, len(messages))
79
        if end < len(messages):
80
            next_memo = messages[end]['message_id'].encode('rot13')
81
        else:
82
            next_memo = None
83
        messages = messages[start:end]
27 by Aaron Bentley
get_messages supports header parameter.
84
        new_messages = []
85
        for message in messages:
86
            message = dict(message)
87
            if 'headers' in parameters:
88
                headers = dict(
89
                    (k, v) for k, v in message['headers'].iteritems()
90
                    if k in parameters['headers'])
91
                message['headers'] = headers
28 by Aaron Bentley
Extract GrackleStore.
92
            max_body = parameters.get('max_body_length')
93
            if max_body is not None:
94
                message['body'] = message['body'][:max_body]
27 by Aaron Bentley
get_messages supports header parameter.
95
            new_messages.append(message)
16 by Aaron Bentley
Include next_memo, previous_memo in get_messages response.
96
        response = {
27 by Aaron Bentley
get_messages supports header parameter.
97
            'messages': new_messages,
19 by Aaron Bentley
Implement memo/limit support.
98
            'next_memo': next_memo,
99
            'previous_memo': previous_memo
16 by Aaron Bentley
Include next_memo, previous_memo in get_messages response.
100
            }
28 by Aaron Bentley
Extract GrackleStore.
101
        return response
102
103
104
105
class ForkedFake:
106
107
    def __init__(self, port, messages=None):
108
        self.pid = None
109
        self.port = port
110
        self.messages = messages
111
        self.read_end, self.write_end = os.pipe()
112
113
    def is_ready(self):
114
        os.write(self.write_end, 'asdf')
115
116
    def __enter__(self):
117
        pid = os.fork()
118
        if pid == 0:
119
            self.start_server()
120
        self.pid = pid
121
        os.read(self.read_end, 1)
122
        return
123
124
    def start_server(self):
125
        service = HTTPServer(('', self.port), FakeGrackleRequestHandler)
126
        service.store = GrackleStore(self.messages)
127
        for archive_id, messages in service.store.messages.iteritems():
128
            for message in messages:
129
                message.setdefault('headers', {})
130
        self.is_ready()
131
        service.serve_forever()
132
133
    def __exit__(self, exc_type, exc_val, traceback):
134
        os.kill(self.pid, SIGKILL)
135
136
137
SUPPORTED_ORDERS = set(
138
    ['date', 'author', 'subject', 'thread_newest', 'thread_oldest',
139
     'thread_subject'])
140
141
142
class FakeGrackleRequestHandler(BaseHTTPRequestHandler):
143
144
    def do_POST(self):
145
        message = self.rfile.read(int(self.headers['content-length']))
146
        if message == 'This is a message':
147
            self.send_response(httplib.CREATED)
148
            self.end_headers()
149
            self.wfile.close()
150
        else:
151
            self.send_error(httplib.BAD_REQUEST)
152
153
    def do_GET(self):
154
        scheme, netloc, path, params, query_string, fragments = (
155
            urlparse(self.path))
156
        parts = path.split('/')
157
        if parts[1] == 'archive':
158
            try:
159
                response = self.server.store.get_messages(
160
                    parts[2], query_string)
161
                self.send_response(httplib.OK)
162
                self.end_headers()
163
                self.wfile.write(simplejson.dumps(response))
164
            except UnsupportedOrder:
165
                self.send_response(httplib.BAD_REQUEST)
166
                self.wfile.write('Unsupported order')
167
                return
13 by Aaron Bentley
Retrieve messages.
168
5 by Aaron Bentley
Actual fake service working.
169
11 by Aaron Bentley
Start working on GET.
170
def fake_grackle_service(client, messages=None):
171
    if messages is None:
172
        messages = {}
12 by Aaron Bentley
Use pipe to ensure we only use HTTP once it's running.
173
    return ForkedFake(client.port, messages)
11 by Aaron Bentley
Start working on GET.
174
4 by Aaron Bentley
Initial test.
175
3 by Aaron Bentley
Add test framework.
176
class TestPutMessage(TestCase):
177
178
    def test_put_message(self):
12 by Aaron Bentley
Use pipe to ensure we only use HTTP once it's running.
179
        client = GrackleClient('localhost', 8436)
11 by Aaron Bentley
Start working on GET.
180
        with fake_grackle_service(client):
7 by Aaron Bentley
Fix URLs etc.
181
            client.put_message('arch1', 'asdf', StringIO('This is a message'))
5 by Aaron Bentley
Actual fake service working.
182
            with ExpectedException(Exception, 'wtf'):
7 by Aaron Bentley
Fix URLs etc.
183
                client.put_message('arch1', 'asdf',
184
                    StringIO('This is not a message'))
11 by Aaron Bentley
Start working on GET.
185
186
187
class TestGetMessages(TestCase):
188
20 by Aaron Bentley
Support order by date
189
    def assertIDOrder(self, ids, messages):
190
        self.assertEqual(ids, [m['message_id'] for m in messages])
191
19 by Aaron Bentley
Implement memo/limit support.
192
    def assertMessageIDs(self, ids, messages):
20 by Aaron Bentley
Support order by date
193
        self.assertIDOrder(
194
            sorted(ids), sorted(messages, key=lambda m:m['message_id']))
19 by Aaron Bentley
Implement memo/limit support.
195
11 by Aaron Bentley
Start working on GET.
196
    def test_get_messages(self):
197
        client = GrackleClient('localhost', 8435)
198
        with fake_grackle_service(client,
199
            {'baz':
17 by Aaron Bentley
Switch hyphens to underscores.
200
            [{'message_id': 'foo'},
201
             {'message_id': 'bar'}]}):
15 by Aaron Bentley
Test filtering by message-id.
202
            response = client.get_messages('baz')
17 by Aaron Bentley
Switch hyphens to underscores.
203
        self.assertEqual(['bar', 'foo'], sorted(m['message_id'] for m in
16 by Aaron Bentley
Include next_memo, previous_memo in get_messages response.
204
            response['messages']))
205
        self.assertIs(None, response['next_memo'])
206
        self.assertIs(None, response['previous_memo'])
15 by Aaron Bentley
Test filtering by message-id.
207
208
    def test_get_messages_by_id(self):
209
        client = GrackleClient('localhost', 8437)
210
        with fake_grackle_service(client,
211
            {'baz':
17 by Aaron Bentley
Switch hyphens to underscores.
212
            [{'message_id': 'foo'},
213
             {'message_id': 'bar'}]}):
16 by Aaron Bentley
Include next_memo, previous_memo in get_messages response.
214
            response = client.get_messages('baz', message_ids=['foo'])
215
        message, = response['messages']
17 by Aaron Bentley
Switch hyphens to underscores.
216
        self.assertEqual('foo', message['message_id'])
19 by Aaron Bentley
Implement memo/limit support.
217
218
    def test_get_messages_batching(self):
20 by Aaron Bentley
Support order by date
219
        client = GrackleClient('localhost', 8438)
19 by Aaron Bentley
Implement memo/limit support.
220
        with fake_grackle_service(client,
221
            {'baz':
222
            [{'message_id': 'foo'},
223
             {'message_id': 'bar'}]}):
224
            response = client.get_messages('baz', limit=1)
225
            self.assertEqual(1, len(response['messages']))
226
            messages = response['messages']
227
            response = client.get_messages(
228
                'baz', limit=1, memo=response['next_memo'])
229
            self.assertEqual(1, len(response['messages']))
230
            messages.extend(response['messages'])
231
            self.assertMessageIDs(['foo', 'bar'], messages)
20 by Aaron Bentley
Support order by date
232
22 by Aaron Bentley
Order by thread subject.
233
    def get_messages_member_order_test(self, key):
20 by Aaron Bentley
Support order by date
234
        client = GrackleClient('localhost', 8439)
235
        with fake_grackle_service(client,
22 by Aaron Bentley
Order by thread subject.
236
                {'baz': [{'message_id': 'foo', key: '2011-03-25'},
237
                 {'message_id': 'bar', key: '2011-03-24'}]}):
20 by Aaron Bentley
Support order by date
238
            response = client.get_messages('baz')
239
            self.assertIDOrder(['foo', 'bar'], response['messages'])
22 by Aaron Bentley
Order by thread subject.
240
            response = client.get_messages('baz', order=key)
20 by Aaron Bentley
Support order by date
241
            self.assertIDOrder(['bar', 'foo'], response['messages'])
21 by Aaron Bentley
Test unsupported orders.
242
22 by Aaron Bentley
Order by thread subject.
243
    def test_get_messages_date_order(self):
244
        self.get_messages_member_order_test('date')
245
246
    def test_get_messages_author_order(self):
247
        self.get_messages_member_order_test('author')
248
249
    def test_get_messages_subject_order(self):
250
        self.get_messages_member_order_test('subject')
251
252
    def test_get_messages_thread_subject_order(self):
253
        client = GrackleClient('localhost', 8439)
254
        with fake_grackle_service(client, {'baz': [
255
            {'message_id': 'bar', 'subject': 'y'},
256
            {'message_id': 'qux', 'subject': 'z'},
257
            {'message_id': 'foo', 'subject': 'x', 'in_reply_to': 'qux'},
258
            ]}):
259
            response = client.get_messages('baz')
260
            self.assertIDOrder(['bar', 'qux', 'foo'], response['messages'])
261
            response = client.get_messages('baz', order='subject')
262
            self.assertIDOrder(['foo', 'bar', 'qux'], response['messages'])
263
            response = client.get_messages('baz', order='thread_subject')
264
            self.assertIDOrder(['bar', 'qux', 'foo'], response['messages'])
265
23 by Aaron Bentley
Support thread_oldest order.
266
    def test_get_messages_thread_oldest_order(self):
267
        client = GrackleClient('localhost', 8439)
268
        with fake_grackle_service(client, {'baz': [
269
            {'message_id': 'bar', 'date': 'x'},
270
            {'message_id': 'qux', 'date': 'z'},
271
            {'message_id': 'foo', 'date': 'y', 'in_reply_to': 'qux'},
272
            ]}):
273
            response = client.get_messages('baz')
274
            self.assertIDOrder(['bar', 'qux', 'foo'], response['messages'])
275
            response = client.get_messages('baz', order='date')
276
            self.assertIDOrder(['bar', 'foo', 'qux'], response['messages'])
277
            response = client.get_messages('baz', order='thread_oldest')
278
            self.assertIDOrder(['bar', 'qux', 'foo'], response['messages'])
279
24 by Aaron Bentley
Support thread_newest threading.
280
    def test_get_messages_thread_newest_order(self):
281
        client = GrackleClient('localhost', 8439)
282
        with fake_grackle_service(client, {'baz': [
283
            {'message_id': 'bar', 'date': 'x'},
284
            {'message_id': 'qux', 'date': 'w'},
285
            {'message_id': 'foo', 'date': 'y', 'in_reply_to': 'bar'},
286
            {'message_id': 'baz', 'date': 'z', 'in_reply_to': 'qux'},
287
            ]}):
288
            response = client.get_messages('baz', order='date')
289
            self.assertIDOrder(
290
                ['qux', 'bar', 'foo', 'baz'], response['messages'])
291
            response = client.get_messages('baz', order='thread_newest')
292
            self.assertIDOrder(
293
                ['bar', 'foo', 'qux', 'baz'], response['messages'])
294
21 by Aaron Bentley
Test unsupported orders.
295
    def test_get_messages_unsupported_order(self):
296
        client = GrackleClient('localhost', 8439)
297
        with fake_grackle_service(client,
298
                {'baz': [{'message_id': 'foo', 'date': '2011-03-25'},
299
                 {'message_id': 'bar', 'date': '2011-03-24'}]}):
300
            with ExpectedException(UnsupportedOrder):
301
                client.get_messages('baz', order='nonsense')
27 by Aaron Bentley
get_messages supports header parameter.
302
303
    def test_get_messages_headers_no_headers(self):
304
        client = GrackleClient('localhost', 8440)
305
        with fake_grackle_service(client,
306
            {'baz': [
307
                {'message_id': 'foo'}
308
            ]}):
309
            response = client.get_messages('baz', headers=[
310
                'Subject', 'Date', 'X-Launchpad-Message-Rationale'])
311
        first_message = response['messages'][0]
312
        self.assertEqual('foo', first_message['message_id'])
313
        self.assertEqual({}, first_message['headers'])
314
315
    def test_get_messages_headers_exclude_headers(self):
316
        client = GrackleClient('localhost', 8440)
317
        with fake_grackle_service(client,
318
            {'baz': [
319
                {'message_id': 'foo', 'headers': {'From': 'me'}}
320
            ]}):
321
            response = client.get_messages('baz', headers=[
322
                'Subject', 'Date', 'X-Launchpad-Message-Rationale'])
323
        first_message = response['messages'][0]
324
        self.assertEqual('foo', first_message['message_id'])
325
        self.assertEqual({}, first_message['headers'])
326
327
    def test_get_messages_headers_include_headers(self):
328
        client = GrackleClient('localhost', 8440)
329
        with fake_grackle_service(client,
330
            {'baz': [
331
                {'message_id': 'foo', 'headers': {'From': 'me', 'To': 'you'}}
332
            ]}):
333
            response = client.get_messages('baz', headers=[
334
                'From', 'To'])
335
        first_message = response['messages'][0]
336
        self.assertEqual('foo', first_message['message_id'])
337
        self.assertEqual({'From': 'me', 'To': 'you'}, first_message['headers'])
28 by Aaron Bentley
Extract GrackleStore.
338
339
    def test_get_messages_max_body_length(self):
340
        client = GrackleClient('localhost', 8440)
341
        with fake_grackle_service(client,
342
            {'baz': [
343
                {'message_id': 'foo', 'body': u'abcdefghi'}
344
            ]}):
345
            response = client.get_messages('baz', max_body_length=3)
346
        first_message = response['messages'][0]
347
        self.assertEqual('abc', first_message['body'])
348