From e2fac45c413110ef053ea254d190afe6ca1d0da1 Mon Sep 17 00:00:00 2001 From: mongkok Date: Tue, 7 Nov 2017 01:34:56 +0530 Subject: [PATCH] Test cases --- tests/test_backends.py | 4 +++ tests/test_middleware.py | 34 ++++++++++++++++-- tests/test_mutations.py | 29 +++++++++++++--- tests/test_settings.py | 17 +++++++++ tests/test_utils.py | 74 ++++++++++++++++++++++++++++++++++++++++ tests/urls.py | 8 ++++- 6 files changed, 159 insertions(+), 7 deletions(-) create mode 100644 tests/test_settings.py create mode 100644 tests/test_utils.py diff --git a/tests/test_backends.py b/tests/test_backends.py index 5d252ae6..91d03ee6 100644 --- a/tests/test_backends.py +++ b/tests/test_backends.py @@ -26,6 +26,10 @@ def test_authenticate_fail(self): with self.assertRaises(GraphQLJWTError): JWTBackend().authenticate(request=request) + def test_authenticate_null_request(self): + user = JWTBackend().authenticate(request=None) + self.assertIsNone(user) + def test_get_user(self): user = JWTBackend().get_user(self.user.username) self.assertEqual(user, self.user) diff --git a/tests/test_middleware.py b/tests/test_middleware.py index 04b5b2da..cd8ff63f 100644 --- a/tests/test_middleware.py +++ b/tests/test_middleware.py @@ -1,6 +1,6 @@ import json -from unittest.mock import MagicMock +from unittest.mock import patch, MagicMock from django.http import JsonResponse from graphql_jwt.middleware import JWTMiddleware @@ -26,6 +26,17 @@ def test_authenticate(self): self.get_response_mock.assert_called_once_with(request) + @patch('graphql_jwt.middleware.authenticate') + def test_user_not_authenticate(self, *args): + headers = { + 'HTTP_AUTHORIZATION': 'JWT ' + self.token, + } + + request = self.factory.get('/', **headers) + self.middleware(request) + + self.get_response_mock.assert_called_once_with(request) + def test_graphql_error(self): headers = { 'HTTP_AUTHORIZATION': 'JWT invalid', @@ -33,6 +44,25 @@ def test_graphql_error(self): request = self.factory.get('/', **headers) response = self.middleware(request) + content = json.loads(response.content.decode('utf-8')) - self.assertTrue(json.loads(response.content.decode('utf-8'))['errors']) + self.assertTrue(content['errors']) self.get_response_mock.assert_not_called() + + def test_header_not_found(self): + request = self.factory.get('/') + response = self.middleware(request) + + self.assertTrue(dir(response)) + self.get_response_mock.assert_called_once_with(request) + + def test_user_is_authenticated(self): + headers = { + 'HTTP_AUTHORIZATION': 'JWT ' + self.token, + } + + request = self.factory.get('/', **headers) + request.user = self.user + self.middleware(request) + + self.get_response_mock.assert_called_once_with(request) diff --git a/tests/test_mutations.py b/tests/test_mutations.py index d15ca713..238d33fa 100644 --- a/tests/test_mutations.py +++ b/tests/test_mutations.py @@ -2,9 +2,10 @@ from unittest.mock import patch from graphql_jwt import settings -from graphql_jwt.utils import jwt_encode +from graphql_jwt.utils import jwt_encode, jwt_payload from .base import GraphQLJWTTestCase +from .decorators import override_settings class MutationsTests(GraphQLJWTTestCase): @@ -69,9 +70,10 @@ def test_refresh_expired(self): self.assertTrue(response.errors) - def test_refresh_error(self): - del self.payload['orig_iat'] - token = jwt_encode(self.payload) + @override_settings(JWT_ALLOW_REFRESH=False) + def test_refresh_error(self, *args): + payload = jwt_payload(self.user) + token = jwt_encode(payload) query = ''' mutation RefreshToken($token: String!) { @@ -82,3 +84,22 @@ def test_refresh_error(self): response = self.client.execute(query, token=token) self.assertTrue(response.errors) + + @override_settings(JWT_VERIFY_REFRESH_EXPIRATION=False) + def test_refresh_not_verify(self, *args): + query = ''' + mutation RefreshToken($token: String!) { + refreshToken(token: $token) { + data + } + }''' + + with patch('graphql_jwt.mutations.datetime') as datetime_mock: + datetime_mock.utcnow.return_value = datetime.utcnow() +\ + settings.JWT_REFRESH_EXPIRATION_DELTA +\ + timedelta(seconds=1) + + response = self.client.execute(query, token=self.token) + + data = response.data['refreshToken']['data'] + self.assertEqual(self.user.username, data['payload']['username']) diff --git a/tests/test_settings.py b/tests/test_settings.py new file mode 100644 index 00000000..6a41cdff --- /dev/null +++ b/tests/test_settings.py @@ -0,0 +1,17 @@ +from datetime import timedelta +from unittest.mock import patch + +from django.test import TestCase +from graphql_jwt import settings + + +class SettingsTests(TestCase): + + @patch.dict('os.environ', { + 'TEST_TIMEDELTA': 'hours=1,days=1' + }) + def test_env_timedelta_cast(self): + env = settings.Env() + var = env.timedelta('TEST_TIMEDELTA') + + self.assertEqual(var, timedelta(hours=1, days=1)) diff --git a/tests/test_utils.py b/tests/test_utils.py new file mode 100644 index 00000000..13dd007e --- /dev/null +++ b/tests/test_utils.py @@ -0,0 +1,74 @@ +from datetime import timedelta +from unittest.mock import patch, Mock, PropertyMock + +from django.contrib.auth import get_user_model +from django.test import RequestFactory, TestCase + +from graphql_jwt import utils +from graphql_jwt.exceptions import GraphQLJWTError +from .decorators import override_settings + + +class UtilsTests(TestCase): + + def setUp(self): + self.user = get_user_model().objects.create_user(username='test') + self.factory = RequestFactory() + + @patch('django.contrib.auth.models.User.get_username', + return_value=Mock(pk='test')) + def test_payload_foreign_key_pk(self, *args): + payload = utils.jwt_payload(self.user) + username_field = get_user_model().USERNAME_FIELD + + self.assertEqual(payload[username_field], 'test') + + @override_settings(JWT_AUDIENCE='test') + def test_payload_audience(self): + payload = utils.jwt_payload(self.user) + self.assertEqual(payload['aud'], 'test') + + @override_settings(JWT_ISSUER='test') + def test_payload_issuer(self): + payload = utils.jwt_payload(self.user) + self.assertEqual(payload['iss'], 'test') + + def test_invalid_authorization_header_prefix(self): + headers = { + 'HTTP_AUTHORIZATION': 'INVALID token', + } + + request = self.factory.get('/', **headers) + header = utils.get_authorization_header(request) + + self.assertIsNone(header) + + @override_settings(JWT_VERIFY_EXPIRATION=True) + @override_settings(JWT_EXPIRATION_DELTA=timedelta(seconds=-1)) + def test_payload_expired_signature(self): + payload = utils.jwt_payload(self.user) + token = utils.jwt_encode(payload) + + with self.assertRaises(GraphQLJWTError): + utils.get_payload(token) + + def test_payload_decoding_error(self): + with self.assertRaises(GraphQLJWTError): + utils.get_payload('invalid') + + def test_user_by_natural_key_not_exists(self): + user = utils.get_user_by_natural_key(0) + self.assertIsNone(user) + + def test_user_by_invalid_payload(self): + with self.assertRaises(GraphQLJWTError): + utils.get_user_by_payload({}) + + @patch('django.contrib.auth.models.User.is_active', + new_callable=PropertyMock, + return_value=False) + def test_user_disabled_by_payload(self, *args): + payload = utils.jwt_payload(self.user) + + with self.assertRaises(GraphQLJWTError): + utils.get_user_by_payload(payload) diff --git a/tests/urls.py b/tests/urls.py index 637600f5..2534b910 100644 --- a/tests/urls.py +++ b/tests/urls.py @@ -1 +1,7 @@ -urlpatterns = [] +from django.conf.urls import url +from graphene_django.views import GraphQLView + + +urlpatterns = [ + url(r'^$', GraphQLView.as_view(), name='index') +]