1
0
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:
Tyler Yahn 2023-04-04 08:06:10 -07:00 committed by GitHub
parent 65ebe5e50f
commit a25f4fe7ef
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 39 additions and 2 deletions

View File

@ -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()

View File

@ -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
}