github.com/bytom/bytom@v1.1.2-0.20221014091027-bbcba3df6075/api/api_test.go (about) 1 package api 2 3 import ( 4 "context" 5 "net/http/httptest" 6 "os" 7 "testing" 8 9 "github.com/bytom/bytom/accesstoken" 10 "github.com/bytom/bytom/blockchain/rpc" 11 dbm "github.com/bytom/bytom/database/leveldb" 12 "github.com/bytom/bytom/testutil" 13 ) 14 15 func TestAPIHandler(t *testing.T) { 16 a := &API{} 17 response := &Response{} 18 19 // init httptest server 20 a.buildHandler() 21 server := httptest.NewServer(a.handler) 22 defer server.Close() 23 24 // create accessTokens 25 testDB := dbm.NewDB("testdb", "leveldb", "temp") 26 defer os.RemoveAll("temp") 27 a.accessTokens = accesstoken.NewStore(testDB) 28 29 client := &rpc.Client{ 30 BaseURL: server.URL, 31 AccessToken: "test-user:test-secret", 32 } 33 34 cases := []struct { 35 path string 36 request interface{} 37 respWant *Response 38 }{ 39 { 40 path: "/create-key", 41 request: struct { 42 Alias string `json:"alias"` 43 Password string `json:"password"` 44 }{Alias: "alice", Password: "123456"}, 45 respWant: &Response{ 46 Status: "fail", 47 Msg: "wallet not found, please check that the wallet is open", 48 }, 49 }, 50 { 51 path: "/error", 52 request: nil, 53 respWant: &Response{ 54 Status: "fail", 55 Msg: "wallet not found, please check that the wallet is open", 56 }, 57 }, 58 { 59 path: "/", 60 request: nil, 61 respWant: &Response{ 62 Status: "", 63 Msg: "", 64 }, 65 }, 66 { 67 path: "/create-access-token", 68 request: struct { 69 ID string `json:"id"` 70 Type string `json:"type"` 71 }{ID: "test-access-id", Type: "test-access-type"}, 72 respWant: &Response{ 73 Status: "success", 74 Msg: "", 75 Data: map[string]interface{}{"id": "test-access-id", "type": "test-access-type", "token": "test-access-id:440d87ae0d625a7fcf076275b18372e09a0899e37ec86398879388de90cb0c67"}, 76 }, 77 }, 78 { 79 path: "/gas-rate", 80 request: nil, 81 respWant: &Response{ 82 Status: "success", 83 Msg: "", 84 Data: map[string]interface{}{"gasRate": 1000}, 85 }, 86 }, 87 } 88 89 for _, c := range cases { 90 response = &Response{} 91 client.Call(context.Background(), c.path, c.request, &response) 92 93 if !testutil.DeepEqual(response.Status, c.respWant.Status) { 94 t.Errorf(`got=%#v; want=%#v`, response.Status, c.respWant.Status) 95 } 96 } 97 }