From c700bbcb4baa4b215a67dc587bae70885849bba7 Mon Sep 17 00:00:00 2001 From: Silvin Lubecki Date: Mon, 18 Jan 2021 11:19:37 +0100 Subject: [PATCH] Add specific "json" value to format flag with inspect commands to output json, as empty flag does. Added tests on that new behavior. Signed-off-by: Silvin Lubecki Signed-off-by: Sebastiaan van Stijn --- cli/command/inspect/inspector.go | 2 +- cli/command/inspect/inspector_test.go | 54 +++++++++++++++++++++++++++ 2 files changed, 55 insertions(+), 1 deletion(-) diff --git a/cli/command/inspect/inspector.go b/cli/command/inspect/inspector.go index aef31e62df..15dbea14ce 100644 --- a/cli/command/inspect/inspector.go +++ b/cli/command/inspect/inspector.go @@ -38,7 +38,7 @@ func NewTemplateInspector(outputStream io.Writer, tmpl *template.Template) Inspe // NewTemplateInspectorFromString creates a new TemplateInspector from a string // which is compiled into a template. func NewTemplateInspectorFromString(out io.Writer, tmplStr string) (Inspector, error) { - if tmplStr == "" { + if tmplStr == "" || tmplStr == "json" { return NewIndentedInspector(out), nil } diff --git a/cli/command/inspect/inspector_test.go b/cli/command/inspect/inspector_test.go index 702df3d8cc..74c49b2f82 100644 --- a/cli/command/inspect/inspector_test.go +++ b/cli/command/inspect/inspector_test.go @@ -257,3 +257,57 @@ func TestTemplateInspectorRawFallbackNumber(t *testing.T) { b.Reset() } } + +func TestNewTemplateInspectorFromString(t *testing.T) { + testCases := []struct { + name string + template string + expected string + }{ + { + name: "empty template outputs json by default", + template: "", + expected: `[ + { + "Name": "test" + } +] +`, + }, + { + name: "json specific value outputs json", + template: "json", + expected: `[ + { + "Name": "test" + } +] +`, + }, + { + name: "template is applied", + template: "{{.Name}}", + expected: "test\n", + }, + } + value := struct { + Name string + }{ + "test", + } + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + b := new(bytes.Buffer) + i, err := NewTemplateInspectorFromString(b, tc.template) + assert.NilError(t, err) + + err = i.Inspect(value, nil) + assert.NilError(t, err) + + err = i.Flush() + assert.NilError(t, err) + + assert.Equal(t, b.String(), tc.expected) + }) + } +}