NodeKind/String: Don't panic on unknown

NodeKind.String() will currently panic if called with an unknown
NodeKind.

This change verifies that the name of the NodeKind is known before
looking it up in kindNames. If the name is unknown, a generic
`NodeKind(N)` string representation is used.
This commit is contained in:
Abhinav Gupta 2020-03-05 22:47:15 -08:00
parent 21437947a3
commit ca5561990e
2 changed files with 32 additions and 1 deletions

View file

@ -26,7 +26,10 @@ const (
type NodeKind int
func (k NodeKind) String() string {
if int(k) < len(kindNames) {
return kindNames[k]
}
return fmt.Sprintf("NodeKind(%v)", int(k))
}
var kindMax NodeKind

View file

@ -73,3 +73,31 @@ func node(n Node, children ...Node) Node {
}
return n
}
func TestNodeKindString(t *testing.T) {
tests := []struct {
name string
give NodeKind
want string
}{
{
name: "known",
give: KindLink,
want: "Link",
},
{
name: "unknown",
give: NodeKind(500),
want: "NodeKind(500)",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := tt.give.String()
if tt.want != got {
t.Errorf("String() expected %q, got %q", tt.want, got)
}
})
}
}