github.com/blend/go-sdk@v1.20220411.3/async/interval_test.go (about)

     1  /*
     2  
     3  Copyright (c) 2022 - Present. Blend Labs, Inc. All rights reserved
     4  Use of this source code is governed by a MIT license that can be found in the LICENSE file.
     5  
     6  */
     7  
     8  package async
     9  
    10  import (
    11  	"context"
    12  	"fmt"
    13  	"testing"
    14  	"time"
    15  
    16  	"github.com/blend/go-sdk/assert"
    17  	"github.com/blend/go-sdk/graceful"
    18  )
    19  
    20  // Assert a latch is graceful
    21  var (
    22  	_ graceful.Graceful = (*Interval)(nil)
    23  )
    24  
    25  func Test_Interval(t *testing.T) {
    26  	assert := assert.New(t)
    27  
    28  	var didWork bool
    29  	unbuffered := make(chan bool)
    30  	w := NewInterval(func(_ context.Context) error {
    31  		didWork = true
    32  		<-unbuffered
    33  		return nil
    34  	}, time.Millisecond)
    35  
    36  	assert.Equal(time.Millisecond, w.Interval)
    37  
    38  	go func() { _ = w.Start() }()
    39  	<-w.NotifyStarted()
    40  
    41  	assert.True(w.IsStarted())
    42  	unbuffered <- true
    43  	close(unbuffered)
    44  	assert.Nil(w.Stop())
    45  	assert.True(w.IsStopped())
    46  	assert.True(didWork)
    47  }
    48  
    49  func Test_Interval_StopOnError(t *testing.T) {
    50  	its := assert.New(t)
    51  
    52  	var didWork bool
    53  	unbuffered := make(chan bool)
    54  	w := NewInterval(func(_ context.Context) error {
    55  		didWork = true
    56  		<-unbuffered
    57  		return fmt.Errorf("this is just a test")
    58  	}, time.Millisecond, OptIntervalStopOnError(true))
    59  
    60  	its.Equal(time.Millisecond, w.Interval)
    61  
    62  	startErrors := make(chan error)
    63  	go func() {
    64  		startErrors <- w.Start()
    65  	}()
    66  	<-w.NotifyStarted()
    67  
    68  	its.True(w.IsStarted())
    69  	unbuffered <- true
    70  	close(unbuffered)
    71  	its.True(didWork)
    72  	err := <-startErrors
    73  	its.Equal(fmt.Errorf("this is just a test"), err)
    74  	its.True(w.IsStopped())
    75  }