aboutsummaryrefslogtreecommitdiff
path: root/pkg/instance/instance_test.go
blob: 6ca7bafd47da3b60ce8b9ae48c87b4f120877e22 (plain)
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
43
44
45
46
47
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package instance

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

	"git.sigsum.org/sigsum-log-go/pkg/types"
)

// TestHandlers check that the expected handlers are configured
func TestHandlers(t *testing.T) {
	endpoints := map[types.Endpoint]bool{
		types.EndpointAddLeaf:             false,
		types.EndpointAddCosignature:      false,
		types.EndpointGetTreeHeadLatest:   false,
		types.EndpointGetTreeHeadToSign:   false,
		types.EndpointGetTreeHeadCosigned: false,
		types.EndpointGetConsistencyProof: false,
		types.EndpointGetInclusionProof:   false,
		types.EndpointGetLeaves:           false,
		types.Endpoint("get-checkpoint"):  false,
	}
	i := &Instance{
		Config: testConfig,
	}
	for _, handler := range i.Handlers() {
		if _, ok := endpoints[handler.Endpoint]; !ok {
			t.Errorf("got unexpected endpoint: %s", handler.Endpoint)
		}
		endpoints[handler.Endpoint] = true
	}
	for endpoint, ok := range endpoints {
		if !ok {
			t.Errorf("endpoint %s is not configured", endpoint)
		}
	}
}

// TestServeHTTP checks that invalid HTTP methods are rejected
func TestServeHTTP(t *testing.T) {
	i := &Instance{
		Config: testConfig,
	}
	for _, handler := range i.Handlers() {
		// Prepare invalid HTTP request
		method := http.MethodPost
		if method == handler.Method {
			method = http.MethodGet
		}
		url := handler.Endpoint.Path("http://example.com", i.Prefix)
		req, err := http.NewRequest(method, url, nil)
		if err != nil {
			t.Fatalf("must create HTTP request: %v", err)
		}
		w := httptest.NewRecorder()

		// Check that it is rejected
		handler.ServeHTTP(w, req)
		if got, want := w.Code, http.StatusMethodNotAllowed; got != want {
			t.Errorf("got HTTP code %v but wanted %v for endpoint %q", got, want, handler.Endpoint)
		}
	}
}

// TestPath checks that Path works for an endpoint (add-leaf)
func TestPath(t *testing.T) {
	for _, table := range []struct {
		description string
		prefix      string
		want        string
	}{
		{
			description: "no prefix",
			want:        "/sigsum/v0/add-leaf",
		},
		{
			description: "a prefix",
			prefix:      "test-prefix",
			want:        "/test-prefix/sigsum/v0/add-leaf",
		},
	} {
		instance := &Instance{
			Config: Config{
				Prefix: table.prefix,
			},
		}
		handler := Handler{
			Instance: instance,
			Handler:  addLeaf,
			Endpoint: types.EndpointAddLeaf,
			Method:   http.MethodPost,
		}
		if got, want := handler.Path(), table.want; got != want {
			t.Errorf("got path %v but wanted %v", got, want)
		}
	}
}