import json import logging import unittest from flask import Response from mock import patch from moto import mock_dynamodb2 from tests.mocks import patch_decode_token from tests.v1.constants import MOCK_SERVER_NAME, MOCK_TOKEN_RESPONSE LOG = logging.getLogger(__name__) @mock_dynamodb2 class TestAuthView(unittest.TestCase): def setUp(self): self.mock_decode = patch_decode_token() self.mock_decode.start() self.access_token = MOCK_TOKEN_RESPONSE.get('access_token') self.mock_fetch_token = patch( 'authlib.integrations.requests_client.oauth2_session.OAuth2Session.fetch_access_token', return_value=MOCK_TOKEN_RESPONSE) self.mock_fetch_token.start() from slz_api_service.core.app import get_app self.app = get_app().app self.app.testing = True self.app.config['SERVER_NAME'] = MOCK_SERVER_NAME self.client = self.app.test_client() def tearDown(self): self.mock_decode.stop() self.mock_fetch_token.stop() def test_oauth_token_missing_required_params(self): route = '/oauth/token' body = { 'client_id': 'client_id', } headers = { 'Content-Type': 'application/json', } with self.app.app_context(): response: Response = self.client.post(route, data=json.dumps(body), headers=headers) self.assertTrue(response.status_code, 400) def test_oauth_token_success(self): route = '/oauth/token' body = { 'client_id': 'client_id', 'client_secret': 'client_secret', 'grant_type': 'client_credentials', } headers = { 'Content-Type': 'application/json', } with self.app.app_context(): response: Response = self.client.post(route, data=json.dumps(body), headers=headers) self.assertTrue(response.status_code, 200) def test_oauth_token_invalid(self): """Ensure this runs last as the mock patch is stopped""" self.mock_fetch_token.stop() route = '/oauth/token' body = { 'client_id': 'client_id', 'client_secret': 'client_secret', 'grant_type': 'client_credentials', } headers = { 'Content-Type': 'application/json', } with self.app.app_context(): response: Response = self.client.post(route, data=json.dumps(body), headers=headers) self.assertTrue(response.status_code, 401) def test_oauth_exception(self): from authlib.integrations.requests_client import OAuthError route = '/oauth/token' body = { 'client_id': 'client_id', 'client_secret': 'client_secret', 'grant_type': 'client_credentials', } headers = { 'Content-Type': 'application/json', } with patch('authlib.integrations.requests_client' '.oauth2_session.OAuth2Session.fetch_access_token') as mock_fetch: mock_fetch.side_effect = OAuthError with self.app.app_context(): response: Response = self.client.post(route, data=json.dumps(body), headers=headers) self.assertTrue(response.status_code, 401)