aboutsummaryrefslogtreecommitdiff
path: root/promise_test.go
blob: bafa184399b07e50cd0e85d28fda41a640f6dfa0 (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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
// SPDX-FileCopyrightText: © 2024 Grégoire Duchêne <gduchene@awhk.org>
// SPDX-License-Identifier: ISC

package core_test

import (
	"context"
	"errors"
	"fmt"
	"testing"
	"time"

	"go.awhk.org/core"
)

func TestPromise(s *testing.T) {
	t := core.T{T: s}
	someError := errors.New("some error")

	t.Run("Success", func(t *core.T) {
		p := core.NewPromise[int]()

		t.AssertErrorIs(nil, p.SucceedWith(1))
		t.AssertEqual(1, <-p.Value())
	})

	t.Run("SuccessThenError", func(t *core.T) {
		p := core.NewPromise[int]()

		t.AssertErrorIs(nil, p.SucceedWith(1))
		t.AssertErrorIs(core.ErrPromiseFulfilled, p.FailWith(someError))
		t.AssertEqual(1, <-p.Value())
	})

	t.Run("Error", func(t *core.T) {
		p := core.NewPromise[int]()

		t.AssertErrorIs(nil, p.FailWith(someError))
		t.AssertErrorIs(someError, <-p.Err())
	})

	t.Run("ErrorThenSuccess", func(t *core.T) {
		p := core.NewPromise[int]()

		t.AssertErrorIs(nil, p.FailWith(someError))
		t.AssertErrorIs(core.ErrPromiseFulfilled, p.SucceedWith(1))
		t.AssertErrorIs(someError, <-p.Err())
	})
}

func ExamplePromise() {
	p := core.NewPromise[string]()

	go func() {
		time.Sleep(time.Millisecond)
		p.SucceedWith("Hello World!")
	}()

	select {
	case s := <-p.Value():
		fmt.Printf("Received %q.\n", s)
	case err := <-p.Err():
		fmt.Printf("Received an error: %s.\n", err)
	}
	// Output: Received "Hello World!".
}

func ExamplePromise_withContext() {
	var (
		ctx, cancel = context.WithTimeout(context.Background(), time.Second)
		p           = core.NewPromise[string]()
	)
	defer cancel()

	go func() {
		time.Sleep(time.Millisecond)
		p.FailWith(errors.New("some error"))
	}()

	select {
	case s := <-p.Value():
		fmt.Printf("Received %q.\n", s)
	case err := <-p.Err():
		fmt.Printf("Received an error: %s.\n", err)
	case <-ctx.Done():
		fmt.Printf("Context was cancelled: %s.\n", ctx.Err())
	}
	// Output: Received an error: some error.
}