0

Trying to work on a project and get my head around unit Testing. I'm confused why client.get is getting a diffrent redirect than both Firefox and Chrome.

Details below, but can someone give me an idea this is occuring.

  • Django Version 3
  • Python verson 3.8
  • Running on Ubuntu in WSL in windows.

My View Function.

class UserDashboardView(View):

    def get(self, request, *args, **kwargs):
        return HttpResponseRedirect('/accounts/login')

My Test Case

import unittest
from django.test import TestCase

class DashboardPageTest(TestCase):

    def test_unauthenticated_user_redirected_to_login(self):
        response = self.client.get('/dashboard')
        print(response)

What occurs.

1 - If I go to /dashboard in Chrome and Firefox the debug shows a 302 with a location key of /accounts/login, and so the browser follows to /accounts/login

2 - If I run the unit test (python manage.py test) the print of the response returns

<HttpResponsePermanentRedirect status_code=301, "text/html; charset=utf-8", url="/dashboard/">

I have a feeling their is something I just don't get about the way the browsers vs the TestCase does redirects. Can someone please explain it?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
huntsfromshadow
  • 1,085
  • 8
  • 12

2 Answers2

3

You have missed out trailing slash in your unit test, so it is redirecting from /dashboard to /dashboard/.

Alasdair
  • 298,606
  • 55
  • 578
  • 516
0

Solved it. Found the solution at Django test client gets 301 redirection when accessing url

Basically Django was being helpfull and adding a / to the end of the request. Thus it was sending back a permanet redirect to let me know. Chrome and firefox must have dealt with it Changed the line in the test case to

response = self.client.get('/dashboard/') instead of response = self.client.get('/dashboard') and it returns 302. And now that I look at the browsers I was going to /dashboard/ in the browsers.

huntsfromshadow
  • 1,085
  • 8
  • 12
  • If you go to `/dashboard` in your browser, it will follow the 301 redirect to `/dashboard/` then the 302 redirect to `/accounts/login`. The [test client](https://docs.djangoproject.com/en/3.0/topics/testing/tools/#django.test.Client.get) doesn't follow the redirects because `follow=False` by default. – Alasdair Jan 08 '20 at 17:01