github.com/status-im/status-go@v1.1.0/transactions/conditionalrepeater_test.go (about)

     1  package transactions
     2  
     3  import (
     4  	"context"
     5  	"sync"
     6  	"testing"
     7  	"time"
     8  
     9  	"github.com/stretchr/testify/require"
    10  )
    11  
    12  func TestConditionalRepeater_RunOnce(t *testing.T) {
    13  	var wg sync.WaitGroup
    14  	runCount := 0
    15  	wg.Add(1)
    16  	taskRunner := NewConditionalRepeater(1*time.Nanosecond, func(ctx context.Context) bool {
    17  		runCount++
    18  		defer wg.Done()
    19  		return WorkDone
    20  	})
    21  	taskRunner.RunUntilDone()
    22  	// Wait for task to run
    23  	wg.Wait()
    24  	taskRunner.Stop()
    25  	require.Greater(t, runCount, 0)
    26  }
    27  
    28  func TestConditionalRepeater_RunUntilDone_MultipleCalls(t *testing.T) {
    29  	var wg sync.WaitGroup
    30  	wg.Add(5)
    31  	runCount := 0
    32  	taskRunner := NewConditionalRepeater(1*time.Nanosecond, func(ctx context.Context) bool {
    33  		runCount++
    34  		wg.Done()
    35  		return runCount == 5
    36  	})
    37  	for i := 0; i < 10; i++ {
    38  		taskRunner.RunUntilDone()
    39  	}
    40  	// Wait for all tasks to run
    41  	wg.Wait()
    42  	taskRunner.Stop()
    43  	require.Greater(t, runCount, 4)
    44  }
    45  
    46  func TestConditionalRepeater_Stop(t *testing.T) {
    47  	var taskRunningWG, taskCanceledWG, taskFinishedWG sync.WaitGroup
    48  	taskRunningWG.Add(1)
    49  	taskCanceledWG.Add(1)
    50  	taskFinishedWG.Add(1)
    51  	taskRunner := NewConditionalRepeater(1*time.Nanosecond, func(ctx context.Context) bool {
    52  		defer taskFinishedWG.Done()
    53  		select {
    54  		case <-ctx.Done():
    55  			require.Fail(t, "task should not be canceled yet")
    56  		default:
    57  		}
    58  
    59  		// Wait to caller to stop the task
    60  		taskRunningWG.Done()
    61  		taskCanceledWG.Wait()
    62  
    63  		select {
    64  		case <-ctx.Done():
    65  			require.Error(t, ctx.Err())
    66  		default:
    67  			require.Fail(t, "task should be canceled")
    68  		}
    69  
    70  		return WorkDone
    71  	})
    72  	taskRunner.RunUntilDone()
    73  	taskRunningWG.Wait()
    74  
    75  	taskRunner.Stop()
    76  	taskCanceledWG.Done()
    77  
    78  	taskFinishedWG.Wait()
    79  }