mirror of
https://github.com/open-telemetry/opentelemetry-go.git
synced 2025-04-09 07:03:54 +02:00
Guard zero value Set methods (#3957)
Co-authored-by: Chester Cheung <cheung.zhy.csu@gmail.com>
This commit is contained in:
parent
65ebe5e50f
commit
a25f4fe7ef
@ -98,7 +98,7 @@ func (l *Set) Len() int {
|
||||
|
||||
// Get returns the KeyValue at ordered position idx in this set.
|
||||
func (l *Set) Get(idx int) (KeyValue, bool) {
|
||||
if l == nil {
|
||||
if l == nil || !l.equivalent.Valid() {
|
||||
return KeyValue{}, false
|
||||
}
|
||||
value := l.equivalent.reflectValue()
|
||||
@ -114,7 +114,7 @@ func (l *Set) Get(idx int) (KeyValue, bool) {
|
||||
|
||||
// Value returns the value of a specified key in this set.
|
||||
func (l *Set) Value(k Key) (Value, bool) {
|
||||
if l == nil {
|
||||
if l == nil || !l.equivalent.Valid() {
|
||||
return Value{}, false
|
||||
}
|
||||
rValue := l.equivalent.reflectValue()
|
||||
|
@ -15,9 +15,11 @@
|
||||
package attribute_test
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"regexp"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
@ -188,3 +190,38 @@ func TestLookup(t *testing.T) {
|
||||
_, has = set.Value("D")
|
||||
require.False(t, has)
|
||||
}
|
||||
|
||||
func TestZeroSetExportedMethodsNoPanic(t *testing.T) {
|
||||
rType := reflect.TypeOf((*attribute.Set)(nil))
|
||||
rVal := reflect.ValueOf(&attribute.Set{})
|
||||
for n := 0; n < rType.NumMethod(); n++ {
|
||||
mType := rType.Method(n)
|
||||
if !mType.IsExported() {
|
||||
t.Logf("ignoring unexported %s", mType.Name)
|
||||
continue
|
||||
}
|
||||
t.Run(mType.Name, func(t *testing.T) {
|
||||
m := rVal.MethodByName(mType.Name)
|
||||
if !m.IsValid() {
|
||||
t.Errorf("unknown method: %s", mType.Name)
|
||||
}
|
||||
assert.NotPanics(t, func() { _ = m.Call(args(mType)) })
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func args(m reflect.Method) []reflect.Value {
|
||||
numIn := m.Type.NumIn() - 1 // Do not include the receiver arg.
|
||||
if numIn <= 0 {
|
||||
return nil
|
||||
}
|
||||
if m.Type.IsVariadic() {
|
||||
numIn--
|
||||
}
|
||||
out := make([]reflect.Value, numIn)
|
||||
for i := range out {
|
||||
aType := m.Type.In(i + 1) // Skip receiver arg.
|
||||
out[i] = reflect.New(aType).Elem()
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user