Django test client gets 301 redirection when accessing url

空扰寡人 提交于 2020-04-07 02:38:09

问题


I am writing unittests for django views. I have observed that one of my views returns redirection code 301, which is not expected.
Here is my views.py mentioned earlier.

def index(request):
    return render(request, 'index.html',
                  {'form': QueryForm()})

def query(request):
    if request.is_ajax():
        form = QueryForm(request.POST)
        return HttpResponse('valid')

Below is urls.py.

urlpatterns = patterns('',
         url(r'^$', 'core.views.index'),
         url(r'^query/$', 'core.views.query')
         )

And unittest that will fail.

def so_test(self):
    response = self.client.post('/')
    self.assertEquals(response.status_code, 200)

    response = self.client.post('/query', {})
    self.assertEquals(response.status_code, 200)

My question is: why there is status 301 returned?


回答1:


You have defined a url that matches /query/, but you are testing /query. Django is redirecting to the url with the trailing slash because APPEND_SLASH=True in your settings.

You probably want to change your test to:

response = self.client.post('/query/', {})



回答2:


For me, the problem was that I mistakenly ran the tests with a setting.py file that had SECURE_SSL_REDIRECT = True. Changing to SECURE_SSL_REDIRECT = False solved the issue.

Another option is to use the client with secure=True, i.e.:

response = self.client.post('/query/', {}, secure=True)

which will make the client emulate an HTTPS request.



来源:https://stackoverflow.com/questions/12784905/django-test-client-gets-301-redirection-when-accessing-url

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!