github.com/zignig/go-ipfs@v0.0.0-20141111235910-c9e5fdf55a52/server/http/http_test.go (about) 1 package http 2 3 import ( 4 "bytes" 5 "errors" 6 "io" 7 "io/ioutil" 8 "net/http" 9 "net/http/httptest" 10 "strings" 11 "testing" 12 13 dag "github.com/jbenet/go-ipfs/merkledag" 14 u "github.com/jbenet/go-ipfs/util" 15 ) 16 17 type test struct { 18 url string 19 code int 20 reqbody string 21 respbody string 22 } 23 24 func TestServeHTTP(t *testing.T) { 25 testhandler := &handler{&testIpfsHandler{}} 26 tests := []test{ 27 {"/ipfs/", http.StatusInternalServerError, "", ""}, 28 {"/ipfs/hash", http.StatusOK, "", "some fine data"}, 29 {"/ipfs/hash2", http.StatusInternalServerError, "", ""}, 30 } 31 32 for _, test := range tests { 33 req, _ := http.NewRequest("GET", test.url, nil) 34 resp := httptest.NewRecorder() 35 testhandler.ServeHTTP(resp, req) 36 37 if resp.Code != test.code { 38 t.Error("expected status code", test.code, "received", resp.Code) 39 } 40 41 if resp.Body.String() != test.respbody { 42 t.Error("expected body:", test.respbody) 43 t.Error("received body:", resp.Body) 44 } 45 } 46 } 47 48 func TestPostHandler(t *testing.T) { 49 testhandler := &handler{&testIpfsHandler{}} 50 tests := []test{ 51 {"/ifps/", http.StatusInternalServerError, "", ""}, 52 {"/ipfs/", http.StatusInternalServerError, "something that causes an error in adding to DAG", ""}, 53 {"/ipfs/", http.StatusCreated, "some fine data", "jSQBpNSebeYbPBjs1vp"}, 54 } 55 56 for _, test := range tests { 57 req, _ := http.NewRequest("POST", test.url, strings.NewReader(test.reqbody)) 58 resp := httptest.NewRecorder() 59 testhandler.postHandler(resp, req) 60 61 if resp.Code != test.code { 62 t.Error("expected status code", test.code, "received", resp.Code) 63 } 64 65 if resp.Body.String() != test.respbody { 66 t.Error("expected body:", test.respbody) 67 t.Error("received body:", resp.Body) 68 } 69 } 70 } 71 72 type testIpfsHandler struct{} 73 74 func (i *testIpfsHandler) ResolvePath(path string) (*dag.Node, error) { 75 if path == "/hash" { 76 return &dag.Node{Data: []byte("some fine data")}, nil 77 } 78 79 if path == "/hash2" { 80 return &dag.Node{Data: []byte("data that breaks dagreader")}, nil 81 } 82 83 return nil, errors.New("") 84 } 85 86 func (i *testIpfsHandler) NewDagFromReader(r io.Reader) (*dag.Node, error) { 87 if data, err := ioutil.ReadAll(r); err == nil { 88 return &dag.Node{Data: data}, nil 89 } 90 91 return nil, errors.New("") 92 } 93 94 func (i *testIpfsHandler) AddNodeToDAG(nd *dag.Node) (u.Key, error) { 95 if len(nd.Data) != 0 && string(nd.Data) != "something that causes an error in adding to DAG" { 96 return u.Key(nd.Data), nil 97 } 98 99 return "", errors.New("") 100 } 101 102 func (i *testIpfsHandler) NewDagReader(nd *dag.Node) (io.Reader, error) { 103 if string(nd.Data) != "data that breaks dagreader" { 104 return bytes.NewReader(nd.Data), nil 105 } 106 107 return nil, errors.New("") 108 }