diff --git a/cmd/version/version.go b/cmd/version/version.go index 13472ea..017f2c9 100644 --- a/cmd/version/version.go +++ b/cmd/version/version.go @@ -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 { @@ -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") } @@ -51,6 +53,7 @@ func (c command) Run(context.Context) error { // Setup the command func (c command) Setup() error { + c.getVersionCmd = debug.ReadBuildInfo return nil } diff --git a/cmd/version/version_test.go b/cmd/version/version_test.go new file mode 100644 index 0000000..7c8d121 --- /dev/null +++ b/cmd/version/version_test.go @@ -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) + } + }) +} diff --git a/internal/version.go b/internal/version.go deleted file mode 100644 index 5bf0569..0000000 --- a/internal/version.go +++ /dev/null @@ -1 +0,0 @@ -package internal