func TestUpBadMigration(t *testing.T) { for dname := range mans { utils.ClearTestTables(dname) utils.ClearTestMigrations() utils.SetupTestingFolders(dname) utils.GenerateMigrationFiles([]utils.TestMigration{ utils.TestMigration{ Identifier: transporter.MigrationIdentifier(), UpCommand: "Create table other_table (a varchar(255) );", DownCommand: "Drop Table other_table;", }, utils.TestMigration{ Identifier: transporter.MigrationIdentifier(), UpCommand: "Alter table shshshshs other_table add column o varchar(12);", DownCommand: "Drop column Wihii;", }, utils.TestMigration{ Identifier: transporter.MigrationIdentifier(), UpCommand: "Alter table other_table drop column a;", DownCommand: "", }, }) context := cli.NewContext(nil, &flag.FlagSet{}, nil) Up(context) con, _ := utils.BuildTestingConnection(dname) _, err := con.Query("Select a from other_table;") assert.Nil(t, err) } }
func TestDownBadMigration(t *testing.T) { for dname, man := range mans { utils.ClearTestTables(dname) utils.ClearTestMigrations() utils.SetupTestingFolders(dname) firstID := transporter.MigrationIdentifier() lastID := transporter.MigrationIdentifier() utils.GenerateMigrationFiles([]utils.TestMigration{ utils.TestMigration{ Identifier: firstID, UpCommand: "CREATE TABLE down_table (a varchar(255))", DownCommand: "DROP TABLE down_table", }, utils.TestMigration{ Identifier: lastID, UpCommand: "ALTER TABLE down_table ADD COLUMN o varchar(255)", DownCommand: "WUHdnns oius (Bad mig!);", }, }) context := cli.NewContext(nil, &flag.FlagSet{}, nil) Up(context) Down(context) con, _ := utils.BuildTestingConnection(dname) transporter.SetManager(man) version := transporter.DatabaseVersion(con) assert.Equal(t, version, strconv.FormatInt(lastID, 10)) defer con.Close() } }
func TestCommandYamlFileTestGlobalEnvVarWinsNested(t *testing.T) { app := cli.NewApp() set := flag.NewFlagSet("test", 0) ioutil.WriteFile("current.yaml", []byte(`top: test: 15`), 0666) defer os.Remove("current.yaml") os.Setenv("THE_TEST", "10") defer os.Setenv("THE_TEST", "") test := []string{"test-cmd", "--load", "current.yaml"} set.Parse(test) c := cli.NewContext(app, set, nil) command := &cli.Command{ Name: "test-cmd", Aliases: []string{"tc"}, Usage: "this is for testing", Description: "testing", Action: func(c *cli.Context) error { val := c.Int("top.test") expect(t, val, 10) return nil }, Flags: []cli.Flag{ NewIntFlag(cli.IntFlag{Name: "top.test", EnvVar: "THE_TEST"}), cli.StringFlag{Name: "load"}}, } command.Before = InitInputSourceWithContext(command.Flags, NewYamlSourceFromFlagFunc("load")) err := command.Run(c) expect(t, err, nil) }
func TestCommandTomlFileTestDefaultValueFileWinsNested(t *testing.T) { app := cli.NewApp() set := flag.NewFlagSet("test", 0) ioutil.WriteFile("current.toml", []byte("[top]\ntest = 15"), 0666) defer os.Remove("current.toml") test := []string{"test-cmd", "--load", "current.toml"} set.Parse(test) c := cli.NewContext(app, set, nil) command := &cli.Command{ Name: "test-cmd", Aliases: []string{"tc"}, Usage: "this is for testing", Description: "testing", Action: func(c *cli.Context) error { val := c.Int("top.test") expect(t, val, 15) return nil }, Flags: []cli.Flag{ NewIntFlag(cli.IntFlag{Name: "top.test", Value: 7}), cli.StringFlag{Name: "load"}}, } command.Before = InitInputSourceWithContext(command.Flags, NewTomlSourceFromFlagFunc("load")) err := command.Run(c) expect(t, err, nil) }
func SecurityCliContext() *cli.Context { app := cli.NewApp() set := flag.NewFlagSet("test", flag.ContinueOnError) set.String("security", "aws-internal", "apply security") set.String("aws-role", "test-role", "apply security") context := cli.NewContext(app, set, nil) return context }
func TestProjectFactoryProjectNameIsNormalized(t *testing.T) { projects := []struct { name string expected string }{ { name: "example", expected: "example", }, { name: "example-test", expected: "exampletest", }, { name: "aW3Ird_Project_with_$$", expected: "aw3irdprojectwith", }, } tmpDir, err := ioutil.TempDir("", "project-factory-test") if err != nil { t.Fatal(err) } composeFile := filepath.Join(tmpDir, "docker-compose.yml") ioutil.WriteFile(composeFile, []byte(`hello: image: busybox`), 0700) for _, projectCase := range projects { globalSet := flag.NewFlagSet("test", 0) // Set the project-name flag globalSet.String("project-name", projectCase.name, "doc") // Set the compose file flag globalSet.Var(&cli.StringSlice{composeFile}, "file", "doc") c := cli.NewContext(nil, globalSet, nil) factory := &ProjectFactory{} p, err := factory.Create(c) if err != nil { t.Fatal(err) } if p.(*project.Project).Name != projectCase.expected { t.Fatalf("expected %s, got %s", projectCase.expected, p.(*project.Project).Name) } } }
func runTest(t *testing.T, test testApplyInputSource) *cli.Context { inputSource := &MapInputSource{valueMap: map[interface{}]interface{}{test.FlagName: test.MapValue}} set := flag.NewFlagSet(test.FlagSetName, flag.ContinueOnError) c := cli.NewContext(nil, set, nil) if test.EnvVarName != "" && test.EnvVarValue != "" { os.Setenv(test.EnvVarName, test.EnvVarValue) defer os.Setenv(test.EnvVarName, "") } test.Flag.Apply(set) if test.ContextValue != nil { flag := set.Lookup(test.FlagName) flag.Value = test.ContextValue } if test.ContextValueString != "" { set.Set(test.FlagName, test.ContextValueString) } test.Flag.ApplyInputSourceValue(c, inputSource) return c }
func testContext(t *testing.T, u *url.URL) *cli.Context { var err error // only chdir once, because testdata is relative to current directory if testdataDir == "" { testdataDir, err = filepath.Abs("./testdata") require.Nil(t, err) err = os.Chdir(testdataDir) require.Nil(t, err) } err = os.Setenv("DATABASE_URL", u.String()) require.Nil(t, err) app := NewApp() flagset := flag.NewFlagSet(app.Name, flag.ContinueOnError) for _, f := range app.Flags { f.Apply(flagset) } return cli.NewContext(app, flagset, nil) }
func TestDown(t *testing.T) { for dname := range mans { utils.ClearTestTables(dname) utils.ClearTestMigrations() utils.SetupTestingFolders(dname) utils.GenerateMigrationFiles([]utils.TestMigration{ utils.TestMigration{ Identifier: transporter.MigrationIdentifier(), UpCommand: "CREATE TABLE down_table (a varchar(255))", DownCommand: "DROP TABLE down_table", }, utils.TestMigration{ Identifier: transporter.MigrationIdentifier(), UpCommand: "ALTER TABLE down_table ADD COLUMN o varchar(255)", DownCommand: "ALTER TABLE down_table DROP COLUMN o", }, }) context := cli.NewContext(nil, &flag.FlagSet{}, nil) Up(context) Down(context) con, _ := utils.BuildTestingConnection(dname) defer con.Close() _, err := con.Query("SELECT a FROM down_table") assert.Nil(t, err) Down(context) _, err = con.Query("SELECT a FROM down_table") log.Println(err) assert.NotNil(t, err) } }
func TestProjectFactoryFileArgMayContainMultipleFiles(t *testing.T) { sep := string(os.PathListSeparator) fileCases := []struct { requested []string available []string expected []string }{ { requested: []string{}, available: []string{"docker-compose.yml"}, expected: []string{"docker-compose.yml"}, }, { requested: []string{}, available: []string{"docker-compose.yml", "docker-compose.override.yml"}, expected: []string{"docker-compose.yml", "docker-compose.override.yml"}, }, { requested: []string{"one.yml"}, available: []string{"one.yml"}, expected: []string{"one.yml"}, }, { requested: []string{"one.yml"}, available: []string{"docker-compose.yml", "one.yml"}, expected: []string{"one.yml"}, }, { requested: []string{"one.yml", "two.yml", "three.yml"}, available: []string{"one.yml", "two.yml", "three.yml"}, expected: []string{"one.yml", "two.yml", "three.yml"}, }, { requested: []string{"one.yml" + sep + "two.yml" + sep + "three.yml"}, available: []string{"one.yml", "two.yml", "three.yml"}, expected: []string{"one.yml", "two.yml", "three.yml"}, }, { requested: []string{"one.yml" + sep + "two.yml", "three.yml" + sep + "four.yml"}, available: []string{"one.yml", "two.yml", "three.yml", "four.yml"}, expected: []string{"one.yml", "two.yml", "three.yml", "four.yml"}, }, { requested: []string{"one.yml", "two.yml" + sep + "three.yml"}, available: []string{"one.yml", "two.yml", "three.yml"}, expected: []string{"one.yml", "two.yml", "three.yml"}, }, } for _, fileCase := range fileCases { tmpDir, err := ioutil.TempDir("", "project-factory-test") if err != nil { t.Fatal(err) } defer os.RemoveAll(tmpDir) if err = os.Chdir(tmpDir); err != nil { t.Fatal(err) } for _, file := range fileCase.available { ioutil.WriteFile(file, []byte(`hello: image: busybox`), 0700) } globalSet := flag.NewFlagSet("test", 0) // Set the project-name flag globalSet.String("project-name", "example", "doc") // Set the compose file flag fcr := cli.StringSlice(fileCase.requested) globalSet.Var(&fcr, "file", "doc") c := cli.NewContext(nil, globalSet, nil) factory := &ProjectFactory{} p, err := factory.Create(c) if err != nil { t.Fatal(err) } for i, v := range p.(*project.Project).Files { if v != fileCase.expected[i] { t.Fatalf("requested %s, available %s, expected %s, got %s", fileCase.requested, fileCase.available, fileCase.expected, p.(*project.Project).Files) } } } }
func main() { app := cli.NewApp() app.Name = "kənˈtrīv" app.Version = "19.99.0" app.Compiled = time.Now() app.Authors = []cli.Author{ cli.Author{ Name: "Example Human", Email: "*****@*****.**", }, } app.Copyright = "(c) 1999 Serious Enterprise" app.HelpName = "contrive" app.Usage = "demonstrate available API" app.UsageText = "contrive - demonstrating the available API" app.ArgsUsage = "[args and such]" app.Commands = []cli.Command{ cli.Command{ Name: "doo", Aliases: []string{"do"}, Category: "motion", Usage: "do the doo", UsageText: "doo - does the dooing", Description: "no really, there is a lot of dooing to be done", ArgsUsage: "[arrgh]", Flags: []cli.Flag{ cli.BoolFlag{Name: "forever, forevvarr"}, }, Subcommands: cli.Commands{ cli.Command{ Name: "wop", Action: wopAction, }, }, SkipFlagParsing: false, HideHelp: false, Hidden: false, HelpName: "doo!", BashComplete: func(c *cli.Context) { fmt.Fprintf(c.App.Writer, "--better\n") }, Before: func(c *cli.Context) error { fmt.Fprintf(c.App.Writer, "brace for impact\n") return nil }, After: func(c *cli.Context) error { fmt.Fprintf(c.App.Writer, "did we lose anyone?\n") return nil }, Action: func(c *cli.Context) error { c.Command.FullName() c.Command.HasName("wop") c.Command.Names() c.Command.VisibleFlags() fmt.Fprintf(c.App.Writer, "dodododododoodododddooooododododooo\n") if c.Bool("forever") { c.Command.Run(c) } return nil }, OnUsageError: func(c *cli.Context, err error, isSubcommand bool) error { fmt.Fprintf(c.App.Writer, "for shame\n") return err }, }, } app.Flags = []cli.Flag{ cli.BoolFlag{Name: "fancy"}, cli.BoolTFlag{Name: "fancier"}, cli.DurationFlag{Name: "howlong, H", Value: time.Second * 3}, cli.Float64Flag{Name: "howmuch"}, cli.GenericFlag{Name: "wat", Value: &genericType{}}, cli.Int64Flag{Name: "longdistance"}, cli.Int64SliceFlag{Name: "intervals"}, cli.IntFlag{Name: "distance"}, cli.IntSliceFlag{Name: "times"}, cli.StringFlag{Name: "dance-move, d"}, cli.StringSliceFlag{Name: "names, N"}, cli.UintFlag{Name: "age"}, cli.Uint64Flag{Name: "bigage"}, } app.EnableBashCompletion = true app.HideHelp = false app.HideVersion = false app.BashComplete = func(c *cli.Context) { fmt.Fprintf(c.App.Writer, "lipstick\nkiss\nme\nlipstick\nringo\n") } app.Before = func(c *cli.Context) error { fmt.Fprintf(c.App.Writer, "HEEEERE GOES\n") return nil } app.After = func(c *cli.Context) error { fmt.Fprintf(c.App.Writer, "Phew!\n") return nil } app.CommandNotFound = func(c *cli.Context, command string) { fmt.Fprintf(c.App.Writer, "Thar be no %q here.\n", command) } app.OnUsageError = func(c *cli.Context, err error, isSubcommand bool) error { if isSubcommand { return err } fmt.Fprintf(c.App.Writer, "WRONG: %#v\n", err) return nil } app.Action = func(c *cli.Context) error { cli.DefaultAppComplete(c) cli.HandleExitCoder(errors.New("not an exit coder, though")) cli.ShowAppHelp(c) cli.ShowCommandCompletions(c, "nope") cli.ShowCommandHelp(c, "also-nope") cli.ShowCompletions(c) cli.ShowSubcommandHelp(c) cli.ShowVersion(c) categories := c.App.Categories() categories.AddCommand("sounds", cli.Command{ Name: "bloop", }) for _, category := range c.App.Categories() { fmt.Fprintf(c.App.Writer, "%s\n", category.Name) fmt.Fprintf(c.App.Writer, "%#v\n", category.Commands) fmt.Fprintf(c.App.Writer, "%#v\n", category.VisibleCommands()) } fmt.Printf("%#v\n", c.App.Command("doo")) if c.Bool("infinite") { c.App.Run([]string{"app", "doo", "wop"}) } if c.Bool("forevar") { c.App.RunAsSubcommand(c) } c.App.Setup() fmt.Printf("%#v\n", c.App.VisibleCategories()) fmt.Printf("%#v\n", c.App.VisibleCommands()) fmt.Printf("%#v\n", c.App.VisibleFlags()) fmt.Printf("%#v\n", c.Args().First()) if len(c.Args()) > 0 { fmt.Printf("%#v\n", c.Args()[1]) } fmt.Printf("%#v\n", c.Args().Present()) fmt.Printf("%#v\n", c.Args().Tail()) set := flag.NewFlagSet("contrive", 0) nc := cli.NewContext(c.App, set, c) fmt.Printf("%#v\n", nc.Args()) fmt.Printf("%#v\n", nc.Bool("nope")) fmt.Printf("%#v\n", nc.BoolT("nerp")) fmt.Printf("%#v\n", nc.Duration("howlong")) fmt.Printf("%#v\n", nc.Float64("hay")) fmt.Printf("%#v\n", nc.Generic("bloop")) fmt.Printf("%#v\n", nc.Int64("bonk")) fmt.Printf("%#v\n", nc.Int64Slice("burnks")) fmt.Printf("%#v\n", nc.Int("bips")) fmt.Printf("%#v\n", nc.IntSlice("blups")) fmt.Printf("%#v\n", nc.String("snurt")) fmt.Printf("%#v\n", nc.StringSlice("snurkles")) fmt.Printf("%#v\n", nc.Uint("flub")) fmt.Printf("%#v\n", nc.Uint64("florb")) fmt.Printf("%#v\n", nc.GlobalBool("global-nope")) fmt.Printf("%#v\n", nc.GlobalBoolT("global-nerp")) fmt.Printf("%#v\n", nc.GlobalDuration("global-howlong")) fmt.Printf("%#v\n", nc.GlobalFloat64("global-hay")) fmt.Printf("%#v\n", nc.GlobalGeneric("global-bloop")) fmt.Printf("%#v\n", nc.GlobalInt("global-bips")) fmt.Printf("%#v\n", nc.GlobalIntSlice("global-blups")) fmt.Printf("%#v\n", nc.GlobalString("global-snurt")) fmt.Printf("%#v\n", nc.GlobalStringSlice("global-snurkles")) fmt.Printf("%#v\n", nc.FlagNames()) fmt.Printf("%#v\n", nc.GlobalFlagNames()) fmt.Printf("%#v\n", nc.GlobalIsSet("wat")) fmt.Printf("%#v\n", nc.GlobalSet("wat", "nope")) fmt.Printf("%#v\n", nc.NArg()) fmt.Printf("%#v\n", nc.NumFlags()) fmt.Printf("%#v\n", nc.Parent()) nc.Set("wat", "also-nope") ec := cli.NewExitError("ohwell", 86) fmt.Fprintf(c.App.Writer, "%d", ec.ExitCode()) fmt.Printf("made it!\n") return ec } if os.Getenv("HEXY") != "" { app.Writer = &hexWriter{} app.ErrWriter = &hexWriter{} } app.Metadata = map[string]interface{}{ "layers": "many", "explicable": false, "whatever-values": 19.99, } app.Run(os.Args) }
func DefaultContext() *cli.Context { app := cli.NewApp() set := flag.NewFlagSet("test", flag.ContinueOnError) context := cli.NewContext(app, set, nil) return context }