This repository has been archived by the owner on Dec 2, 2021. It is now read-only.
forked from mackerelio/mackerel-agent
-
Notifications
You must be signed in to change notification settings - Fork 0
/
start_test.go
102 lines (95 loc) · 2.31 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
96
97
98
99
100
101
102
package main
import (
"encoding/json"
"flag"
"fmt"
"io/ioutil"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"testing"
"time"
"github.com/mackerelio/mackerel-agent/mackerel"
mkr "github.com/mackerelio/mackerel-client-go"
)
func respJSON(w http.ResponseWriter, data map[string]interface{}) {
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]interface{}{
"host": mkr.Host{
ID: hostID,
Name: "host.example.com",
Status: "standby",
},
})
case "PUT":
respJSON(w, map[string]interface{}{
"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":
payload := []mackerel.CreatingMetricsValue{}
err := json.NewDecoder(r.Body).Decode(&payload)
if err != nil {
t.Errorf("decode failed: %s", err)
}
respJSON(w, map[string]interface{}{
"success": true,
})
default:
t.Errorf("request method should be POST but: %s", r.Method)
}
})
ts := httptest.NewServer(mux)
defer ts.Close()
root, err := ioutil.TempDir("", "mackerel-config-test")
if err != nil {
t.Fatalf("Could not create temporary dir for test")
}
defer os.RemoveAll(root)
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)
}
}