Skip to content

Commit

Permalink
Test cases
Browse files Browse the repository at this point in the history
  • Loading branch information
mongkok committed Nov 6, 2017
1 parent 0d2b81b commit e2fac45
Show file tree
Hide file tree
Showing 6 changed files with 159 additions and 7 deletions.
4 changes: 4 additions & 0 deletions tests/test_backends.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
34 changes: 32 additions & 2 deletions tests/test_middleware.py
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -26,13 +26,43 @@ 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',
}

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)
29 changes: 25 additions & 4 deletions tests/test_mutations.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down Expand Up @@ -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!) {
Expand All @@ -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'])
17 changes: 17 additions & 0 deletions tests/test_settings.py
Original file line number Diff line number Diff line change
@@ -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))
74 changes: 74 additions & 0 deletions tests/test_utils.py
Original file line number Diff line number Diff line change
@@ -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)
8 changes: 7 additions & 1 deletion tests/urls.py
Original file line number Diff line number Diff line change
@@ -1 +1,7 @@
urlpatterns = []
from django.conf.urls import url
from graphene_django.views import GraphQLView


urlpatterns = [
url(r'^$', GraphQLView.as_view(), name='index')
]

0 comments on commit e2fac45

Please sign in to comment.