"""Tests for the graphql_router model.""" from unittest.mock import call, patch import pytest from callee import Matching from gql import gql as gql_query from notifications.constants import context from notifications.models import graphql_router @patch('notifications.models.graphql_router.Client', autospec=True) @patch('notifications.models.graphql_router.RequestsHTTPTransport', autospec=True) def test_make_request(mock_gql_transport, mock_gql_client): """Test low level graphql_router requests.""" mock_query = """ query doSomething { func { data { id } } } """ mock_variables = {'abc': '123'} graphql_router._make_request(mock_query, mock_variables, headers={'xyz': '456'}) test_url = 'https://test-graphql-router.theorchard.io/graphql' mock_gql_transport.assert_called_once_with( headers={ 'xyz': '456', 'apollographql-client-name': 'ows-notifications', 'apollographql-client-version': '1', }, retries=3, url=test_url, use_json=True, verify=True, ) mock_gql_client.assert_called_once_with( fetch_schema_from_transport=False, transport=mock_gql_transport(url=test_url) ) mock_gql_client.return_value.execute.assert_called_once_with( Matching(lambda v: str(v) == str(gql_query(mock_query))), variable_values=mock_variables ) @pytest.mark.parametrize( 'mock_graph_response, expected_result', [ ({'globalSoundRecordingByISRC': None}, (None, None, [])), ( { 'globalSoundRecordingByISRC': { 'globalParticipants': [{'id': 'yyy'}, {'id': 'zzz'}], 'name': 'bbb', 'id': 'aaa', } }, ('aaa', 'bbb', ['yyy', 'zzz']), ), ], ) def test_get_sound_recording_details(mocker, mock_graph_response, expected_result): """Test get sound recording details.""" mock_call = mocker.patch.object( graphql_router, '_make_request', return_value=mock_graph_response ) result = graphql_router.get_sound_recording_details('abcd') assert result == expected_result assert mock_call.call_args_list == [ call( 'query globalSoundRecordingByISRC($term: String!) { globalSoundRecordingByISRC(isrc: $term) { id, name, globalParticipants {id} } }', # noqa:E501 {'term': 'abcd'}, context.NOTIFICATION_USER_HEADERS, ) ] @pytest.mark.parametrize( 'mock_graph_response, expected_result', [ ({'globalParticipantByChartmetricId': None}, (None, None)), ({'globalParticipantByChartmetricId': [{'id': 'aaa', 'name': 'bbb'}]}, ('aaa', 'bbb')), ], ) def test_get_participant_by_chartmetric_id(mocker, mock_graph_response, expected_result): """Test get participant by chartmetric id.""" mock_call = mocker.patch.object( graphql_router, '_make_request', return_value=mock_graph_response ) result = graphql_router.get_participant_by_chartmetric_id('xyz') assert result == expected_result assert mock_call.call_args_list == [ call( 'query globalParticipantByChartmetricId($term: Int!) { globalParticipantByChartmetricId(chartmetricId: $term) { id, name } }', # noqa:E501 {'term': 'xyz'}, context.NOTIFICATION_USER_HEADERS, ) ]