"""Test the token handler.""" import json import flexmock from oto import status from auth.connectors import sentry from auth.logic import api from tests.fixtures import fixture_token TOKEN_URL = '/token' def test_getting_access_token(fixture_client): """Test getting access token.""" code_token = fixture_token.get_code_token_data() access_token = fixture_token.get_ows_user_access_token_response() (flexmock(api) .should_receive('get_access_token') .with_args(headers=None, data=code_token) .and_return(access_token) .once()) result = fixture_client.post(TOKEN_URL, data=code_token) content = json.loads(result.data.decode('utf8')) assert result.status_code == status.OK assert content == access_token.message def test_getting_access_token_with_x_forwarding_ip_header(fixture_client): """Test getting an access token with a forwarding up.""" code_token = fixture_token.get_code_token_data() headers = {'X-Forwarded-For': '127.0.0.1'} access_token = fixture_token.get_ows_user_access_token_response() (flexmock(api) .should_receive('get_access_token') .with_args(headers=headers, data=code_token) .and_return(access_token) .once()) result = fixture_client.post(TOKEN_URL, data=code_token, headers=headers) assert result.status_code == status.OK def test_token_api_fails(fixture_client): """Test failures.""" error = 'Oh no, everything is horrible' token_response = fixture_token.get_ows_users_token_failure_response(error) data = fixture_token.get_code_token_data() (flexmock(api) .should_receive('get_access_token') .with_args(headers=None, data=data) .and_return(token_response) .once()) (flexmock(sentry) .should_receive('send_response_to_sentry') .with_args( token_response, message='Failed call to Grass /token' ) .once()) result = fixture_client.post(TOKEN_URL, data=data) assert result.status_code == status.BAD_REQUEST