| 1396 | } |
| 1397 | |
| 1398 | func TestRenderCustomTemplateFuncs(t *testing.T) { |
| 1399 | modTime := time.Now() |
| 1400 | |
| 1401 | // Create a chart with two templates that use custom functions |
| 1402 | c := &chart.Chart{ |
| 1403 | Metadata: &chart.Metadata{Name: "CustomFunc"}, |
| 1404 | Templates: []*common.File{ |
| 1405 | { |
| 1406 | Name: "templates/manifest", |
| 1407 | ModTime: modTime, |
| 1408 | Data: []byte(`{{exclaim .Values.message}}`), |
| 1409 | }, |
| 1410 | { |
| 1411 | Name: "templates/override", |
| 1412 | ModTime: modTime, |
| 1413 | Data: []byte(`{{ upper .Values.message }}`), |
| 1414 | }, |
| 1415 | }, |
| 1416 | } |
| 1417 | v := common.Values{ |
| 1418 | "Values": common.Values{ |
| 1419 | "message": "hello", |
| 1420 | }, |
| 1421 | "Chart": c.Metadata, |
| 1422 | "Release": common.Values{ |
| 1423 | "Name": "TestRelease", |
| 1424 | }, |
| 1425 | } |
| 1426 | |
| 1427 | // Define a custom template function "exclaim" that appends "!!!" to a string and override "upper" function |
| 1428 | customFuncs := template.FuncMap{ |
| 1429 | "exclaim": func(input string) string { |
| 1430 | return input + "!!!" |
| 1431 | }, |
| 1432 | "upper": func(s string) string { |
| 1433 | return "custom:" + s |
| 1434 | }, |
| 1435 | } |
| 1436 | |
| 1437 | // Create an engine instance and set the CustomTemplateFuncs. |
| 1438 | e := new(Engine) |
| 1439 | e.CustomTemplateFuncs = customFuncs |
| 1440 | |
| 1441 | // Render the chart. |
| 1442 | out, err := e.Render(c, v) |
| 1443 | if err != nil { |
| 1444 | t.Fatal(err) |
| 1445 | } |
| 1446 | |
| 1447 | // Expected output should be "hello!!!". |
| 1448 | expected := "hello!!!" |
| 1449 | key := "CustomFunc/templates/manifest" |
| 1450 | if rendered, ok := out[key]; !ok || rendered != expected { |
| 1451 | t.Errorf("Expected %q, got %q", expected, rendered) |
| 1452 | } |
| 1453 | |
| 1454 | // Verify that the rendered template used the custom "upper" function. |
| 1455 | expected = "custom:hello" |