github.com/hashicorp/go-metrics@v0.5.3/inmem_signal_test.go (about)

     1  package metrics
     2  
     3  import (
     4  	"bytes"
     5  	"os"
     6  	"strings"
     7  	"sync"
     8  	"syscall"
     9  	"testing"
    10  	"time"
    11  )
    12  
    13  func TestInmemSignal(t *testing.T) {
    14  	buf := newBuffer()
    15  	inm := NewInmemSink(10*time.Millisecond, 50*time.Millisecond)
    16  	sig := NewInmemSignal(inm, syscall.SIGUSR1, buf)
    17  	defer sig.Stop()
    18  
    19  	inm.SetGauge([]string{"foo"}, 42)
    20  	inm.EmitKey([]string{"bar"}, 42)
    21  	inm.IncrCounter([]string{"baz"}, 42)
    22  	inm.AddSample([]string{"wow"}, 42)
    23  	inm.SetGaugeWithLabels([]string{"asdf"}, 42, []Label{{"a", "b"}})
    24  	inm.IncrCounterWithLabels([]string{"qwer"}, 42, []Label{{"a", "b"}})
    25  	inm.AddSampleWithLabels([]string{"zxcv"}, 42, []Label{{"a", "b"}})
    26  
    27  	// Wait for period to end
    28  	time.Sleep(15 * time.Millisecond)
    29  
    30  	// Send signal!
    31  	syscall.Kill(os.Getpid(), syscall.SIGUSR1)
    32  
    33  	// Wait for flush
    34  	time.Sleep(10 * time.Millisecond)
    35  
    36  	// Check the output
    37  	out := buf.String()
    38  	if !strings.Contains(out, "[G] 'foo': 42") {
    39  		t.Fatalf("bad: %v", out)
    40  	}
    41  	if !strings.Contains(out, "[P] 'bar': 42") {
    42  		t.Fatalf("bad: %v", out)
    43  	}
    44  	if !strings.Contains(out, "[C] 'baz': Count: 1 Sum: 42") {
    45  		t.Fatalf("bad: %v", out)
    46  	}
    47  	if !strings.Contains(out, "[S] 'wow': Count: 1 Sum: 42") {
    48  		t.Fatalf("bad: %v", out)
    49  	}
    50  	if !strings.Contains(out, "[G] 'asdf.b': 42") {
    51  		t.Fatalf("bad: %v", out)
    52  	}
    53  	if !strings.Contains(out, "[C] 'qwer.b': Count: 1 Sum: 42") {
    54  		t.Fatalf("bad: %v", out)
    55  	}
    56  	if !strings.Contains(out, "[S] 'zxcv.b': Count: 1 Sum: 42") {
    57  		t.Fatalf("bad: %v", out)
    58  	}
    59  }
    60  
    61  func newBuffer() *syncBuffer {
    62  	return &syncBuffer{buf: bytes.NewBuffer(nil)}
    63  }
    64  
    65  type syncBuffer struct {
    66  	buf  *bytes.Buffer
    67  	lock sync.Mutex
    68  }
    69  
    70  func (s *syncBuffer) Write(p []byte) (int, error) {
    71  	s.lock.Lock()
    72  	defer s.lock.Unlock()
    73  
    74  	return s.buf.Write(p)
    75  }
    76  
    77  func (s *syncBuffer) String() string {
    78  	s.lock.Lock()
    79  	defer s.lock.Unlock()
    80  
    81  	return s.buf.String()
    82  }