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

« back to all changes in this revision

Viewing changes to grackle/tests/test_client.py

  • Committer: Aaron Bentley
  • Date: 2012-01-13 15:14:10 UTC
  • mto: (6.1.30 trunk)
  • mto: This revision was merged to the branch mainline in revision 45.
  • Revision ID: aaron@canonical.com-20120113151410-pexfwaq390oirhr2
Extract GrackleStore.

Show diffs side-by-side

added added

removed removed

Lines of Context:
34
34
    return threads.values()
35
35
 
36
36
 
37
 
class ForkedFake:
 
37
class GrackleStore:
38
38
 
39
 
    def __init__(self, port, messages=None):
40
 
        self.pid = None
41
 
        self.port = port
 
39
    def __init__(self, messages):
42
40
        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')
47
 
 
48
 
    def __enter__(self):
49
 
        pid = os.fork()
50
 
        if pid == 0:
51
 
            self.start_server()
52
 
        self.pid = pid
53
 
        os.read(self.read_end, 1)
54
 
        return
55
 
 
56
 
    def start_server(self):
57
 
        service = HTTPServer(('', self.port), FakeGrackleRequestHandler)
58
 
        service.messages = self.messages
59
 
        for archive_id, messages in service.messages.iteritems():
60
 
            for message in messages:
61
 
                message.setdefault('headers', {})
62
 
        self.is_ready()
63
 
        service.serve_forever()
64
 
 
65
 
    def __exit__(self, exc_type, exc_val, traceback):
66
 
        os.kill(self.pid, SIGKILL)
67
 
 
68
 
 
69
 
SUPPORTED_ORDERS = set(
70
 
    ['date', 'author', 'subject', 'thread_newest', 'thread_oldest',
71
 
     'thread_subject'])
72
 
 
73
 
 
74
 
class FakeGrackleRequestHandler(BaseHTTPRequestHandler):
75
 
 
76
 
    def do_POST(self):
77
 
        message = self.rfile.read(int(self.headers['content-length']))
78
 
        if message == 'This is a message':
79
 
            self.send_response(httplib.CREATED)
80
 
            self.end_headers()
81
 
            self.wfile.close()
82
 
        else:
83
 
            self.send_error(httplib.BAD_REQUEST)
84
 
 
85
 
    def do_GET(self):
86
 
        scheme, netloc, path, params, query_string, fragments = (
87
 
            urlparse(self.path))
88
 
        parts = path.split('/')
89
 
        if parts[1] == 'archive':
90
 
            self.get_messages(parts[2], query_string)
91
41
 
92
42
    def get_messages(self, archive_id, query_string):
93
43
        query = parse_qs(query_string)
94
44
        parameters = simplejson.loads(query['parameters'][0])
95
45
        order = parameters.get('order')
96
 
        messages = self.server.messages[archive_id]
 
46
        messages = self.messages[archive_id]
97
47
        if order is not None :
98
48
            if order not in SUPPORTED_ORDERS:
99
 
                self.send_response(httplib.BAD_REQUEST)
100
 
                self.wfile.write('Unsupported order')
101
 
                return
 
49
                raise UnsupportedOrder
102
50
            elif order.startswith('thread_'):
103
51
                threaded = threaded_messages(messages)
104
52
                messages = []
115
63
        messages = [m for m in messages
116
64
                    if 'message_ids' not in parameters or
117
65
                    m['message_id'] in parameters['message_ids']]
118
 
        self.send_response(httplib.OK)
119
 
        self.end_headers()
120
66
        limit = parameters.get('limit', 100)
121
67
        memo = parameters.get('memo')
122
68
        message_id_indices = dict(
143
89
                    (k, v) for k, v in message['headers'].iteritems()
144
90
                    if k in parameters['headers'])
145
91
                message['headers'] = headers
 
92
            max_body = parameters.get('max_body_length')
 
93
            if max_body is not None:
 
94
                message['body'] = message['body'][:max_body]
146
95
            new_messages.append(message)
147
96
        response = {
148
97
            'messages': new_messages,
149
98
            'next_memo': next_memo,
150
99
            'previous_memo': previous_memo
151
100
            }
152
 
        self.wfile.write(simplejson.dumps(response))
 
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
153
168
 
154
169
 
155
170
def fake_grackle_service(client, messages=None):
320
335
        first_message = response['messages'][0]
321
336
        self.assertEqual('foo', first_message['message_id'])
322
337
        self.assertEqual({'From': 'me', 'To': 'you'}, first_message['headers'])
 
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