import pytest
import json

from io import BytesIO
from poe_new_relic.api import NewRelic, NERDGRAPH_URL
from test_utils.mock import MockApi
from typing import Tuple


class TestNewRelic_UnitTests:

    @pytest.mark.unit
    def test_nerdgraph_entitysearch(self):
        # Set expected values
        expected_api_key = 'derp'
        expected_query = 'sql'
        expected_output_keys = 'keys'
        expected_next_cursor = ''
        expected_on = '... on SyntheticMonitorEntityOutline'
        expected_full_query = {"query":f"{{actor {{{expected_query} {{results{expected_next_cursor} {{entities {{{expected_on} {expected_output_keys}}}nextCursor}}}}}}}}", "variables":""}
        expected_resp_json = {'data': {'actor': {'entitySearch': {'results': [{'name': 'derp'}]}}}}

        # Set up mocks
        mock_request = MockApi()
        setattr(mock_request, 'url',  NERDGRAPH_URL)
        setattr(mock_request, 'method', 'POST')
        setattr(mock_request, 'headers', {})
        mock_resp = MockApi()
        setattr(mock_resp, 'request', mock_request)
        mock_resp.on('raise_for_status').return_val(None)
        mock_resp.on('json').return_val(expected_resp_json)
        mock_http_session = MockApi()
        mock_http_session.on(
            'post',
            NERDGRAPH_URL,
            headers={
                'Accept': 'application/json',
                'Api-Key': expected_api_key,
                'Content-Type': 'application/json'
            },
            data=json.dumps(expected_full_query)
        ).return_val(mock_resp)

        # Test get_compliance_scores()
        nr = NewRelic(expected_api_key, http_session=mock_http_session)
        resp = nr.nerdgraph_entitysearch(expected_query, expected_output_keys, on=expected_on)
        assert resp == expected_resp_json
        mock_resp.assert_expectations()
        mock_http_session.assert_expectations()
