| 1 |
package proton |
| 2 |
|
| 3 |
import ( |
| 4 |
"math/rand" |
| 5 |
"testing" |
| 6 |
"time" |
| 7 |
|
| 8 |
"github.com/ProtonMail/gluon/async" |
| 9 |
"github.com/stretchr/testify/require" |
| 10 |
) |
| 11 |
|
| 12 |
func TestFuture(t *testing.T) { |
| 13 |
resCh := make(chan int) |
| 14 |
|
| 15 |
NewFuture(async.NoopPanicHandler{}, func() (int, error) { |
| 16 |
return 42, nil |
| 17 |
}).Then(func(res int, err error) { |
| 18 |
resCh <- res |
| 19 |
}) |
| 20 |
|
| 21 |
require.Equal(t, 42, <-resCh) |
| 22 |
} |
| 23 |
|
| 24 |
func TestGroup(t *testing.T) { |
| 25 |
group := NewGroup[int](async.NoopPanicHandler{}) |
| 26 |
|
| 27 |
for i := 0; i < 10; i++ { |
| 28 |
i := i |
| 29 |
|
| 30 |
group.Add(func() (int, error) { |
| 31 |
// Sleep a random amount of time so that results are returned in a random order. |
| 32 |
time.Sleep(time.Duration(rand.Int()%10) * time.Millisecond) //nolint:gosec |
| 33 |
|
| 34 |
// Return the job index [0, 10]. |
| 35 |
return i, nil |
| 36 |
}) |
| 37 |
} |
| 38 |
|
| 39 |
resCh := make(chan int) |
| 40 |
|
| 41 |
go func() { |
| 42 |
require.Equal(t, group.ForEach(func(res int) error { resCh <- res; return nil }), nil) |
| 43 |
}() |
| 44 |
|
| 45 |
// Results should be returned in the original order. |
| 46 |
for i := 0; i < 10; i++ { |
| 47 |
require.Equal(t, i, <-resCh) |
| 48 |
} |
| 49 |
} |