def test_redirect(self): from_url = "http://example.com/a.html" to_url = "http://example.com/b.html" h = HTTPRedirectHandler() o = h.parent = MockOpener() # ordinary redirect behaviour for code in 301, 302, 303, 307, "refresh": for data in None, "blah\nblah\n": method = getattr(h, "http_error_%s" % code) req = Request(from_url, data) req.add_header("Nonsense", "viking=withhold") req.add_unredirected_header("Spam", "spam") req.origin_req_host = "example.com" # XXX try: method(req, MockFile(), code, "Blah", MockHeaders({"location": to_url})) except urllib2.HTTPError: # 307 in response to POST requires user OK self.assert_(code == 307 and data is not None) self.assert_(o.req.get_full_url() == to_url) try: self.assert_(o.req.get_method() == "GET") except AttributeError: self.assert_(not o.req.has_data()) self.assert_(o.req.headers["Nonsense"] == "viking=withhold") self.assert_(not o.req.headers.has_key("Spam")) self.assert_(not o.req.unredirected_hdrs.has_key("Spam")) # loop detection def redirect(h, req, url=to_url): h.http_error_302(req, MockFile(), 302, "Blah", MockHeaders({"location": url})) # Note that the *original* request shares the same record of # redirections with the sub-requests caused by the redirections. # detect infinite loop redirect of a URL to itself req = Request(from_url) req.origin_req_host = "example.com" count = 0 try: while 1: redirect(h, req, "http://example.com/") count = count + 1 except urllib2.HTTPError: # don't stop until max_repeats, because cookies may introduce state self.assert_(count == HTTPRedirectHandler.max_repeats) # detect endless non-repeating chain of redirects req = Request(from_url) req.origin_req_host = "example.com" count = 0 try: while 1: redirect(h, req, "http://example.com/%d" % count) count = count + 1 except urllib2.HTTPError: self.assert_(count == HTTPRedirectHandler.max_redirections)