(goctl): fix #4943 (#4953)

This commit is contained in:
kesonan
2025-06-14 23:36:30 +08:00
committed by GitHub
parent 0ba86b1849
commit 0d31e6c375
2 changed files with 77 additions and 0 deletions

View File

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

View File

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