From 0d31e6c3752b63e8bcaba896e96cacdefec0c5ec Mon Sep 17 00:00:00 2001 From: kesonan Date: Sat, 14 Jun 2025 23:36:30 +0800 Subject: [PATCH] (goctl): fix #4943 (#4953) --- tools/goctl/api/spec/tags.go | 9 ++++ tools/goctl/api/spec/tags_test.go | 68 +++++++++++++++++++++++++++++++ 2 files changed, 77 insertions(+) create mode 100644 tools/goctl/api/spec/tags_test.go diff --git a/tools/goctl/api/spec/tags.go b/tools/goctl/api/spec/tags.go index 312772d35..1e3d153b3 100644 --- a/tools/goctl/api/spec/tags.go +++ b/tools/goctl/api/spec/tags.go @@ -49,6 +49,9 @@ func Parse(tag string) (*Tags, error) { // Get gets tag value by specified key func (t *Tags) Get(key string) (*Tag, error) { + if t == nil { + return nil, errTagNotExist + } for _, tag := range t.tags { if tag.Key == key { return tag, nil @@ -60,6 +63,9 @@ func (t *Tags) Get(key string) (*Tag, error) { // Keys returns all keys in Tags func (t *Tags) Keys() []string { + if t == nil { + return []string{} + } var keys []string for _, tag := range t.tags { keys = append(keys, tag.Key) @@ -69,5 +75,8 @@ func (t *Tags) Keys() []string { // Tags returns all tags in Tags func (t *Tags) Tags() []*Tag { + if t == nil { + return []*Tag{} + } return t.tags } diff --git a/tools/goctl/api/spec/tags_test.go b/tools/goctl/api/spec/tags_test.go new file mode 100644 index 000000000..417b1f621 --- /dev/null +++ b/tools/goctl/api/spec/tags_test.go @@ -0,0 +1,68 @@ +package spec + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestTags_Get(t *testing.T) { + tags := &Tags{ + tags: []*Tag{ + {Key: "json", Name: "foo", Options: []string{"omitempty"}}, + {Key: "xml", Name: "bar", Options: nil}, + }, + } + + tag, err := tags.Get("json") + assert.NoError(t, err) + assert.NotNil(t, tag) + assert.Equal(t, "json", tag.Key) + assert.Equal(t, "foo", tag.Name) + + _, err = tags.Get("yaml") + assert.Error(t, err) + + var nilTags *Tags + _, err = nilTags.Get("json") + assert.Error(t, err) +} + +func TestTags_Keys(t *testing.T) { + tags := &Tags{ + tags: []*Tag{ + {Key: "json", Name: "foo", Options: []string{"omitempty"}}, + {Key: "xml", Name: "bar", Options: nil}, + }, + } + + keys := tags.Keys() + expected := []string{"json", "xml"} + assert.Equal(t, expected, keys) + + var nilTags *Tags + nilKeys := nilTags.Keys() + assert.Empty(t, nilKeys) +} + +func TestTags_Tags(t *testing.T) { + tags := &Tags{ + tags: []*Tag{ + {Key: "json", Name: "foo", Options: []string{"omitempty"}}, + {Key: "xml", Name: "bar", Options: nil}, + }, + } + + result := tags.Tags() + assert.Len(t, result, 2) + assert.Equal(t, "json", result[0].Key) + assert.Equal(t, "foo", result[0].Name) + assert.Equal(t, []string{"omitempty"}, result[0].Options) + assert.Equal(t, "xml", result[1].Key) + assert.Equal(t, "bar", result[1].Name) + assert.Nil(t, result[1].Options) + + var nilTags *Tags + nilResult := nilTags.Tags() + assert.Empty(t, nilResult) +}