Skip to content

Commit

Permalink
Added tests for version command
Browse files Browse the repository at this point in the history
  • Loading branch information
baalimago committed Aug 18, 2024
1 parent 25749cc commit 70042f4
Show file tree
Hide file tree
Showing 3 changed files with 66 additions and 3 deletions.
7 changes: 5 additions & 2 deletions cmd/version/version.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,9 @@ var (
BUILD_CHECKSUM = ""
)

type command struct{}
type command struct {
getVersionCmd func() (*debug.BuildInfo, bool)
}

// Describe the version command
func (c command) Describe() string {
Expand All @@ -33,7 +35,7 @@ func (c command) Help() string {

// Run the command, printing the version using either the debugbuild or tagged version
func (c command) Run(context.Context) error {
bi, ok := debug.ReadBuildInfo()
bi, ok := c.getVersionCmd()
if !ok {
return errors.New("failed to read build info")
}
Expand All @@ -51,6 +53,7 @@ func (c command) Run(context.Context) error {

// Setup the command
func (c command) Setup() error {
c.getVersionCmd = debug.ReadBuildInfo

Check failure on line 56 in cmd/version/version.go

View workflow job for this annotation

GitHub Actions / call-workflow / validate

ineffective assignment to field command.getVersionCmd (SA4005)
return nil
}

Expand Down
61 changes: 61 additions & 0 deletions cmd/version/version_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
package version

import (
"context"
"runtime/debug"
"testing"

"github.com/baalimago/go_away_boilerplate/pkg/testboil"
)

func TestCommand(t *testing.T) {
cmd := Command()

if cmd == nil {
t.Fatal("Expected command to be non-nil")
}

if cmd.Describe() != "print the version of wd-40" {
t.Fatalf("Unexpected describe: %v", cmd.Describe())
}

fs := cmd.Flagset()
if fs == nil {
t.Fatal("Expected flagset to be non-nil")
}

help := cmd.Help()
if help != "Print the version of wd-40" {
t.Fatalf("Unexpected help output: %v", help)
}
}

func TestRun(t *testing.T) {
cmd := Command()
ctx := context.Background()

t.Run("it should print version info correctly", func(t *testing.T) {
cmd.getVersionCmd = func() (*debug.BuildInfo, bool) {
return &debug.BuildInfo{
Main: debug.Module{
Version: "v1.2.3",
Sum: "h1:checksum",
},
GoVersion: "go1.18",
}, true
}

// Capture output
got := testboil.CaptureStdout(t, func(t *testing.T) {
err := cmd.Run(ctx)
if err != nil {
t.Fatalf("Run failed: %v", err)
}
})

expected := "version: v1.2.3, go version: go1.18, checksum: h1:checksum\n"
if got != expected {
t.Fatalf("Expected output %s, got %s", expected, got)
}
})
}
1 change: 0 additions & 1 deletion internal/version.go

This file was deleted.

0 comments on commit 70042f4

Please sign in to comment.