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

     1  package gorill
     2  
     3  import (
     4  	"bytes"
     5  	"testing"
     6  	"time"
     7  )
     8  
     9  func TestTimedReadCloser(t *testing.T) {
    10  	corpus := "this is a test"
    11  	bb := bytes.NewReader([]byte(corpus))
    12  	rc := NewTimedReadCloser(NopCloseReader(bb), time.Second)
    13  	defer rc.Close()
    14  
    15  	buf := make([]byte, 1000)
    16  	n, err := rc.Read(buf)
    17  	if actual, want := n, len(corpus); actual != want {
    18  		t.Errorf("Actual: %#v; Expected: %#v", actual, want)
    19  	}
    20  	if actual, want := string(buf[:n]), corpus; actual != want {
    21  		t.Errorf("Actual: %#v; Expected: %#v", actual, want)
    22  	}
    23  	if actual, want := err, error(nil); actual != want {
    24  		t.Errorf("Actual: %#v; Expected: %#v", actual, want)
    25  	}
    26  }
    27  
    28  func TestTimedReadCloserTimesOut(t *testing.T) {
    29  	corpus := "this is a test"
    30  	bb := bytes.NewReader([]byte(corpus))
    31  	sr := SlowReader(bb, 10*time.Millisecond)
    32  	rc := NewTimedReadCloser(NopCloseReader(sr), time.Millisecond)
    33  	defer rc.Close()
    34  
    35  	buf := make([]byte, 1000)
    36  	n, err := rc.Read(buf)
    37  	if actual, want := n, 0; actual != want {
    38  		t.Errorf("Actual: %#v; Expected: %#v", actual, want)
    39  	}
    40  	if actual, want := string(buf[:n]), ""; actual != want {
    41  		t.Errorf("Actual: %#v; Expected: %#v", actual, want)
    42  	}
    43  	if actual, want := err, ErrTimeout(time.Millisecond); actual != want {
    44  		t.Errorf("Actual: %s; Expected: %s", actual, want)
    45  	}
    46  }
    47  
    48  func TestTimedReadCloserReadAfterCloseReturnsError(t *testing.T) {
    49  	bb := NewNopCloseBuffer()
    50  	rc := NewTimedReadCloser(NopCloseReader(bb), time.Millisecond)
    51  	rc.Close()
    52  
    53  	buf := make([]byte, 1000)
    54  	n, err := rc.Read(buf)
    55  	if actual, want := n, 0; actual != want {
    56  		t.Errorf("Actual: %#v; Expected: %#v", actual, want)
    57  	}
    58  	if actual, want := string(buf[:n]), ""; actual != want {
    59  		t.Errorf("Actual: %#v; Expected: %#v", actual, want)
    60  	}
    61  	if _, ok := err.(ErrReadAfterClose); err == nil || !ok {
    62  		t.Errorf("Actual: %s; Expected: %#v", err, ErrReadAfterClose{})
    63  	}
    64  }