diff --git a/cmd/builder/internal/version.go b/cmd/builder/internal/version.go index 8424e08a493..b9fc4f9658a 100644 --- a/cmd/builder/internal/version.go +++ b/cmd/builder/internal/version.go @@ -14,14 +14,16 @@ var ( version = "" ) +type debugReadBuildInfoFunc func() (info *debug.BuildInfo, ok bool) + // binVersion returns the version of the binary. // If the version is not set, it attempts to read the build information. // Returns an error if the build information cannot be read. -func binVersion() (string, error) { +func binVersion(fn debugReadBuildInfoFunc) (string, error) { if version != "" { return version, nil } - info, ok := debug.ReadBuildInfo() + info, ok := fn() if !ok { return "", fmt.Errorf("failed to read build info") } @@ -34,7 +36,7 @@ func versionCommand() *cobra.Command { Short: "Version of ocb", Long: "Prints the version of the ocb binary", RunE: func(cmd *cobra.Command, _ []string) error { - version, err := binVersion() + version, err := binVersion(debug.ReadBuildInfo) if err != nil { return err } diff --git a/cmd/builder/internal/version_test.go b/cmd/builder/internal/version_test.go new file mode 100644 index 00000000000..9dd66ce6d5b --- /dev/null +++ b/cmd/builder/internal/version_test.go @@ -0,0 +1,55 @@ +// Copyright The OpenTelemetry Authors +// SPDX-License-Identifier: Apache-2.0 + +package internal + +import ( + "fmt" + "runtime/debug" + "testing" +) + +// Mock debug.ReadBuildInfo function +var readBuildInfo = debug.ReadBuildInfo + +func TestBinVersion(t *testing.T) { + // Test case: version is set + version = "v1.0.0" + v, err := binVersion(debug.ReadBuildInfo) + if err != nil { + t.Fatalf("expected no error, got %v", err) + } + if v != "v1.0.0" { + t.Fatalf("expected version 'v1.0.0', got %v", v) + } + + // // Test case: version is not set, ReadBuildInfo returns valid info + version = "" + readBuildInfo = func() (*debug.BuildInfo, bool) { + return &debug.BuildInfo{ + Main: debug.Module{ + Version: "v2.0.0", + }, + }, true + } + v, err = binVersion(readBuildInfo) + fmt.Printf("v: %v, err: %v", v, err) + if err != nil { + t.Fatalf("expected no error, got %v", err) + } + if v != "v2.0.0" { + t.Fatalf("expected version 'v2.0.0', got %v", v) + } + + // Test case: version is not set, ReadBuildInfo fails + readBuildInfo = func() (*debug.BuildInfo, bool) { + return nil, false + } + v, err = binVersion(readBuildInfo) + if err == nil { + t.Fatalf("expected error, got nil") + } + if v != "" { + t.Fatalf("expected empty version, got %v", v) + } +}