From c57677da45ee91007c6250e7f6f42bb3d4b4b90f Mon Sep 17 00:00:00 2001 From: jmontesi Date: Tue, 16 Jul 2024 15:42:48 +0200 Subject: [PATCH] cmd/certsuite: refactor main to allow unit testing subcommands Also adds a unit test for the "certsuite version" command. --- cmd/certsuite/info/info.go | 1 - cmd/certsuite/main.go | 11 +++++++---- cmd/certsuite/main_test.go | 36 ++++++++++++++++++++++++++++++++++++ 3 files changed, 43 insertions(+), 5 deletions(-) diff --git a/cmd/certsuite/info/info.go b/cmd/certsuite/info/info.go index 97f520d12..51aefa56a 100644 --- a/cmd/certsuite/info/info.go +++ b/cmd/certsuite/info/info.go @@ -40,7 +40,6 @@ func showInfo(cmd *cobra.Command, _ []string) error { //nolint:funlen lineMaxWidth := 120 if term.IsTerminal(0) { width, _, err := term.GetSize(0) - fmt.Println("Term Width: ", width) if err != nil { return fmt.Errorf("could not get terminal size, err: %v", err) } diff --git a/cmd/certsuite/main.go b/cmd/certsuite/main.go index 91bee49a6..040863b9b 100644 --- a/cmd/certsuite/main.go +++ b/cmd/certsuite/main.go @@ -14,14 +14,12 @@ import ( "github.com/test-network-function/cnf-certification-test/cmd/certsuite/version" ) -var ( - rootCmd = &cobra.Command{ +func newRootCmd() *cobra.Command { + rootCmd := cobra.Command{ Use: "certsuite", Short: "A CLI tool for the Red Hat Best Practices Test Suite for Kubernetes.", } -) -func main() { rootCmd.AddCommand(claim.NewCommand()) rootCmd.AddCommand(generate.NewCommand()) rootCmd.AddCommand(check.NewCommand()) @@ -29,6 +27,11 @@ func main() { rootCmd.AddCommand(info.NewCommand()) rootCmd.AddCommand(version.NewCommand()) + return &rootCmd +} + +func main() { + rootCmd := newRootCmd() if err := rootCmd.Execute(); err != nil { log.Error("%v", err) os.Exit(1) diff --git a/cmd/certsuite/main_test.go b/cmd/certsuite/main_test.go index 06ab7d0f9..f651c86d7 100644 --- a/cmd/certsuite/main_test.go +++ b/cmd/certsuite/main_test.go @@ -1 +1,37 @@ package main + +import ( + "io" + "os" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/test-network-function/cnf-certification-test/pkg/versions" +) + +func TestCertsuiteVersionCmd(t *testing.T) { + // Prepare context + versions.GitCommit = "aaabbbccc" + versions.GitRelease = "v0.0.0" + versions.ClaimFormatVersion = "v0.0.0" + + // Run the command + savedStdout := os.Stdout + r, w, _ := os.Pipe() + os.Stdout = w + + cmd := newRootCmd() + cmd.SetArgs([]string{ + "version", + }) + err := cmd.Execute() + assert.Nil(t, err) + + w.Close() + out, _ := io.ReadAll(r) + os.Stdout = savedStdout + + // Check the result + const expectedOut = "Certsuite version: v0.0.0 (aaabbbccc)\nClaim file version: v0.0.0\n" + assert.Equal(t, expectedOut, string(out)) +}