2023-05-03 18:02:11 +02:00
|
|
|
//go:build unit
|
|
|
|
// +build unit
|
|
|
|
|
2019-10-31 14:57:29 +02:00
|
|
|
package cmd
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"github.com/stretchr/testify/assert"
|
2019-11-05 22:51:44 +02:00
|
|
|
"io"
|
|
|
|
"os"
|
|
|
|
"testing"
|
2019-10-31 14:57:29 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
func TestVersion(t *testing.T) {
|
|
|
|
|
|
|
|
t.Run("versionAndTagInitialValues", func(t *testing.T) {
|
|
|
|
|
|
|
|
result := runVersionCommand(t, "", "")
|
|
|
|
assert.Contains(t, result, "commit: \"<n/a>\"")
|
|
|
|
assert.Contains(t, result, "tag: \"<n/a>\"")
|
|
|
|
})
|
|
|
|
|
|
|
|
t.Run("versionAndTagSet", func(t *testing.T) {
|
|
|
|
|
|
|
|
result := runVersionCommand(t, "16bafe", "v1.2.3")
|
|
|
|
assert.Contains(t, result, "commit: \"16bafe\"")
|
|
|
|
assert.Contains(t, result, "tag: \"v1.2.3\"")
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
func runVersionCommand(t *testing.T, commitID, tag string) string {
|
|
|
|
|
|
|
|
orig := os.Stdout
|
2019-11-05 22:51:44 +02:00
|
|
|
defer func() { os.Stdout = orig }()
|
2019-10-31 14:57:29 +02:00
|
|
|
|
2019-11-05 22:51:44 +02:00
|
|
|
r, w, e := os.Pipe()
|
2019-10-31 14:57:29 +02:00
|
|
|
if e != nil {
|
|
|
|
t.Error("Cannot setup pipes.")
|
|
|
|
}
|
|
|
|
|
|
|
|
os.Stdout = w
|
|
|
|
|
|
|
|
//
|
|
|
|
// needs to be set in the free wild by the build process:
|
|
|
|
// go build -ldflags "-X github.com/SAP/jenkins-library/cmd.GitCommit=${GIT_COMMIT} -X github.com/SAP/jenkins-library/cmd.GitTag=${GIT_TAG}"
|
2019-11-05 22:51:44 +02:00
|
|
|
if len(commitID) > 0 {
|
|
|
|
GitCommit = commitID
|
|
|
|
}
|
|
|
|
if len(tag) > 0 {
|
|
|
|
GitTag = tag
|
|
|
|
}
|
2019-10-31 14:57:29 +02:00
|
|
|
defer func() { GitCommit = ""; GitTag = "" }()
|
|
|
|
//
|
|
|
|
//
|
|
|
|
|
2020-06-19 14:39:19 +02:00
|
|
|
version()
|
2019-10-31 14:57:29 +02:00
|
|
|
|
|
|
|
w.Close()
|
|
|
|
|
|
|
|
var buf bytes.Buffer
|
2022-07-21 09:04:21 +02:00
|
|
|
_, _ = io.Copy(&buf, r)
|
2019-10-31 14:57:29 +02:00
|
|
|
return buf.String()
|
2019-11-05 22:51:44 +02:00
|
|
|
}
|