master
go 76 lines 1.86 KB
Raw
1 package corehttp
2
3 import (
4 "fmt"
5 "io"
6 "net/http"
7 "net/http/httptest"
8 "testing"
9
10 version "github.com/ipfs/kubo"
11 )
12
13 type testcasecheckversion struct {
14 userAgent string
15 uri string
16 shouldHandle bool
17 responseBody string
18 responseCode int
19 }
20
21 func (tc testcasecheckversion) body() string {
22 if !tc.shouldHandle && tc.responseBody == "" {
23 return fmt.Sprintf("%s (%s != %s)\n", errAPIVersionMismatch, version.ApiVersion, tc.userAgent)
24 }
25
26 return tc.responseBody
27 }
28
29 func TestCheckVersionOption(t *testing.T) {
30 tcs := []testcasecheckversion{
31 {"/go-ipfs/0.1/", APIPath + "/test/", false, "", http.StatusBadRequest},
32 {"/go-ipfs/0.1/", APIPath + "/version", true, "check!", http.StatusOK},
33 {version.ApiVersion, APIPath + "/test", true, "check!", http.StatusOK},
34 {"Mozilla Firefox/no go-ipfs node", APIPath + "/test", true, "check!", http.StatusOK},
35 {"/go-ipfs/0.1/", "/webui", true, "check!", http.StatusOK},
36 }
37
38 for _, tc := range tcs {
39 t.Logf("%#v", tc)
40 r := httptest.NewRequest(http.MethodPost, tc.uri, nil)
41 r.Header.Add("User-Agent", tc.userAgent) // old version, should fail
42
43 called := false
44 root := http.NewServeMux()
45 mux, err := CheckVersionOption()(nil, nil, root)
46 if err != nil {
47 t.Fatal(err)
48 }
49
50 mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
51 called = true
52 if !tc.shouldHandle {
53 t.Error("handler was called even though version didn't match")
54 }
55 if _, err := io.WriteString(w, "check!"); err != nil {
56 t.Error(err)
57 }
58 })
59
60 w := httptest.NewRecorder()
61
62 root.ServeHTTP(w, r)
63
64 if tc.shouldHandle && !called {
65 t.Error("handler wasn't called even though it should have")
66 }
67
68 if w.Code != tc.responseCode {
69 t.Errorf("expected code %d but got %d", tc.responseCode, w.Code)
70 }
71
72 if w.Body.String() != tc.body() {
73 t.Errorf("expected error message %q, got %q", tc.body(), w.Body.String())
74 }
75 }
76 }