aboutsummaryrefslogtreecommitdiff
path: root/internal/node/primary/endpoint_internal_test.go
blob: 6c76c33745c6ac900d62093cb6425b81c0cf8ffe (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
package primary

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

	mocksDB "git.sigsum.org/log-go/internal/mocks/db"
	"git.sigsum.org/log-go/internal/node/handler"
	"git.sigsum.org/sigsum-go/pkg/merkle"
	"git.sigsum.org/sigsum-go/pkg/types"
	"github.com/golang/mock/gomock"
)

var (
	testTH = &types.TreeHead{
		Timestamp: 0,
		TreeSize:  0,
		RootHash:  *merkle.HashFn([]byte("root hash")),
	}
)

func TestGetTreeHeadUnsigned(t *testing.T) {
	for _, table := range []struct {
		description string
		expect      bool            // set if a mock answer is expected
		rsp         *types.TreeHead // tree head from Trillian client
		err         error           // error from Trillian client
		wantCode    int             // HTTP status ok
	}{
		{
			description: "invalid: backend failure",
			expect:      true,
			err:         fmt.Errorf("something went wrong"),
			wantCode:    http.StatusInternalServerError,
		},
		{
			description: "valid",
			expect:      true,
			rsp:         testTH,
			wantCode:    http.StatusOK,
		},
	} {
		// Run deferred functions at the end of each iteration
		func() {
			ctrl := gomock.NewController(t)
			defer ctrl.Finish()
			trillianClient := mocksDB.NewMockClient(ctrl)
			trillianClient.EXPECT().GetTreeHead(gomock.Any()).Return(table.rsp, table.err)

			node := Primary{
				Config:         testConfig,
				TrillianClient: trillianClient,
			}

			// Create HTTP request
			url := types.EndpointGetTreeHeadUnsigned.Path("http://example.com", node.Prefix())
			req, err := http.NewRequest("GET", url, nil)
			if err != nil {
				t.Fatalf("must create http request: %v", err)
			}

			// Run HTTP request
			w := httptest.NewRecorder()
			mustHandleInternal(t, node, types.EndpointGetTreeHeadUnsigned).ServeHTTP(w, req)
			if got, want := w.Code, table.wantCode; got != want {
				t.Errorf("got HTTP status code %v but wanted %v in test %q", got, want, table.description)
			}
		}()
	}
}

func mustHandleInternal(t *testing.T, p Primary, e types.Endpoint) handler.Handler {
	for _, handler := range p.InternalHTTPHandlers() {
		if handler.Endpoint == e {
			return handler
		}
	}
	t.Fatalf("must handle endpoint: %v", e)
	return handler.Handler{}
}