Start development series 0.46-post
[zeroinstall/solver.git] / tests / server.py
blobc6771e9e0e3d39815b5871aaa251b5638aadda2b
1 #!/usr/bin/env python
2 import os, sys, urlparse
3 import BaseHTTPServer
4 import traceback
6 next_step = None
8 class Give404:
9 def __init__(self, path):
10 self.path = path
12 def __str__(self):
13 return self.path
15 def __repr__(self):
16 return "404 on " + self.path
18 class MyHandler(BaseHTTPServer.BaseHTTPRequestHandler):
19 def do_GET(self):
20 parsed = urlparse.urlparse(self.path)
22 leaf = os.path.basename(parsed.path)
24 acceptable = dict([(str(x), x) for x in next_step])
26 resp = acceptable.get(parsed.path, None) or \
27 acceptable.get(leaf, None) or \
28 acceptable.get('*', None)
30 if not resp:
31 self.send_error(404, "Expected %s; got %s" % (next_step, parsed.path))
32 elif parsed.path.startswith('/key-info/'):
33 self.send_response(200)
34 self.end_headers()
35 self.wfile.write('<key-lookup/>')
36 self.wfile.close()
37 elif os.path.exists(leaf) and not isinstance(resp, Give404):
38 self.send_response(200)
39 self.end_headers()
40 self.wfile.write(file(leaf).read())
41 self.wfile.close()
42 else:
43 self.send_error(404, "Missing: %s" % leaf)
45 def handle_requests(*script):
46 server_address = ('localhost', 8000)
47 httpd = BaseHTTPServer.HTTPServer(server_address, MyHandler)
48 child = os.fork()
49 if child:
50 return child
51 # We are the child
52 try:
53 sys.stderr = sys.stdout
54 print "Waiting for request"
55 global next_step
56 for next_step in script:
57 if type(next_step) != tuple: next_step = (next_step,)
58 for x in next_step:
59 httpd.handle_request()
60 print "Done"
61 os._exit(0)
62 except:
63 traceback.print_exc()
64 os._exit(1)