github.com/Bytom/bytom@v1.1.2-0.20210127130405-ae40204c0b09/blockchain/rpc/rpc_test.go (about)

     1  package rpc
     2  
     3  import (
     4  	"context"
     5  	"encoding/json"
     6  	"net/http"
     7  	"net/http/httptest"
     8  	"net/url"
     9  	"strings"
    10  	"testing"
    11  
    12  	"github.com/bytom/bytom/testutil"
    13  )
    14  
    15  func TestRPCCallJSON(t *testing.T) {
    16  	requestBody := map[string]interface{}{
    17  		"hello": "world",
    18  	}
    19  
    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"`
    25  	}
    26  
    27  	response := &TestResponse{}
    28  	result := &TestResponse{
    29  		Status: "success",
    30  		Msg:    "right",
    31  		Data:   requestBody,
    32  	}
    33  
    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"))
    38  		}
    39  		if !strings.HasPrefix(req.Header.Get("User-Agent"), "Bytom; ") {
    40  			t.Errorf("got=%s; want prefix='Bytom; '", req.Header.Get("User-Agent"))
    41  		}
    42  		if req.URL.Path != "/example/rpc/path" {
    43  			t.Errorf("got=%s want=/example/rpc/path", req.URL.Path)
    44  		}
    45  		un, pw, ok := req.BasicAuth()
    46  		if !ok {
    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)
    52  		}
    53  
    54  		decodedRequestBody := map[string]interface{}{}
    55  		if err := json.NewDecoder(req.Body).Decode(&decodedRequestBody); err != nil {
    56  			t.Fatal(err)
    57  		}
    58  		defer req.Body.Close()
    59  		if !testutil.DeepEqual(decodedRequestBody, requestBody) {
    60  			t.Errorf("got=%#v; want=%#v", decodedRequestBody, requestBody)
    61  		}
    62  
    63  		// Provide a dummy rpc response
    64  		rw.Header().Set("Content-Type", "application/json")
    65  		data, err := json.Marshal(result)
    66  		if err != nil {
    67  			t.Fatal(err)
    68  		}
    69  		rw.Write(data)
    70  	}))
    71  	defer server.Close()
    72  
    73  	//response := map[string]string{}
    74  	client := &Client{
    75  		BaseURL:     server.URL,
    76  		AccessToken: "test-user:test-secret",
    77  	}
    78  	err := client.Call(context.Background(), "/example/rpc/path", requestBody, &response)
    79  	if err != nil {
    80  		t.Fatal(err)
    81  	}
    82  
    83  	// Ensure that the response is as we expect.
    84  	if !testutil.DeepEqual(response, result) {
    85  		t.Errorf(`got=%#v; want=%#v`, response, result)
    86  	}
    87  
    88  	// Ensure that supplying a nil response is OK.
    89  	err = client.Call(context.Background(), "/example/rpc/path", requestBody, nil)
    90  	if err != nil {
    91  		t.Fatal(err)
    92  	}
    93  }
    94  
    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)
    98  	}))
    99  	defer server.Close()
   100  
   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)
   106  	}
   107  }
   108  
   109  func TestCleanedURLString(t *testing.T) {
   110  	u, _ := url.Parse("https://user:pass@foobar.com")
   111  	want := "https://foobar.com"
   112  
   113  	got := cleanedURLString(u)
   114  	if got != want {
   115  		t.Errorf("clean = %q want %q", got, want)
   116  	}
   117  }