Fixed some ResourceWarnings on Python 3
[zeroinstall/solver.git] / tests / server.py
blobcd41805df81de88c6f6ac85480aa43660ba11358
1 #!/usr/bin/env python
3 from __future__ import print_function
5 import os, sys
6 import traceback
8 if sys.version_info[0] > 2:
9 from urllib import parse as urlparse # Python 3
10 from http import server
11 import pickle
12 else:
13 import urlparse
14 import BaseHTTPServer as server
15 import cPickle as pickle
17 next_step = None
19 class Give404:
20 def __init__(self, path):
21 self.path = path
23 def __str__(self):
24 return self.path
26 def __repr__(self):
27 return "404 on " + self.path
29 class MyHandler(server.BaseHTTPRequestHandler):
30 def do_GET(self):
31 parsed = urlparse.urlparse(self.path)
33 print(parsed)
34 if parsed.path.startswith('/redirect/'):
35 self.send_response(302)
36 self.wfile.write(('Location: /' + parsed.path[1:].split('/', 1)[1]).encode('utf-8'))
37 return
39 leaf = os.path.basename(parsed.path)
41 acceptable = dict([(str(x), x) for x in next_step])
43 resp = acceptable.get(parsed.path, None) or \
44 acceptable.get(leaf, None) or \
45 acceptable.get('*', None)
47 # (don't use a symlink as they don't work on Windows)
48 if leaf == 'latest.xml':
49 leaf = 'Hello.xml'
50 elif parsed.path == '/0mirror/archive/http%3A%23%23example.com%3A8000%23HelloWorld.tgz':
51 leaf = 'HelloWorld.tgz'
52 elif parsed.path == '/0mirror/feeds/http/example.com:8000/Hello.xml/impl/sha1=3ce644dc725f1d21cfcf02562c76f375944b266a':
53 leaf = 'HelloWorld.tar.bz2'
55 if not resp:
56 self.send_error(404, "Expected %s; got %s" % (next_step, parsed.path))
57 elif parsed.path.startswith('/key-info/'):
58 self.send_response(200)
59 self.end_headers()
60 self.wfile.write(b'<key-lookup><item vote="good">Approved for testing</item></key-lookup>')
61 self.wfile.close()
62 elif os.path.exists(leaf) and not isinstance(resp, Give404):
63 self.send_response(200)
64 self.end_headers()
65 with open(leaf, 'rb') as stream:
66 self.wfile.write(stream.read())
67 self.wfile.close()
68 else:
69 self.send_error(404, "Missing: %s" % leaf)
71 def handle_requests(*script):
72 from subprocess import Popen, PIPE
74 # Pass the script on the command line as a pickle.
75 child = Popen(
76 [sys.executable, __file__, repr(pickle.dumps(script)) ],
77 stdout=PIPE, universal_newlines=True)
79 # Make sure the server is actually running before we try to
80 # interact with it.
81 l = child.stdout.readline()
82 assert l == 'Waiting for request\n', l
83 return child
85 def main():
86 # Grab the script that was passed on the command line from the parent
87 script = pickle.loads(eval(sys.argv[1]))
88 server_address = ('localhost', 8000)
89 httpd = server.HTTPServer(server_address, MyHandler)
90 try:
91 sys.stderr = sys.stdout
92 #sys.stdout = sys.stderr
93 print("Waiting for request")
94 sys.stdout.flush() # Make sure the "Waiting..." message is seen by the parent
95 global next_step
96 for next_step in script:
97 if type(next_step) != tuple: next_step = (next_step,)
98 for x in next_step:
99 httpd.handle_request()
100 print("Done")
101 os._exit(0)
102 except:
103 traceback.print_exc()
104 os._exit(1)
106 if __name__ == '__main__':
107 # This is the child process. We have to import ourself and
108 # run the main routine there, or the pickled Give404 instances
109 # passed from the parent won't be recognized as having the
110 # same class (server.Give404).
111 import server
112 server.main()