github.com/gagliardetto/solana-go@v1.11.0/rpc/rpc_test.go (about) 1 // Copyright 2021 github.com/gagliardetto 2 // This file has been modified by github.com/gagliardetto 3 // 4 // Copyright 2020 dfuse Platform Inc. 5 // 6 // Licensed under the Apache License, Version 2.0 (the "License"); 7 // you may not use this file except in compliance with the License. 8 // You may obtain a copy of the License at 9 // 10 // http://www.apache.org/licenses/LICENSE-2.0 11 // 12 // Unless required by applicable law or agreed to in writing, software 13 // distributed under the License is distributed on an "AS IS" BASIS, 14 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 // See the License for the specific language governing permissions and 16 // limitations under the License. 17 18 package rpc 19 20 import ( 21 stdjson "encoding/json" 22 "io/ioutil" 23 "net/http" 24 "net/http/httptest" 25 "testing" 26 27 "github.com/stretchr/testify/require" 28 ) 29 30 type mockJSONRPCServer struct { 31 *httptest.Server 32 body []byte 33 } 34 35 func mockJSONRPC(t *testing.T, response interface{}) (mock *mockJSONRPCServer, close func()) { 36 mock = &mockJSONRPCServer{ 37 Server: httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { 38 var err error 39 mock.body, err = ioutil.ReadAll(req.Body) 40 require.NoError(t, err) 41 42 var responseBody []byte 43 if v, ok := response.(stdjson.RawMessage); ok { 44 responseBody = v 45 } else { 46 responseBody, err = json.Marshal(response) 47 require.NoError(t, err) 48 } 49 50 rw.Write(responseBody) 51 })), 52 } 53 54 return mock, func() { mock.Close() } 55 } 56 57 func (s *mockJSONRPCServer) RequestBodyAsJSON(t *testing.T) (out string) { 58 return string(s.body) 59 } 60 61 func (s *mockJSONRPCServer) RequestBody(t *testing.T) (out map[string]interface{}) { 62 err := json.Unmarshal(s.body, &out) 63 require.NoError(t, err) 64 65 return out 66 }