Skip to content

Commit

Permalink
Fix field path for uint-type map key (#15)
Browse files Browse the repository at this point in the history
  • Loading branch information
rodaine authored Jul 5, 2023
1 parent fe202ff commit bc6c2ad
Show file tree
Hide file tree
Showing 2 changed files with 67 additions and 1 deletion.
14 changes: 13 additions & 1 deletion internal/evaluator/map.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@
package evaluator

import (
"fmt"
"strconv"

"github.com/bufbuild/protovalidate-go/internal/errors"
"google.golang.org/protobuf/reflect/protoreflect"
)
Expand All @@ -32,7 +35,7 @@ func (m kvPairs) Evaluate(val protoreflect.Value, failFast bool) (err error) {
val.Map().Range(func(key protoreflect.MapKey, value protoreflect.Value) bool {
evalErr := m.evalPairs(key, value, failFast)
if evalErr != nil {
errors.PrefixErrorPaths(evalErr, "[%#v]", key.Interface())
errors.PrefixErrorPaths(evalErr, "[%s]", m.formatKey(key.Interface()))
}
ok, err = errors.Merge(err, evalErr, failFast)
return ok
Expand All @@ -57,4 +60,13 @@ func (m kvPairs) Tautology() bool {
m.ValueConstraints.Tautology()
}

func (m kvPairs) formatKey(key any) string {
switch k := key.(type) {
case string:
return strconv.Quote(k)
default:
return fmt.Sprintf("%v", key)
}
}

var _ evaluator = kvPairs{}
54 changes: 54 additions & 0 deletions internal/evaluator/map_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
package evaluator

import (
"testing"

"github.com/stretchr/testify/assert"
)

func TestFormatKey(t *testing.T) {
t.Parallel()
tests := []struct {
key any
expected string
}{
{
key: int32(32),
expected: "32",
},
{
key: int64(64),
expected: "64",
},
{
key: uint32(32),
expected: "32",
},
{
key: uint32(64),
expected: "64",
},
{
key: true,
expected: "true",
},
{
key: false,
expected: "false",
},
{
key: `"foobar"`,
expected: `"\"foobar\""`,
},
}

kv := kvPairs{}
for _, tc := range tests {
test := tc
t.Run(test.expected, func(t *testing.T) {
t.Parallel()
actual := kv.formatKey(test.key)
assert.Equal(t, test.expected, actual)
})
}
}

0 comments on commit bc6c2ad

Please sign in to comment.