github.com/bingoohuang/gg@v0.0.0-20240325092523-45da7dee9335/pkg/jsoni/extra/naming_strategy_test.go (about) 1 package extra 2 3 import ( 4 "testing" 5 6 "github.com/bingoohuang/gg/pkg/jsoni" 7 "github.com/stretchr/testify/require" 8 ) 9 10 func Test_lower_case_with_underscores(t *testing.T) { 11 should := require.New(t) 12 should.Equal("hello_world", LowerCaseWithUnderscores("helloWorld")) 13 should.Equal("hello_world", LowerCaseWithUnderscores("HelloWorld")) 14 SetNamingStrategy(LowerCaseWithUnderscores) 15 output, err := jsoni.Marshal(struct { 16 UserName string 17 FirstLanguage string 18 }{ 19 UserName: "taowen", 20 FirstLanguage: "Chinese", 21 }) 22 should.Nil(err) 23 should.Equal(`{"user_name":"taowen","first_language":"Chinese"}`, string(output)) 24 } 25 26 func Test_set_naming_strategy_with_overrides(t *testing.T) { 27 should := require.New(t) 28 SetNamingStrategy(LowerCaseWithUnderscores) 29 output, err := jsoni.Marshal(struct { 30 UserName string `json:"UserName"` 31 FirstLanguage string 32 }{ 33 UserName: "taowen", 34 FirstLanguage: "Chinese", 35 }) 36 should.Nil(err) 37 should.Equal(`{"UserName":"taowen","first_language":"Chinese"}`, string(output)) 38 } 39 40 func Test_set_naming_strategy_with_omitempty(t *testing.T) { 41 should := require.New(t) 42 SetNamingStrategy(LowerCaseWithUnderscores) 43 output, err := jsoni.Marshal(struct { 44 UserName string 45 FirstLanguage string `json:",omitempty"` 46 }{ 47 UserName: "taowen", 48 }) 49 should.Nil(err) 50 should.Equal(`{"user_name":"taowen"}`, string(output)) 51 } 52 53 func Test_set_naming_strategy_with_private_field(t *testing.T) { 54 should := require.New(t) 55 SetNamingStrategy(LowerCaseWithUnderscores) 56 output, err := jsoni.Marshal(struct { 57 UserName string 58 userId int 59 _UserAge int 60 }{ 61 UserName: "allen", 62 userId: 100, 63 _UserAge: 30, 64 }) 65 should.Nil(err) 66 should.Equal(`{"user_name":"allen"}`, string(output)) 67 }