github.com/philpearl/plenc@v0.0.15/plenccodec/output_test.go (about) 1 package plenccodec_test 2 3 import ( 4 "encoding/json" 5 "testing" 6 "time" 7 8 "github.com/google/go-cmp/cmp" 9 "github.com/philpearl/plenc/plenccodec" 10 ) 11 12 func TestJSONOutput(t *testing.T) { 13 tests := []struct { 14 sequence func(j *plenccodec.JSONOutput) 15 exp string 16 }{ 17 { 18 sequence: func(j *plenccodec.JSONOutput) { 19 j.StartObject() 20 j.NameField("fred") 21 j.Bool(true) 22 j.NameField("brian") 23 j.StartArray() 24 j.Int64(1) 25 j.Int64(2) 26 j.Int64(3) 27 j.EndArray() 28 j.NameField("sheila") 29 j.StartObject() 30 j.EndObject() 31 j.EndObject() 32 }, 33 exp: `{ 34 "fred": true, 35 "brian": [ 36 1, 37 2, 38 3 39 ], 40 "sheila": { 41 } 42 } 43 `, 44 }, 45 { 46 sequence: func(j *plenccodec.JSONOutput) { 47 j.String(` £∞§¶•ªº˙©"ƒ∂µµµPhi\l`) 48 }, 49 exp: `"\t£∞§¶•ªº˙©\"ƒ∂µµµPhi\\l" 50 `, 51 }, 52 53 { 54 sequence: func(j *plenccodec.JSONOutput) { 55 j.Bool(true) 56 }, 57 exp: "true\n", 58 }, 59 { 60 sequence: func(j *plenccodec.JSONOutput) { 61 j.Time(time.Date(1970, 3, 15, 0, 0, 0, 0, time.UTC)) 62 }, 63 exp: "\"1970-03-15T00:00:00Z\"\n", 64 }, 65 66 { 67 sequence: func(j *plenccodec.JSONOutput) { 68 j.StartObject() 69 j.NameField(`a§a§"a`) 70 j.String("a˙©ƒ∂†¥˚˙") 71 j.EndObject() 72 }, 73 exp: `{ 74 "a§a§\"a": "a˙©ƒ∂†¥˚˙" 75 } 76 `, 77 }, 78 } 79 80 var j plenccodec.JSONOutput 81 82 for _, test := range tests { 83 t.Run("", func(t *testing.T) { 84 j.Reset() 85 test.sequence(&j) 86 out := j.Done() 87 88 if diff := cmp.Diff(test.exp, string(out)); diff != "" { 89 t.Fatal(diff) 90 } 91 92 if !json.Valid(out) { 93 t.Fatal("output is not valid JSON") 94 } 95 }) 96 } 97 }