github.com/haraldrudell/parl@v0.4.176/future_test.go (about)

     1  /*
     2  © 2023–present Harald Rudell <harald.rudell@gmail.com> (https://haraldrudell.github.io/haraldrudell/)
     3  ISC License
     4  */
     5  
     6  package parl
     7  
     8  import (
     9  	"sync"
    10  	"testing"
    11  )
    12  
    13  func TestAwaitableCalculation(t *testing.T) {
    14  	value := 1
    15  
    16  	var calculation *Future[int]
    17  	var result int
    18  	var isValid bool
    19  
    20  	calculation = NewFuture[int]()
    21  
    22  	var wgStart sync.WaitGroup
    23  	wgStart.Add(1)
    24  	var wgEnd sync.WaitGroup
    25  	wgEnd.Add(1)
    26  	go func() {
    27  		defer wgEnd.Done()
    28  		wgStart.Done()
    29  		result, isValid = calculation.Result()
    30  	}()
    31  	wgStart.Wait()
    32  
    33  	if calculation.IsCompleted() {
    34  		t.Error("calculation.IsCompleted true")
    35  	}
    36  
    37  	calculation.End(&value, nil, nil)
    38  	if !calculation.IsCompleted() {
    39  		t.Error("calculation.IsCompleted false")
    40  	}
    41  
    42  	wgEnd.Wait()
    43  	if !isValid {
    44  		t.Error("isValid false")
    45  	}
    46  	if result != value {
    47  		t.Errorf("result bad: %d exp %d", result, value)
    48  	}
    49  }