github.com/cli/cli@v1.14.1-0.20210902173923-1af6a669e342/pkg/export/filter_test.go (about) 1 package export 2 3 import ( 4 "bytes" 5 "io" 6 "strings" 7 "testing" 8 9 "github.com/MakeNowJust/heredoc" 10 ) 11 12 func Test_filterJSON(t *testing.T) { 13 type args struct { 14 json io.Reader 15 query string 16 } 17 tests := []struct { 18 name string 19 args args 20 wantW string 21 wantErr bool 22 }{ 23 { 24 name: "simple", 25 args: args{ 26 json: strings.NewReader(`{"name":"Mona", "arms":8}`), 27 query: `.name`, 28 }, 29 wantW: "Mona\n", 30 }, 31 { 32 name: "multiple queries", 33 args: args{ 34 json: strings.NewReader(`{"name":"Mona", "arms":8}`), 35 query: `.name,.arms`, 36 }, 37 wantW: "Mona\n8\n", 38 }, 39 { 40 name: "object as JSON", 41 args: args{ 42 json: strings.NewReader(`{"user":{"login":"monalisa"}}`), 43 query: `.user`, 44 }, 45 wantW: "{\"login\":\"monalisa\"}\n", 46 }, 47 { 48 name: "complex", 49 args: args{ 50 json: strings.NewReader(heredoc.Doc(`[ 51 { 52 "title": "First title", 53 "labels": [{"name":"bug"}, {"name":"help wanted"}] 54 }, 55 { 56 "title": "Second but not last", 57 "labels": [] 58 }, 59 { 60 "title": "Alas, tis' the end", 61 "labels": [{}, {"name":"feature"}] 62 } 63 ]`)), 64 query: `.[] | [.title,(.labels | map(.name) | join(","))] | @tsv`, 65 }, 66 wantW: heredoc.Doc(` 67 First title bug,help wanted 68 Second but not last 69 Alas, tis' the end ,feature 70 `), 71 }, 72 } 73 for _, tt := range tests { 74 t.Run(tt.name, func(t *testing.T) { 75 w := &bytes.Buffer{} 76 if err := FilterJSON(w, tt.args.json, tt.args.query); (err != nil) != tt.wantErr { 77 t.Errorf("filterJSON() error = %v, wantErr %v", err, tt.wantErr) 78 return 79 } 80 if gotW := w.String(); gotW != tt.wantW { 81 t.Errorf("filterJSON() = %q, want %q", gotW, tt.wantW) 82 } 83 }) 84 } 85 }