client_test.go 1.95 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
package http

import (
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"

	cmds "github.com/ipfs/go-ipfs-cmds"
)

func TestClientUserAgent(t *testing.T) {
	type testcase struct {
		host string
		ua   string
		path []string
	}

	tcs := []testcase{
		{ua: "/go-ipfs/0.4", path: []string{"version"}},
	}

	for _, tc := range tcs {
		var called bool

		s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			called = true
			t.Log(r)

			if ua := r.Header.Get("User-Agent"); ua != tc.ua {
				t.Errorf("expected user agent %q, got %q", tc.ua, ua)
			}

			expPath := "/" + strings.Join(tc.path, "/")
			if path := r.URL.Path; path != expPath {
				t.Errorf("expected path %q, got %q", expPath, path)
			}

			w.WriteHeader(http.StatusOK)
		}))
		testClient := s.Client()
		tc.host = s.URL
keks's avatar
keks committed
43
		r := &cmds.Request{Path: tc.path, Command: &cmds.Command{}, Root: &cmds.Command{}}
44 45 46

		c := NewClient(tc.host, ClientWithUserAgent(tc.ua)).(*client)
		c.httpClient = testClient
47
		c.send(r)
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82

		if !called {
			t.Error("handler has not been called")
		}
	}
}

func TestClientAPIPrefix(t *testing.T) {
	type testcase struct {
		host   string
		prefix string
		path   []string
	}

	tcs := []testcase{
		{prefix: "/api/v0", path: []string{"version"}},
		{prefix: "/api/v1", path: []string{"version"}},
	}

	for _, tc := range tcs {
		var called bool

		s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			called = true
			t.Log(r)

			expPath := tc.prefix + "/" + strings.Join(tc.path, "/")
			if path := r.URL.Path; path != expPath {
				t.Errorf("expected path %q, got %q", expPath, path)
			}

			w.WriteHeader(http.StatusOK)
		}))
		testClient := s.Client()
		tc.host = s.URL
keks's avatar
keks committed
83
		r := &cmds.Request{Path: tc.path, Command: &cmds.Command{}, Root: &cmds.Command{}}
84 85 86

		c := NewClient(tc.host, ClientWithAPIPrefix(tc.prefix)).(*client)
		c.httpClient = testClient
87
		c.send(r)
88 89 90 91 92 93

		if !called {
			t.Error("handler has not been called")
		}
	}
}