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