From 1db8d5fd56e0231475f1f42e098587172f560dd9 Mon Sep 17 00:00:00 2001 From: Sverre Nystad Date: Fri, 5 Jan 2024 22:51:34 +0100 Subject: [PATCH] Test: Add login tests for JWT token generation --- backend/users/tests.py | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/backend/users/tests.py b/backend/users/tests.py index f79122d6..34db750d 100644 --- a/backend/users/tests.py +++ b/backend/users/tests.py @@ -104,10 +104,15 @@ def setUp(self): self.user = User.objects.create_user( username="logintestuser", password=self.user_pasword ) + self.different_user_password = "differentuserpassword" + self.different_user = User.objects.create_user( + username="differentuser", password=self.different_user_password + ) def tearDown(self): # This code will run after each test self.user.delete() + self.different_user.delete() def test_invalid_login_attempt_with_empty_fields(self): client = Client() @@ -177,3 +182,33 @@ def test_correct_pass_valid_on_existing_user(self): response = client.post(self.login_end_point, request_body) self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED) + + def test_valid_login_gets_jwt_tokens(self): + client = Client() + request_body = {"username": self.user.username, "password": self.user_pasword} + + response = client.post(self.login_end_point, request_body) + self.assertEqual(response.status_code, status.HTTP_200_OK) + self.assertTrue("refresh" in response.data) + self.assertTrue("access" in response.data) + access = response.data.get("access") + refresh = response.data.get("refresh") + self.assertNotEqual(access, refresh) + + def test_valid_logins_gets_different_jwt_tokens(self): + client = Client() + request_body1 = {"username": self.user.username, "password": self.user_pasword} + request_body2 = { + "username": self.different_user.username, + "password": self.different_user_password, + } + response1 = client.post(self.login_end_point, request_body1) + response2 = client.post(self.login_end_point, request_body2) + self.assertEqual(response1.status_code, status.HTTP_200_OK) + + access1 = response1.data.get("access") + refresh1 = response1.data.get("refresh") + access2 = response2.data.get("access") + refresh2 = response2.data.get("refresh") + self.assertNotEqual(access1, access2) + self.assertNotEqual(refresh1, refresh2)