"""
Contains tests that assert the compliance with the
JSON RPC 2.0 specifications (http://www.jsonrpc.org/specification)
"""

import logging

import simplejson as json
import pytest

from tests.services.service_jsonrpc_specs import ServiceJsonRpcSpecs


@pytest.fixture
def app():
    service = ServiceJsonRpcSpecs()
    service._initial_setup()
    return service.make_tornado_app()


@pytest.mark.gen_test
def test_incomplete_json(http_client, base_url):
    body = json.dumps({"jsonrpc": "2.0", "method": "subtract"})[:15]
    result = yield http_client.fetch(base_url + "/api", method="POST", body=body,
                                     headers={"content-type": "application/json"})

    assert result.code == 200
    response_body = json.loads(result.body)
    assert response_body["result"] is None
    assert response_body["jsonrpc"] == "2.0"
    assert response_body["error"] == {"code": -32700, "message": "Parse error"}


# examples from http://www.jsonrpc.org/specification

@pytest.mark.gen_test
def test_rpc_call_with_positional_parameters(http_client, base_url):
    base_url += "/api"
    body = json.dumps({"jsonrpc": "2.0", "method": "subtract", "params": [42, 23], "id": 1})
    result = yield http_client.fetch(base_url, method="POST", body=body,
                                     headers={"content-type": "application/json"})

    assert result.code == 200
    response_body = json.loads(result.body)
    assert response_body["jsonrpc"] == "2.0"
    assert response_body["result"] == 19
    assert response_body["id"] == 1

    body = json.dumps({"jsonrpc": "2.0", "method": "subtract", "params": [23, 42], "id": 2})
    result = yield http_client.fetch(base_url, method="POST", body=body,
                                     headers={"content-type": "application/json"})