github.com/wawandco/oxplugins@v0.7.11/tools/cli/help/command_test.go (about) 1 package help 2 3 import ( 4 "context" 5 "fmt" 6 "strings" 7 "testing" 8 9 "github.com/wawandco/oxplugins/plugins" 10 ) 11 12 func TestFindCommand(t *testing.T) { 13 hp := Command{ 14 commands: []plugins.Command{}, 15 } 16 17 migrate := &subPl{} 18 pop := &testPlugin{} 19 pop.Receive([]plugins.Plugin{ 20 migrate, 21 }) 22 23 hp.commands = append(hp.commands, pop) 24 25 t.Run("not enough arguments", func(*testing.T) { 26 result, names := hp.findCommand([]string{"help"}) 27 if result != nil || names != nil { 28 t.Fatal("Should be nil") 29 } 30 }) 31 32 t.Run("top level command", func(*testing.T) { 33 result, names := hp.findCommand([]string{"help", "pop"}) 34 expected := []string{ 35 "pop", 36 } 37 if result.Name() != "pop" || strings.Join(names, " ") != strings.Join(expected, " ") { 38 t.Fatal("didn't find our guy") 39 } 40 }) 41 42 t.Run("subcommand lookup", func(*testing.T) { 43 result, names := hp.findCommand([]string{"help", "pop", "migrate"}) 44 expected := []string{ 45 "pop", 46 "migrate", 47 } 48 49 ht, ok := result.(plugins.HelpTexter) 50 fmt.Println(ok, result.Name()) 51 if result.Name() != "migrate" || !ok || ht.HelpText() != migrate.HelpText() || strings.Join(names, " ") != strings.Join(expected, " ") { 52 t.Fatal("didn't find our guy") 53 } 54 }) 55 56 t.Run("extra args on non-subcommander", func(*testing.T) { 57 result, names := hp.findCommand([]string{"help", "pop", "migrate", "other", "thing"}) 58 expected := []string{ 59 "pop", 60 "migrate", 61 } 62 ht, ok := result.(plugins.HelpTexter) 63 if result.Name() != "migrate" || !ok || ht.HelpText() != migrate.HelpText() || strings.Join(names, " ") != strings.Join(expected, " ") { 64 t.Fatal("didn't find our guy") 65 } 66 }) 67 68 } 69 70 type testPlugin struct { 71 subcommands []plugins.Command 72 } 73 74 func (tp testPlugin) Name() string { 75 return "pop" 76 } 77 78 func (tp testPlugin) ParentName() string { 79 return "" 80 } 81 82 func (tp testPlugin) HelpText() string { 83 return "pop help text" 84 } 85 86 func (tp *testPlugin) Run(ctx context.Context, root string, args []string) error { 87 return nil 88 } 89 90 func (tp *testPlugin) Receive(pls []plugins.Plugin) { 91 for _, pl := range pls { 92 c, ok := pl.(plugins.Command) 93 if !ok || c.ParentName() != tp.Name() { 94 continue 95 } 96 97 tp.subcommands = append(tp.subcommands, c) 98 } 99 100 fmt.Println(tp.subcommands) 101 } 102 103 func (tp *testPlugin) Subcommands() []plugins.Command { 104 return tp.subcommands 105 } 106 107 type subPl struct{} 108 109 func (tp subPl) Name() string { 110 return "migrate" 111 } 112 113 func (tp subPl) ParentName() string { 114 return "pop" 115 } 116 117 func (tp subPl) HelpText() string { 118 return "migrate help text" 119 } 120 121 func (tp subPl) Run(ctx context.Context, root string, args []string) error { 122 return nil 123 }