|
| 1 | +// Unless explicitly stated otherwise all files in this repository are licensed |
| 2 | +// under the Apache License Version 2.0. |
| 3 | +// This product includes software developed at Datadog (https://www.datadoghq.com/). |
| 4 | +// Copyright 2023-present Datadog, Inc. |
| 5 | + |
| 6 | +package main |
| 7 | + |
| 8 | +import ( |
| 9 | + "encoding/json" |
| 10 | + "errors" |
| 11 | + "testing" |
| 12 | + |
| 13 | + "github.com/spf13/cobra" |
| 14 | + "github.com/stretchr/testify/assert" |
| 15 | + |
| 16 | + "github.com/DataDog/datadog-agent/pkg/fleet/installer/commands" |
| 17 | +) |
| 18 | + |
| 19 | +func TestFormatError_HumanReadable(t *testing.T) { |
| 20 | + cmd := &cobra.Command{ |
| 21 | + Annotations: map[string]string{commands.AnnotationHumanReadableErrors: "true"}, |
| 22 | + } |
| 23 | + err := errors.New("something went wrong") |
| 24 | + |
| 25 | + result := formatError(cmd, err) |
| 26 | + |
| 27 | + assert.Equal(t, "something went wrong", result) |
| 28 | + assert.NotContains(t, result, `"code"`) |
| 29 | +} |
| 30 | + |
| 31 | +func TestFormatError_JSON(t *testing.T) { |
| 32 | + cmd := &cobra.Command{} |
| 33 | + err := errors.New("something went wrong") |
| 34 | + |
| 35 | + result := formatError(cmd, err) |
| 36 | + |
| 37 | + var parsed map[string]interface{} |
| 38 | + unmarshalErr := json.Unmarshal([]byte(result), &parsed) |
| 39 | + assert.NoError(t, unmarshalErr, "result should be valid JSON") |
| 40 | + assert.Contains(t, parsed, "error") |
| 41 | + assert.Contains(t, parsed, "code") |
| 42 | + assert.Equal(t, "something went wrong", parsed["error"]) |
| 43 | +} |
| 44 | + |
| 45 | +func TestFormatError_NilCommand(t *testing.T) { |
| 46 | + err := errors.New("something went wrong") |
| 47 | + |
| 48 | + result := formatError(nil, err) |
| 49 | + |
| 50 | + // Should fall back to JSON when command is nil |
| 51 | + var parsed map[string]interface{} |
| 52 | + unmarshalErr := json.Unmarshal([]byte(result), &parsed) |
| 53 | + assert.NoError(t, unmarshalErr, "result should be valid JSON") |
| 54 | + assert.Contains(t, parsed, "error") |
| 55 | + assert.Equal(t, "something went wrong", parsed["error"]) |
| 56 | +} |
0 commit comments