1package command
2
3import (
4	"strings"
5	"testing"
6)
7
8type testData struct {
9	Region string
10	ID     string
11	Name   string
12}
13
14const expectJSON = `{
15    "ID": "1",
16    "Name": "example",
17    "Region": "global"
18}`
19
20var (
21	tData        = testData{"global", "1", "example"}
22	testFormat   = map[string]string{"json": "", "template": "{{.Region}}"}
23	expectOutput = map[string]string{"json": expectJSON, "template": "global"}
24)
25
26func TestDataFormat(t *testing.T) {
27	t.Parallel()
28	for k, v := range testFormat {
29		fm, err := DataFormat(k, v)
30		if err != nil {
31			t.Fatalf("err: %v", err)
32		}
33
34		result, err := fm.TransformData(tData)
35		if err != nil {
36			t.Fatalf("err: %v", err)
37		}
38
39		if result != expectOutput[k] {
40			t.Fatalf("expected output:\n%s\nactual:\n%s", expectOutput[k], result)
41		}
42	}
43}
44
45func TestInvalidJSONTemplate(t *testing.T) {
46	t.Parallel()
47	// Invalid template {{.foo}}
48	fm, err := DataFormat("template", "{{.foo}}")
49	if err != nil {
50		t.Fatalf("err: %v", err)
51	}
52	_, err = fm.TransformData(tData)
53	if !strings.Contains(err.Error(), "can't evaluate field foo") {
54		t.Fatalf("expected invalid template error, got: %s", err.Error())
55	}
56
57	// No template is specified
58	fm, err = DataFormat("template", "")
59	if err != nil {
60		t.Fatalf("err: %v", err)
61	}
62	_, err = fm.TransformData(tData)
63	if !strings.Contains(err.Error(), "template needs to be specified the golang templates.") {
64		t.Fatalf("expected not specified template error, got: %s", err.Error())
65	}
66}
67