Some lvm specific basic tests
[grml-unittests.git] / webserver.py
1 #!/usr/bin/env python
2 import sys
3 import select
4 from os import curdir, sep
5 from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
6 from optparse import OptionParser
7
8
9 USAGE = "Usage: %prog [options] "
10 parser = OptionParser(usage=USAGE)
11 parser.add_option("-p", "--port", dest="port",
12                   help="http server port", default="8080")
13 parser.add_option("-t", "--test", dest="test_name",
14                   help="test name", metavar="NAME")
15
16
17 # ugly ;0
18 options = None
19 return_value = 0
20 keep_running = True
21 message = None
22
23 class MyHandler(BaseHTTPRequestHandler):
24
25     def stop(self, msg, retval):
26         global keep_running
27         global message
28         global error
29         keep_running=False
30         message=msg
31         return_value=retval
32         return
33
34
35     def do_POST(self):
36         data = ""
37         length = self.headers.getheader('content-length')
38         try:
39             nbytes = int(length)
40         except (TypeError, ValueError):
41             nbytes = 0
42         if nbytes > 0:
43             data = self.rfile.read(nbytes)
44         while select.select([self.rfile._sock], [], [], 0)[0]:
45             if not self.rfile._sock.recv(1):
46                 break
47
48         if self.path.endswith("FAIL"):
49             self.stop("FAILED - %s" % data, 1)
50             return
51
52         if self.path.endswith("DONE"):
53             self.stop("OK - %s" % data, 0)
54             return
55
56
57     def do_GET(self):
58         if self.path.endswith("FAIL"):
59             self.stop("FAILED", 1)
60             return
61
62         if self.path.endswith("DONE"):
63             self.stop("OK", 0)
64             return
65         try:
66             f = open(curdir + sep + self.path)
67             self.send_response(200)
68             self.end_headers()
69             self.wfile.write(f.read())
70             f.close()
71             return
72         except IOError:
73             self.send_error(404,'File Not Found: %s' % self.path)
74     def log_message(self, *args):
75         pass
76     def log_error(self, *args):
77         pass
78
79
80 def main():
81     global options
82     (options, args) = parser.parse_args()
83     if not options.test_name:
84         parser.error("Define test name")
85         sys.exit(1)
86
87     try:
88         server = HTTPServer(('', int(options.port)), MyHandler)
89         while keep_running:
90             server.handle_request()
91         sys.stderr.write("%s: %s\n" % (options.test_name, message))
92         sys.exit(return_value)
93     except KeyboardInterrupt:
94         server.socket.close()
95
96 if __name__ == '__main__':
97     main()