github.com/karrick/gorill@v1.10.3/spooledWriteCloser_test.go (about)

     1  package gorill
     2  
     3  import (
     4  	"bytes"
     5  	"testing"
     6  	"time"
     7  )
     8  
     9  func TestSpooledWriteCloserFlushForcesBytesWritten(t *testing.T) {
    10  	test := func(buf []byte, flushPeriodicity time.Duration) {
    11  		bb := new(bytes.Buffer)
    12  
    13  		SlowWriter := SlowWriter(bb, 10*time.Millisecond)
    14  		spoolWriter, _ := NewSpooledWriteCloser(NopCloseWriter(SlowWriter), Flush(flushPeriodicity))
    15  		defer func() {
    16  			if err := spoolWriter.Close(); err != nil {
    17  				t.Errorf("Actual: %s; Expected: %#v", err, nil)
    18  			}
    19  		}()
    20  
    21  		n, err := spoolWriter.Write(buf)
    22  		if want := len(buf); n != want {
    23  			t.Errorf("Actual: %#v; Expected: %#v", n, want)
    24  		}
    25  		if err != nil {
    26  			t.Errorf("Actual: %#v; Expected: %#v", err, nil)
    27  		}
    28  		if err = spoolWriter.Flush(); err != nil {
    29  			t.Errorf("Actual: %s; Expected: %#v", err, nil)
    30  		}
    31  		if want := string(buf); bb.String() != want {
    32  			t.Errorf("Actual: %#v; Expected: %#v", bb.String(), want)
    33  		}
    34  	}
    35  	test(smallBuf, time.Millisecond)
    36  	test(largeBuf, time.Millisecond)
    37  
    38  	test(smallBuf, time.Hour)
    39  	test(largeBuf, time.Hour)
    40  }
    41  
    42  func TestSpooledWriteCloserCloseCausesFlush(t *testing.T) {
    43  	test := func(buf []byte, flushPeriodicity time.Duration) {
    44  		bb := NewNopCloseBuffer()
    45  
    46  		spoolWriter, _ := NewSpooledWriteCloser(bb, Flush(flushPeriodicity))
    47  
    48  		n, err := spoolWriter.Write(buf)
    49  		if want := len(buf); n != want {
    50  			t.Errorf("Actual: %#v; Expected: %#v", n, want)
    51  		}
    52  		if err != nil {
    53  			t.Errorf("Actual: %#v; Expected: %#v", err, nil)
    54  		}
    55  		if err := spoolWriter.Close(); err != nil {
    56  			t.Errorf("Actual: %s; Expected: %#v", err, nil)
    57  		}
    58  		if want := string(buf); bb.String() != want {
    59  			t.Errorf("Actual: %#v; Expected: %#v", bb.String(), want)
    60  		}
    61  	}
    62  	test(smallBuf, time.Millisecond)
    63  	test(largeBuf, time.Millisecond)
    64  
    65  	test(smallBuf, time.Hour)
    66  	test(largeBuf, time.Hour)
    67  }