github.com/ari-anchor/sei-tendermint@v0.0.0-20230519144642-dc826b7b56bb/test/fuzz/tests/rpc_jsonrpc_server_test.go (about) 1 //go:build gofuzz || go1.18 2 3 package tests 4 5 import ( 6 "bytes" 7 "context" 8 "encoding/json" 9 "io" 10 "net/http" 11 "net/http/httptest" 12 "testing" 13 14 "github.com/ari-anchor/sei-tendermint/libs/log" 15 rpcserver "github.com/ari-anchor/sei-tendermint/rpc/jsonrpc/server" 16 "github.com/ari-anchor/sei-tendermint/rpc/jsonrpc/types" 17 ) 18 19 func FuzzRPCJSONRPCServer(f *testing.F) { 20 type args struct { 21 S string `json:"s"` 22 I int `json:"i"` 23 } 24 var rpcFuncMap = map[string]*rpcserver.RPCFunc{ 25 "c": rpcserver.NewRPCFunc(func(context.Context, *args) (string, error) { 26 return "foo", nil 27 }), 28 } 29 30 mux := http.NewServeMux() 31 rpcserver.RegisterRPCFuncs(mux, rpcFuncMap, log.NewNopLogger()) 32 f.Fuzz(func(t *testing.T, data []byte) { 33 if len(data) == 0 { 34 return 35 } 36 37 req, err := http.NewRequest("POST", "http://localhost/", bytes.NewReader(data)) 38 if err != nil { 39 panic(err) 40 } 41 rec := httptest.NewRecorder() 42 mux.ServeHTTP(rec, req) 43 res := rec.Result() 44 blob, err := io.ReadAll(res.Body) 45 if err != nil { 46 panic(err) 47 } 48 if err := res.Body.Close(); err != nil { 49 panic(err) 50 } 51 if len(blob) == 0 { 52 return 53 } 54 55 if outputJSONIsSlice(blob) { 56 var recv []types.RPCResponse 57 if err := json.Unmarshal(blob, &recv); err != nil { 58 panic(err) 59 } 60 return 61 } 62 var recv types.RPCResponse 63 if err := json.Unmarshal(blob, &recv); err != nil { 64 panic(err) 65 } 66 }) 67 } 68 69 func outputJSONIsSlice(input []byte) bool { 70 var slice []json.RawMessage 71 return json.Unmarshal(input, &slice) == nil 72 }