OSDN Git Service

add rpc test (#503)
authoroysheng <33340252+oysheng@users.noreply.github.com>
Fri, 30 Mar 2018 10:51:22 +0000 (18:51 +0800)
committerPaladz <yzhu101@uottawa.ca>
Fri, 30 Mar 2018 10:51:22 +0000 (18:51 +0800)
* add rpc test
delete the no used function NetInfo

* fix BTM format fot transaction request

blockchain/rpc/net.go [deleted file]
blockchain/rpc/rpc_test.go [new file with mode: 0644]
cmd/bytomcli/commands/transaction.go

diff --git a/blockchain/rpc/net.go b/blockchain/rpc/net.go
deleted file mode 100644 (file)
index 309c50b..0000000
+++ /dev/null
@@ -1,28 +0,0 @@
-package rpc
-
-import (
-       ctypes "github.com/bytom/blockchain/rpc/types"
-       "github.com/bytom/p2p"
-)
-
-// NetInfo return p2p net status
-func NetInfo(p2pSwitch *p2p.Switch) (*ctypes.ResultNetInfo, error) {
-       listening := p2pSwitch.IsListening()
-       listeners := []string{}
-       for _, listener := range p2pSwitch.Listeners() {
-               listeners = append(listeners, listener.String())
-       }
-       peers := []ctypes.Peer{}
-       for _, peer := range p2pSwitch.Peers().List() {
-               peers = append(peers, ctypes.Peer{
-                       NodeInfo:         *peer.NodeInfo,
-                       IsOutbound:       peer.IsOutbound(),
-                       ConnectionStatus: peer.Connection().Status(),
-               })
-       }
-       return &ctypes.ResultNetInfo{
-               Listening: listening,
-               Listeners: listeners,
-               Peers:     peers,
-       }, nil
-}
diff --git a/blockchain/rpc/rpc_test.go b/blockchain/rpc/rpc_test.go
new file mode 100644 (file)
index 0000000..7f6a478
--- /dev/null
@@ -0,0 +1,117 @@
+package rpc
+
+import (
+       "context"
+       "encoding/json"
+       "net/http"
+       "net/http/httptest"
+       "net/url"
+       "strings"
+       "testing"
+
+       "github.com/bytom/testutil"
+)
+
+func TestRPCCallJSON(t *testing.T) {
+       requestBody := map[string]interface{}{
+               "hello": "world",
+       }
+
+       // the TestResponse is same with api Response
+       type TestResponse struct {
+               Status string      `json:"status,omitempty"`
+               Msg    string      `json:"msg,omitempty"`
+               Data   interface{} `json:"data,omitempty"`
+       }
+
+       response := &TestResponse{}
+       result := &TestResponse{
+               Status: "success",
+               Msg:    "right",
+               Data:   requestBody,
+       }
+
+       server := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
+               // Inspect the request and ensure that it's what we expect.
+               if req.Header.Get("Content-Type") != "application/json" {
+                       t.Errorf("got=%s; want=application/json", req.Header.Get("Content-Type"))
+               }
+               if !strings.HasPrefix(req.Header.Get("User-Agent"), "Bytom; ") {
+                       t.Errorf("got=%s; want prefix='Bytom; '", req.Header.Get("User-Agent"))
+               }
+               if req.URL.Path != "/example/rpc/path" {
+                       t.Errorf("got=%s want=/example/rpc/path", req.URL.Path)
+               }
+               un, pw, ok := req.BasicAuth()
+               if !ok {
+                       t.Error("no user/password set")
+               } else if un != "test-user" {
+                       t.Errorf("got=%s; want=test-user", un)
+               } else if pw != "test-secret" {
+                       t.Errorf("got=%s; want=test-secret", pw)
+               }
+
+               decodedRequestBody := map[string]interface{}{}
+               if err := json.NewDecoder(req.Body).Decode(&decodedRequestBody); err != nil {
+                       t.Fatal(err)
+               }
+               defer req.Body.Close()
+               if !testutil.DeepEqual(decodedRequestBody, requestBody) {
+                       t.Errorf("got=%#v; want=%#v", decodedRequestBody, requestBody)
+               }
+
+               // Provide a dummy rpc response
+               rw.Header().Set("Content-Type", "application/json")
+               data, err := json.Marshal(result)
+               if err != nil {
+                       t.Fatal(err)
+               }
+               rw.Write(data)
+       }))
+       defer server.Close()
+
+       //response := map[string]string{}
+       client := &Client{
+               BaseURL:     server.URL,
+               AccessToken: "test-user:test-secret",
+       }
+       err := client.Call(context.Background(), "/example/rpc/path", requestBody, &response)
+       if err != nil {
+               t.Fatal(err)
+       }
+
+       // Ensure that the response is as we expect.
+       if !testutil.DeepEqual(response, result) {
+               t.Errorf(`got=%#v; want=%#v`, response, result)
+       }
+
+       // Ensure that supplying a nil response is OK.
+       err = client.Call(context.Background(), "/example/rpc/path", requestBody, nil)
+       if err != nil {
+               t.Fatal(err)
+       }
+}
+
+func TestRPCCallError(t *testing.T) {
+       server := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
+               http.Error(rw, "a terrible error", http.StatusInternalServerError)
+       }))
+       defer server.Close()
+
+       client := &Client{BaseURL: server.URL}
+       wantErr := ErrStatusCode{URL: server.URL + "/error", StatusCode: 500}
+       err := client.Call(context.Background(), "/error", nil, nil)
+       if !testutil.DeepEqual(wantErr, err) {
+               t.Errorf("got=%#v; want=%#v", err, wantErr)
+       }
+}
+
+func TestCleanedURLString(t *testing.T) {
+       u, _ := url.Parse("https://user:pass@foobar.com")
+       want := "https://foobar.com"
+
+       got := cleanedURLString(u)
+       if got != want {
+               t.Errorf("clean = %q want %q", got, want)
+       }
+}
index edab496..c68dd88 100644 (file)
@@ -54,7 +54,7 @@ var buildIssueReqFmt = `
 
 var buildIssueReqFmtByAlias = `
        {"actions": [
-               {"type": "spend_account", "asset_alias": "btm", "amount":%s, "account_alias": "%s"},
+               {"type": "spend_account", "asset_alias": "BTM", "amount":%s, "account_alias": "%s"},
                {"type": "issue", "asset_alias": "%s", "amount": %s},
                {"type": "control_account", "asset_alias": "%s", "amount": %s, "account_alias": "%s"}
        ]}`
@@ -68,7 +68,7 @@ var buildSpendReqFmt = `
 
 var buildSpendReqFmtByAlias = `
        {"actions": [
-               {"type": "spend_account", "asset_alias": "btm", "amount":%s, "account_alias": "%s"},
+               {"type": "spend_account", "asset_alias": "BTM", "amount":%s, "account_alias": "%s"},
                {"type": "spend_account", "asset_alias": "%s","amount": %s,"account_alias": "%s"},
                {"type": "control_receiver", "asset_alias": "%s", "amount": %s, "receiver":{"control_program": "%s","expires_at":"2017-12-28T12:52:06.78309768+08:00"}}
        ]}`
@@ -82,7 +82,7 @@ var buildRetireReqFmt = `
 
 var buildRetireReqFmtByAlias = `
        {"actions": [
-               {"type": "spend_account", "asset_alias": "btm", "amount":%s, "account_alias": "%s"},
+               {"type": "spend_account", "asset_alias": "BTM", "amount":%s, "account_alias": "%s"},
                {"type": "spend_account", "asset_alias": "%s","amount": %s,"account_alias": "%s"},
                {"type": "retire", "asset_alias": "%s","amount": %s,"account_alias": "%s"}
        ]}`
@@ -96,7 +96,7 @@ var buildControlAddressReqFmt = `
 
 var buildControlAddressReqFmtByAlias = `
        {"actions": [
-               {"type": "spend_account", "asset_id": "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", "amount":%s, "account_alias": "%s"},
+               {"type": "spend_account", "asset_alias": "BTM", "amount":%s, "account_alias": "%s"},
                {"type": "spend_account", "asset_alias": "%s","amount": %s, "account_alias": "%s"},
                {"type": "control_address", "asset_alias": "%s", "amount": %s,"address": "%s"}
        ]}`