dubbo.apache.org/dubbo-go/v3@v3.1.1/metrics/util/aggregate/aggregator_test.go (about)

     1  /*
     2   * Licensed to the Apache Software Foundation (ASF) under one or more
     3   * contributor license agreements.  See the NOTICE file distributed with
     4   * this work for additional information regarding copyright ownership.
     5   * The ASF licenses this file to You under the Apache License, Version 2.0
     6   * (the "License"); you may not use this file except in compliance with
     7   * the License.  You may obtain a copy of the License at
     8   *
     9   *     http://www.apache.org/licenses/LICENSE-2.0
    10   *
    11   * Unless required by applicable law or agreed to in writing, software
    12   * distributed under the License is distributed on an "AS IS" BASIS,
    13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    14   * See the License for the specific language governing permissions and
    15   * limitations under the License.
    16   */
    17  
    18  package aggregate
    19  
    20  import (
    21  	"math/rand"
    22  	"reflect"
    23  	"sync"
    24  	"testing"
    25  )
    26  
    27  func TestTimeWindowAggregatorAddAndResult(t *testing.T) {
    28  	timeWindowAggregator := NewTimeWindowAggregator(10, 1)
    29  	timeWindowAggregator.Add(10)
    30  	timeWindowAggregator.Add(20)
    31  	timeWindowAggregator.Add(30)
    32  
    33  	tests := []struct {
    34  		name string
    35  		want *Result
    36  	}{
    37  		{
    38  			name: "Result",
    39  			want: &Result{
    40  				Total: 60,
    41  				Min:   10,
    42  				Max:   30,
    43  				Avg:   20,
    44  				Count: 3,
    45  			},
    46  		},
    47  	}
    48  
    49  	for _, tt := range tests {
    50  		t.Run(tt.name, func(t *testing.T) {
    51  			got := timeWindowAggregator.Result()
    52  			got.Last = 0 // NaN can not equal
    53  			if !reflect.DeepEqual(got, tt.want) {
    54  				t.Errorf("Result() = %v, want %v", got, tt.want)
    55  			}
    56  		})
    57  	}
    58  }
    59  
    60  func BenchmarkTimeWindowAggregatorAdd(b *testing.B) {
    61  	wg := sync.WaitGroup{}
    62  	tw := NewTimeWindowAggregator(10, 1)
    63  	for i := 0; i < b.N; i++ {
    64  		wg.Add(1)
    65  		go func() {
    66  			defer wg.Done()
    67  			tw.Add(rand.Float64() * 100)
    68  		}()
    69  	}
    70  	wg.Wait()
    71  }
    72  
    73  func BenchmarkTimeWindowAggregatorResult(b *testing.B) {
    74  	wg := sync.WaitGroup{}
    75  	tw := NewTimeWindowAggregator(10, 1)
    76  	for i := 0; i < b.N; i++ {
    77  		wg.Add(1)
    78  		go func() {
    79  			tw.Add(rand.Float64() * 100)
    80  		}()
    81  		go func() {
    82  			defer wg.Done()
    83  			tw.Result()
    84  		}()
    85  	}
    86  	wg.Wait()
    87  }