github.com/dolthub/dolt/go@v0.40.5-0.20240520175717-68db7794bea6/libraries/events/metrics_test.go (about)

     1  // Copyright 2019 Dolthub, Inc.
     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  package events
    16  
    17  import (
    18  	"sync"
    19  	"testing"
    20  	"time"
    21  
    22  	"github.com/stretchr/testify/assert"
    23  
    24  	eventsapi "github.com/dolthub/dolt/go/gen/proto/dolt/services/eventsapi/v1alpha1"
    25  )
    26  
    27  func TestCounterAtomicity(t *testing.T) {
    28  	c := NewCounter(eventsapi.MetricID_METRIC_UNSPECIFIED)
    29  	wg := &sync.WaitGroup{}
    30  
    31  	for i := 0; i < 10; i++ {
    32  		wg.Add(1)
    33  		go func() {
    34  			defer wg.Done()
    35  
    36  			c.Add(10)
    37  			time.Sleep(time.Millisecond)
    38  			c.Inc()
    39  			time.Sleep(time.Millisecond)
    40  			c.Add(-5)
    41  			time.Sleep(time.Millisecond)
    42  			c.Dec()
    43  		}()
    44  	}
    45  
    46  	wg.Wait()
    47  	cem := c.AsClientEventMetric()
    48  
    49  	assert.Equal(t, int32(50), cem.GetCount())
    50  }
    51  
    52  func TestTimer(t *testing.T) {
    53  	EventNowFunc = func() time.Time { return time.Date(2018, 8, 6, 10, 0, 0, 0, time.UTC) }
    54  	timer := NewTimer(eventsapi.MetricID_METRIC_UNSPECIFIED)
    55  	EventNowFunc = func() time.Time { return time.Date(2018, 8, 6, 10, 1, 0, 0, time.UTC) }
    56  	timer.Restart()
    57  	EventNowFunc = func() time.Time { return time.Date(2018, 8, 6, 10, 1, 5, 123, time.UTC) }
    58  	timer.Stop()
    59  	EventNowFunc = time.Now
    60  
    61  	cem := timer.AsClientEventMetric()
    62  	assert.Equal(t, int64(5), cem.GetDuration().Seconds)
    63  	assert.Equal(t, int32(123), cem.GetDuration().Nanos)
    64  }
    65  
    66  func TestPanicOnAddUnstoppedTimer(t *testing.T) {
    67  	assert.Panics(t, func() {
    68  		timer := NewTimer(eventsapi.MetricID_METRIC_UNSPECIFIED)
    69  		timer.AsClientEventMetric()
    70  	})
    71  }