Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 762
akxlr Avatar asked Jun 20 '18 05:06

akxlr


People also ask

How do I skip a Django test?

Just trick it to always skip with the argument True : @skipIf(True, "I don't want to run this test yet") def test_something(): ... If you are looking to simply not run certain test files, the best way is probably to use fab or other tool and run particular tests.

How do I run test PY in Django?

Open /catalog/tests/test_models.py.from django. test import TestCase # Create your tests here. Often you will add a test class for each model/view/form you want to test, with individual methods for testing specific functionality.

What is self client in Django?

self. client , is the built-in Django test client. This isn't a real browser, and doesn't even make real requests. It just constructs a Django HttpRequest object and passes it through the request/response process - middleware, URL resolver, view, template - and returns whatever Django produces.

What is client in Django test?

The test client is a Python class that acts as a dummy web browser, allowing you to test your views and interact with your Django-powered application programmatically.


2 Answers

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)

like image 184
Daniel Backman Avatar answered Sep 18 '22 13:09

Daniel Backman


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')
like image 22
Umair Mohammad Avatar answered Sep 22 '22 13:09

Umair Mohammad