github.imxd.top/openshift/source-to-image@v1.2.0/pkg/util/timeout_test.go (about)

     1  package util
     2  
     3  import (
     4  	"fmt"
     5  	"reflect"
     6  	"testing"
     7  	"time"
     8  )
     9  
    10  func TestTimeoutAfter(t *testing.T) {
    11  	type testCase struct {
    12  		fn      func(*time.Timer) error
    13  		msg     string
    14  		timeout time.Duration
    15  		expect  interface{}
    16  	}
    17  	table := []testCase{
    18  		{
    19  			fn:      func(timer *time.Timer) error { time.Sleep(1 * time.Second); return nil },
    20  			timeout: 50 * time.Millisecond,
    21  			expect:  &TimeoutError{after: 50 * time.Millisecond},
    22  		},
    23  		{
    24  			fn:      func(timer *time.Timer) error { return fmt.Errorf("foo") },
    25  			timeout: 50 * time.Millisecond,
    26  			expect:  fmt.Errorf("foo"),
    27  		},
    28  		{
    29  			fn:      func(timer *time.Timer) error { time.Sleep(1 * time.Second); return fmt.Errorf("foo") },
    30  			msg:     "bar",
    31  			timeout: 50 * time.Millisecond,
    32  			expect:  fmt.Errorf("bar timed out after 50ms"),
    33  		},
    34  		{
    35  			fn:      func(timer *time.Timer) error { return nil },
    36  			timeout: 50 * time.Millisecond,
    37  			expect:  nil,
    38  		},
    39  	}
    40  	for _, item := range table {
    41  		got := TimeoutAfter(item.timeout, item.msg, item.fn)
    42  		if len(item.msg) > 0 {
    43  			expect, ok := item.expect.(error)
    44  			if !ok {
    45  				t.Errorf("expect must be an error, got %+v", item.expect)
    46  			}
    47  			if expect.Error() != got.Error() {
    48  				t.Errorf("expected message %q, got %q", item.msg, got.Error())
    49  			}
    50  			continue
    51  		}
    52  		if !reflect.DeepEqual(item.expect, got) {
    53  			t.Errorf("expected %+v, got %+v", item.expect, got)
    54  		}
    55  		if _, ok := item.expect.(*TimeoutError); ok {
    56  			if !IsTimeoutError(got) {
    57  				t.Errorf("expected %+v to be timeout error", got)
    58  			}
    59  		}
    60  	}
    61  }