@@ -17,6 +17,68 @@ import (
1717 ectest "github.com/go-kratos/kratos/v2/internal/testdata/encoding"
1818)
1919
20+ // This variable can be replaced with -ldflags like below:
21+ // go test "-ldflags=-X github.com/go-kratos/kratos/v2/encoding/form.tagNameTest=form"
22+ var tagNameTest string
23+
24+ func init () {
25+ if tagNameTest == "" {
26+ tagNameTest = tagName
27+ }
28+ }
29+
30+ func TestFormEncoderAndDecoder (t * testing.T ) {
31+ t .Cleanup (func () {
32+ encoder .SetTagName (tagName )
33+ decoder .SetTagName (tagName )
34+ })
35+
36+ encoder .SetTagName (tagNameTest )
37+ decoder .SetTagName (tagNameTest )
38+
39+ type testFormTagName struct {
40+ Name string `form:"name_form" json:"name_json"`
41+ }
42+ v , err := encoder .Encode (& testFormTagName {
43+ Name : "test tag name" ,
44+ })
45+ if err != nil {
46+ t .Fatal (err )
47+ }
48+ jsonName := v .Get ("name_json" )
49+ formName := v .Get ("name_form" )
50+ switch tagNameTest {
51+ case "json" :
52+ if jsonName != "test tag name" {
53+ t .Errorf ("got: %s" , jsonName )
54+ }
55+ if formName != "" {
56+ t .Errorf ("want: empty, got: %s" , formName )
57+ }
58+ case "form" :
59+ if formName != "test tag name" {
60+ t .Errorf ("got: %s" , formName )
61+ }
62+ if jsonName != "" {
63+ t .Errorf ("want: empty, got: %s" , jsonName )
64+ }
65+ default :
66+ t .Fatalf ("unknown tag name: %s" , tagNameTest )
67+ }
68+
69+ var tn * testFormTagName
70+ err = decoder .Decode (& tn , v )
71+ if err != nil {
72+ t .Fatal (err )
73+ }
74+ if tn == nil {
75+ t .Fatal ("nil tag name" )
76+ }
77+ if tn .Name != "test tag name" {
78+ t .Errorf ("got %s" , tn .Name )
79+ }
80+ }
81+
2082type LoginRequest struct {
2183 Username string `json:"username,omitempty"`
2284 Password string `json:"password,omitempty"`
0 commit comments