~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.6 by Aaron Bentley
Use pipe to ensure we only use HTTP once it's running.
22
class ForkedFake:
5 by Aaron Bentley
Actual fake service working.
23
6.1.6 by Aaron Bentley
Use pipe to ensure we only use HTTP once it's running.
24
    def __init__(self, port, messages=None):
5 by Aaron Bentley
Actual fake service working.
25
        self.pid = None
6.1.6 by Aaron Bentley
Use pipe to ensure we only use HTTP once it's running.
26
        self.port = port
27
        self.messages = messages
28
        self.read_end, self.write_end = os.pipe()
29
30
    def is_ready(self):
31
        os.write(self.write_end, 'asdf')
5 by Aaron Bentley
Actual fake service working.
32
33
    def __enter__(self):
34
        pid = os.fork()
6.1.6 by Aaron Bentley
Use pipe to ensure we only use HTTP once it's running.
35
        if pid == 0:
36
            self.start_server()
37
        self.pid = pid
38
        os.read(self.read_end, 1)
39
        return
5 by Aaron Bentley
Actual fake service working.
40
6.1.6 by Aaron Bentley
Use pipe to ensure we only use HTTP once it's running.
41
    def start_server(self):
42
        service = HTTPServer(('', self.port), FakeGrackleRequestHandler)
43
        service.messages = self.messages
44
        self.is_ready()
45
        service.serve_forever()
5 by Aaron Bentley
Actual fake service working.
46
47
    def __exit__(self, exc_type, exc_val, traceback):
48
        os.kill(self.pid, SIGKILL)
49
50
6.1.15 by Aaron Bentley
Test unsupported orders.
51
SUPPORTED_ORDERS = set(['date'])
52
53
5 by Aaron Bentley
Actual fake service working.
54
class FakeGrackleRequestHandler(BaseHTTPRequestHandler):
55
6.1.5 by Aaron Bentley
Start working on GET.
56
    def do_POST(self):
5 by Aaron Bentley
Actual fake service working.
57
        message = self.rfile.read(int(self.headers['content-length']))
58
        if message == 'This is a message':
6 by Aaron Bentley
Use constants.
59
            self.send_response(httplib.CREATED)
5 by Aaron Bentley
Actual fake service working.
60
            self.end_headers()
61
            self.wfile.close()
62
        else:
6 by Aaron Bentley
Use constants.
63
            self.send_error(httplib.BAD_REQUEST)
5 by Aaron Bentley
Actual fake service working.
64
6.1.7 by Aaron Bentley
Retrieve messages.
65
    def do_GET(self):
6.1.9 by Aaron Bentley
Test filtering by message-id.
66
        scheme, netloc, path, params, query_string, fragments = (
67
            urlparse(self.path))
6.1.7 by Aaron Bentley
Retrieve messages.
68
        archive = os.path.split(path)[1]
6.1.9 by Aaron Bentley
Test filtering by message-id.
69
        query = parse_qs(query_string)
70
        parameters = simplejson.loads(query['parameters'][0])
71
        messages = [m for m in self.server.messages[archive] if 'message_ids'
6.1.11 by Aaron Bentley
Switch hyphens to underscores.
72
                    not in parameters or m['message_id'] in
6.1.9 by Aaron Bentley
Test filtering by message-id.
73
                    parameters['message_ids']]
6.1.14 by Aaron Bentley
Support order by date
74
        if 'order' in parameters:
6.1.15 by Aaron Bentley
Test unsupported orders.
75
            if parameters['order'] not in SUPPORTED_ORDERS:
76
                self.send_response(httplib.BAD_REQUEST)
77
                self.wfile.write('Unsupported order')
78
                return
6.1.14 by Aaron Bentley
Support order by date
79
            messages.sort(key=lambda m: m[parameters['order']])
6.1.15 by Aaron Bentley
Test unsupported orders.
80
        self.send_response(httplib.OK)
81
        self.end_headers()
6.1.13 by Aaron Bentley
Implement memo/limit support.
82
        limit = parameters.get('limit', 100)
83
        memo = parameters.get('memo')
84
        message_id_indices = dict(
85
            (m['message_id'], idx) for idx, m in enumerate(messages))
86
        if memo is None:
87
            start = 0
88
        else:
89
            start = message_id_indices[memo.encode('rot13')]
90
        if start > 0:
91
            previous_memo = messages[start - 1]['message_id'].encode('rot13')
92
        else:
93
            previous_memo = None
94
        end = min(start + limit, len(messages))
95
        if end < len(messages):
96
            next_memo = messages[end]['message_id'].encode('rot13')
97
        else:
98
            next_memo = None
99
        messages = messages[start:end]
6.1.10 by Aaron Bentley
Include next_memo, previous_memo in get_messages response.
100
        response = {
101
            'messages': messages,
6.1.13 by Aaron Bentley
Implement memo/limit support.
102
            'next_memo': next_memo,
103
            'previous_memo': previous_memo
6.1.10 by Aaron Bentley
Include next_memo, previous_memo in get_messages response.
104
            }
105
        self.wfile.write(simplejson.dumps(response))
6.1.7 by Aaron Bentley
Retrieve messages.
106
5 by Aaron Bentley
Actual fake service working.
107
6.1.5 by Aaron Bentley
Start working on GET.
108
def fake_grackle_service(client, messages=None):
109
    if messages is None:
110
        messages = {}
6.1.6 by Aaron Bentley
Use pipe to ensure we only use HTTP once it's running.
111
    return ForkedFake(client.port, messages)
6.1.5 by Aaron Bentley
Start working on GET.
112
4 by Aaron Bentley
Initial test.
113
3 by Aaron Bentley
Add test framework.
114
class TestPutMessage(TestCase):
115
116
    def test_put_message(self):
6.1.6 by Aaron Bentley
Use pipe to ensure we only use HTTP once it's running.
117
        client = GrackleClient('localhost', 8436)
6.1.5 by Aaron Bentley
Start working on GET.
118
        with fake_grackle_service(client):
6.1.1 by Aaron Bentley
Fix URLs etc.
119
            client.put_message('arch1', 'asdf', StringIO('This is a message'))
5 by Aaron Bentley
Actual fake service working.
120
            with ExpectedException(Exception, 'wtf'):
6.1.1 by Aaron Bentley
Fix URLs etc.
121
                client.put_message('arch1', 'asdf',
122
                    StringIO('This is not a message'))
6.1.5 by Aaron Bentley
Start working on GET.
123
124
125
class TestGetMessages(TestCase):
126
6.1.14 by Aaron Bentley
Support order by date
127
    def assertIDOrder(self, ids, messages):
128
        self.assertEqual(ids, [m['message_id'] for m in messages])
129
6.1.13 by Aaron Bentley
Implement memo/limit support.
130
    def assertMessageIDs(self, ids, messages):
6.1.14 by Aaron Bentley
Support order by date
131
        self.assertIDOrder(
132
            sorted(ids), sorted(messages, key=lambda m:m['message_id']))
6.1.13 by Aaron Bentley
Implement memo/limit support.
133
6.1.5 by Aaron Bentley
Start working on GET.
134
    def test_get_messages(self):
135
        client = GrackleClient('localhost', 8435)
136
        with fake_grackle_service(client,
137
            {'baz':
6.1.11 by Aaron Bentley
Switch hyphens to underscores.
138
            [{'message_id': 'foo'},
139
             {'message_id': 'bar'}]}):
6.1.9 by Aaron Bentley
Test filtering by message-id.
140
            response = client.get_messages('baz')
6.1.11 by Aaron Bentley
Switch hyphens to underscores.
141
        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.
142
            response['messages']))
143
        self.assertIs(None, response['next_memo'])
144
        self.assertIs(None, response['previous_memo'])
6.1.9 by Aaron Bentley
Test filtering by message-id.
145
146
    def test_get_messages_by_id(self):
147
        client = GrackleClient('localhost', 8437)
148
        with fake_grackle_service(client,
149
            {'baz':
6.1.11 by Aaron Bentley
Switch hyphens to underscores.
150
            [{'message_id': 'foo'},
151
             {'message_id': 'bar'}]}):
6.1.10 by Aaron Bentley
Include next_memo, previous_memo in get_messages response.
152
            response = client.get_messages('baz', message_ids=['foo'])
153
        message, = response['messages']
6.1.11 by Aaron Bentley
Switch hyphens to underscores.
154
        self.assertEqual('foo', message['message_id'])
6.1.13 by Aaron Bentley
Implement memo/limit support.
155
156
    def test_get_messages_batching(self):
6.1.14 by Aaron Bentley
Support order by date
157
        client = GrackleClient('localhost', 8438)
6.1.13 by Aaron Bentley
Implement memo/limit support.
158
        with fake_grackle_service(client,
159
            {'baz':
160
            [{'message_id': 'foo'},
161
             {'message_id': 'bar'}]}):
162
            response = client.get_messages('baz', limit=1)
163
            self.assertEqual(1, len(response['messages']))
164
            messages = response['messages']
165
            response = client.get_messages(
166
                'baz', limit=1, memo=response['next_memo'])
167
            self.assertEqual(1, len(response['messages']))
168
            messages.extend(response['messages'])
169
            self.assertMessageIDs(['foo', 'bar'], messages)
6.1.14 by Aaron Bentley
Support order by date
170
171
    def test_get_messages_date_order(self):
172
        client = GrackleClient('localhost', 8439)
173
        with fake_grackle_service(client,
174
                {'baz': [{'message_id': 'foo', 'date': '2011-03-25'},
175
                 {'message_id': 'bar', 'date': '2011-03-24'}]}):
176
            response = client.get_messages('baz')
177
            self.assertIDOrder(['foo', 'bar'], response['messages'])
178
            response = client.get_messages('baz', order='date')
179
            self.assertIDOrder(['bar', 'foo'], response['messages'])
6.1.15 by Aaron Bentley
Test unsupported orders.
180
181
    def test_get_messages_unsupported_order(self):
182
        client = GrackleClient('localhost', 8439)
183
        with fake_grackle_service(client,
184
                {'baz': [{'message_id': 'foo', 'date': '2011-03-25'},
185
                 {'message_id': 'bar', 'date': '2011-03-24'}]}):
186
            with ExpectedException(UnsupportedOrder):
187
                client.get_messages('baz', order='nonsense')