~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
from BaseHTTPServer import (
    HTTPServer,
    BaseHTTPRequestHandler,
    )
import httplib
import os
from signal import SIGKILL
from StringIO import StringIO
from unittest import TestCase

from testtools import ExpectedException

from grackle.client import (
    GrackleClient,
    )


class Forked:

    def __init__(self, func_or_method, *args):
        self.func_or_method = func_or_method
        self.pid = None
        self.args = args

    def __enter__(self):
        pid = os.fork()
        if pid != 0:
            self.pid = pid
            return
        self.func_or_method(*self.args)


    def __exit__(self, exc_type, exc_val, traceback):
        os.kill(self.pid, SIGKILL)


class FakeGrackleRequestHandler(BaseHTTPRequestHandler):

    def do_POST(self):
        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 run_service(port, messages):
    service = HTTPServer(('', port), FakeGrackleRequestHandler)
    service.messages = messages
    service.serve_forever()


def fake_grackle_service(client, messages=None):
    if messages is None:
        messages = {}
    return Forked(run_service, client.port, messages)


class TestPutMessage(TestCase):

    def test_put_message(self):
        client = GrackleClient('localhost', 8435)
        with fake_grackle_service(client):
            import time; time.sleep(0.5)
            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 test_get_messages(self):
        client = GrackleClient('localhost', 8435)
        with fake_grackle_service(client,
            {'baz':
            [{'message-id': 'foo'},
             {'message-id': 'bar'}]}):
            response = client.get_messages('baz')
        self.assertEqual(['bar', 'foo'], sorted(response.keys()))