1
0
mirror of https://github.com/ipfs/kubo.git synced 2025-07-01 02:30:39 +08:00
This commit is contained in:
Brian Tiger Chow
2014-11-05 06:45:50 -08:00
parent 23096de3c4
commit ed247ec154
2 changed files with 57 additions and 0 deletions

15
util/do.go Normal file
View File

@ -0,0 +1,15 @@
package util
import "code.google.com/p/go.net/context"
func Do(ctx context.Context, f func() error) error {
ch := make(chan error)
go func() { ch <- f() }()
select {
case <-ctx.Done():
return ctx.Err()
case val := <-ch:
return val
}
return nil
}

42
util/do_test.go Normal file
View File

@ -0,0 +1,42 @@
package util
import (
"errors"
"testing"
"code.google.com/p/go.net/context"
)
func TestDoReturnsContextErr(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
ch := make(chan struct{})
err := Do(ctx, func() error {
cancel()
ch <- struct{}{} // won't return
return nil
})
if err != ctx.Err() {
t.Fail()
}
}
func TestDoReturnsFuncError(t *testing.T) {
ctx := context.Background()
expected := errors.New("expected to be returned by Do")
err := Do(ctx, func() error {
return expected
})
if err != expected {
t.Fail()
}
}
func TestDoReturnsNil(t *testing.T) {
ctx := context.Background()
err := Do(ctx, func() error {
return nil
})
if err != nil {
t.Fail()
}
}