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

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
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 testtools import ExpectedException

from grackle.client import (
    GrackleClient,
    UnparsableDateRange,
    UnsupportedDisplayType,
    UnsupportedOrder,
    )
from grackle.store import (
    MemoryStore,
    )


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': [],
        'replies': headers.get('in-reply-to', None),
        'body': body,
        }
    return message


def make_mime_message(message_id, body='body', headers=None, hidden=False,
                      attachment_type=None):
    message = MIMEMultipart()
    message.attach(MIMEText(body))
    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)
    return make_message(message_id, message.get_payload(), headers, hidden)


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 = MemoryStore(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)


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 Exception, error:
                self.send_response(
                    httplib.BAD_REQUEST, error.__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', 8420)
        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', 8430)
        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'])

    def test_date_range(self):
        client = GrackleClient('localhost', 8448)
        archive = {
            'baz': [
                make_mime_message(
                    'foo', 'abcdefghi', headers={'date': '2011-12-31'}),
                make_mime_message(
                    'bar', 'abcdefghi', headers={'date': '2012-01-01'}),
                make_mime_message(
                    'qux', 'abcdefghi', headers={'date': '2012-01-15'}),
                make_mime_message(
                    'naf', 'abcdefghi', headers={'date': '2012-01-31'}),
                make_mime_message(
                    'doh', 'abcdefghi', headers={'date': '2012-02-01'}),
                    ]}
        with ForkedFakeService.from_client(client, archive):
            response = client.get_messages(
                'baz', date_range='2012-01-01..2012-01-31')
        ids = sorted(m['message_id'] for m in response['messages'])
        self.assertEqual(['bar', 'naf', 'qux'], ids)

    def test_date_range_unparsabledaterange(self):
        client = GrackleClient('localhost', 8449)
        archive = {'baz': [make_message('foo', body=u'abcdefghi')]}
        with ForkedFakeService.from_client(client, archive):
            with ExpectedException(UnparsableDateRange, ''):
                client.get_messages('baz', date_range='2012-01-01')

    def test_date_range_unparsabledaterange_missing_part(self):
        client = GrackleClient('localhost', 8450)
        archive = {'baz': [make_message('foo', body=u'abcdefghi')]}
        with ForkedFakeService.from_client(client, archive):
            with ExpectedException(UnparsableDateRange, ''):
                client.get_messages('baz', date_range='2012-01-01..')

    def test_date_range_unparsabledaterange_extra_part(self):
        client = GrackleClient('localhost', 8451)
        archive = {'baz': [make_message('foo', body=u'abcdefghi')]}
        with ForkedFakeService.from_client(client, archive):
            with ExpectedException(UnparsableDateRange, ''):
                client.get_messages('baz', date_range='2012-01..12-02..12-03')