github.com/opensearch-project/opensearch-go/v2@v2.3.0/opensearchutil/json_reader_internal_test.go (about) 1 // SPDX-License-Identifier: Apache-2.0 2 // 3 // The OpenSearch Contributors require contributions made to 4 // this file be licensed under the Apache-2.0 license or a 5 // compatible open source license. 6 // 7 // Modifications Copyright OpenSearch Contributors. See 8 // GitHub history for details. 9 10 // Licensed to Elasticsearch B.V. under one or more contributor 11 // license agreements. See the NOTICE file distributed with 12 // this work for additional information regarding copyright 13 // ownership. Elasticsearch B.V. licenses this file to you under 14 // the Apache License, Version 2.0 (the "License"); you may 15 // not use this file except in compliance with the License. 16 // You may obtain a copy of the License at 17 // 18 // http://www.apache.org/licenses/LICENSE-2.0 19 // 20 // Unless required by applicable law or agreed to in writing, 21 // software distributed under the License is distributed on an 22 // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 23 // KIND, either express or implied. See the License for the 24 // specific language governing permissions and limitations 25 // under the License. 26 27 // +build !integration 28 29 package opensearchutil 30 31 import ( 32 "bytes" 33 "errors" 34 "io" 35 "io/ioutil" 36 "strings" 37 "testing" 38 ) 39 40 type errReader struct{} 41 42 func (errReader) Read(p []byte) (int, error) { return 1, errors.New("MOCK ERROR") } 43 func (errReader) Write(p []byte) (int, error) { return 0, errors.New("MOCK ERROR") } 44 func (errReader) WriteTo(w io.Writer) (int64, error) { return 0, errors.New("MOCK ERROR") } 45 46 type Foo struct { 47 Bar string 48 } 49 50 func (f Foo) EncodeJSON(w io.Writer) error { 51 _, err := w.Write([]byte(`{"bar":"` + strings.ToUpper(f.Bar) + `"}` + "\n")) 52 if err != nil { 53 return err 54 } 55 return nil 56 } 57 58 func TestJSONReader(t *testing.T) { 59 t.Run("Default", func(t *testing.T) { 60 out, _ := ioutil.ReadAll(NewJSONReader(map[string]string{"foo": "bar"})) 61 if string(out) != `{"foo":"bar"}`+"\n" { 62 t.Fatalf("Unexpected output: %s", out) 63 } 64 }) 65 66 t.Run("Custom", func(t *testing.T) { 67 out, _ := ioutil.ReadAll(NewJSONReader(Foo{Bar: "baz"})) 68 if string(out) != `{"bar":"BAZ"}`+"\n" { 69 t.Fatalf("Unexpected output: %s", out) 70 } 71 }) 72 73 t.Run("WriteTo", func(t *testing.T) { 74 b := bytes.NewBuffer([]byte{}) 75 r := JSONReader{val: map[string]string{"foo": "bar"}} 76 r.WriteTo(b) 77 if b.String() != `{"foo":"bar"}`+"\n" { 78 t.Fatalf("Unexpected output: %s", b.String()) 79 } 80 }) 81 82 t.Run("Read error", func(t *testing.T) { 83 b := []byte{} 84 r := JSONReader{val: map[string]string{"foo": "bar"}, buf: errReader{}} 85 _, err := r.Read(b) 86 if err == nil { 87 t.Fatalf("Expected error, got: %#v", err) 88 } 89 }) 90 }