github.com/grailbio/bigslice@v0.0.0-20230519005545-30c4c12152ad/metrics/metrics_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  	"context"
     9  	"fmt"
    10  	"log"
    11  	"testing"
    12  
    13  	"github.com/grailbio/bigslice"
    14  	"github.com/grailbio/bigslice/exec"
    15  	"github.com/grailbio/bigslice/metrics"
    16  )
    17  
    18  func TestCounter(t *testing.T) {
    19  	var (
    20  		a, b metrics.Scope
    21  		c    = metrics.NewCounter()
    22  	)
    23  	c.Incr(&a, 2)
    24  	if got, want := c.Value(&a), int64(2); got != want {
    25  		t.Errorf("got %v, want %v", got, want)
    26  	}
    27  
    28  	c.Incr(&b, 123)
    29  	if got, want := c.Value(&a), int64(2); got != want {
    30  		t.Errorf("got %v, want %v", got, want)
    31  	}
    32  	if got, want := c.Value(&b), int64(123); got != want {
    33  		t.Errorf("got %v, want %v", got, want)
    34  	}
    35  
    36  	a.Merge(&b)
    37  	if got, want := c.Value(&a), int64(125); got != want {
    38  		t.Errorf("got %v, want %v", got, want)
    39  	}
    40  }
    41  
    42  func ExampleCounter() {
    43  	filterCount := metrics.NewCounter()
    44  	filterFunc := bigslice.Func(func() (slice bigslice.Slice) {
    45  		slice = bigslice.Const(1, []int{1, 2, 3, 4, 5, 6})
    46  		slice = bigslice.Filter(slice, func(ctx context.Context, i int) bool {
    47  			scope := metrics.ContextScope(ctx)
    48  			if i%2 == 0 {
    49  				filterCount.Incr(scope, 1)
    50  				return false
    51  			}
    52  			return true
    53  		})
    54  		return
    55  	})
    56  
    57  	sess := exec.Start(exec.Local)
    58  	res, err := sess.Run(context.Background(), filterFunc)
    59  	if err != nil {
    60  		log.Fatal(err)
    61  	}
    62  
    63  	fmt.Println("filtered:", filterCount.Value(res.Scope()))
    64  	// Output: filtered: 3
    65  }