1
0
mirror of https://github.com/open-telemetry/opentelemetry-go.git synced 2025-02-03 13:11:53 +02:00
Tyler Yahn 1f5b159161
Use already enabled revive linter and add depguard (#2883)
* Refactor golangci-lint conf

Order settings alphabetically.

* Add revive settings to golangci conf

* Check blank imports

* Check bool-literal-in-expr

* Check constant-logical-expr

* Check context-as-argument

* Check context-key-type

* Check deep-exit

* Check defer

* Check dot-imports

* Check duplicated-imports

* Check early-return

* Check empty-block

* Check empty-lines

* Check error-naming

* Check error-return

* Check error-strings

* Check errorf

* Stop ignoring context first arg in tests

* Check exported comments

* Check flag-parameter

* Check identical branches

* Check if-return

* Check increment-decrement

* Check indent-error-flow

* Check deny list of go imports

* Check import shadowing

* Check package comments

* Check range

* Check range val in closure

* Check range val address

* Check redefines builtin id

* Check string-format

* Check struct tag

* Check superfluous else

* Check time equal

* Check var naming

* Check var declaration

* Check unconditional recursion

* Check unexported return

* Check unhandled errors

* Check unnecessary stmt

* Check unnecessary break

* Check waitgroup by value

* Exclude deep-exit check in example*_test.go files
2022-05-19 15:15:07 -05:00

308 lines
8.3 KiB
Go

// Copyright The OpenTelemetry Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package aggregatortest // import "go.opentelemetry.io/otel/sdk/metric/aggregator/aggregatortest"
import (
"context"
"errors"
"math/rand"
"os"
"sort"
"testing"
"unsafe"
"github.com/stretchr/testify/require"
ottest "go.opentelemetry.io/otel/internal/internaltest"
"go.opentelemetry.io/otel/sdk/metric/aggregator"
"go.opentelemetry.io/otel/sdk/metric/export/aggregation"
"go.opentelemetry.io/otel/sdk/metric/number"
"go.opentelemetry.io/otel/sdk/metric/sdkapi"
)
// Magnitude is the upper-bound of random numbers used in profile tests.
const Magnitude = 1000
// Profile is an aggregator test profile.
type Profile struct {
NumberKind number.Kind
Random func(sign int) number.Number
}
// NoopAggregator is an aggregator that performs no operations.
type NoopAggregator struct{}
// NoopAggregation is an aggregation that performs no operations.
type NoopAggregation struct{}
var _ aggregator.Aggregator = NoopAggregator{}
var _ aggregation.Aggregation = NoopAggregation{}
func newProfiles() []Profile {
rnd := rand.New(rand.NewSource(rand.Int63()))
return []Profile{
{
NumberKind: number.Int64Kind,
Random: func(sign int) number.Number {
return number.NewInt64Number(int64(sign) * int64(rnd.Intn(Magnitude+1)))
},
},
{
NumberKind: number.Float64Kind,
Random: func(sign int) number.Number {
return number.NewFloat64Number(float64(sign) * rnd.Float64() * Magnitude)
},
},
}
}
// NewAggregatorTest returns a descriptor for mkind and nkind.
func NewAggregatorTest(mkind sdkapi.InstrumentKind, nkind number.Kind) *sdkapi.Descriptor {
desc := sdkapi.NewDescriptor("test.name", mkind, nkind, "", "")
return &desc
}
// RunProfiles runs all test profile against the factory function f.
func RunProfiles(t *testing.T, f func(*testing.T, Profile)) {
for _, profile := range newProfiles() {
t.Run(profile.NumberKind.String(), func(t *testing.T) {
f(t, profile)
})
}
}
// TestMain ensures local struct alignment prior to running tests.
func TestMain(m *testing.M) {
fields := []ottest.FieldOffset{
{
Name: "Numbers.numbers",
Offset: unsafe.Offsetof(Numbers{}.numbers),
},
}
if !ottest.Aligned8Byte(fields, os.Stderr) {
// nolint:revive // this is a main func, allow Exit.
os.Exit(1)
}
// nolint:revive // this is a main func, allow Exit.
os.Exit(m.Run())
}
// Numbers are a collection of measured data point values.
type Numbers struct {
// numbers has to be aligned for 64-bit atomic operations.
numbers []number.Number
kind number.Kind
}
// NewNumbers returns a new Numbers for the passed kind.
func NewNumbers(kind number.Kind) Numbers {
return Numbers{
kind: kind,
}
}
// Append appends v to the numbers n.
func (n *Numbers) Append(v number.Number) {
n.numbers = append(n.numbers, v)
}
// Sort sorts all the numbers contained in n.
func (n *Numbers) Sort() {
sort.Sort(n)
}
// Less returns if the number at index i is less than the number at index j.
func (n *Numbers) Less(i, j int) bool {
return n.numbers[i].CompareNumber(n.kind, n.numbers[j]) < 0
}
// Len returns number of data points Numbers contains.
func (n *Numbers) Len() int {
return len(n.numbers)
}
// Swap swaps the location of the numbers at index i and j.
func (n *Numbers) Swap(i, j int) {
n.numbers[i], n.numbers[j] = n.numbers[j], n.numbers[i]
}
// Sum returns the sum of all data points.
func (n *Numbers) Sum() number.Number {
var sum number.Number
for _, num := range n.numbers {
sum.AddNumber(n.kind, num)
}
return sum
}
// Count returns the number of data points Numbers contains.
func (n *Numbers) Count() uint64 {
return uint64(len(n.numbers))
}
// Min returns the min number.
func (n *Numbers) Min() number.Number {
return n.numbers[0]
}
// Max returns the max number.
func (n *Numbers) Max() number.Number {
return n.numbers[len(n.numbers)-1]
}
// Points returns the slice of number for all data points.
func (n *Numbers) Points() []number.Number {
return n.numbers
}
// CheckedUpdate performs the same range test the SDK does on behalf of the aggregator.
func CheckedUpdate(t *testing.T, agg aggregator.Aggregator, n number.Number, descriptor *sdkapi.Descriptor) {
ctx := context.Background()
// Note: Aggregator tests are written assuming that the SDK
// has performed the RangeTest. Therefore we skip errors that
// would have been detected by the RangeTest.
err := aggregator.RangeTest(n, descriptor)
if err != nil {
return
}
if err := agg.Update(ctx, n, descriptor); err != nil {
t.Error("Unexpected Update failure", err)
}
}
// CheckedMerge verifies aggFrom merges into aggInto with the scope of
// descriptor.
func CheckedMerge(t *testing.T, aggInto, aggFrom aggregator.Aggregator, descriptor *sdkapi.Descriptor) {
if err := aggInto.Merge(aggFrom, descriptor); err != nil {
t.Error("Unexpected Merge failure", err)
}
}
// Kind returns a Noop aggregation Kind.
func (NoopAggregation) Kind() aggregation.Kind {
return aggregation.Kind("Noop")
}
// Aggregation returns a NoopAggregation.
func (NoopAggregator) Aggregation() aggregation.Aggregation {
return NoopAggregation{}
}
// Update performs no operation.
func (NoopAggregator) Update(context.Context, number.Number, *sdkapi.Descriptor) error {
return nil
}
// SynchronizedMove performs no operation.
func (NoopAggregator) SynchronizedMove(aggregator.Aggregator, *sdkapi.Descriptor) error {
return nil
}
// Merge performs no operation.
func (NoopAggregator) Merge(aggregator.Aggregator, *sdkapi.Descriptor) error {
return nil
}
// SynchronizedMoveResetTest tests SynchronizedMove behavior for an aggregator
// during resets.
func SynchronizedMoveResetTest(t *testing.T, mkind sdkapi.InstrumentKind, nf func(*sdkapi.Descriptor) aggregator.Aggregator) {
t.Run("reset on nil", func(t *testing.T) {
// Ensures that SynchronizedMove(nil, descriptor) discards and
// resets the aggregator.
RunProfiles(t, func(t *testing.T, profile Profile) {
descriptor := NewAggregatorTest(
mkind,
profile.NumberKind,
)
agg := nf(descriptor)
for i := 0; i < 10; i++ {
x1 := profile.Random(+1)
CheckedUpdate(t, agg, x1, descriptor)
}
require.NoError(t, agg.SynchronizedMove(nil, descriptor))
if count, ok := agg.(aggregation.Count); ok {
c, err := count.Count()
require.Equal(t, uint64(0), c)
require.NoError(t, err)
}
if sum, ok := agg.(aggregation.Sum); ok {
s, err := sum.Sum()
require.Equal(t, number.Number(0), s)
require.NoError(t, err)
}
if lv, ok := agg.(aggregation.LastValue); ok {
v, _, err := lv.LastValue()
require.Equal(t, number.Number(0), v)
require.Error(t, err)
require.True(t, errors.Is(err, aggregation.ErrNoData))
}
})
})
t.Run("no reset on incorrect type", func(t *testing.T) {
// Ensures that SynchronizedMove(wrong_type, descriptor) does not
// reset the aggregator.
RunProfiles(t, func(t *testing.T, profile Profile) {
descriptor := NewAggregatorTest(
mkind,
profile.NumberKind,
)
agg := nf(descriptor)
var input number.Number
const inval = 100
if profile.NumberKind == number.Int64Kind {
input = number.NewInt64Number(inval)
} else {
input = number.NewFloat64Number(inval)
}
CheckedUpdate(t, agg, input, descriptor)
err := agg.SynchronizedMove(NoopAggregator{}, descriptor)
require.Error(t, err)
require.True(t, errors.Is(err, aggregation.ErrInconsistentType))
// Test that the aggregator was not reset
if count, ok := agg.(aggregation.Count); ok {
c, err := count.Count()
require.Equal(t, uint64(1), c)
require.NoError(t, err)
}
if sum, ok := agg.(aggregation.Sum); ok {
s, err := sum.Sum()
require.Equal(t, input, s)
require.NoError(t, err)
}
if lv, ok := agg.(aggregation.LastValue); ok {
v, _, err := lv.LastValue()
require.Equal(t, input, v)
require.NoError(t, err)
}
})
})
}