Search code examples
djangodjango-testingdjango-1.11

Django assertRedirects test fails due to http://testserver prefix


I want to test that /sitemap.xml/ redirects to /sitemap.xml. I'm using this code:

res = self.client.get('/sitemap.xml/')
self.assertRedirects(res, '/sitemap.xml', status_code=301)

And getting the following error:

AssertionError: Response redirected to 'http://testserver/sitemap.xml', expected '/sitemap.xml'

How should I write this test to avoid the testserver clash?


Solution

  • I guess the redirect url/response is created with the fullpath using build_absolute_uri or something similar.? Just a guess...

    Firstly, using urlnames instead of hardcoded paths may be easier in the long run. url=reverse('sitemap.xml'), url = reverse('sitemap.xml') + '/' to give some idea...

    Django naming url patterns

    Anyway this may solve your problem without having to bother about the host.

    res = self.client.get('/sitemap.xml/')
    expected_url = res.wsgi_request.build_absolute_uri('/sitemap.xml')
    self.assertRedirects(res, expected_url, status_code=301)
    

    (Tested on Django 1.10.6)