package jsonv import ( "encoding/json" "math" "testing" ) func TestStr(t *testing.T) { tests := []struct { in any want string }{ {nil, ""}, {"abc", "abc"}, {float64(42), "42"}, {float64(13.5), "13.5"}, {true, "true"}, {[]any{1}, "[1]"}, } for _, tt := range tests { if got := Str(tt.in); got != tt.want { t.Errorf("Str(%v) = %q, want %q", tt.in, got, tt.want) } } } // TestStrOnDecodedJSON is the case that matters: userId comes back as a JSON // number, and formatting it as "42" rather than "4.2e+01" is what makes it // usable as an identifier in later requests. func TestStrOnDecodedJSON(t *testing.T) { var v map[string]any if err := json.Unmarshal([]byte(`{"userId":1234567890}`), &v); err != nil { t.Fatal(err) } if got, want := Str(v["userId"]), "1234567890"; got != want { t.Errorf("Str(userId) = %q, want %q", got, want) } } func TestNum(t *testing.T) { tests := []struct { in any want float64 wantOK bool }{ {float64(82), 82, true}, {"82", 82, true}, {" 13.5 ", 13.5, true}, {true, 1, true}, {false, 0, true}, {"", 0, false}, {"abc", 0, false}, {nil, 0, false}, {map[string]any{}, 0, false}, {[]any{}, 0, false}, } for _, tt := range tests { got, ok := Num(tt.in) if ok != tt.wantOK || (ok && got != tt.want) { t.Errorf("Num(%#v) = (%v, %v), want (%v, %v)", tt.in, got, ok, tt.want, tt.wantOK) } } } func TestNumRejectsNonFinite(t *testing.T) { // A NaN or Inf would render as an invalid metric value, so it is better to // know which way these go. for _, s := range []string{"NaN", "Inf", "+Inf"} { if v, ok := Num(s); ok && !math.IsNaN(v) && !math.IsInf(v, 0) { t.Errorf("Num(%q) = %v, expected NaN/Inf or a rejection", s, v) } } }