File: future_test.go

package info (click to toggle)
golang-github-henrybear327-go-proton-api 1.0.0-4
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,088 kB
  • sloc: sh: 55; makefile: 26
file content (49 lines) | stat: -rw-r--r-- 990 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package proton

import (
	"math/rand"
	"testing"
	"time"

	"github.com/ProtonMail/gluon/async"
	"github.com/stretchr/testify/require"
)

func TestFuture(t *testing.T) {
	resCh := make(chan int)

	NewFuture(async.NoopPanicHandler{}, func() (int, error) {
		return 42, nil
	}).Then(func(res int, err error) {
		resCh <- res
	})

	require.Equal(t, 42, <-resCh)
}

func TestGroup(t *testing.T) {
	group := NewGroup[int](async.NoopPanicHandler{})

	for i := 0; i < 10; i++ {
		i := i

		group.Add(func() (int, error) {
			// Sleep a random amount of time so that results are returned in a random order.
			time.Sleep(time.Duration(rand.Int()%10) * time.Millisecond) //nolint:gosec

			// Return the job index [0, 10].
			return i, nil
		})
	}

	resCh := make(chan int)

	go func() {
		require.Equal(t, group.ForEach(func(res int) error { resCh <- res; return nil }), nil)
	}()

	// Results should be returned in the original order.
	for i := 0; i < 10; i++ {
		require.Equal(t, i, <-resCh)
	}
}