226
227
return TestingHTTPRequestHandler.translate_path(self, path)
230
class RedirectRequestHandler(TestingHTTPRequestHandler):
231
"""Redirect all request to the specified server"""
233
def parse_request(self):
234
"""Redirect a single HTTP request to another host"""
235
valid = TestingHTTPRequestHandler.parse_request(self)
237
tcs = self.server.test_case_server
238
code, target = tcs.is_redirected(self.path)
239
if code is not None and target is not None:
240
# Redirect as instructed
241
self.send_response(code)
242
self.send_header('Location', target)
244
return False # The job is done
246
# We leave the parent class serve the request
251
class HTTPServerRedirecting(HttpServer):
252
"""An HttpServer redirecting to another server """
254
def __init__(self, request_handler=RedirectRequestHandler):
255
HttpServer.__init__(self, request_handler)
256
# redirections is a list of tuples (source, target, code)
257
# - source is a regexp for the paths requested
258
# - target is a replacement for re.sub describing where
259
# the request will be redirected
260
# - code is the http error code associated to the
261
# redirection (301 permanent, 302 temporarry, etc
262
self.redirections = []
264
def redirect_to(self, host, port):
265
"""Redirect all requests to a specific host:port"""
266
self.redirections = [('(.*)',
267
r'http://%s:%s\1' % (host, port) ,
270
def is_redirected(self, path):
271
"""Is the path redirected by this server.
273
:param path: the requested relative path
275
:returns: a tuple (code, target) if a matching
276
redirection is found, (None, None) otherwise.
280
for (rsource, rtarget, rcode) in self.redirections:
281
target, match = re.subn(rsource, rtarget, path)
284
break # The first match wins
290
class TestCaseWithRedirectedWebserver(TestCaseWithTwoWebservers):
291
"""A support class providing redirections from one server to another.
293
We set up two webservers to allows various tests involving
295
The 'old' server is redirected to the 'new' server.
298
def create_transport_secondary_server(self):
299
"""Create the secondary server redirecting to the primary server"""
300
new = self.get_readonly_server()
301
redirecting = HTTPServerRedirecting()
302
redirecting.redirect_to(new.host, new.port)
306
super(TestCaseWithRedirectedWebserver, self).setUp()
307
# The redirections will point to the new server
308
self.new_server = self.get_readonly_server()
309
# The requests to the old server will be redirected
310
self.old_server = self.get_secondary_server()