summaryrefslogtreecommitdiff
path: root/internal/cli/runtime_test.go
blob: e024a4e9b61780b18ad4860b869ac2542389f8b6 (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
package cli

import (
	"context"
	"net/http"
	"testing"
	"time"

	"github.com/mimecast/dtail/internal/io/dlog"
	"github.com/mimecast/dtail/internal/profiling"
)

func TestClientRuntimeStopShutsDownPProf(t *testing.T) {
	prevClient := dlog.Client
	dlog.Client = &dlog.DLog{}
	t.Cleanup(func() {
		dlog.Client = prevClient
	})

	ctx, cancel := context.WithCancel(context.Background())
	runtime := &ClientRuntime{
		ctx:      ctx,
		cancel:   cancel,
		profiler: profiling.NewProfiler(profiling.Config{}),
	}

	runtime.StartPProf("127.0.0.1:0")
	if runtime.pprofServer == nil {
		t.Fatal("expected pprof server to start")
	}

	url := "http://" + runtime.pprofServer.Address() + "/debug/pprof/"
	waitForHTTPStatus(t, url, http.StatusOK)

	runtime.Stop()
	waitForHTTPError(t, url)
}

func waitForHTTPStatus(t *testing.T, url string, want int) {
	t.Helper()

	deadline := time.Now().Add(3 * time.Second)
	for time.Now().Before(deadline) {
		resp, err := http.Get(url)
		if err == nil {
			resp.Body.Close()
			if resp.StatusCode == want {
				return
			}
		}
		time.Sleep(10 * time.Millisecond)
	}

	t.Fatalf("timed out waiting for %s to return %d", url, want)
}

func waitForHTTPError(t *testing.T, url string) {
	t.Helper()

	deadline := time.Now().Add(3 * time.Second)
	for time.Now().Before(deadline) {
		resp, err := http.Get(url)
		if err != nil {
			return
		}
		resp.Body.Close()
		time.Sleep(10 * time.Millisecond)
	}

	t.Fatalf("timed out waiting for %s to stop serving", url)
}