gitee.com/liuxuezhan/go-micro-v1.18.0@v1.0.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/micro/cli"
     9  	"gitee.com/liuxuezhan/go-micro-v1.18.0/config/cmd"
    10  	"gitee.com/liuxuezhan/go-micro-v1.18.0/config/source"
    11  )
    12  
    13  func test(t *testing.T, withContext bool) {
    14  	var src source.Source
    15  
    16  	// setup app
    17  	app := cmd.App()
    18  	app.Name = "testapp"
    19  	app.Flags = []cli.Flag{
    20  		cli.StringFlag{Name: "db-host"},
    21  	}
    22  
    23  	// with context
    24  	if withContext {
    25  		// set action
    26  		app.Action = func(c *cli.Context) {
    27  			src = WithContext(c)
    28  		}
    29  
    30  		// run app
    31  		app.Run([]string{"run", "-db-host", "localhost"})
    32  		// no context
    33  	} else {
    34  		// set args
    35  		os.Args = []string{"run", "-db-host", "localhost"}
    36  		src = NewSource()
    37  	}
    38  
    39  	// test config
    40  	c, err := src.Read()
    41  	if err != nil {
    42  		t.Error(err)
    43  	}
    44  
    45  	var actual map[string]interface{}
    46  	if err := json.Unmarshal(c.Data, &actual); err != nil {
    47  		t.Error(err)
    48  	}
    49  
    50  	actualDB := actual["db"].(map[string]interface{})
    51  	if actualDB["host"] != "localhost" {
    52  		t.Errorf("expected localhost, got %v", actualDB["name"])
    53  	}
    54  
    55  }
    56  
    57  func TestCliSource(t *testing.T) {
    58  	// without context
    59  	test(t, false)
    60  }
    61  
    62  func TestCliSourceWithContext(t *testing.T) {
    63  	// with context
    64  	test(t, true)
    65  }