2023-04-10 15:36:59 +00:00
|
|
|
// Copyright (c) HashiCorp, Inc.
|
|
|
|
// SPDX-License-Identifier: MPL-2.0
|
|
|
|
|
2016-07-30 10:20:43 +00:00
|
|
|
package command
|
|
|
|
|
|
|
|
import (
|
|
|
|
"testing"
|
2022-03-15 12:42:43 +00:00
|
|
|
|
|
|
|
"github.com/hashicorp/nomad/ci"
|
2023-02-07 19:07:20 +00:00
|
|
|
"github.com/shoenig/test/must"
|
2016-07-30 10:20:43 +00:00
|
|
|
)
|
|
|
|
|
2023-02-07 19:07:20 +00:00
|
|
|
func TestDataFormat(t *testing.T) {
|
|
|
|
ci.Parallel(t)
|
|
|
|
type testData struct {
|
|
|
|
Region string
|
|
|
|
ID string
|
|
|
|
Name string
|
|
|
|
}
|
|
|
|
|
|
|
|
var tData = testData{"global", "1", "example"}
|
2016-07-30 10:20:43 +00:00
|
|
|
|
2023-02-07 19:07:20 +00:00
|
|
|
// Note: this variable is space indented (4) and requires the final brace to
|
|
|
|
// be at char 1
|
|
|
|
const expectJSON = `{
|
2016-07-30 10:20:43 +00:00
|
|
|
"ID": "1",
|
2017-02-16 00:28:28 +00:00
|
|
|
"Name": "example",
|
|
|
|
"Region": "global"
|
2016-07-30 10:20:43 +00:00
|
|
|
}`
|
|
|
|
|
2023-02-07 19:07:20 +00:00
|
|
|
var tcs = map[string]struct {
|
|
|
|
format string
|
|
|
|
template string
|
|
|
|
expect string
|
|
|
|
isError bool
|
|
|
|
}{
|
|
|
|
"json_good": {
|
|
|
|
format: "json",
|
|
|
|
template: "",
|
|
|
|
expect: expectJSON,
|
|
|
|
},
|
|
|
|
"template_good": {
|
|
|
|
format: "template",
|
|
|
|
template: "{{.Region}}",
|
|
|
|
expect: "global",
|
|
|
|
},
|
|
|
|
"template_bad": {
|
|
|
|
format: "template",
|
|
|
|
template: "{{.foo}}",
|
|
|
|
isError: true,
|
|
|
|
expect: "can't evaluate field foo",
|
|
|
|
},
|
|
|
|
"template_empty": {
|
|
|
|
format: "template",
|
|
|
|
template: "",
|
|
|
|
isError: true,
|
|
|
|
expect: "template needs to be specified in golang's text/template format.",
|
|
|
|
},
|
|
|
|
"template_sprig": {
|
|
|
|
format: "template",
|
|
|
|
template: `{{$a := 1}}{{ $a | sprig_add 1 }}`,
|
|
|
|
expect: "2",
|
|
|
|
},
|
2016-08-09 13:50:18 +00:00
|
|
|
}
|
|
|
|
|
2023-02-07 19:07:20 +00:00
|
|
|
for name, tc := range tcs {
|
|
|
|
t.Run(name, func(t *testing.T) {
|
|
|
|
tc := tc
|
|
|
|
ci.Parallel(t)
|
|
|
|
fm, err := DataFormat(tc.format, tc.template)
|
|
|
|
must.NoError(t, err)
|
|
|
|
result, err := fm.TransformData(tData)
|
|
|
|
if tc.isError {
|
|
|
|
must.ErrorContains(t, err, tc.expect)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
must.NoError(t, err)
|
|
|
|
must.Eq(t, tc.expect, result)
|
|
|
|
})
|
2016-08-09 13:50:18 +00:00
|
|
|
}
|
|
|
|
}
|