nandi/oripublic Fork 0
5d476ff5f3dc3b7db3afaccaedc7d9661981449e
Commits
Clone
git clone https://git.rickub.com/nandi/ori.git
git clone ssh://git@rickub.com/nandi/ori.git

Host key fingerprint (ed25519): SHA256:iycHnxEyq0Q7uyVpB7JlznP0G7JrTPXLYRcAU5CSLhc — verify it before your first connect.

forked from bots-garden/ori

health_test.go · 80 lines · 2.2 KBGo Blame HistoryRaw
 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
package health

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

func TestCheckHealthyServer(t *testing.T) {
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if r.URL.Path != "/healthz" || r.Method != http.MethodGet {
			http.NotFound(w, r)
			return
		}
		w.Header().Set("Content-Type", "application/json")
		_, _ = w.Write([]byte(`{"status":"ok"}`))
	}))
	defer srv.Close()

	rep := Check(context.Background(), srv.Client(), srv.URL)
	if !rep.OK {
		t.Fatalf("expected OK, got %+v", rep)
	}
	if rep.StatusCode != http.StatusOK || rep.URL != srv.URL+"/healthz" {
		t.Fatalf("unexpected report %+v", rep)
	}
	if !strings.Contains(rep.Detail, "status: ok") {
		t.Fatalf("detail should quote the status, got %q", rep.Detail)
	}
}

func TestCheckNonOriServer(t *testing.T) {
	srv := httptest.NewServer(http.NotFoundHandler())
	defer srv.Close()

	rep := Check(context.Background(), srv.Client(), srv.URL)
	if rep.OK {
		t.Fatalf("expected failure for 404, got %+v", rep)
	}
	if rep.StatusCode != http.StatusNotFound || !strings.Contains(rep.Detail, "404") {
		t.Fatalf("unexpected report %+v", rep)
	}
}

func TestCheckUnreachableServer(t *testing.T) {
	srv := httptest.NewServer(http.NotFoundHandler())
	addr := srv.URL
	srv.Close() // nothing listens there any more

	rep := Check(context.Background(), nil, addr)
	if rep.OK || rep.StatusCode != 0 {
		t.Fatalf("expected transport failure, got %+v", rep)
	}
	if !strings.Contains(rep.Detail, "cannot reach ori") {
		t.Fatalf("unexpected detail %q", rep.Detail)
	}
}

func TestCheckPlainOKBody(t *testing.T) {
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
		_, _ = w.Write([]byte("OK"))
	}))
	defer srv.Close()

	rep := Check(context.Background(), srv.Client(), srv.URL)
	if !rep.OK || rep.Detail != "ori is reachable" {
		t.Fatalf("a 2xx with a non-JSON body must still count as healthy, got %+v", rep)
	}
}

func TestCheckCancelledContext(t *testing.T) {
	ctx, cancel := context.WithCancel(context.Background())
	cancel()
	rep := Check(ctx, nil, "http://127.0.0.1:1")
	if rep.OK {
		t.Fatalf("expected failure with a cancelled context, got %+v", rep)
	}
}