github.com/bhojpur/cache@v0.0.4/pkg/ioutils/writers_test.go (about) 1 package ioutils 2 3 // Copyright (c) 2018 Bhojpur Consulting Private Limited, India. All rights reserved. 4 5 // Permission is hereby granted, free of charge, to any person obtaining a copy 6 // of this software and associated documentation files (the "Software"), to deal 7 // in the Software without restriction, including without limitation the rights 8 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 // copies of the Software, and to permit persons to whom the Software is 10 // furnished to do so, subject to the following conditions: 11 12 // The above copyright notice and this permission notice shall be included in 13 // all copies or substantial portions of the Software. 14 15 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 // THE SOFTWARE. 22 23 import ( 24 "bytes" 25 "strings" 26 "testing" 27 ) 28 29 func TestWriteCloserWrapperClose(t *testing.T) { 30 called := false 31 writer := bytes.NewBuffer([]byte{}) 32 wrapper := NewWriteCloserWrapper(writer, func() error { 33 called = true 34 return nil 35 }) 36 if err := wrapper.Close(); err != nil { 37 t.Fatal(err) 38 } 39 if !called { 40 t.Fatalf("writeCloserWrapper should have call the anonymous function.") 41 } 42 } 43 44 func TestNopWriteCloser(t *testing.T) { 45 writer := bytes.NewBuffer([]byte{}) 46 wrapper := NopWriteCloser(writer) 47 if err := wrapper.Close(); err != nil { 48 t.Fatal("NopWriteCloser always return nil on Close.") 49 } 50 51 } 52 53 func TestNopWriter(t *testing.T) { 54 nw := &NopWriter{} 55 l, err := nw.Write([]byte{'c'}) 56 if err != nil { 57 t.Fatal(err) 58 } 59 if l != 1 { 60 t.Fatalf("Expected 1 got %d", l) 61 } 62 } 63 64 func TestWriteCounter(t *testing.T) { 65 dummy1 := "This is a dummy string." 66 dummy2 := "This is another dummy string." 67 totalLength := int64(len(dummy1) + len(dummy2)) 68 69 reader1 := strings.NewReader(dummy1) 70 reader2 := strings.NewReader(dummy2) 71 72 var buffer bytes.Buffer 73 wc := NewWriteCounter(&buffer) 74 75 reader1.WriteTo(wc) 76 reader2.WriteTo(wc) 77 78 if wc.Count != totalLength { 79 t.Errorf("Wrong count: %d vs. %d", wc.Count, totalLength) 80 } 81 82 if buffer.String() != dummy1+dummy2 { 83 t.Error("Wrong message written") 84 } 85 }