-
Notifications
You must be signed in to change notification settings - Fork 0
/
ttn_exporter_test.go
96 lines (84 loc) · 2.3 KB
/
ttn_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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package main
import (
"io"
"net/http"
"net/http/httptest"
"os"
"path"
"testing"
"time"
"github.com/go-kit/log"
"github.com/prometheus/client_golang/prometheus"
)
const (
apiKey = "test-api-key"
)
func newTTNServer(t *testing.T) *httptest.Server {
mux := http.NewServeMux()
mux.HandleFunc("/api/v3/gateways", func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Authorization") != "Bearer "+apiKey {
w.WriteHeader(http.StatusUnauthorized)
return
}
file, err := os.Open(path.Join("test", "gateways_list_response.json"))
if err != nil {
t.Error(err)
}
bytes, err := io.ReadAll(file)
if err != nil {
t.Error(err)
}
w.WriteHeader(http.StatusOK)
_, _ = w.Write(bytes)
})
// NOTE: Golang does not support regex in patterns, so we're hardcoding this
mux.HandleFunc("/api/v3/gs/gateways", func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Authorization") != "Bearer "+apiKey {
w.WriteHeader(http.StatusUnauthorized)
return
}
if r.URL.Path != "/api/v3/gs/gateways/a111111aaa111222/connection/stats" {
http.NotFound(w, r)
return
}
file, err := os.Open(path.Join("test", "gateway_stats_response.json"))
if err != nil {
t.Error(err)
}
bytes, err := io.ReadAll(file)
if err != nil {
t.Error(err)
}
w.WriteHeader(http.StatusOK)
_, _ = w.Write(bytes)
})
ts := httptest.NewServer(mux)
return ts
}
func expectMetrics(t *testing.T, c prometheus.Collector, fixture string) {
_, err := os.Open(path.Join("test", fixture))
if err != nil {
t.Fatalf("Error opening fixture file %q: %v", fixture, err)
}
// if err := testutil.CollectAndCompare(c, exp); err != nil {
// t.Fatal("Unexpected metrics returned:", err)
// }
}
func TestServer(t *testing.T) {
h := newTTNServer(t)
defer h.Close()
e, _ := NewExporter(h.URL, apiKey, false, 5*time.Second, log.NewNopLogger())
expectMetrics(t, e, "gateway_stats.metrics")
}
func TestInvalidScheme(t *testing.T) {
e, err := NewExporter("gopher://gopher.quux.org", apiKey, false, 1*time.Second, log.NewNopLogger())
if expect, got := (*Exporter)(nil), e; expect != got {
t.Errorf("expected %v, got %v", expect, got)
}
if err == nil {
t.Fatalf("expected non-nil error")
}
if expect, got := `invalid URI scheme`, err.Error(); expect != got {
t.Errorf("expected %q, got %q", expect, got)
}
}