Skip to content

Commit

Permalink
add unit tests for version.go
Browse files Browse the repository at this point in the history
  • Loading branch information
jackgopack4 committed Sep 18, 2024
1 parent 536fc13 commit 53bb6e9
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 3 deletions.
8 changes: 5 additions & 3 deletions cmd/builder/internal/version.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
}
Expand All @@ -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
}
Expand Down
55 changes: 55 additions & 0 deletions cmd/builder/internal/version_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
}

0 comments on commit 53bb6e9

Please sign in to comment.