github.com/lingyao2333/mo-zero@v1.4.1/core/fx/timeout_test.go (about)

     1  package fx
     2  
     3  import (
     4  	"context"
     5  	"testing"
     6  	"time"
     7  
     8  	"github.com/stretchr/testify/assert"
     9  )
    10  
    11  func TestWithPanic(t *testing.T) {
    12  	assert.Panics(t, func() {
    13  		_ = DoWithTimeout(func() error {
    14  			panic("hello")
    15  		}, time.Millisecond*50)
    16  	})
    17  }
    18  
    19  func TestWithTimeout(t *testing.T) {
    20  	assert.Equal(t, ErrTimeout, DoWithTimeout(func() error {
    21  		time.Sleep(time.Millisecond * 50)
    22  		return nil
    23  	}, time.Millisecond))
    24  }
    25  
    26  func TestWithoutTimeout(t *testing.T) {
    27  	assert.Nil(t, DoWithTimeout(func() error {
    28  		return nil
    29  	}, time.Millisecond*50))
    30  }
    31  
    32  func TestWithCancel(t *testing.T) {
    33  	ctx, cancel := context.WithCancel(context.Background())
    34  	go func() {
    35  		time.Sleep(time.Millisecond * 10)
    36  		cancel()
    37  	}()
    38  	err := DoWithTimeout(func() error {
    39  		time.Sleep(time.Minute)
    40  		return nil
    41  	}, time.Second, WithContext(ctx))
    42  	assert.Equal(t, ErrCanceled, err)
    43  }