aboutsummaryrefslogtreecommitdiff
path: root/pkg/coroutine/coroutine_test.go
blob: e876ec3bd69b256426e2dad9fb6c2f1b17ab7348 (plain)
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
//go:build unit

package coroutine

import (
	"context"
	"errors"
	"sync"
	"testing"
	"time"

	"git.sr.ht/~gabrielgio/img/pkg/testkit"
)

var rError = errors.New("This is a error")

func imediatReturn() (string, error) {
	return "A string", nil
}

func imediatErrorReturn() (string, error) {
	return "", rError
}

func haltedReturn() (string, error) {
	time.Sleep(time.Hour)
	return "", nil
}

func TestImediatReturn(t *testing.T) {
	ctx := context.Background()
	v, err := WrapProcess(ctx, imediatReturn)
	testkit.TestError(t, "WrapProcess", nil, err)
	testkit.TestValue(t, "WrapProcess", "A string", v)
}

func TestImediatErrorReturn(t *testing.T) {
	ctx := context.Background()
	v, err := WrapProcess(ctx, imediatErrorReturn)
	testkit.TestError(t, "WrapProcess", rError, err)
	testkit.TestValue(t, "WrapProcess", "", v)
}

func TestHaltedReturn(t *testing.T) {
	ctx := context.Background()
	ctx, cancel := context.WithCancel(ctx)

	var (
		err error
		wg  sync.WaitGroup
	)

	wg.Add(1)
	go func(err *error) {
		defer wg.Done()
		_, *err = WrapProcess(ctx, haltedReturn)
	}(&err)

	cancel()
	wg.Wait()

	testkit.TestError(t, "WrapProcess", context.Canceled, err)
}