mirror of
https://github.com/ipfs/kubo.git
synced 2025-07-01 19:24:14 +08:00
add do
This commit is contained in:
15
util/do.go
Normal file
15
util/do.go
Normal 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
42
util/do_test.go
Normal 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()
|
||||||
|
}
|
||||||
|
}
|
Reference in New Issue
Block a user