Skip to content

Commit

Permalink
Add test for main Collect function
Browse files Browse the repository at this point in the history
Before this test the `luxws_up` metric wasn't tested at all. Even now
only the error case is tested as a fully server would be required
otherwise.

Signed-off-by: Michael Hanselmann <public@hansmi.ch>
  • Loading branch information
hansmi committed Sep 24, 2022
1 parent 048e6ad commit ce3b2e2
Showing 1 changed file with 56 additions and 1 deletion.
57 changes: 56 additions & 1 deletion luxws-exporter/collector_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ package main

import (
"context"
"io"
"log"
"net/http"
"net/http/httptest"
"net/url"
Expand All @@ -17,9 +19,23 @@ import (
"github.com/prometheus/client_golang/prometheus/testutil"
)

func discardAllLogs(t *testing.T) {
t.Helper()

orig := log.Writer()

t.Cleanup(func() {
log.SetOutput(orig)
})

log.SetOutput(io.Discard)
}

type adapter struct {
c *collector

metricNames []string

collect func(ch chan<- prometheus.Metric) error
collectErr error
}
Expand All @@ -35,7 +51,7 @@ func (a *adapter) Collect(ch chan<- prometheus.Metric) {
func (a *adapter) collectAndCompare(t *testing.T, want string, wantErr error) {
t.Helper()

if err := testutil.CollectAndCompare(a, strings.NewReader(want)); err != nil {
if err := testutil.CollectAndCompare(a, strings.NewReader(want), a.metricNames...); err != nil {
t.Error(err)
}

Expand Down Expand Up @@ -477,3 +493,42 @@ luxws_node_time_seconds 1136214245
}
a.collectAndCompare(t, want, nil)
}

func TestCollect(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Error(w, "", http.StatusServiceUnavailable)
}))
t.Cleanup(server.Close)

c := newCollector(collectorOpts{
terms: luxwslang.English,
loc: time.Local,
})

if serverURL, err := url.Parse(server.URL); err != nil {
t.Error(err)
} else {
c.address = serverURL.Host
c.httpAddress = serverURL.Host
}

want := `
# HELP luxws_up Whether scrape was successful
# TYPE luxws_up gauge
luxws_up{status="collection via LuxWS protocol failed: websocket: bad handshake"} 0
`

discardAllLogs(t)

a := &adapter{
c: c,
metricNames: []string{
"luxws_up",
},
collect: func(ch chan<- prometheus.Metric) error {
c.Collect(ch)
return nil
},
}
a.collectAndCompare(t, want, nil)
}

0 comments on commit ce3b2e2

Please sign in to comment.