diff --git a/pkg/output/output_test.go b/pkg/output/output_test.go index 31e048db..36255250 100644 --- a/pkg/output/output_test.go +++ b/pkg/output/output_test.go @@ -105,6 +105,24 @@ func TestYAMLFormatter(t *testing.T) { } } +func TestYAMLFormatterKeepsLargeIntegersPlain(t *testing.T) { + r := sampleResult() + r.TestDate = 1795635868754 + out, err := (&YAMLFormatter{}).Format(r) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(out, "testDate: 1795635868754\n") { + t.Errorf("expected plain integer testDate, got:\n%s", out) + } + if !strings.Contains(out, "elapsedTime: 1500\n") { + t.Errorf("expected plain integer elapsedTime, got:\n%s", out) + } + if strings.Contains(out, `: "0"`) { + t.Errorf("expected nested numbers to stay unquoted, got:\n%s", out) + } +} + func TestGitHubActionsFormatter(t *testing.T) { out, err := (&GitHubActionsFormatter{}).Format(sampleResult()) if err != nil { diff --git a/pkg/output/yaml_formatter.go b/pkg/output/yaml_formatter.go index faf101d4..3396e430 100644 --- a/pkg/output/yaml_formatter.go +++ b/pkg/output/yaml_formatter.go @@ -16,6 +16,7 @@ package output import ( + "bytes" "encoding/json" "github.com/microcks/microcks-cli/pkg/connectors" @@ -32,12 +33,40 @@ func (f *YAMLFormatter) Format(r *connectors.TestResult) (string, error) { return "", err } var generic interface{} - if err := json.Unmarshal(j, &generic); err != nil { + dec := json.NewDecoder(bytes.NewReader(j)) + dec.UseNumber() + if err := dec.Decode(&generic); err != nil { return "", err } - b, err := yaml.Marshal(generic) + b, err := yaml.Marshal(normalizeNumbers(generic)) if err != nil { return "", err } return string(b), nil } + +// normalizeNumbers converts json.Number values to int64 when possible so that +// large integers such as millisecond timestamps are not rendered in scientific +// notation, falling back to float64 for decimal values. +func normalizeNumbers(v interface{}) interface{} { + switch t := v.(type) { + case map[string]interface{}: + for k, val := range t { + t[k] = normalizeNumbers(val) + } + return t + case []interface{}: + for i, val := range t { + t[i] = normalizeNumbers(val) + } + return t + case json.Number: + if i, err := t.Int64(); err == nil { + return i + } + f, _ := t.Float64() + return f + default: + return v + } +}