But what if I want to check without login. For example, I have one api logout which is having LoginRequired mixin, I want to test that anyone cannot hit logout if hes not logged in. So I created testcase as below.
@pytest.mark.django_db
def test_user_logout_logged_in_user(self, client):
url = reverse('logout')
response = client.get(url)
assert response.status_code == 302
assertRedirects(response, reverse('login'))
but I got this error, AssertionError: '/auth/login-view/?next=/auth/logout-view/' != '/auth/login-view/'
Means I get ?next={something for after login api}.
How do I check that redirected api is login api.
My logout api is as below:
class LogoutView(LoginRequiredMixin, View):
"""
description: This is user logout view.
GET request will log out user and redirects to home page.
"""
def get(self, request):
return LogoutService.logout_user(request=request)
class LogoutService:
@staticmethod
def logout_user(request):
logout(request)
messages.success(request, ACCOUNT_LOGOUT_SUCCESS)
return redirect('home')
Django test for a page that redirects
I tried this answer, but it is for logged-in user. I want to test for un authenticated user.
CodePudding user response:
To test that a view redirects with the "next" parameter correctly you need to add the next get parameter to the login URL when testing
@pytest.mark.django_db
def test_login_required_redirect(self, client):
url = reverse('someview')
response = client.get(url)
assertRedirects(response, f"{reverse('login')}?next={url}")
Don't use LoginRequiredMixin
for your logout view, you set next to your logout view this way and that will cause the user to instantly logout after they login - handle the redirect manually in your view
class LogoutView(View):
def get(self, request):
if not request.user.is_authenticated:
return redirect('login')
return LogoutService.logout_user(request=request)