diff --git a/internal/core/bootstrap_test.go b/internal/core/bootstrap_test.go index 8525841810..1154bab9a1 100644 --- a/internal/core/bootstrap_test.go +++ b/internal/core/bootstrap_test.go @@ -5,6 +5,7 @@ import ( "reflect" "testing" + "github.com/alecthomas/assert" "github.com/scaleway/scaleway-cli/internal/args" "github.com/scaleway/scaleway-cli/internal/interactive" ) @@ -44,7 +45,7 @@ func TestInterruptError(t *testing.T) { Cmd: "scw test code error", Check: TestCheckExitCode(99), })) - t.Run("emtpy-error", Test(&TestConfig{ + t.Run("empty-error", Test(&TestConfig{ Commands: NewCommands( &Command{ Namespace: "test", @@ -64,7 +65,7 @@ func TestInterruptError(t *testing.T) { TestCheckStderrGolden(), ), })) - t.Run("emtpy-error-json", Test(&TestConfig{ + t.Run("empty-error-json", Test(&TestConfig{ Commands: NewCommands( &Command{ Namespace: "test", @@ -131,4 +132,22 @@ func TestInterruptError(t *testing.T) { Cmd: "scw -o json test empty success", Check: TestCheckStdoutGolden(), })) + t.Run("empty-list-json", Test(&TestConfig{ + Commands: NewCommands( + &Command{ + Namespace: "test", + Resource: "empty", + Verb: "success", + ArgsType: reflect.TypeOf(args.RawArgs{}), + Run: func(ctx context.Context, argsI interface{}) (i interface{}, e error) { + return []int(nil), nil + }, + AllowAnonymousClient: true, + }, + ), + Cmd: "scw -o json test empty success", + Check: func(t *testing.T, ctx *CheckFuncCtx) { + assert.Equal(t, "[]\n", string(ctx.Stdout)) + }, + })) } diff --git a/internal/core/testdata/test-interrupt-error-emtpy-error-json.stderr.golden b/internal/core/testdata/test-interrupt-error-empty-error-json.stderr.golden similarity index 100% rename from internal/core/testdata/test-interrupt-error-emtpy-error-json.stderr.golden rename to internal/core/testdata/test-interrupt-error-empty-error-json.stderr.golden diff --git a/internal/printer/json.go b/internal/printer/json.go index 37495655f7..1f284b014f 100644 --- a/internal/printer/json.go +++ b/internal/printer/json.go @@ -3,6 +3,7 @@ package printer import ( "encoding/json" "io" + "reflect" "github.com/scaleway/scaleway-cli/internal/human" ) @@ -34,5 +35,9 @@ func (o *jsonPrinter) Print(data interface{}, opt *human.MarshalOpt) error { } } + if reflect.TypeOf(data).Kind() == reflect.Slice && reflect.ValueOf(data).IsNil() { + _, err := o.Writer.Write([]byte("[]\n")) + return err + } return json.NewEncoder(o.Writer).Encode(data) }