Added missing import
[zeroinstall/solver.git] / tests / server.py
blob9536433d9aab89ea738c3c28de15a41c4f998fbe
1 #!/usr/bin/env python
3 from __future__ import print_function
5 import os, sys, urlparse
6 import BaseHTTPServer
7 import traceback
9 next_step = None
11 class Give404:
12 def __init__(self, path):
13 self.path = path
15 def __str__(self):
16 return self.path
18 def __repr__(self):
19 return "404 on " + self.path
21 class MyHandler(BaseHTTPServer.BaseHTTPRequestHandler):
22 def do_GET(self):
23 parsed = urlparse.urlparse(self.path)
25 leaf = os.path.basename(parsed.path)
27 acceptable = dict([(str(x), x) for x in next_step])
29 resp = acceptable.get(parsed.path, None) or \
30 acceptable.get(leaf, None) or \
31 acceptable.get('*', None)
33 # (don't use a symlink as they don't work on Windows)
34 if leaf == 'latest.xml':
35 leaf = 'Hello.xml'
37 if not resp:
38 self.send_error(404, "Expected %s; got %s" % (next_step, parsed.path))
39 elif parsed.path.startswith('/key-info/'):
40 self.send_response(200)
41 self.end_headers()
42 self.wfile.write('<key-lookup><item vote="good">Approved for testing</item></key-lookup>')
43 self.wfile.close()
44 elif os.path.exists(leaf) and not isinstance(resp, Give404):
45 self.send_response(200)
46 self.end_headers()
47 self.wfile.write(file(leaf).read())
48 self.wfile.close()
49 else:
50 self.send_error(404, "Missing: %s" % leaf)
52 def handle_requests(*script):
53 server_address = ('localhost', 8000)
54 httpd = BaseHTTPServer.HTTPServer(server_address, MyHandler)
55 child = os.fork()
56 if child:
57 return child
58 # We are the child
59 try:
60 sys.stderr = sys.stdout
61 #sys.stdout = sys.stderr
62 print("Waiting for request")
63 global next_step
64 for next_step in script:
65 if type(next_step) != tuple: next_step = (next_step,)
66 for x in next_step:
67 httpd.handle_request()
68 print("Done")
69 os._exit(0)
70 except:
71 traceback.print_exc()
72 os._exit(1)