github.com/elves/elvish@v0.15.0/pkg/cli/term/file_reader_unix_test.go (about)

     1  // +build !windows,!plan9
     2  
     3  package term
     4  
     5  import (
     6  	"fmt"
     7  	"io"
     8  	"os"
     9  	"testing"
    10  
    11  	"github.com/elves/elvish/pkg/testutil"
    12  )
    13  
    14  func TestFileReader_ReadByteWithTimeout(t *testing.T) {
    15  	r, w, cleanup := setupFileReader()
    16  	defer cleanup()
    17  
    18  	content := []byte("0123456789")
    19  	w.Write(content)
    20  
    21  	// Test successful ReadByteWithTimeout calls.
    22  	for i := 0; i < len(content); i++ {
    23  		t.Run(fmt.Sprintf("byte %d", i), func(t *testing.T) {
    24  			b, err := r.ReadByteWithTimeout(-1)
    25  			if err != nil {
    26  				t.Errorf("got err %v, want nil", err)
    27  			}
    28  			if b != content[i] {
    29  				t.Errorf("got byte %q, want %q", b, content[i])
    30  			}
    31  		})
    32  	}
    33  }
    34  
    35  func TestFileReader_ReadByteWithTimeout_EOF(t *testing.T) {
    36  	r, w, cleanup := setupFileReader()
    37  	defer cleanup()
    38  
    39  	w.Close()
    40  	_, err := r.ReadByteWithTimeout(-1)
    41  	if err != io.EOF {
    42  		t.Errorf("got byte %v, want %v", err, io.EOF)
    43  	}
    44  }
    45  
    46  func TestFileReader_ReadByteWithTimeout_Timeout(t *testing.T) {
    47  	r, _, cleanup := setupFileReader()
    48  	defer cleanup()
    49  
    50  	_, err := r.ReadByteWithTimeout(testutil.ScaledMs(1))
    51  	if err != errTimeout {
    52  		t.Errorf("got err %v, want %v", err, errTimeout)
    53  	}
    54  }
    55  
    56  func TestFileReader_Stop(t *testing.T) {
    57  	r, _, cleanup := setupFileReader()
    58  	defer cleanup()
    59  
    60  	errCh := make(chan error, 1)
    61  	go func() {
    62  		_, err := r.ReadByteWithTimeout(-1)
    63  		errCh <- err
    64  	}()
    65  	r.Stop()
    66  
    67  	if err := <-errCh; err != ErrStopped {
    68  		t.Errorf("got err %v, want %v", err, ErrStopped)
    69  	}
    70  }
    71  
    72  func setupFileReader() (reader fileReader, writer *os.File, cleanup func()) {
    73  	pr, pw, err := os.Pipe()
    74  	if err != nil {
    75  		panic(err)
    76  	}
    77  	r, err := newFileReader(pr)
    78  	if err != nil {
    79  		panic(err)
    80  	}
    81  	return r, pw, func() {
    82  		r.Close()
    83  		pr.Close()
    84  		pw.Close()
    85  	}
    86  }