Skip to content

Commit 0d31e6c

Browse files
authored
(goctl): fix #4943 (#4953)
1 parent 0ba86b1 commit 0d31e6c

File tree

2 files changed

+77
-0
lines changed

2 files changed

+77
-0
lines changed

tools/goctl/api/spec/tags.go

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,9 @@ func Parse(tag string) (*Tags, error) {
4949

5050
// Get gets tag value by specified key
5151
func (t *Tags) Get(key string) (*Tag, error) {
52+
if t == nil {
53+
return nil, errTagNotExist
54+
}
5255
for _, tag := range t.tags {
5356
if tag.Key == key {
5457
return tag, nil
@@ -60,6 +63,9 @@ func (t *Tags) Get(key string) (*Tag, error) {
6063

6164
// Keys returns all keys in Tags
6265
func (t *Tags) Keys() []string {
66+
if t == nil {
67+
return []string{}
68+
}
6369
var keys []string
6470
for _, tag := range t.tags {
6571
keys = append(keys, tag.Key)
@@ -69,5 +75,8 @@ func (t *Tags) Keys() []string {
6975

7076
// Tags returns all tags in Tags
7177
func (t *Tags) Tags() []*Tag {
78+
if t == nil {
79+
return []*Tag{}
80+
}
7281
return t.tags
7382
}

tools/goctl/api/spec/tags_test.go

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
package spec
2+
3+
import (
4+
"testing"
5+
6+
"github.com/stretchr/testify/assert"
7+
)
8+
9+
func TestTags_Get(t *testing.T) {
10+
tags := &Tags{
11+
tags: []*Tag{
12+
{Key: "json", Name: "foo", Options: []string{"omitempty"}},
13+
{Key: "xml", Name: "bar", Options: nil},
14+
},
15+
}
16+
17+
tag, err := tags.Get("json")
18+
assert.NoError(t, err)
19+
assert.NotNil(t, tag)
20+
assert.Equal(t, "json", tag.Key)
21+
assert.Equal(t, "foo", tag.Name)
22+
23+
_, err = tags.Get("yaml")
24+
assert.Error(t, err)
25+
26+
var nilTags *Tags
27+
_, err = nilTags.Get("json")
28+
assert.Error(t, err)
29+
}
30+
31+
func TestTags_Keys(t *testing.T) {
32+
tags := &Tags{
33+
tags: []*Tag{
34+
{Key: "json", Name: "foo", Options: []string{"omitempty"}},
35+
{Key: "xml", Name: "bar", Options: nil},
36+
},
37+
}
38+
39+
keys := tags.Keys()
40+
expected := []string{"json", "xml"}
41+
assert.Equal(t, expected, keys)
42+
43+
var nilTags *Tags
44+
nilKeys := nilTags.Keys()
45+
assert.Empty(t, nilKeys)
46+
}
47+
48+
func TestTags_Tags(t *testing.T) {
49+
tags := &Tags{
50+
tags: []*Tag{
51+
{Key: "json", Name: "foo", Options: []string{"omitempty"}},
52+
{Key: "xml", Name: "bar", Options: nil},
53+
},
54+
}
55+
56+
result := tags.Tags()
57+
assert.Len(t, result, 2)
58+
assert.Equal(t, "json", result[0].Key)
59+
assert.Equal(t, "foo", result[0].Name)
60+
assert.Equal(t, []string{"omitempty"}, result[0].Options)
61+
assert.Equal(t, "xml", result[1].Key)
62+
assert.Equal(t, "bar", result[1].Name)
63+
assert.Nil(t, result[1].Options)
64+
65+
var nilTags *Tags
66+
nilResult := nilTags.Tags()
67+
assert.Empty(t, nilResult)
68+
}

0 commit comments

Comments
 (0)