-
Notifications
You must be signed in to change notification settings - Fork 121
/
rpcmock.go
49 lines (43 loc) · 1019 Bytes
/
rpcmock.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package testutils
import (
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
)
type mockReq struct {
JsonRpc string `json:"jsonrpc"`
ID float64 `json:"id"`
Method string `json:"method"`
}
type mockRes struct {
JsonRpc string `json:"jsonrpc"`
ID float64 `json:"id"`
Result any `json:"result"`
}
type MethodMocks map[string]any
func RpcMock(mocks MethodMocks) *httptest.Server {
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var req mockReq
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
panic(err)
}
mock, ok := mocks[req.Method]
if !ok {
w.WriteHeader(http.StatusBadRequest)
if _, err := w.Write([]byte(fmt.Sprintf("method not in mocks: %s", req.Method))); err != nil {
panic(err)
}
return
}
res := &mockRes{
JsonRpc: req.JsonRpc,
ID: req.ID,
Result: mock,
}
w.WriteHeader(http.StatusOK)
if err := json.NewEncoder(w).Encode(res); err != nil {
panic(err)
}
}))
}