Drop close in timed call.

This commit is contained in:
jregan
2020-12-28 07:14:23 -08:00
parent 90654b39bf
commit 99c9edfc3d
6 changed files with 104 additions and 39 deletions

View File

@@ -0,0 +1,36 @@
// Copyright 2020 The Kubernetes Authors.
// SPDX-License-Identifier: Apache-2.0
package utils
import (
"fmt"
"time"
"github.com/pkg/errors"
)
type errTimeOut struct {
duration time.Duration
cmd string
}
func NewErrTimeOut(d time.Duration, c string) errTimeOut {
return errTimeOut{duration: d, cmd: c}
}
func (e errTimeOut) Error() string {
return fmt.Sprintf("hit %s timeout running '%s'", e.duration, e.cmd)
}
func IsErrTimeout(err error) bool {
if err == nil {
return false
}
_, ok := err.(errTimeOut)
if ok {
return true
}
_, ok = errors.Cause(err).(errTimeOut)
return ok
}

View File

@@ -0,0 +1,23 @@
// Copyright 2020 The Kubernetes Authors.
// SPDX-License-Identifier: Apache-2.0
package utils
import (
"time"
)
// TimedCall runs fn, failing if it doesn't complete in the given duration.
// The description is used in the timeout error message.
func TimedCall(description string, d time.Duration, fn func() error) error {
done := make(chan error)
timer := time.NewTimer(d)
defer timer.Stop()
go func() { done <- fn() }()
select {
case err := <-done:
return err
case <-timer.C:
return NewErrTimeOut(d, description)
}
}

View File

@@ -0,0 +1,64 @@
// Copyright 2020 The Kubernetes Authors.
// SPDX-License-Identifier: Apache-2.0
package utils_test
import (
"fmt"
"testing"
"time"
"github.com/stretchr/testify/assert"
. "sigs.k8s.io/kustomize/api/internal/utils"
)
const (
timeToWait = 10 * time.Millisecond
tooSlow = 2 * timeToWait
)
func errMsg(msg string) string {
return fmt.Sprintf("hit %s timeout running '%s'", timeToWait, msg)
}
func TestTimedCallFastNoError(t *testing.T) {
err := TimedCall(
"fast no error", timeToWait,
func() error { return nil })
if !assert.NoError(t, err) {
t.Fatal(err)
}
}
func TestTimedCallFastWithError(t *testing.T) {
err := TimedCall(
"fast with error", timeToWait,
func() error { return assert.AnError })
if assert.Error(t, err) {
assert.EqualError(t, err, assert.AnError.Error())
} else {
t.Fail()
}
}
func TestTimedCallSlowNoError(t *testing.T) {
err := TimedCall(
"slow no error", timeToWait,
func() error { time.Sleep(tooSlow); return nil })
if assert.Error(t, err) {
assert.EqualError(t, err, errMsg("slow no error"))
} else {
t.Fail()
}
}
func TestTimedCallSlowWithError(t *testing.T) {
err := TimedCall(
"slow with error", timeToWait,
func() error { time.Sleep(tooSlow); return assert.AnError })
if assert.Error(t, err) {
assert.EqualError(t, err, errMsg("slow with error"))
} else {
t.Fail()
}
}