template_test.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. /*
  2. Copyright 2017 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package util
  14. import (
  15. "testing"
  16. )
  17. const (
  18. validTmpl = "image: {{ .ImageRepository }}/pause:3.1"
  19. validTmplOut = "image: k8s.gcr.io/pause:3.1"
  20. doNothing = "image: k8s.gcr.io/pause:3.1"
  21. invalidTmpl1 = "{{ .baz }/d}"
  22. invalidTmpl2 = "{{ !foobar }}"
  23. )
  24. func TestParseTemplate(t *testing.T) {
  25. var tmplTests = []struct {
  26. name string
  27. template string
  28. data interface{}
  29. output string
  30. errExpected bool
  31. }{
  32. {
  33. name: "should parse a valid template and set the right values",
  34. template: validTmpl,
  35. data: struct{ ImageRepository, Arch string }{
  36. ImageRepository: "k8s.gcr.io",
  37. Arch: "amd64",
  38. },
  39. output: validTmplOut,
  40. errExpected: false,
  41. },
  42. {
  43. name: "should noop if there aren't any {{ .foo }} present",
  44. template: doNothing,
  45. data: struct{ ImageRepository, Arch string }{
  46. ImageRepository: "k8s.gcr.io",
  47. Arch: "amd64",
  48. },
  49. output: doNothing,
  50. errExpected: false,
  51. },
  52. {
  53. name: "invalid syntax, passing nil",
  54. template: invalidTmpl1,
  55. data: nil,
  56. output: "",
  57. errExpected: true,
  58. },
  59. {
  60. name: "invalid syntax",
  61. template: invalidTmpl2,
  62. data: struct{}{},
  63. output: "",
  64. errExpected: true,
  65. },
  66. }
  67. for _, tt := range tmplTests {
  68. t.Run(tt.name, func(t *testing.T) {
  69. outbytes, err := ParseTemplate(tt.template, tt.data)
  70. if tt.errExpected != (err != nil) {
  71. t.Errorf(
  72. "failed TestParseTemplate:\n\texpected err: %t\n\t actual: %s",
  73. tt.errExpected,
  74. err,
  75. )
  76. }
  77. if tt.output != string(outbytes) {
  78. t.Errorf(
  79. "failed TestParseTemplate:\n\texpected bytes: %s\n\t actual: %s",
  80. tt.output,
  81. outbytes,
  82. )
  83. }
  84. })
  85. }
  86. }