~unity-2d-team/unity-2d/Shell-MultiMonitor

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