| 1 | package acp |
| 2 | |
| 3 | import ( |
| 4 | "encoding/json" |
| 5 | "strings" |
| 6 | "testing" |
| 7 | "unicode/utf8" |
| 8 | ) |
| 9 | |
| 10 | func TestClipStatusValuePreservesUTF8AcrossJSON(t *testing.T) { |
| 11 | const limit = 2_048 |
| 12 | want := strings.Repeat("x", limit-1) |
| 13 | clipped := clipStatusValue(want+"中", limit) |
| 14 | |
| 15 | if clipped != want { |
| 16 | t.Fatalf("clipStatusValue() = %q, want the complete UTF-8 prefix", clipped) |
| 17 | } |
| 18 | if len(clipped) > limit { |
| 19 | t.Fatalf("clipStatusValue() returned %d bytes, limit %d", len(clipped), limit) |
| 20 | } |
| 21 | if !utf8.ValidString(clipped) { |
| 22 | t.Fatalf("clipStatusValue() returned invalid UTF-8: %q", clipped) |
| 23 | } |
| 24 | |
| 25 | wire, err := json.Marshal(clipped) |
| 26 | if err != nil { |
| 27 | t.Fatalf("json.Marshal() error = %v", err) |
| 28 | } |
| 29 | var decoded string |
| 30 | if err := json.Unmarshal(wire, &decoded); err != nil { |
| 31 | t.Fatalf("json.Unmarshal() error = %v", err) |
| 32 | } |
| 33 | if decoded != clipped { |
| 34 | t.Fatalf("JSON round trip changed clipped diagnostic: got %q, want %q", decoded, clipped) |
| 35 | } |
| 36 | } |
| 37 | |
| 38 | func TestClipStatusValueRepairsInvalidUTF8(t *testing.T) { |
| 39 | clipped := clipStatusValue("status: \xff", 32) |
| 40 | if !utf8.ValidString(clipped) { |
| 41 | t.Fatalf("clipStatusValue() returned invalid UTF-8: %q", clipped) |
| 42 | } |
| 43 | if clipped != "status: \uFFFD" { |
| 44 | t.Fatalf("clipStatusValue() = %q, want invalid bytes replaced", clipped) |
| 45 | } |
| 46 | } |
| 47 |