go.fuchsia.dev/infra@v0.0.0-20240507153436-9b593402251b/cmd/bigquery/query_test.go (about) 1 // Copyright 2021 The Fuchsia Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 package main 6 7 import ( 8 "bytes" 9 "encoding/json" 10 "os" 11 "path/filepath" 12 "testing" 13 14 "cloud.google.com/go/bigquery" 15 "github.com/google/go-cmp/cmp" 16 ) 17 18 func TestWriteOutput(t *testing.T) { 19 t.Run("writes to json output path", func(t *testing.T) { 20 rows := []map[string]bigquery.Value{ 21 { 22 "number": float64(1), // All numbers are coerced to floats by round-tripping through JSON. 23 "bool": true, 24 "string": "foo", 25 }, 26 } 27 28 outputPath := filepath.Join(t.TempDir(), "output.json") 29 if err := writeOutput(rows, outputPath, nil); err != nil { 30 t.Fatal(err) 31 } 32 33 b, err := os.ReadFile(outputPath) 34 if err != nil { 35 t.Fatal(err) 36 } 37 38 var outputRows []map[string]bigquery.Value 39 if err := json.Unmarshal(b, &outputRows); err != nil { 40 t.Fatal(err) 41 } 42 43 if diff := cmp.Diff(rows, outputRows); diff != "" { 44 t.Fatalf("got wrong output rows (-want +got)\n%s", diff) 45 } 46 }) 47 48 t.Run("writes to stdout if json output path is unset", func(t *testing.T) { 49 rows := []map[string]bigquery.Value{ 50 {"a": "foo", "b": "bar"}, 51 {"c": "foo", "d": "bar"}, 52 } 53 54 stdout := bytes.NewBuffer([]byte{}) 55 if err := writeOutput(rows, "", stdout); err != nil { 56 t.Fatal(err) 57 } 58 59 var outputRows []map[string]bigquery.Value 60 if err := json.Unmarshal(stdout.Bytes(), &outputRows); err != nil { 61 t.Fatal(err) 62 } 63 64 if diff := cmp.Diff(rows, outputRows); diff != "" { 65 t.Fatalf("got wrong output rows (-want +got)\n%s", diff) 66 } 67 }) 68 }