12 "github.com/vapor/testutil"
15 func TestRPCCallJSON(t *testing.T) {
16 requestBody := map[string]interface{}{
20 // the TestResponse is same with api Response
21 type TestResponse struct {
22 Status string `json:"status,omitempty"`
23 Msg string `json:"msg,omitempty"`
24 Data interface{} `json:"data,omitempty"`
27 response := &TestResponse{}
28 result := &TestResponse{
34 server := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
35 // Inspect the request and ensure that it's what we expect.
36 if req.Header.Get("Content-Type") != "application/json" {
37 t.Errorf("got=%s; want=application/json", req.Header.Get("Content-Type"))
39 if !strings.HasPrefix(req.Header.Get("User-Agent"), "Bytom; ") {
40 t.Errorf("got=%s; want prefix='Bytom; '", req.Header.Get("User-Agent"))
42 if req.URL.Path != "/example/rpc/path" {
43 t.Errorf("got=%s want=/example/rpc/path", req.URL.Path)
45 un, pw, ok := req.BasicAuth()
47 t.Error("no user/password set")
48 } else if un != "test-user" {
49 t.Errorf("got=%s; want=test-user", un)
50 } else if pw != "test-secret" {
51 t.Errorf("got=%s; want=test-secret", pw)
54 decodedRequestBody := map[string]interface{}{}
55 if err := json.NewDecoder(req.Body).Decode(&decodedRequestBody); err != nil {
58 defer req.Body.Close()
59 if !testutil.DeepEqual(decodedRequestBody, requestBody) {
60 t.Errorf("got=%#v; want=%#v", decodedRequestBody, requestBody)
63 // Provide a dummy rpc response
64 rw.Header().Set("Content-Type", "application/json")
65 data, err := json.Marshal(result)
73 //response := map[string]string{}
76 AccessToken: "test-user:test-secret",
78 err := client.Call(context.Background(), "/example/rpc/path", requestBody, &response)
83 // Ensure that the response is as we expect.
84 if !testutil.DeepEqual(response, result) {
85 t.Errorf(`got=%#v; want=%#v`, response, result)
88 // Ensure that supplying a nil response is OK.
89 err = client.Call(context.Background(), "/example/rpc/path", requestBody, nil)
95 func TestRPCCallError(t *testing.T) {
96 server := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
97 http.Error(rw, "a terrible error", http.StatusInternalServerError)
101 client := &Client{BaseURL: server.URL}
102 wantErr := ErrStatusCode{URL: server.URL + "/error", StatusCode: 500}
103 err := client.Call(context.Background(), "/error", nil, nil)
104 if !testutil.DeepEqual(wantErr, err) {
105 t.Errorf("got=%#v; want=%#v", err, wantErr)
109 func TestCleanedURLString(t *testing.T) {
110 u, _ := url.Parse("https://user:pass@foobar.com")
111 want := "https://foobar.com"
113 got := cleanedURLString(u)
115 t.Errorf("clean = %q want %q", got, want)