github.com/aretext/aretext@v1.3.0/state/task_test.go (about)

     1  package state
     2  
     3  import (
     4  	"context"
     5  	"testing"
     6  	"time"
     7  
     8  	"github.com/stretchr/testify/assert"
     9  	"github.com/stretchr/testify/require"
    10  )
    11  
    12  func TestStartTask(t *testing.T) {
    13  	state := NewEditorState(100, 100, nil, nil)
    14  	StartTask(state, func(ctx context.Context) func(*EditorState) {
    15  		return func(s *EditorState) {
    16  			SetStatusMsg(s, StatusMsg{
    17  				Style: StatusMsgStyleSuccess,
    18  				Text:  "task completed",
    19  			})
    20  		}
    21  	})
    22  	assert.Equal(t, InputModeTask, state.InputMode())
    23  
    24  	select {
    25  	case action := <-state.TaskResultChan():
    26  		action(state)
    27  		assert.Equal(t, "task completed", state.StatusMsg().Text)
    28  		assert.Equal(t, InputModeNormal, state.InputMode())
    29  	case <-time.After(5 * time.Second):
    30  		require.Fail(t, "Timed out")
    31  	}
    32  }
    33  
    34  func TestCancelTaskIfRunning(t *testing.T) {
    35  	cancelChan := make(chan struct{})
    36  	state := NewEditorState(100, 100, nil, nil)
    37  	StartTask(state, func(ctx context.Context) func(*EditorState) {
    38  		select {
    39  		case <-ctx.Done():
    40  			cancelChan <- struct{}{}
    41  		case <-time.After(5 * time.Second):
    42  			break
    43  		}
    44  		return func(s *EditorState) {}
    45  	})
    46  
    47  	assert.Equal(t, InputModeTask, state.InputMode())
    48  	CancelTaskIfRunning(state)
    49  	assert.Nil(t, state.TaskResultChan())
    50  	assert.Equal(t, InputModeNormal, state.InputMode())
    51  
    52  	select {
    53  	case <-cancelChan:
    54  		// Successfully cancelled.
    55  		break
    56  	case <-time.After(5 * time.Second):
    57  		require.Fail(t, "Timed out")
    58  	}
    59  }