| 158 | } |
| 159 | |
| 160 | func TestJoinElements(t *testing.T) { |
| 161 | tests := []struct { |
| 162 | doc string |
| 163 | data any |
| 164 | expOut string |
| 165 | expErr string |
| 166 | }{ |
| 167 | { |
| 168 | doc: "nil", |
| 169 | data: nil, |
| 170 | expOut: `output: ""`, |
| 171 | }, |
| 172 | { |
| 173 | doc: "non-slice", |
| 174 | data: "hello", |
| 175 | expOut: `output: "`, |
| 176 | expErr: `error calling join: expected slice, got string`, |
| 177 | }, |
| 178 | { |
| 179 | doc: "structs", |
| 180 | data: []struct{ A, B string }{{"1", "2"}, {"3", "4"}}, |
| 181 | expOut: `output: "{1 2}, {3 4}"`, |
| 182 | }, |
| 183 | { |
| 184 | doc: "map with strings", |
| 185 | data: map[string]string{"A": "1", "B": "2", "C": "3"}, |
| 186 | expOut: `output: "1, 2, 3"`, |
| 187 | }, |
| 188 | { |
| 189 | doc: "map with stringers", |
| 190 | data: map[string]stringerString{"A": "1", "B": "2", "C": "3"}, |
| 191 | expOut: `output: "stringer1, stringer2, stringer3"`, |
| 192 | }, |
| 193 | { |
| 194 | doc: "map with errors", |
| 195 | data: []stringerAndError{"1", "2", "3"}, |
| 196 | expOut: `output: "error1, error2, error3"`, |
| 197 | }, |
| 198 | { |
| 199 | doc: "stringers", |
| 200 | data: []stringerString{"1", "2", "3"}, |
| 201 | expOut: `output: "stringer1, stringer2, stringer3"`, |
| 202 | }, |
| 203 | { |
| 204 | doc: "stringer with errors", |
| 205 | data: []stringerAndError{"1", "2", "3"}, |
| 206 | expOut: `output: "error1, error2, error3"`, |
| 207 | }, |
| 208 | { |
| 209 | doc: "slice of bools", |
| 210 | data: []bool{true, false, true}, |
| 211 | expOut: `output: "true, false, true"`, |
| 212 | }, |
| 213 | } |
| 214 | |
| 215 | const formatStr = `output: "{{- join . ", " -}}"` |
| 216 | tmpl, err := New("my-template").Funcs(template.FuncMap{"join": joinElements}).Parse(formatStr) |
| 217 | assert.NilError(t, err) |