-
Notifications
You must be signed in to change notification settings - Fork 25
/
nut_exporter_test.go
82 lines (72 loc) · 1.54 KB
/
nut_exporter_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
package main
import (
"fmt"
"io/ioutil"
"net/http"
"os"
"os/exec"
"testing"
"time"
)
var (
binary = "nut_exporter"
)
const (
address = "localhost:19100"
)
func TestSuccessfulLaunch(t *testing.T) {
if _, err := os.Stat(binary); err != nil {
return
}
exporter := exec.Command(binary, "--web.listen-address", address)
test := func(pid int) error {
if err := queryExporter(address); err != nil {
return err
}
return nil
}
if err := runCommandAndTests(exporter, address, test); err != nil {
t.Error(err)
}
}
func queryExporter(address string) error {
resp, err := http.Get(fmt.Sprintf("http://%s/metrics", address))
if err != nil {
return err
}
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
if err := resp.Body.Close(); err != nil {
return err
}
if want, have := http.StatusOK, resp.StatusCode; want != have {
return fmt.Errorf("want /metrics status code %d, have %d. Body:\n%s", want, have, b)
}
return nil
}
func runCommandAndTests(cmd *exec.Cmd, address string, fn func(pid int) error) error {
if err := cmd.Start(); err != nil {
return fmt.Errorf("failed to start command: %s", err)
}
time.Sleep(50 * time.Millisecond)
for i := 0; i < 10; i++ {
if err := queryExporter(address); err == nil {
break
}
time.Sleep(500 * time.Millisecond)
if cmd.Process == nil || i == 9 {
return fmt.Errorf("can't start command")
}
}
errc := make(chan error)
go func(pid int) {
errc <- fn(pid)
}(cmd.Process.Pid)
err := <-errc
if cmd.Process != nil {
cmd.Process.Kill()
}
return err
}