gitee.com/sasukebo/go-micro/v4@v4.7.1/config/source/cli/cli_test.go (about) 1 package cli 2 3 import ( 4 "encoding/json" 5 "os" 6 "testing" 7 8 "gitee.com/sasukebo/go-micro/v4" 9 "gitee.com/sasukebo/go-micro/v4/cmd" 10 "gitee.com/sasukebo/go-micro/v4/config" 11 "gitee.com/sasukebo/go-micro/v4/config/source" 12 "github.com/urfave/cli/v2" 13 ) 14 15 func TestCliSourceDefault(t *testing.T) { 16 const expVal string = "flagvalue" 17 18 service := micro.NewService( 19 micro.Flags( 20 // to be able to run inside go test 21 &cli.StringFlag{ 22 Name: "test.timeout", 23 }, 24 &cli.BoolFlag{ 25 Name: "test.v", 26 }, 27 &cli.StringFlag{ 28 Name: "test.run", 29 }, 30 &cli.StringFlag{ 31 Name: "test.testlogfile", 32 }, 33 &cli.StringFlag{ 34 Name: "test.paniconexit0", 35 }, 36 &cli.StringFlag{ 37 Name: "flag", 38 Usage: "It changes something", 39 EnvVars: []string{"flag"}, 40 Value: expVal, 41 }, 42 ), 43 ) 44 var cliSrc source.Source 45 service.Init( 46 // Loads CLI configuration 47 micro.Action(func(c *cli.Context) error { 48 cliSrc = NewSource( 49 Context(c), 50 ) 51 return nil 52 }), 53 ) 54 55 config.Load(cliSrc) 56 if fval := config.Get("flag").String("default"); fval != expVal { 57 t.Fatalf("default flag value not loaded %v != %v", fval, expVal) 58 } 59 } 60 61 func test(t *testing.T, withContext bool) { 62 var src source.Source 63 64 // setup app 65 app := cmd.App() 66 app.Name = "testapp" 67 app.Flags = []cli.Flag{ 68 &cli.StringFlag{ 69 Name: "db-host", 70 EnvVars: []string{"db-host"}, 71 Value: "myval", 72 }, 73 } 74 75 // with context 76 if withContext { 77 // set action 78 app.Action = func(c *cli.Context) error { 79 src = WithContext(c) 80 return nil 81 } 82 83 // run app 84 app.Run([]string{"run", "-db-host", "localhost"}) 85 // no context 86 } else { 87 // set args 88 os.Args = []string{"run", "-db-host", "localhost"} 89 src = NewSource() 90 } 91 92 // test config 93 c, err := src.Read() 94 if err != nil { 95 t.Error(err) 96 } 97 98 var actual map[string]interface{} 99 if err := json.Unmarshal(c.Data, &actual); err != nil { 100 t.Error(err) 101 } 102 103 actualDB := actual["db"].(map[string]interface{}) 104 if actualDB["host"] != "localhost" { 105 t.Errorf("expected localhost, got %v", actualDB["name"]) 106 } 107 108 } 109 110 func TestCliSource(t *testing.T) { 111 // without context 112 test(t, false) 113 } 114 115 func TestCliSourceWithContext(t *testing.T) { 116 // with context 117 test(t, true) 118 }