232
233
"""Redirect a single HTTP request to another host"""
233
234
valid = TestingHTTPRequestHandler.parse_request(self)
235
rhost, rport = self.server.test_case_server.redirected_to_address()
236
if rhost is not None and rport is not None:
237
# Just redirect permanently
238
self.send_response(301)
239
target = 'http://%s:%s%s' % (rhost, rport, self.path)
236
tcs = self.server.test_case_server
237
code, target = tcs.is_redirected(self.path)
238
if code is not None and target is not None:
239
# Redirect as instructed
240
self.send_response(code)
240
241
self.send_header('Location', target)
241
242
self.end_headers()
242
243
return False # The job is done
245
# We leave the parent class serve the request
249
253
def __init__(self, request_handler=RedirectRequestHandler):
250
254
HttpServer.__init__(self, request_handler)
251
self._redirect_to_host = None
252
self._redirect_to_port = None
254
def redirect_to(self, redir_host, redir_port):
255
self._redirect_to_host = redir_host
256
self._redirect_to_port = redir_port
258
def redirected_to_address(self):
259
return self._redirect_to_host, self._redirect_to_port
255
# redirections is a list of tuples (source, target, code)
256
# - source is a regexp for the paths requested
257
# - target is a replacement for re.sub describing where
258
# the request will be redirected
259
# - code is the http error code associated to the
260
# redirection (301 permanent, 302 temporarry, etc
261
self.redirections = []
263
def redirect_to(self, host, port):
264
"""Redirect all requests to a specific host:port"""
265
self.redirections = [('(.*)',
266
r'http://%s:%s\1' % (host, port) ,
269
def is_redirected(self, path):
270
"""Is the path redirected by this server.
272
:param path: the requested relative path
274
:returns: a tuple (code, target) if a matching
275
redirection is found, (None, None) otherwise.
279
for (rsource, rtarget, rcode) in self.redirections:
280
target, match = re.subn(rsource, rtarget, path)
283
break # The first match wins
262
289
class TestCaseWithRedirectedWebserver(TestCaseWithTwoWebservers):