From 31558fe3b4dcc9736867a861a1d46a177121d726 Mon Sep 17 00:00:00 2001 From: Fedor Korotkiy Date: Thu, 16 Apr 2020 17:20:03 +0300 Subject: [PATCH] Add jsonrpc --- jsonrpc/jsonrpc.go | 13 ++++++++ jsonrpc/jsonrpc_test.go | 69 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 82 insertions(+) diff --git a/jsonrpc/jsonrpc.go b/jsonrpc/jsonrpc.go index 389dd15..2a52257 100644 --- a/jsonrpc/jsonrpc.go +++ b/jsonrpc/jsonrpc.go @@ -1,3 +1,16 @@ // +build !solution package jsonrpc + +import ( + "context" + "net/http" +) + +func MakeHandler(service interface{}) http.Handler { + panic("implement me") +} + +func Call(ctx context.Context, endpoint string, method string, req, rsp interface{}) error { + panic("implement me") +} diff --git a/jsonrpc/jsonrpc_test.go b/jsonrpc/jsonrpc_test.go index 29a4d6a..df7c74e 100644 --- a/jsonrpc/jsonrpc_test.go +++ b/jsonrpc/jsonrpc_test.go @@ -1 +1,70 @@ package jsonrpc + +import ( + "context" + "fmt" + "net/http/httptest" + "testing" + + "github.com/stretchr/testify/require" +) + +type testService struct{} + +type PingRequest struct{} +type PingResponse struct{} + +func (*testService) Ping(ctx context.Context, req *PingRequest) (*PingResponse, error) { + return &PingResponse{}, nil +} + +type AddRequest struct{ A, B int } +type AddResponse struct{ Sum int } + +func (*testService) Add(ctx context.Context, req *AddRequest) (*AddResponse, error) { + return &AddResponse{Sum: req.A + req.B}, nil +} + +type ErrorRequest struct{} +type ErrorResponse struct{} + +func (*testService) Error(ctx context.Context, req *ErrorRequest) (*ErrorResponse, error) { + return nil, fmt.Errorf("cache is empty") +} + +func TestJSONRPC(t *testing.T) { + server := httptest.NewServer(MakeHandler(&testService{})) + defer server.Close() + + ctx := context.Background() + + t.Run("Ping", func(t *testing.T) { + var ( + req PingRequest + rsp PingResponse + ) + + require.NoError(t, Call(ctx, server.URL, "Ping", &req, &rsp)) + }) + + t.Run("Add", func(t *testing.T) { + var ( + req = AddRequest{A: 1, B: 2} + rsp AddResponse + ) + + require.NoError(t, Call(ctx, server.URL, "Add", &req, &rsp)) + require.Equal(t, 3, rsp.Sum) + }) + + t.Run("Error", func(t *testing.T) { + var ( + req ErrorRequest + rsp ErrorResponse + ) + + err := Call(ctx, server.URL, "Error", &req, &rsp) + require.Error(t, err) + require.Contains(t, err.Error(), "cache is empty") + }) +}