github.com/SAP/jenkins-library@v1.362.0/cmd/version_test.go (about)

     1  //go:build unit
     2  // +build unit
     3  
     4  package cmd
     5  
     6  import (
     7  	"bytes"
     8  	"github.com/stretchr/testify/assert"
     9  	"io"
    10  	"os"
    11  	"testing"
    12  )
    13  
    14  func TestVersion(t *testing.T) {
    15  
    16  	t.Run("versionAndTagInitialValues", func(t *testing.T) {
    17  
    18  		result := runVersionCommand(t, "", "")
    19  		assert.Contains(t, result, "commit: \"<n/a>\"")
    20  		assert.Contains(t, result, "tag: \"<n/a>\"")
    21  	})
    22  
    23  	t.Run("versionAndTagSet", func(t *testing.T) {
    24  
    25  		result := runVersionCommand(t, "16bafe", "v1.2.3")
    26  		assert.Contains(t, result, "commit: \"16bafe\"")
    27  		assert.Contains(t, result, "tag: \"v1.2.3\"")
    28  	})
    29  }
    30  
    31  func runVersionCommand(t *testing.T, commitID, tag string) string {
    32  
    33  	orig := os.Stdout
    34  	defer func() { os.Stdout = orig }()
    35  
    36  	r, w, e := os.Pipe()
    37  	if e != nil {
    38  		t.Error("Cannot setup pipes.")
    39  	}
    40  
    41  	os.Stdout = w
    42  
    43  	//
    44  	// needs to be set in the free wild by the build process:
    45  	// go build -ldflags "-X github.com/SAP/jenkins-library/cmd.GitCommit=${GIT_COMMIT} -X github.com/SAP/jenkins-library/cmd.GitTag=${GIT_TAG}"
    46  	if len(commitID) > 0 {
    47  		GitCommit = commitID
    48  	}
    49  	if len(tag) > 0 {
    50  		GitTag = tag
    51  	}
    52  	defer func() { GitCommit = ""; GitTag = "" }()
    53  	//
    54  	//
    55  
    56  	version()
    57  
    58  	w.Close()
    59  
    60  	var buf bytes.Buffer
    61  	_, _ = io.Copy(&buf, r)
    62  	return buf.String()
    63  }