github.com/soulteary/pocket-bookcase@v0.0.0-20240428065142-0b5a9a0fc98a/internal/cmd/server_test.go (about) 1 package cmd 2 3 import ( 4 "testing" 5 6 "github.com/soulteary/pocket-bookcase/internal/config" 7 "github.com/spf13/pflag" 8 "github.com/stretchr/testify/require" 9 ) 10 11 func Test_setIfFlagChanged(t *testing.T) { 12 type args struct { 13 flagName string 14 flags func() *pflag.FlagSet 15 cfg *config.Config 16 fn func(cfg *config.Config) 17 } 18 tests := []struct { 19 name string 20 args args 21 assertFn func(t *testing.T, cfg *config.Config) 22 }{ 23 { 24 name: "Flag didn't change", 25 args: args{ 26 flagName: "port", 27 flags: func() *pflag.FlagSet { 28 return &pflag.FlagSet{} 29 }, 30 cfg: &config.Config{ 31 Http: &config.HttpConfig{ 32 Port: 8080, 33 }, 34 }, 35 fn: func(cfg *config.Config) { 36 cfg.Http.Port = 9999 37 }, 38 }, 39 assertFn: func(t *testing.T, cfg *config.Config) { 40 require.Equal(t, cfg.Http.Port, 8080) 41 }, 42 }, 43 { 44 name: "Flag changed", 45 args: args{ 46 flagName: "port", 47 flags: func() *pflag.FlagSet { 48 pf := &pflag.FlagSet{} 49 pf.IntP("port", "p", 8080, "Port used by the server") 50 pf.Set("port", "9999") 51 return pf 52 }, 53 cfg: &config.Config{ 54 Http: &config.HttpConfig{ 55 Port: 8080, 56 }, 57 }, 58 fn: func(cfg *config.Config) { 59 cfg.Http.Port = 9999 60 }, 61 }, 62 assertFn: func(t *testing.T, cfg *config.Config) { 63 require.Equal(t, cfg.Http.Port, 9999) 64 }, 65 }, 66 } 67 for _, tt := range tests { 68 t.Run(tt.name, func(t *testing.T) { 69 setIfFlagChanged(tt.args.flagName, tt.args.flags(), tt.args.cfg, tt.args.fn) 70 }) 71 } 72 }