diff --git a/snok.go b/snok.go index adc14fdbc1c59faee9c62477b79da1e3e15104bd..ccd27b90ac1c649b3fbda8602e67723432216efa 100644 --- a/snok.go +++ b/snok.go @@ -34,19 +34,21 @@ type container struct { } type CommandTest struct { - t *testing.T - RootCmd *cobra.Command - Debug bool - Trace bool - containers map[string]container + t *testing.T + RootCmd *cobra.Command + Debug bool + Trace bool + containers map[string]container + handleUnexpectedError func(require.TestingT, error, ...interface{}) } func NewCommandTest(cmd *cobra.Command) *CommandTest { ct := &CommandTest{ - RootCmd: cmd, - Debug: false, - Trace: false, - containers: make(map[string]container), + RootCmd: cmd, + Debug: false, + Trace: false, + containers: make(map[string]container), + handleUnexpectedError: require.NoError, } fmt.Println("parse flags") flag.BoolVar(&ct.Debug, "debug", false, "debug") @@ -102,7 +104,7 @@ func (ct *CommandTest) testCmd(t *testing.T, cmd *cobra.Command, args []string) if test.ExpectError { require.Error(t, err, "Expected error") } else if err != nil { - require.NoError(t, err, "Unexpected error") + ct.handleUnexpectedError(t, err, "Unexpected error") } else if test.Output != nil { output = strings.TrimRightFunc(output, unicode.IsSpace) r, err := regexp.Compile(*test.Output) @@ -114,6 +116,7 @@ func (ct *CommandTest) testCmd(t *testing.T, cmd *cobra.Command, args []string) }) } if cmd.HasSubCommands() { + // Todo: Use a DAG to determine the order of the tests slices.SortFunc(cmd.Commands(), func(a, b *cobra.Command) int { return getOrder(a) - getOrder(b) }) diff --git a/snok_test.go b/snok_test.go index 52cb562786e5b8a2b5fcc50d01e5844f707ce161..02050a55276d74a2be4430ab109dd62a4f8c643a 100644 --- a/snok_test.go +++ b/snok_test.go @@ -10,15 +10,23 @@ import ( "unicode" "github.com/spf13/cobra" + "github.com/stretchr/testify/require" "github.com/testcontainers/testcontainers-go" ) var ct *CommandTest +func mockUnexpectedError(t require.TestingT, err error, msgAndArgs ...interface{}) { + if err.Error() != "expect the unexpected" { + require.NoError(t, err, msgAndArgs...) + } +} + func TestMain(m *testing.M) { rootCmd.AddCommand(envCmd, echoCmd, errorCmd) echoCmd.Flags().BoolP("reverse", "r", false, "reverse the output") ct = NewCommandTest(rootCmd) + ct.handleUnexpectedError = mockUnexpectedError ct.AddContainer("Test", mockContainer) os.Exit(m.Run()) } @@ -128,6 +136,11 @@ var errorCmd = &cobra.Command{ "name": "Expected Error", "args": ["hello","world"], "expectError": true + }, + { + "name": "Unexpected Error", + "args": ["expect","the","unexpected"], + "expectError": false } ]`, },