From 7121ea07f91f6435e245111b7f48ee1b0f5106ff Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Erik=20Hedenstr=C3=B6m?= <erik@hedenstroem.com> Date: Sat, 18 May 2024 17:00:07 +0000 Subject: [PATCH] Full coverage --- snok.go | 23 +++++++++++++---------- snok_test.go | 13 +++++++++++++ 2 files changed, 26 insertions(+), 10 deletions(-) diff --git a/snok.go b/snok.go index adc14fd..ccd27b9 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 52cb562..02050a5 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 } ]`, }, -- GitLab