github.com/matrixorigin/matrixone@v0.7.0/pkg/common/stopper/stopper_test.go (about)

     1  // Copyright 2021 - 2022 Matrix Origin
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //      http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package stopper
    16  
    17  import (
    18  	"context"
    19  	"testing"
    20  	"time"
    21  
    22  	"github.com/stretchr/testify/assert"
    23  )
    24  
    25  func TestRunTaskOnNotRunning(t *testing.T) {
    26  	s := NewStopper("TestRunTaskOnNotRunning")
    27  	s.Stop()
    28  	assert.Equal(t, ErrUnavailable, s.RunTask(func(ctx context.Context) {
    29  
    30  	}))
    31  }
    32  
    33  func TestRunTask(t *testing.T) {
    34  	s := NewStopper("TestRunTask")
    35  	defer s.Stop()
    36  
    37  	c := make(chan struct{})
    38  	assert.NoError(t, s.RunTask(func(ctx context.Context) {
    39  		close(c)
    40  	}))
    41  	select {
    42  	case <-c:
    43  		break
    44  	case <-time.After(time.Second):
    45  		assert.Fail(t, "run task timeout")
    46  	}
    47  }
    48  
    49  func TestRunTaskWithTimeout(t *testing.T) {
    50  	c := make(chan struct{})
    51  	defer close(c)
    52  	var names []string
    53  	s := NewStopper("TestRunTaskWithTimeout",
    54  		WithStopTimeout(time.Millisecond*10),
    55  		WithTimeoutTaskHandler(func(tasks []string, timeAfterStop time.Duration) {
    56  			select {
    57  			case c <- struct{}{}:
    58  			default:
    59  			}
    60  			names = append(names, tasks...)
    61  		}))
    62  
    63  	assert.NoError(t, s.RunNamedTask("timeout", func(ctx context.Context) {
    64  		<-c
    65  	}))
    66  
    67  	s.Stop()
    68  	assert.Equal(t, 1, len(names))
    69  	assert.Equal(t, "timeout", names[0])
    70  }