summaryrefslogtreecommitdiff
path: root/internal/command/healthcheck/healthcheck_test.go
blob: d05e563abd2a40280462bad8c4c3daf217f0cae6 (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
package healthcheck

import (
	"bytes"
	"context"
	"encoding/json"
	"net/http"
	"testing"

	"github.com/stretchr/testify/require"

	"gitlab.com/gitlab-org/gitlab-shell/client/testserver"
	"gitlab.com/gitlab-org/gitlab-shell/internal/command/readwriter"
	"gitlab.com/gitlab-org/gitlab-shell/internal/config"
	"gitlab.com/gitlab-org/gitlab-shell/internal/gitlabnet/healthcheck"
)

var (
	okResponse = &healthcheck.Response{
		APIVersion:     "v4",
		GitlabVersion:  "v12.0.0-ee",
		GitlabRevision: "3b13818e8330f68625d80d9bf5d8049c41fbe197",
		Redis:          true,
	}

	badRedisResponse = &healthcheck.Response{Redis: false}

	okHandlers       = buildTestHandlers(200, okResponse)
	badRedisHandlers = buildTestHandlers(200, badRedisResponse)
	brokenHandlers   = buildTestHandlers(500, nil)
)

func buildTestHandlers(code int, rsp *healthcheck.Response) []testserver.TestRequestHandler {
	return []testserver.TestRequestHandler{
		{
			Path: "/api/v4/internal/check",
			Handler: func(w http.ResponseWriter, r *http.Request) {
				w.WriteHeader(code)
				if rsp != nil {
					json.NewEncoder(w).Encode(rsp)
				}
			},
		},
	}
}

func TestExecute(t *testing.T) {
	url, cleanup := testserver.StartSocketHttpServer(t, okHandlers)
	defer cleanup()

	buffer := &bytes.Buffer{}
	cmd := &Command{
		Config:     &config.Config{GitlabUrl: url},
		ReadWriter: &readwriter.ReadWriter{Out: buffer},
	}

	err := cmd.Execute(context.Background())

	require.NoError(t, err)
	require.Equal(t, "Internal API available: OK\nRedis available via internal API: OK\n", buffer.String())
}

func TestFailingRedisExecute(t *testing.T) {
	url, cleanup := testserver.StartSocketHttpServer(t, badRedisHandlers)
	defer cleanup()

	buffer := &bytes.Buffer{}
	cmd := &Command{
		Config:     &config.Config{GitlabUrl: url},
		ReadWriter: &readwriter.ReadWriter{Out: buffer},
	}

	err := cmd.Execute(context.Background())
	require.Error(t, err, "Redis available via internal API: FAILED")
	require.Equal(t, "Internal API available: OK\n", buffer.String())
}

func TestFailingAPIExecute(t *testing.T) {
	url, cleanup := testserver.StartSocketHttpServer(t, brokenHandlers)
	defer cleanup()

	buffer := &bytes.Buffer{}
	cmd := &Command{
		Config:     &config.Config{GitlabUrl: url},
		ReadWriter: &readwriter.ReadWriter{Out: buffer},
	}

	err := cmd.Execute(context.Background())
	require.Empty(t, buffer.String())
	require.EqualError(t, err, "Internal API available: FAILED - Internal API error (500)")
}