rutina/rutina_test.go

92 lines
1.8 KiB
Go
Raw Normal View History

2018-12-05 00:48:33 +03:00
package rutina
import (
"context"
2019-01-11 17:22:06 +03:00
"errors"
2018-12-05 00:48:33 +03:00
"testing"
"time"
)
func TestSuccess(t *testing.T) {
r := New(
2019-01-17 07:54:39 +03:00
WithStdLogger(),
WithContext(context.Background()),
)
2018-12-05 00:48:33 +03:00
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()
2018-12-05 00:48:33 +03:00
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()
2018-12-05 00:48:33 +03:00
cc := false
r.Go(func(ctx context.Context) error {
<-time.After(1 * time.Second)
return nil
}, ShutdownIfDone)
2018-12-05 00:48:33 +03:00
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")
}
}, ShutdownIfDone)
2018-12-05 00:48:33 +03:00
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")
}
}