Initial code checkin
[grml-unittests.git] / webserver.py
1 #!/usr/bin/env python
2 import sys
3 from os import curdir, sep
4 from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
5 from optparse import OptionParser
6
7
8 USAGE = "Usage: %prog [options] "
9 parser = OptionParser(usage=USAGE)
10 parser.add_option("-p", "--port", dest="port",
11                   help="http server port", default="8080")
12 parser.add_option("-t", "--test", dest="test_name",
13                   help="test name", metavar="NAME")
14
15
16 # ugly ;0
17 options = None
18 error = 0
19 keep_running = True
20 message = None
21
22 class MyHandler(BaseHTTPRequestHandler):
23     def do_GET(self):
24         global keep_running
25         global message
26         global error
27         if self.path.endswith("FAIL"):
28             self.send_error(404, 'Failed')
29             keep_running = False
30             error = 1
31             message = "FAILED"
32             return
33
34         if self.path.endswith("DONE"):
35             self.send_error(404, 'done')
36             error = 0
37             keep_running = False
38             message = "OK"
39             return
40         try:
41                 f = open(curdir + sep + self.path)
42                 self.send_response(200)
43                 self.end_headers()
44                 self.wfile.write(f.read())
45                 f.close()
46                 return
47         except IOError:
48             self.send_error(404,'File Not Found: %s' % self.path)
49     def log_message(self, *args):
50         pass
51     def log_error(self, *args):
52         pass
53
54
55 def main():
56     global options
57     (options, args) = parser.parse_args()
58     if not options.test_name:
59         parser.error("Define test name")
60         sys.exit(1)
61
62     try:
63         server = HTTPServer(('', int(options.port)), MyHandler)
64         while keep_running:
65             server.handle_request()
66         sys.stderr.write("%s: %s\n" % (options.test_name, message))
67         sys.exit(error)
68     except KeyboardInterrupt:
69         server.socket.close()
70
71 if __name__ == '__main__':
72     main()