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