func TestLoadConfig(t *testing.T) { aws := AWSConfig{ Accesskey: "CF2DC307CC89F49F68F365235AA54BAB2DDD02DA", SecretKey: "ca485e5b709eae0ceacd68b61cdb28119f13942c71bbb68066c8a3cb45185a39", } testName := utils.GetAppName() + "-test" tempDir, _ := ioutil.TempDir("", testName) out := OutConfig{ Root: tempDir, File: true, Bom: true, } log := LogConfig{ Root: tempDir, Verbose: true, JSON: true, } rds := RDSConfig{ MultiAz: true, DBId: utils.GetFormatedDBDisplayName(testName), Region: "us-west-2", User: "******", Pass: "******", Type: "db.m3.medium", } rdsMap := map[string]RDSConfig{ "default": rds, } config := &Config{ Aws: aws, Out: out, Rds: rdsMap, Log: log, } tempFile, err := ioutil.TempFile(tempDir, utils.GetAppName()+"-test") if err != nil { t.Errorf("failed to create the temp file: %s", err.Error()) } if err := toml.NewEncoder(tempFile).Encode(config); err != nil { t.Errorf("failed to create the toml file: %s", err.Error()) } tempFile.Sync() tempFile.Close() defer os.RemoveAll(tempDir) conf, err := LoadConfig(tempFile.Name()) if err != nil { t.Errorf("config file load error: %s", err.Error()) } if !reflect.DeepEqual(config, conf) { t.Errorf("config data not match: %+v/%+v", config, conf) } }
// need to run the caller always "defer os.RemoveAll(temp_dir)" func getTestConfig() (*config.Config, string, error) { aws := config.AWSConfig{ Accesskey: "CF2DC307CC89F49F68F365235AA54BAB2DDD02DA", SecretKey: "ca485e5b709eae0ceacd68b61cdb28119f13942c71bbb68066c8a3cb45185a39", } testName := utils.GetAppName() + "-test" tempDir, _ := ioutil.TempDir("", testName) out := config.OutConfig{ Root: tempDir, File: true, Bom: true, } log := config.LogConfig{ Root: tempDir, Verbose: true, JSON: true, } rds := config.RDSConfig{ MultiAz: true, DBId: utils.GetFormatedDBDisplayName(testName), Region: "us-west-2", User: "******", Pass: "******", Type: "db.m3.medium", } rdsMap := map[string]config.RDSConfig{ "default2": rds, } config := &config.Config{ Aws: aws, Out: out, Rds: rdsMap, Log: log, } tempFile, err := ioutil.TempFile(tempDir, utils.GetAppName()+"-test") if err != nil { return nil, tempDir, err } if err := toml.NewEncoder(tempFile).Encode(config); err != nil { return nil, tempDir, err } tempFile.Sync() tempFile.Close() os.Args = []string{utils.GetAppName(), "-c=" + tempFile.Name(), "-n=default", "ls"} flag.CommandLine = flag.NewFlagSet(os.Args[0], flag.ExitOnError) return config, tempDir, nil }
func TestWriteCSVFile(t *testing.T) { testName := utils.GetAppName() + "-test" tempDir, _ := ioutil.TempDir("", testName) tempFile, err := ioutil.TempFile(tempDir, utils.GetAppName()+"-test") if err != nil { t.Errorf("failed to create the temp file: %s", err.Error()) } fStat, _ := tempFile.Stat() fName := tempFile.Name() tempFile.Sync() tempFile.Close() defer os.RemoveAll(tempDir) db, _ := sql.Open("testdb", "") defer db.Close() sql := "select id, name, age from users" columns := []string{"id", "name", "age", "created"} result := ` 1,tim,20,2012-10-01 01:00:01 2,joe,25,2012-10-02 02:00:02 3,bob,30,2012-10-03 03:00:03 ` testdb.StubQuery(sql, testdb.RowsFromCSVString(columns, result)) res, err := db.Query(sql) args := &writeCSVFileArgs{ Rows: res, FileName: fStat.Name(), Path: tempDir, Bom: false, } csvState := writeCSVFile(args) file, err := os.OpenFile(fName, os.O_RDONLY, 0777) defer file.Close() fStat, _ = file.Stat() if !csvState { t.Errorf("[writeCSVFile] result error: %s", err.Error()) } if fStat.Size() <= 0 { t.Errorf("csv file not out put: %d", fStat.Size()) } }
func TestLoadQuery(t *testing.T) { queries := &Queries{} for i := 0; i < 10; i++ { query := Query{ Name: fmt.Sprintf("name_%d", i+1), SQL: fmt.Sprintf("sql_%d", i+1), } queries.Query = append(queries.Query, query) } tempFile, err := ioutil.TempFile("", utils.GetAppName()+"-test") if err != nil { t.Errorf("failed to create the temp file: %s", err.Error()) } if err := toml.NewEncoder(tempFile).Encode(queries); err != nil { t.Errorf("failed to create the toml file: %s", err.Error()) } tempFile.Sync() tempFile.Close() defer os.Remove(tempFile.Name()) query, err := LoadQuery(tempFile.Name()) if err != nil { t.Errorf("query file load error: %s", err.Error()) } if !reflect.DeepEqual(queries, query) { t.Errorf("query data not match: %+v/%+v", queries, query) } }
// Help is the show help text func (c *LsCommand) Help() string { // to-do: removal of the fixed value helpText := fmt.Sprintf("\nUsage: %s ls [options]\n\n", utils.GetAppName()) helpText += "Options:\n" helpText += " -s, --snap include own db snapshots to list\n" return helpText }
// Help is the show help text func (c *RmCommand) Help() string { // to-do: removal of the fixed value helpText := fmt.Sprintf("\nUsage: %s rm [options]\n\n", utils.GetAppName()) helpText += "Options:\n" helpText += " -s, --snap list up own db snapshots\n" helpText += " -f, --force forced delete without confirmation\n" return helpText }
// Help is the show help text func (c *EsCommand) Help() string { // to-do: removal of the fixed value helpText := fmt.Sprintf("\nUsage: %s es [options]\n\n", utils.GetAppName()) helpText += "Options:\n" helpText += " -q, --query specify an alternate query file\n" helpText += " -s, --snap create snapshot before restore\n" helpText += " -t, --type specify an alternate db instance class\n" return helpText }
// return "httptest.Server" need call close !! // and Command into OutConfig.Root need call remove !! func getTestClient(code int, body string) (*httptest.Server, *Command) { server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(code) w.Header().Set("Content-Type", "application/xml") fmt.Fprintln(w, body) })) transport := &http.Transport{ Proxy: func(req *http.Request) (*url.URL, error) { return url.Parse(server.URL) }, } httpClient := &http.Client{Transport: transport} // Override endpoints testRegion := "rds-try-test-1" awsConf := aws.NewConfig() awsConf = awsConf.WithCredentials(credentials.NewStaticCredentials("awsAccesskey1", "awsSecretKey2", "")) awsConf = awsConf.WithRegion(testRegion) awsConf = awsConf.WithEndpoint(server.URL) awsConf = awsConf.WithHTTPClient(httpClient) awsRds := rds.New(awsConf) testName := utils.GetAppName() + "-test" tempDir, _ := ioutil.TempDir("", testName) defer os.RemoveAll(tempDir) out := config.OutConfig{ Root: tempDir, File: true, Bom: true, } rds := config.RDSConfig{ MultiAz: false, DBId: utils.GetFormatedDBDisplayName(testName), Region: testRegion, User: "******", Pass: "******", Type: "db.m3.medium", } cmdTest := &Command{ OutConfig: out, RDSConfig: rds, RDSClient: awsRds, ARNPrefix: "arn:aws:rds:" + testRegion + ":" + "123456789" + ":", } return server, cmdTest }
func resolveArgs() (*config.Config, int) { // register flag name flag.BoolVar(&helpFlag, "help", false, "show this help message and exit") flag.BoolVar(&helpFlag, "h", false, "show this help message and exit") flag.BoolVar(&versionFlag, "version", false, "show version message and exit") flag.BoolVar(&versionFlag, "v", false, "show version message and exit") flag.StringVar(&configFlag, "config", "", "specify an alternate config file") flag.StringVar(&configFlag, "c", "", "specify an alternate config file") flag.StringVar(&nameFlag, "name", "default", "specify an alternate rds environment name") flag.StringVar(&nameFlag, "n", "default", "specify an alternate rds environment name") // set help func flag.Usage = showHelp() flag.Parse() // show help if helpFlag { flag.Usage() return nil, 0 } // show version if versionFlag { fmt.Printf("%s %s\n", utils.GetAppName(), utils.GetAppVersion()) return nil, 0 } // show help // to-do: want to change the "command name" that has been hard-coded if len(flag.Args()) <= 0 || flag.Args()[0] != "es" && flag.Args()[0] != "ls" && flag.Args()[0] != "rm" { flag.Usage() return nil, 1 } // load config file configFile := config.GetDefaultPath() if configFlag != "" { configFile = configFlag } conf, err := config.LoadConfig(configFile) if err != nil { return nil, 1 } log.Debugf("Config: %+v", conf) return conf, 0 }
func showHelp() func() { return func() { helpText := fmt.Sprintf("\nUsage: %s [globals] <command> [options]\n\n", utils.GetAppName()) helpText += "Globals:\n" globals := make(map[string]string) // list global options flag.VisitAll(func(f *flag.Flag) { if value, ok := globals[f.Usage]; ok { // key exists if len(f.Name) > len(value) { globals[f.Usage] = fmt.Sprintf("-%s, --%s", value, f.Name) } else { globals[f.Usage] = fmt.Sprintf("-%s, --%s", f.Name, value) } } else { // key does not exist globals[f.Usage] = f.Name } }) // to store the keys in slice in sorted order var keys []string textLength := 0 for k, v := range globals { keys = append(keys, k) if len(v) > textLength { textLength = len(v) } } sort.Strings(keys) // to prepare the output format for _, k := range keys { optionText := fmt.Sprintf("%s%s", globals[k], strings.Repeat(" ", textLength-len(globals[k]))) helpText += fmt.Sprintf(" %s %s\n", optionText, k) } helpText += "\nCommands:\n" // make commad list // to-do: want to change the "command name" that has been hard-coded commandList := map[string]command.CmdInterface{ "es": &command.EsCommand{}, "ls": &command.LsCommand{}, "rm": &command.RmCommand{}, } // to store the keys in slice in sorted order keys = nil textLength = 0 for k := range commandList { keys = append(keys, k) if len(k) > textLength { textLength = len(k) } } sort.Strings(keys) // to prepare the output format for _, k := range keys { commandText := fmt.Sprintf("%s%s", k, strings.Repeat(" ", textLength-len(k))) helpText += fmt.Sprintf(" %s %s\n", commandText, commandList[k].Synopsis()) } helpText += "\nOptions:\n" helpText += " show commands options help <command> -h, --help\n" // show a help string fmt.Println(helpText) } }