7

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?

akxlr
  • 1,142
  • 9
  • 23

2 Answers2

12

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)

Daniel Backman
  • 5,121
  • 1
  • 32
  • 37
  • 1
    Good guess - that was exactly my problem. Replaced `request.build_absolute_url()` with `request.get_full_path()` in my redirect middleware and it works as expected! – akxlr Jul 04 '18 at 01:16
3

I think you can use request.path

Something like this :

response = self.client.get('/sitemap.xml/')
self.assertEqual(response.status_code, 301)
self.assertEqual(response.path, '/sitemap.xml')
Umair Mohammad
  • 4,489
  • 2
  • 20
  • 34