'Asserts that a response redirected to a specific URL, and that the
redirect URL can be loaded.
Note that assertRedirects won\'t work for external links since it uses
TestClient to do a request.'

def assertRedirects(self, response, expected_url, status_code=302, target_status_code=200, host=None, msg_prefix=u''):

    if msg_prefix:
        msg_prefix += u':    '
    if hasattr(response, u'redirect_chain'):
        self.assertTrue((len(response.redirect_chain) > 0), (msg_prefix + (u"Response    didn't    redirect    as    expected:    Response    code    was    %d    (expected    %d)" % (response.status_code, status_code))))
        self.assertEqual(response.redirect_chain[0][1], status_code, (msg_prefix + (u"Initial    response    didn't    redirect    as    expected:    Response    code    was    %d    (expected    %d)" % (response.redirect_chain[0][1], status_code))))
        (url, status_code) = response.redirect_chain[(-1)]
        self.assertEqual(response.status_code, target_status_code, (msg_prefix + (u"Response    didn't    redirect    as    expected:    Final    Response    code    was    %d    (expected    %d)" % (response.status_code, target_status_code))))
    else:
        self.assertEqual(response.status_code, status_code, (msg_prefix + (u"Response    didn't    redirect    as    expected:    Response    code    was    %d    (expected    %d)" % (response.status_code, status_code))))
        url = response[u'Location']
        (scheme, netloc, path, query, fragment) = urlsplit(url)
        redirect_response = response.client.get(path, QueryDict(query))
        self.assertEqual(redirect_response.status_code, target_status_code, (msg_prefix + (u"Couldn't    retrieve    redirection    page    '%s':    response    code    was    %d    (expected    %d)" % (path, redirect_response.status_code, target_status_code))))
    (e_scheme, e_netloc, e_path, e_query, e_fragment) = urlsplit(expected_url)
    if (not (e_scheme or e_netloc)):
        expected_url = urlunsplit((u'http', (host or u'testserver'), e_path, e_query, e_fragment))
    self.assertEqual(url, expected_url, (msg_prefix + (u"Response    redirected    to    '%s',    expected    '%s'" % (url, expected_url))))
