More updates to support Python 3
[zeroinstall/solver.git] / tests / server.py
blob9459169b86770362a6931374a97974aa099fa499
1 #!/usr/bin/env python
3 from __future__ import print_function
5 import os, sys, urlparse
6 import BaseHTTPServer
7 import traceback
8 import cPickle as pickle
10 next_step = None
12 class Give404:
13 def __init__(self, path):
14 self.path = path
16 def __str__(self):
17 return self.path
19 def __repr__(self):
20 return "404 on " + self.path
22 class MyHandler(BaseHTTPServer.BaseHTTPRequestHandler):
23 def do_GET(self):
24 parsed = urlparse.urlparse(self.path)
26 print(parsed)
27 if parsed.path.startswith('/redirect/'):
28 self.send_response(302)
29 self.wfile.write('Location: /' + parsed.path[1:].split('/', 1)[1])
30 return
32 leaf = os.path.basename(parsed.path)
34 acceptable = dict([(str(x), x) for x in next_step])
36 resp = acceptable.get(parsed.path, None) or \
37 acceptable.get(leaf, None) or \
38 acceptable.get('*', None)
40 # (don't use a symlink as they don't work on Windows)
41 if leaf == 'latest.xml':
42 leaf = 'Hello.xml'
44 if not resp:
45 self.send_error(404, "Expected %s; got %s" % (next_step, parsed.path))
46 elif parsed.path.startswith('/key-info/'):
47 self.send_response(200)
48 self.end_headers()
49 self.wfile.write('<key-lookup><item vote="good">Approved for testing</item></key-lookup>')
50 self.wfile.close()
51 elif os.path.exists(leaf) and not isinstance(resp, Give404):
52 self.send_response(200)
53 self.end_headers()
54 self.wfile.write(open(leaf).read())
55 self.wfile.close()
56 else:
57 self.send_error(404, "Missing: %s" % leaf)
59 def handle_requests(*script):
60 from subprocess import Popen, PIPE
62 # Pass the script on the command line as a pickle.
63 child = Popen(
64 [sys.executable, __file__, pickle.dumps(script) ],
65 stdout=PIPE, universal_newlines=True)
67 # Make sure the server is actually running before we try to
68 # interact with it.
69 l = child.stdout.readline()
70 assert l == 'Waiting for request\n'
71 return child
73 def main():
74 # Grab the script that was passed on the command line from the parent
75 script = pickle.loads(sys.argv[1])
76 server_address = ('localhost', 8000)
77 httpd = BaseHTTPServer.HTTPServer(server_address, MyHandler)
78 try:
79 sys.stderr = sys.stdout
80 #sys.stdout = sys.stderr
81 print("Waiting for request")
82 sys.stdout.flush() # Make sure the "Waiting..." message is seen by the parent
83 global next_step
84 for next_step in script:
85 if type(next_step) != tuple: next_step = (next_step,)
86 for x in next_step:
87 httpd.handle_request()
88 print("Done")
89 os._exit(0)
90 except:
91 traceback.print_exc()
92 os._exit(1)
94 if __name__ == '__main__':
95 # This is the child process. We have to import ourself and
96 # run the main routine there, or the pickled Give404 instances
97 # passed from the parent won't be recognized as having the
98 # same class (server.Give404).
99 import server
100 server.main()