django test client always returning 301

2.5k views Asked by At

I've run into some problems while running cartridge tests - the test client always returns 301 when doing something like self.client.get('/'). The only way to proceed is adding follow=True, but it's suspicious that I always have to do that. This also means I cannot test POST, since the test client always uses GET for redirects.

I've modified cartridge in a few places, so this is definitely my fault, but I'm not sure how to debug it. Here's what happens:

>>> response = self.client.get('/en/')
>>> response.status_code
301
>>> pp response.__dict__
{'_base_content_is_iter': False,
 '_charset': 'utf-8',
 '_closable_objects': [],
 '_container': [u''],
 '_handler_class': None,
 '_headers': {'content-language': ('Content-Language', 'en'),
              'content-type': ('Content-Type', 'text/html; charset=utf-8'),
              'location': ('Location', 'http://example.com/en/'),
              'vary': ('Vary', 'Accept-Language, Cookie')},
 'client': <django.test.client.Client object at 0x1105364d0>,
 'context': None,
 'cookies': <SimpleCookie: >,
 'request': {u'CONTENT_TYPE': 'text/html; charset=utf-8',
             u'PATH_INFO': '/en/',
             u'QUERY_STRING': '',
             u'REQUEST_METHOD': 'GET'},
 'templates': []}

And with following redirects:

>>> response = self.client.get('/en/', follow=True)
>>> response.status_code
200
>>> response.redirect_chain
[('http://example.com/en/', 301)]

>>> response = self.client.get('http://example.com/en/')
>>> response.status_code
301
>>> response['Location']
'http://example.com/en/'

Even when I try to go directly to the given URL:

>>> response = self.client.get('http://example.com/en/', follow=True)
>>> response.redirect_chain
[('http://example.com/en/', 301)]

where 'example.com' is just the sites live url. Do you have any ideas why that might be happening? Is it normal that it redirects to example.com (or at least pretends, it still seems to be running locally) instead of localhost?

3

There are 3 answers

5
Maciej Gryka On BEST ANSWER

Standardly I've figured out the answer while writing the question... hopefully this will be useful to somebody else!

Somehow the SSL config snuck into my dev settings. In particular I've had the following

SSL_FORCE_HOST = 'example.com'

enabled, which seems to be a problem - after disabling it in dev, the problem disappeared.

0
Vlad T. On

There is also a secure flag that you can set to solve the issue with redirection to https. In my case I tested post:

response = self.client.post(url, data, secure=True)

but client.get() also has this flag.

0
Min On

Check that it is running the test with debug enabled in settings.py. Running with debug disabled can causes it to redirect.

DEBUG = True

I encountered this in a code base that was modified to disable debug by default.