aboutsummaryrefslogtreecommitdiff
path: root/rutina_test.go
blob: cff73c4ccdf9d59abaebef5edd9ae2a753e049cd (plain) (blame)
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
package rutina

import (
	"context"
	"testing"
	"time"

	"github.com/pkg/errors"
)

func TestSuccess(t *testing.T) {
	r, _ := New()
	counter := 0
	f := func(name string, ttl time.Duration) error {
		counter++
		<-time.After(ttl)
		counter--
		t.Log(name)
		return nil
	}
	r.Go(func(ctx context.Context) error {
		return f("one", 1*time.Second)
	})
	r.Go(func(ctx context.Context) error {
		return f("two", 2*time.Second)
	})
	r.Go(func(ctx context.Context) error {
		return f("three", 3*time.Second)
	})
	if err := r.Wait(); err != nil {
		t.Error("Unexpected error", err)
	}
	if counter == 0 {
		t.Log("All routines done")
	} else {
		t.Error("Not all routines stopped")
	}
}

func TestError(t *testing.T) {
	r, _ := New()
	f := func(name string, ttl time.Duration) error {
		<-time.After(ttl)
		t.Log(name)
		return errors.New("error from " + name)
	}
	r.Go(func(ctx context.Context) error {
		return f("one", 1*time.Second)
	})
	r.Go(func(ctx context.Context) error {
		return f("two", 2*time.Second)
	})
	r.Go(func(ctx context.Context) error {
		return f("three", 3*time.Second)
	})
	if err := r.Wait(); err != nil {
		if err.Error() != "error from one" {
			t.Error("Must be error from first routine")
		}
		t.Log(err)
	}
	t.Log("All routines done")
}

func TestContext(t *testing.T) {
	r, _ := New()
	cc := false
	r.Go(func(ctx context.Context) error {
		<-time.After(1 * time.Second)
		return nil
	})
	r.Go(func(ctx context.Context) error {
		select {
		case <-ctx.Done():
			cc = true
			return nil
		case <-time.After(3 * time.Second):
			return errors.New("Timeout")
		}
	})
	if err := r.Wait(); err != nil {
		t.Error("Unexpected error", err)
	}
	if cc {
		t.Log("Second routine succesfuly complete by context done")
	} else {
		t.Error("Routine not completed by context")
	}
}