github.com/jaylevin/jenkins-library@v1.230.4/cmd/version_test.go (about)

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