github.com/hasnat/dolt/go@v0.0.0-20210628190320-9eb5d843fbb7/libraries/utils/iohelp/write_test.go (about) 1 // Copyright 2019 Dolthub, Inc. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package iohelp 16 17 import ( 18 "errors" 19 "reflect" 20 "testing" 21 22 "github.com/dolthub/dolt/go/libraries/utils/test" 23 ) 24 25 type test16ByteWriter struct { 26 Data []byte 27 } 28 29 func (tw *test16ByteWriter) Write(p []byte) (n int, err error) { 30 toCopy := 16 31 if len(p) < toCopy { 32 toCopy = len(p) 33 } 34 35 tw.Data = append(tw.Data, p[:toCopy]...) 36 37 return toCopy, nil 38 } 39 40 func TestWriteAll(t *testing.T) { 41 t16 := &test16ByteWriter{} 42 data := test.RandomData(1000) 43 44 err := WriteAll(t16, data) 45 46 if err != nil { 47 t.Error("Unexpected error", err) 48 } 49 50 if !reflect.DeepEqual(data, t16.Data) { 51 t.Error("Failed to write correctly") 52 } 53 } 54 55 func TestWriteNoErrWrites(t *testing.T) { 56 t16 := &test16ByteWriter{} 57 data := test.RandomData(32) 58 59 var prim int32 60 err := WritePrimIfNoErr(t16, prim, nil) 61 62 if err != nil { 63 t.Error("Unexpected error") 64 } 65 66 err = WriteIfNoErr(t16, data, err) 67 68 if err != nil { 69 t.Error("Unexpected error") 70 } 71 72 sizeAfterSuccesses := len(t16.Data) 73 74 err = errors.New("some error") 75 WritePrimIfNoErr(t16, prim, err) 76 77 if err == nil { 78 t.Error("Expected error") 79 } 80 81 err = WriteIfNoErr(t16, data, err) 82 83 if err == nil { 84 t.Error("Expected error") 85 } 86 87 if len(t16.Data) != sizeAfterSuccesses { 88 t.Error("Should not have written data after err set to non nil.") 89 } 90 } 91 92 func TestWriteLine(t *testing.T) { 93 lineStr := "This is a test of writing a line." 94 95 t16 := &test16ByteWriter{} 96 err := WriteLine(t16, lineStr) 97 98 if err != nil { 99 t.Error("Unexpected error", err) 100 } 101 102 resultStr := string(t16.Data) 103 if resultStr != lineStr+"\n" { 104 t.Errorf(`"%s" != "%s"`, resultStr, lineStr) 105 } 106 }