aboutsummaryrefslogtreecommitdiffstats
path: root/test/functional/util/dummy_http.py
blob: 5a04b3664c0a5ccca6db962167b9d2b352362bb0 (plain)
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
#!/usr/bin/env python

import BaseHTTPServer
import time
import os
import sys
import signal

PORT = 18080
HOST_NAME = '127.0.0.1'

PID = "/tmp/dummy_http.pid"


class MyHandler(BaseHTTPServer.BaseHTTPRequestHandler):

    def do_HEAD(self):
        self.send_response(200)
        self.send_header("Content-type", "text/html")
        self.end_headers()

    def do_GET(self):
        """Respond to a GET request."""
        self.send_response(200)
        self.send_header("Content-type", "text/plain")
        self.end_headers()
        self.wfile.write("hello world")

    def do_POST(self):
        """Respond to a GET request."""
        self.send_response(200)
        self.send_header("Content-type", "text/plain")
        self.end_headers()
        self.wfile.write("hello post")


class MyHttp(BaseHTTPServer.HTTPServer):
    def __init__(self, server_address, RequestHandlerClass, bind_and_activate=False):
        BaseHTTPServer.HTTPServer.__init__(self, server_address, RequestHandlerClass, bind_and_activate)
        self.keep_running = True

    def run(self):
        self.server_bind()
        self.server_activate()

        with open(PID, 'w+') as f:
            f.write(str(os.getpid()))
            f.close()

        while self.keep_running:
            try:
                self.handle_request()
            except Exception:
                pass

    def stop(self):
        self.keep_running = False
        self.server_close()


if __name__ == '__main__':
    server_class = BaseHTTPServer.HTTPServer
    httpd = MyHttp((HOST_NAME, PORT), MyHandler)
    httpd.allow_reuse_address = True
    httpd.timeout = 1

    def alarm_handler(signum, frame):
        httpd.stop()

    signal.signal(signal.SIGALRM, alarm_handler)
    signal.signal(signal.SIGTERM, alarm_handler)
    signal.alarm(5)

    try:
        httpd.run()
    except KeyboardInterrupt:
        pass
    httpd.server_close()