diff --git a/snok.go b/snok.go index 09c419ea66aebc3a3c42a53aea36541b971f43af..adc14fdbc1c59faee9c62477b79da1e3e15104bd 100644 --- a/snok.go +++ b/snok.go @@ -63,6 +63,7 @@ func (ct *CommandTest) Accept(log testcontainers.Log) { ct.t.Helper() ct.t.Logf("%s", log.Content) } + func (ct *CommandTest) Run(t *testing.T) { ct.t = t ct.testCmd(t, ct.RootCmd, []string{}) diff --git a/snok_test.go b/snok_test.go index 63faf25842a6e43b0faa4e2deae2ee1831887cc9..dbafcbd0634b891ac1411486f13758ff06892e24 100644 --- a/snok_test.go +++ b/snok_test.go @@ -1,15 +1,22 @@ package snok import ( + "fmt" + "io" "os" + "strings" "testing" + "unicode" "github.com/spf13/cobra" + "github.com/testcontainers/testcontainers-go" ) var ct *CommandTest func TestMain(m *testing.M) { + rootCmd.AddCommand(echoCmd, errorCmd) + echoCmd.Flags().BoolP("reverse", "r", false, "reverse the output") ct = NewCommandTest(rootCmd) ct.AddContainer("Test", mockContainer) os.Exit(m.Run()) @@ -21,6 +28,11 @@ func TestCmds(t *testing.T) { func mockContainer(ct *CommandTest, t *testing.T) (err error) { if os.Getenv("TEST_MESSAGE") == "" { + log := testcontainers.Log{ + LogType: "test", + Content: []byte("testing"), + } + ct.Accept(log) t.Setenv("TEST_MESSAGE", "testing") } return @@ -29,12 +41,10 @@ func mockContainer(ct *CommandTest, t *testing.T) (err error) { var rootCmd = &cobra.Command{ Version: "1.0.0", Use: "test", - Short: "Root Short", - Long: `Root Long`, DisableAutoGenTag: true, SilenceUsage: true, Annotations: map[string]string{ - "containers": "Vault", + "containers": "Test", "tests": `[ { "name": "Version", @@ -43,6 +53,62 @@ var rootCmd = &cobra.Command{ } ]`, }, - PersistentPreRun: func(cmd *cobra.Command, args []string) { +} + +var echoCmd = &cobra.Command{ + Use: "echo", + Args: cobra.MinimumNArgs(1), + Annotations: map[string]string{ + "order": "1", + "tests": `[ + { + "name": "Echo", + "args": ["hello","world"], + "output": "^hello world$" + }, + { + "name": "Echo Reverse", + "args": ["-r","hello","world"], + "output": "^dlrow olleh$" + }, + { + "name": "Echo Input", + "args": ["-r","The","rain"], + "input": "in Spain falls mainly on the plain", + "output": "^nialp eht no ylniam sllaf niapS ni niar ehT$" + } + ]`, + }, + RunE: func(cmd *cobra.Command, args []string) (err error) { + b, err := io.ReadAll(cmd.InOrStdin()) + str := fmt.Sprintf("%s %s", strings.Join(args, " "), b) + str = strings.TrimRightFunc(str, unicode.IsSpace) + if cmd.Flags().Changed("reverse") { + rstr := "" + for _, v := range str { + rstr = string(v) + rstr + } + str = rstr + } + fmt.Print(str) + return + }, +} + +var errorCmd = &cobra.Command{ + Use: "error", + Args: cobra.MinimumNArgs(1), + Annotations: map[string]string{ + "order": "2", + "tests": `[ + { + "name": "Expected Error", + "args": ["hello","world"], + "expectError": true + } + ]`, + }, + RunE: func(cmd *cobra.Command, args []string) (err error) { + return fmt.Errorf("%s", strings.Join(args, " ")) }, }