0

I've found a few questions relating to the testing of URL redirects, to see if URL redirects land at the desired target URL. I would like to know, though, if there is an attribute that indicates what the final target URL landed upon is.

c = Client()
r = c.get('/sr/portfolios/', follow=True)
r.final_url # something like this?

It seems redirect_chain only tells you URLs you were redirected through, but not those than you ultimately landed on.

r.redirect_chain
# [('http://testserver/sr/?next=/sr/portfolios/', 302)]

Related (but not identical) topic I found: Django : Testing if the page has redirected to the desired url

Community
  • 1
  • 1
kuanb
  • 1,348
  • 14
  • 37
  • Isn't it simply ``r.url``? – axelcdv Feb 04 '15 at 16:11
  • r.url returns: AttributeError: 'HttpResponse' object has no attribute 'url' – kuanb Feb 04 '15 at 16:15
  • My bad, sorry. But you can get the final path, if that's enough for you, in ``r.request['PATH_INFO']``. I'd also expect that the last element in redirect_chain is the final url, but I haven't checked. – axelcdv Feb 04 '15 at 16:23
  • I thought the last item in `redirect_chain` was what you actually landed on..? – Henrik Andersson Feb 04 '15 at 16:39
  • Thanks @axelcdv; `r.request['PATH_INFO']` works perfectly - awesome. Didn't realize r.request returned that dict. As an aside, `redirect_chain` does not return final location: `>>> r.request['PATH_INFO']` returns `'/sr/'` and `>>> r.redirect_chain` returns `[('http://testserver/sr/?next=/sr/portfolios/', 302)]` – kuanb Feb 04 '15 at 16:52

2 Answers2

1

Just to highlight the solution a bit, you can get the final url with r.request['PATH_INFO']. r.wsgi_request.META['PATH_INFO'] works as well.

axelcdv
  • 733
  • 5
  • 17
0

I'm sure there are other ways of doing this, but would a simple in check suffice?

def test_final_url(self):

    final_url = reverse('your_url_name')

    found = False
    for item in r.redirect_chain:
        if final_url in item[0]:
            found = True
            break

    self.assertTrue(found)

Since Python lists don't have a guaranteed order, I'm not sure it's 100% safe to look at r.redirect_chain[-1][0] but it might be the fastest solution.

Brandon
  • 29,908
  • 11
  • 86
  • 125