~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-10 13:46:48 UTC
  • Revision ID: aaron@canonical.com-20120110134648-q991pmjj9jc05mr2
Actual fake service working.

Show diffs side-by-side

added added

removed removed

Lines of Context:
2
2
    HTTPServer,
3
3
    BaseHTTPRequestHandler,
4
4
    )
5
 
import contextlib
6
5
import os
 
6
from signal import SIGKILL
7
7
from StringIO import StringIO
8
8
from unittest import TestCase
9
9
 
 
10
from testtools import ExpectedException
 
11
 
10
12
from grackle import client
11
13
 
12
14
 
13
 
def fake_grackle_service():
14
 
    pid = os.fork()
15
 
    if pid != 0:
16
 
        return pid
17
 
    service = HTTPServer(('', 8435), BaseHTTPRequestHandler)
18
 
    service.handle_request()
19
 
    os._exit(0)
 
15
class Forked:
 
16
 
 
17
    def __init__(self, func_or_method):
 
18
        self.func_or_method = func_or_method
 
19
        self.pid = None
 
20
 
 
21
    def __enter__(self):
 
22
        pid = os.fork()
 
23
        if pid != 0:
 
24
            self.pid = pid
 
25
            return
 
26
        self.func_or_method()
 
27
 
 
28
 
 
29
    def __exit__(self, exc_type, exc_val, traceback):
 
30
        os.kill(self.pid, SIGKILL)
 
31
 
 
32
 
 
33
class FakeGrackleRequestHandler(BaseHTTPRequestHandler):
 
34
 
 
35
    def do_POST(self):
 
36
        message = self.rfile.read(int(self.headers['content-length']))
 
37
        if message == 'This is a message':
 
38
            self.send_response(200)
 
39
            self.end_headers()
 
40
            self.wfile.close()
 
41
        else:
 
42
            self.send_error(400)
 
43
 
 
44
 
 
45
def run_service():
 
46
    service = HTTPServer(('', 8435), FakeGrackleRequestHandler)
 
47
    service.serve_forever()
 
48
 
20
49
 
21
50
 
22
51
class TestPutMessage(TestCase):
23
52
 
24
53
    def test_put_message(self):
25
 
        service = fake_grackle_service()
26
 
        client.put_message('arch1', StringIO('This is a message'))
 
54
        with Forked(run_service):
 
55
            client.put_message('arch1', StringIO('This is a message'))
 
56
            with ExpectedException(Exception, 'wtf'):
 
57
                client.put_message('arch1', StringIO('This is not a message'))