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