github.com/grailbio/bigslice@v0.0.0-20230519005545-30c4c12152ad/metrics/scope_test.go (about)

     1  // Copyright 2019 GRAIL, Inc. All rights reserved.
     2  // Use of this source code is governed by the Apache 2.0
     3  // license that can be found in the LICENSE file.
     4  
     5  package metrics_test
     6  
     7  import (
     8  	"bytes"
     9  	"encoding/gob"
    10  	"io/ioutil"
    11  	"testing"
    12  
    13  	"github.com/grailbio/bigslice/metrics"
    14  )
    15  
    16  func TestScopeEmpty(t *testing.T) {
    17  	var (
    18  		s metrics.Scope
    19  		c = metrics.NewCounter()
    20  	)
    21  	if got, want := c.Value(&s), int64(0); got != want {
    22  		t.Errorf("got %v, want %v", got, want)
    23  	}
    24  }
    25  
    26  func TestScopeMerge(t *testing.T) {
    27  	c := metrics.NewCounter()
    28  
    29  	for _, test := range []struct {
    30  		incrA, incrB int64
    31  	}{
    32  		{0, 0},
    33  		{0, 1},
    34  		{2, 0},
    35  		{100, 200},
    36  	} {
    37  		var a, b metrics.Scope
    38  		c.Incr(&a, test.incrA)
    39  		c.Incr(&b, test.incrB)
    40  		a.Merge(&b)
    41  		if got, want := c.Value(&a), test.incrA+test.incrB; got != want {
    42  			t.Errorf("%v: got %v, want %v", test, got, want)
    43  		}
    44  		a.Reset(&b)
    45  		if got, want := c.Value(&a), test.incrB; got != want {
    46  			t.Errorf("%v: got %v, want %v", test, got, want)
    47  		}
    48  		c.Incr(&a, test.incrA)
    49  		if got, want := c.Value(&a), test.incrA+test.incrB; got != want {
    50  			t.Errorf("%v: got %v, want %v", test, got, want)
    51  		}
    52  	}
    53  }
    54  
    55  func TestScopeGob(t *testing.T) {
    56  	var (
    57  		scope metrics.Scope
    58  		c0    = metrics.NewCounter()
    59  		c1    = metrics.NewCounter()
    60  		b     bytes.Buffer
    61  	)
    62  	c0.Incr(&scope, 123)
    63  	if err := gob.NewEncoder(&b).Encode(&scope); err != nil {
    64  		t.Fatal(err)
    65  	}
    66  	scope.Reset(nil)
    67  	if got, want := c0.Value(&scope), int64(0); got != want {
    68  		t.Fatalf("got %v, want %v", got, want)
    69  	}
    70  	if err := gob.NewDecoder(&b).Decode(&scope); err != nil {
    71  		t.Fatal(err)
    72  	}
    73  	if got, want := c0.Value(&scope), int64(123); got != want {
    74  		t.Fatalf("got %v, want %v", got, want)
    75  	}
    76  	if got, want := c1.Value(&scope), int64(0); got != want {
    77  		t.Fatalf("got %v, want %v", got, want)
    78  	}
    79  }
    80  
    81  func TestScopeGobEmpty(t *testing.T) {
    82  	var scope metrics.Scope
    83  	if err := gob.NewEncoder(ioutil.Discard).Encode(&scope); err != nil {
    84  		t.Fatal(err)
    85  	}
    86  }