github.com/influxdata/influxdb/v2@v2.7.6/telemetry/reporter_test.go (about) 1 package telemetry 2 3 import ( 4 "context" 5 "net/http" 6 "net/http/httptest" 7 "reflect" 8 "sync" 9 "testing" 10 "time" 11 12 pr "github.com/influxdata/influxdb/v2/prometheus" 13 "github.com/prometheus/client_golang/prometheus" 14 dto "github.com/prometheus/client_model/go" 15 "go.uber.org/zap/zaptest" 16 ) 17 18 func TestReport(t *testing.T) { 19 ctx, cancel := context.WithCancel(context.Background()) 20 21 logger := zaptest.NewLogger(t) 22 store := newReportingStore() 23 timestamps := &AddTimestamps{ 24 now: func() time.Time { 25 return time.Unix(0, 0) 26 }, 27 } 28 29 gw := NewPushGateway(logger, store, timestamps) 30 gw.Encoder = &pr.JSON{} 31 32 ts := httptest.NewServer(http.HandlerFunc(gw.Handler)) 33 defer ts.Close() 34 35 mfs := []*dto.MetricFamily{NewCounter("influxdb_buckets_total", 1.0)} 36 gatherer := prometheus.GathererFunc(func() ([]*dto.MetricFamily, error) { 37 return mfs, nil 38 }) 39 40 reporter := NewReporter(logger, gatherer) 41 reporter.Pusher.URL = ts.URL 42 reporter.Interval = 30 * time.Second 43 44 var wg sync.WaitGroup 45 wg.Add(1) 46 defer wg.Wait() 47 go func() { 48 defer wg.Done() 49 reporter.Report(ctx) 50 }() 51 52 got := <-store.ch 53 54 // Encode to JSON to make it easier to compare 55 want, _ := pr.EncodeJSON(timestamps.Transform(mfs)) 56 if !reflect.DeepEqual(got, want) { 57 t.Errorf("Reporter.Report() = %s, want %s", got, want) 58 } 59 60 cancel() 61 } 62 63 func newReportingStore() *reportingStore { 64 return &reportingStore{ 65 ch: make(chan []byte, 1), 66 } 67 } 68 69 type reportingStore struct { 70 ch chan []byte 71 } 72 73 func (s *reportingStore) WriteMessage(ctx context.Context, data []byte) error { 74 s.ch <- data 75 return nil 76 }