Skip to content

Commit 33d1c39

Browse files
committed
test: add test cases for nested variable expansion (maintainer's example)
1 parent b26eec1 commit 33d1c39

1 file changed

Lines changed: 49 additions & 3 deletions

File tree

template/template_test.go

Lines changed: 49 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -266,9 +266,20 @@ func TestInterpolationExternalInterference(t *testing.T) {
266266
}
267267

268268
func TestDefaultsWithNestedExpansion(t *testing.T) {
269+
// Additional test cases with specific variable mapping
270+
additionalDefaults := map[string]string{
271+
"BBBB": "second",
272+
"ZZZZ": "default",
273+
}
274+
additionalMapping := func(name string) (string, bool) {
275+
val, ok := additionalDefaults[name]
276+
return val, ok
277+
}
278+
269279
testCases := []struct {
270-
template string
271-
expected string
280+
template string
281+
expected string
282+
mapping func(string) (string, bool)
272283
}{
273284
{
274285
template: "ok ${UNSET_VAR-$FOO}",
@@ -302,10 +313,45 @@ func TestDefaultsWithNestedExpansion(t *testing.T) {
302313
template: "ok ${BAR+$FOO ${FOO:+second}}",
303314
expected: "ok first second",
304315
},
316+
// Maintainer's example: ${AAAA:-${BBBB:-${ZZZZ}}}
317+
// AAAA is unset, BBBB=second, ZZZZ=default
318+
// Should fall back to BBBB which equals "second"
319+
{
320+
template: "ok ${AAAA:-${BBBB:-${ZZZZ}}}",
321+
expected: "ok second",
322+
mapping: additionalMapping,
323+
},
324+
// Same as above but with only ZZZZ set
325+
{
326+
template: "ok ${AAAA:-${BBBB:-${ZZZZ}}}",
327+
expected: "ok default",
328+
mapping: func(name string) (string, bool) {
329+
if name == "ZZZZ" {
330+
return "default", true
331+
}
332+
return "", false
333+
},
334+
},
335+
// Triple nested: AAAA depends on BBBB depends on ZZZZ
336+
// Only ZZZZ is set, so should use ZZZZ's value
337+
{
338+
template: "${BBBB:-${ZZZZ}}",
339+
expected: "default",
340+
mapping: func(name string) (string, bool) {
341+
if name == "ZZZZ" {
342+
return "default", true
343+
}
344+
return "", false
345+
},
346+
},
305347
}
306348

307349
for _, tc := range testCases {
308-
result, err := Substitute(tc.template, defaultMapping)
350+
mapping := defaultMapping
351+
if tc.mapping != nil {
352+
mapping = tc.mapping
353+
}
354+
result, err := Substitute(tc.template, mapping)
309355
assert.NilError(t, err)
310356
assert.Check(t, is.Equal(tc.expected, result))
311357
}

0 commit comments

Comments
 (0)