github.com/u-root/u-root@v7.0.1-0.20200915234505-ad7babab0a8e+incompatible/pkg/uio/lazy_test.go (about)

     1  // Copyright 2018 the u-root Authors. All rights reserved
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package uio
     6  
     7  import (
     8  	"fmt"
     9  	"io"
    10  	"testing"
    11  )
    12  
    13  type mockReader struct {
    14  	// called is whether Read has been called.
    15  	called bool
    16  
    17  	// err is the error to return on Read.
    18  	err error
    19  }
    20  
    21  func (m *mockReader) Read([]byte) (int, error) {
    22  	m.called = true
    23  	return 0, m.err
    24  }
    25  
    26  func TestLazyOpenerRead(t *testing.T) {
    27  	for i, tt := range []struct {
    28  		openErr    error
    29  		openReader *mockReader
    30  		wantCalled bool
    31  	}{
    32  		{
    33  			openErr:    nil,
    34  			openReader: &mockReader{},
    35  			wantCalled: true,
    36  		},
    37  		{
    38  			openErr:    io.EOF,
    39  			openReader: nil,
    40  			wantCalled: false,
    41  		},
    42  		{
    43  			openErr: nil,
    44  			openReader: &mockReader{
    45  				err: io.ErrUnexpectedEOF,
    46  			},
    47  			wantCalled: true,
    48  		},
    49  	} {
    50  		t.Run(fmt.Sprintf("Test #%02d", i), func(t *testing.T) {
    51  			var opened bool
    52  			lr := NewLazyOpener(func() (io.Reader, error) {
    53  				opened = true
    54  				return tt.openReader, tt.openErr
    55  			})
    56  			_, err := lr.Read([]byte{})
    57  			if !opened {
    58  				t.Fatalf("Read(): Reader was not opened")
    59  			}
    60  			if tt.openErr != nil && err != tt.openErr {
    61  				t.Errorf("Read() = %v, want %v", err, tt.openErr)
    62  			}
    63  			if tt.openReader != nil {
    64  				if got, want := tt.openReader.called, tt.wantCalled; got != want {
    65  					t.Errorf("mockReader.Read() called is %v, want %v", got, want)
    66  				}
    67  				if tt.openReader.err != nil && err != tt.openReader.err {
    68  					t.Errorf("Read() = %v, want %v", err, tt.openReader.err)
    69  				}
    70  			}
    71  		})
    72  	}
    73  }