-
Notifications
You must be signed in to change notification settings - Fork 88
/
start_test.go
95 lines (89 loc) · 2.07 KB
/
start_test.go
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
package main
import (
"encoding/json"
"flag"
"fmt"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"testing"
"time"
mkr "github.com/mackerelio/mackerel-client-go"
)
func respJSON(w http.ResponseWriter, data map[string]any) {
respJSON, _ := json.Marshal(data)
w.Header().Set("Content-Type", "application/json")
fmt.Fprint(w, string(respJSON))
}
func TestStart(t *testing.T) {
hostID := "xxx1234567890"
mux := http.NewServeMux()
mux.HandleFunc("/api/v0/hosts/"+hostID, func(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case "GET":
respJSON(w, map[string]any{
"host": mkr.Host{
ID: hostID,
Name: "host.example.com",
Status: "standby",
},
})
case "PUT":
respJSON(w, map[string]any{
"result": "OK",
})
default:
t.Errorf("request method should be PUT or GET but :%s", r.Method)
}
})
mux.HandleFunc("/api/v0/tsdb", func(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case "POST":
var payload []*mkr.HostMetricValue
err := json.NewDecoder(r.Body).Decode(&payload)
if err != nil {
t.Errorf("decode failed: %s", err)
}
respJSON(w, map[string]any{
"success": true,
})
default:
t.Errorf("request method should be POST but: %s", r.Method)
}
})
ts := httptest.NewServer(mux)
defer ts.Close()
root := t.TempDir()
confFile, err := os.Create(filepath.Join(root, "mackerel-agent.conf"))
if err != nil {
t.Fatalf("Could not create temporary file for test")
}
confFile.WriteString(`apikey="DUMMYAPIKEY"` + "\n")
confFile.Sync()
confFile.Close()
argv := []string{
"-conf=" + confFile.Name(),
"-apibase=" + ts.URL,
"-pidfile=" + root + "/pid",
"-root=" + root,
"-verbose",
}
conf, err := resolveConfig(&flag.FlagSet{}, argv)
if err != nil {
t.Errorf("err should be nil, but got: %s", err)
}
conf.SaveHostID(hostID)
termCh := make(chan struct{})
done := make(chan error)
go func() {
err = start(conf, termCh)
done <- err
}()
time.Sleep(5 * time.Second)
termCh <- struct{}{}
err = <-done
if err != nil {
t.Errorf("err should be nil but: %s", err)
}
}