private void MockResponse(RpcRequest request, RpcResponse response) { handlerMock.Protected() // Setup the PROTECTED method to mock .Setup <Task <HttpResponseMessage> >( "SendAsync", ItExpr.Is <HttpRequestMessage>(p => p.Content.ReadAsStringAsync().Result == request.ToJson().ToString()), ItExpr.IsAny <CancellationToken>() ) // prepare the expected response of the mocked http call .ReturnsAsync(new HttpResponseMessage() { StatusCode = HttpStatusCode.OK, Content = new StringContent(response.ToJson().ToString()), }) .Verifiable(); }
private async void Start() { while (listener.IsListening) { try { HttpListenerContext context = await listener.GetContextAsync(); var requestContent = new StreamReader(context.Request.InputStream).ReadToEnd(); Result <object, RpcError> result; MethodCallContext? call = null; try { call = MethodCallContext.FromJson(requestContent); if (call.JsonRpcVersion != RpcManager.JsonRpcVersion) { result = new Result <object, RpcError>( new InvalidRequest($"Incompatible RPC versions call {call.JsonRpcVersion} vs current {RpcManager.JsonRpcVersion}")); } else { result = RpcManager.Invoke(call.MethodName, call.Params.ToArray()); } } catch (Exception e) { result = new Result <object, RpcError>((ParseError)e); } var response = RpcResponse.ToJson(RpcManager.JsonRpcVersion, result, call == null ? 0 : call.Id); byte[] buffer = System.Text.Encoding.UTF8.GetBytes(response); context.Response.ContentLength64 = buffer.Length; context.Response.OutputStream.Write(buffer, 0, buffer.Length); context.Response.OutputStream.Close(); // Must close output stream } catch (ObjectDisposedException) { return; } } }
public void TestToJson() { var error = new RpcResponseError() { Code = 0, Message = "msg", Data = new JBoolean(true) }; var rep = new RpcResponse() { Id = 1, Jsonrpc = "rpc", Error = error, Result = new JBoolean(true) }; var json = rep.ToJson(); json["id"].AsNumber().Should().Be(1); json["jsonrpc"].AsString().Should().Be("rpc"); json["error"].AsString().Should().Be(error.ToJson().AsString()); json["result"].AsBoolean().Should().BeTrue(); }