Skip to content

Commit 1b5392e

Browse files
authored
Merge pull request #71 from kcp-dev/template-defaults
add basic unit tests for templating
2 parents 9725f26 + a69c7c8 commit 1b5392e

File tree

1 file changed

+86
-0
lines changed

1 file changed

+86
-0
lines changed
Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
/*
2+
Copyright 2025 The KCP Authors.
3+
4+
Licensed under the Apache License, Version 2.0 (the "License");
5+
you may not use this file except in compliance with the License.
6+
You may obtain a copy of the License at
7+
8+
http://www.apache.org/licenses/LICENSE-2.0
9+
10+
Unless required by applicable law or agreed to in writing, software
11+
distributed under the License is distributed on an "AS IS" BASIS,
12+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
See the License for the specific language governing permissions and
14+
limitations under the License.
15+
*/
16+
17+
package templating
18+
19+
import (
20+
"testing"
21+
22+
"github.com/kcp-dev/logicalcluster/v3"
23+
24+
"github.com/kcp-dev/api-syncagent/test/crds"
25+
"github.com/kcp-dev/api-syncagent/test/utils"
26+
27+
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
28+
)
29+
30+
func TestRender(t *testing.T) {
31+
clusterName := logicalcluster.Name("12386rtr4u")
32+
clusterPath := logicalcluster.NewPath("root:yadda:yadda")
33+
34+
crontab := &crds.Crontab{
35+
ObjectMeta: metav1.ObjectMeta{
36+
Name: "my-crontab",
37+
Namespace: "default",
38+
},
39+
Spec: crds.CrontabSpec{
40+
Image: "ubuntu:latest",
41+
},
42+
}
43+
44+
object := utils.ToUnstructured(t, crontab)
45+
object.SetAPIVersion("kcp.example.com/v1")
46+
object.SetKind("CronTab")
47+
48+
testcases := []struct {
49+
name string
50+
template string
51+
data any
52+
expected string
53+
}{
54+
{
55+
name: "simple object access",
56+
data: newLocalObjectNamingContext(object, clusterName, clusterPath),
57+
template: `{{ .Object.spec.image }}`,
58+
expected: crontab.Spec.Image,
59+
},
60+
{
61+
name: "default empty fields",
62+
data: newLocalObjectNamingContext(object, clusterName, clusterPath),
63+
template: `{{ .Object.spec.spec | default "test" }}`,
64+
expected: "test",
65+
},
66+
{
67+
name: "default non-existing field",
68+
data: newLocalObjectNamingContext(object, clusterName, clusterPath),
69+
template: `{{ .Object.does.not.exist | default "test" }}`,
70+
expected: "test",
71+
},
72+
}
73+
74+
for _, testcase := range testcases {
75+
t.Run(testcase.name, func(t *testing.T) {
76+
rendered, err := Render(testcase.template, testcase.data)
77+
if err != nil {
78+
t.Fatalf("Unexpected error: %v.", err)
79+
}
80+
81+
if rendered != testcase.expected {
82+
t.Errorf("Expected %q, but got %q.", testcase.expected, rendered)
83+
}
84+
})
85+
}
86+
}

0 commit comments

Comments
 (0)