github.com/bytom/bytom@v1.1.2-0.20221014091027-bbcba3df6075/errors/writer_test.go (about)

     1  package errors
     2  
     3  import (
     4  	"io"
     5  	"testing"
     6  )
     7  
     8  func TestWriter(t *testing.T) {
     9  	errX := New("x")
    10  	tw := testWriter{nil, errX, nil}
    11  	w := NewWriter(&tw)
    12  	_, err := w.Write([]byte{1})
    13  	if err != nil {
    14  		t.Error("unexpected error", err)
    15  	}
    16  	if g := w.Written(); g != 1 {
    17  		t.Errorf("w.Written() = %d want 1", g)
    18  	}
    19  	if len(tw) != 2 {
    20  		t.Errorf("len(tw) = %d want 2", len(tw))
    21  	}
    22  	for i := 0; i < 10; i++ {
    23  		_, err = w.Write([]byte{1})
    24  		if err != errX {
    25  			t.Errorf("err = %v want %v", err, errX)
    26  		}
    27  		if g := w.Written(); g != 2 {
    28  			t.Errorf("w.Written() = %d want 2", g)
    29  		}
    30  		if len(tw) != 1 {
    31  			t.Errorf("len(tw) = %d want 1", len(tw))
    32  		}
    33  	}
    34  	if got := w.Err(); got != errX {
    35  		t.Errorf("w.Err() = %v want %v", got, errX)
    36  	}
    37  }
    38  
    39  // testWriter returns its errors in order.
    40  // elements of a testWriter may be nil.
    41  // if its len is 0, it returns io.EOF.
    42  type testWriter []error
    43  
    44  func (tw *testWriter) Write(p []byte) (int, error) {
    45  	if len(*tw) == 0 {
    46  		return len(p), io.EOF
    47  	}
    48  	err := (*tw)[0]
    49  	*tw = (*tw)[1:]
    50  	return len(p), err
    51  }