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