github.com/google/cloudprober@v0.11.3/metrics/testutils/testutils.go (about)

     1  // Copyright 2019 The Cloudprober Authors.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //      http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  /*
    16  Package testutils provides utilities for tests.
    17  */
    18  package testutils
    19  
    20  import (
    21  	"context"
    22  	"fmt"
    23  	"time"
    24  
    25  	"github.com/google/cloudprober/metrics"
    26  )
    27  
    28  // MetricsFromChannel reads metrics.EventMetrics from dataChannel with a timeout
    29  func MetricsFromChannel(dataChan chan *metrics.EventMetrics, num int, timeout time.Duration) (results []*metrics.EventMetrics, err error) {
    30  	ctx, cancel := context.WithTimeout(context.Background(), timeout)
    31  	defer cancel()
    32  
    33  	var timedout bool
    34  
    35  	for i := 0; i < num && !timedout; i++ {
    36  		select {
    37  		case em := <-dataChan:
    38  			results = append(results, em)
    39  		case <-ctx.Done():
    40  			timedout = true
    41  		}
    42  	}
    43  
    44  	if timedout {
    45  		err = fmt.Errorf("timed out while waiting for data from dataChannel, got only %d metrics out of %d", len(results), num)
    46  	}
    47  	return
    48  }
    49  
    50  // MetricsMap rearranges a list of metrics into a map of map.
    51  // {
    52  //   "m1": {
    53  //       "target1": [val1, val2..],
    54  //       "target2": [val1],
    55  //   },
    56  //   "m2": {
    57  //       ...
    58  //   }
    59  // }
    60  func MetricsMap(ems []*metrics.EventMetrics) map[string]map[string][]*metrics.EventMetrics {
    61  	results := make(map[string]map[string][]*metrics.EventMetrics)
    62  	for _, em := range ems {
    63  		target := em.Label("dst")
    64  		for _, m := range em.MetricsKeys() {
    65  			if results[m] == nil {
    66  				results[m] = make(map[string][]*metrics.EventMetrics)
    67  			}
    68  			results[m][target] = append(results[m][target], em)
    69  		}
    70  	}
    71  	return results
    72  }