I have created a test case to test my custom login_required decorator.
This is my decorator:
def login_required(view_func):
@wraps(view_func)
def wrapped_view(request, *args, **kwargs):
# Check if the user is logged in
if request.user.is_authenticated:
return view_func(request, *args, **kwargs)
else:
return redirect('/auth/login')
return wrapped_view
This is my test case:
class RegisterViewTests(TestCase):
def setUp(self):
self.client = Client()
def test_register_view_get_not_authenticated(self):
response = self.client.get(reverse('register'))
print(response.url)
self.assertRedirects(response, '/auth/login')
Here when I print response.url I get ‘/auth/login’ but when I use the same to check the redirect I get this error:
FAIL: test_register_view_get_not_authenticated (authentication.tests.test_views.RegisterViewTests.test_register_view_get_not_authenticated)
Traceback (most recent call last):
File “F:AyushCODEDJANGOfinalprojectCBBB Group 1final_repoauthenticationteststest_views.py”, line 61, in test_register_view_get_not_authenticated
self.assertRedirects(response, reverse(‘login_view’))
File “F:AyushCODEDJANGOfinalprojectCBBB Group 1final_repovenvLibsite-packagesdjangotesttestcases.py”, line 432, in assertRedirects
self.assertEqual(
AssertionError: 301 != 200 : Couldn’t retrieve redirection page ‘/auth/login’: response code was 301 (expected 200)
Ran 1 test in 0.033s
FAILED (failures=1)
I tried using reverse(‘login’) inside the assertRedirects but it still gave the same error.