github.com/andrewhsu/cli/v2@v2.0.1-0.20210910131313-d4b4061f5b89/pkg/jsoncolor/jsoncolor_test.go (about) 1 package jsoncolor 2 3 import ( 4 "bytes" 5 "io" 6 "testing" 7 8 "github.com/google/go-cmp/cmp" 9 ) 10 11 func TestWrite(t *testing.T) { 12 type args struct { 13 r io.Reader 14 indent string 15 } 16 tests := []struct { 17 name string 18 args args 19 wantW string 20 wantErr bool 21 }{ 22 { 23 name: "blank", 24 args: args{ 25 r: bytes.NewBufferString(``), 26 indent: "", 27 }, 28 wantW: "", 29 wantErr: false, 30 }, 31 { 32 name: "empty object", 33 args: args{ 34 r: bytes.NewBufferString(`{}`), 35 indent: "", 36 }, 37 wantW: "\x1b[1;38m{\x1b[m\x1b[1;38m}\x1b[m\n", 38 wantErr: false, 39 }, 40 { 41 name: "nested object", 42 args: args{ 43 r: bytes.NewBufferString(`{"hash":{"a":1,"b":2},"array":[3,4]}`), 44 indent: "\t", 45 }, 46 wantW: "\x1b[1;38m{\x1b[m\n\t\x1b[1;34m\"hash\"\x1b[m\x1b[1;38m:\x1b[m " + 47 "\x1b[1;38m{\x1b[m\n\t\t\x1b[1;34m\"a\"\x1b[m\x1b[1;38m:\x1b[m 1\x1b[1;38m,\x1b[m\n\t\t\x1b[1;34m\"b\"\x1b[m\x1b[1;38m:\x1b[m 2\n\t\x1b[1;38m}\x1b[m\x1b[1;38m,\x1b[m" + 48 "\n\t\x1b[1;34m\"array\"\x1b[m\x1b[1;38m:\x1b[m \x1b[1;38m[\x1b[m\n\t\t3\x1b[1;38m,\x1b[m\n\t\t4\n\t\x1b[1;38m]\x1b[m\n\x1b[1;38m}\x1b[m\n", 49 wantErr: false, 50 }, 51 { 52 name: "string", 53 args: args{ 54 r: bytes.NewBufferString(`"foo"`), 55 indent: "", 56 }, 57 wantW: "\x1b[32m\"foo\"\x1b[m\n", 58 wantErr: false, 59 }, 60 { 61 name: "error", 62 args: args{ 63 r: bytes.NewBufferString(`{{`), 64 indent: "", 65 }, 66 wantW: "\x1b[1;38m{\x1b[m\n", 67 wantErr: true, 68 }, 69 } 70 for _, tt := range tests { 71 t.Run(tt.name, func(t *testing.T) { 72 w := &bytes.Buffer{} 73 if err := Write(w, tt.args.r, tt.args.indent); (err != nil) != tt.wantErr { 74 t.Errorf("Write() error = %v, wantErr %v", err, tt.wantErr) 75 return 76 } 77 diff := cmp.Diff(tt.wantW, w.String()) 78 if diff != "" { 79 t.Error(diff) 80 } 81 }) 82 } 83 }