github.com/ouraigua/jenkins-library@v0.0.0-20231028010029-fbeaf2f3aa9b/pkg/piperutils/templateUtils_test.go (about)

     1  //go:build unit
     2  // +build unit
     3  
     4  package piperutils
     5  
     6  import (
     7  	"github.com/stretchr/testify/assert"
     8  	"testing"
     9  	"text/template"
    10  )
    11  
    12  type SomeDescriptor struct {
    13  	GroupID    string
    14  	ArtifactID string
    15  	Version    string
    16  }
    17  
    18  func TestExecuteTemplate(t *testing.T) {
    19  	t.Run("test success", func(t *testing.T) {
    20  		context := SomeDescriptor{GroupID: "com.sap.cp.jenkins", ArtifactID: "piper", Version: "1.2.3"}
    21  		result, err := ExecuteTemplate("{{ .GroupID }}-{{ .ArtifactID }}:{{ .Version}}", context)
    22  		assert.NoError(t, err, "Didn't expect error but got one")
    23  		assert.Equal(t, "com.sap.cp.jenkins-piper:1.2.3", result, "Expected different result")
    24  	})
    25  
    26  	t.Run("test template error", func(t *testing.T) {
    27  		context := SomeDescriptor{GroupID: "com.sap.cp.jenkins", ArtifactID: "piper", Version: "1.2.3"}
    28  		_, err := ExecuteTemplate("{{ $+++.+++GroupID }}-{{ .ArtifactID }}:{{ .Version}}", context)
    29  		assert.Error(t, err, "Expected error but got none")
    30  	})
    31  
    32  	t.Run("test functions", func(t *testing.T) {
    33  		functions := template.FuncMap{
    34  			"testFunc": reverse,
    35  		}
    36  		context := SomeDescriptor{GroupID: "com.sap.cp.jenkins", ArtifactID: "piper", Version: "1.2.3"}
    37  		result, err := ExecuteTemplateFunctions("{{ testFunc .GroupID }}-{{ .ArtifactID }}:{{ .Version}}", functions, context)
    38  		assert.NoError(t, err, "Didn't expect error but got one")
    39  		assert.Equal(t, "sniknej.pc.pas.moc-piper:1.2.3", result, "Expected different result")
    40  	})
    41  }
    42  
    43  func reverse(s string) string {
    44  	runes := []rune(s)
    45  	for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
    46  		runes[i], runes[j] = runes[j], runes[i]
    47  	}
    48  	return string(runes)
    49  }