| 1 |
// Copyright 2020 The Kubernetes Authors. |
| 2 |
// SPDX-License-Identifier: Apache-2.0 |
| 3 |
|
| 4 |
package utils_test |
| 5 |
|
| 6 |
import ( |
| 7 |
"fmt" |
| 8 |
"testing" |
| 9 |
"time" |
| 10 |
|
| 11 |
"github.com/stretchr/testify/assert" |
| 12 |
"go.uber.org/goleak" |
| 13 |
. "sigs.k8s.io/kustomize/api/internal/utils" |
| 14 |
) |
| 15 |
|
| 16 |
const ( |
| 17 |
timeToWait = 10 * time.Millisecond |
| 18 |
tooSlow = 2 * timeToWait |
| 19 |
) |
| 20 |
|
| 21 |
func errMsg(msg string) string { |
| 22 |
return fmt.Sprintf("hit %s timeout running '%s'", timeToWait, msg) |
| 23 |
} |
| 24 |
|
| 25 |
func TestTimedCallFastNoError(t *testing.T) { |
| 26 |
err := TimedCall( |
| 27 |
"fast no error", timeToWait, |
| 28 |
func() error { return nil }) |
| 29 |
if !assert.NoError(t, err) { |
| 30 |
t.Fatal(err) |
| 31 |
} |
| 32 |
} |
| 33 |
|
| 34 |
func TestTimedCallFastWithError(t *testing.T) { |
| 35 |
err := TimedCall( |
| 36 |
"fast with error", timeToWait, |
| 37 |
func() error { return assert.AnError }) |
| 38 |
if assert.Error(t, err) { |
| 39 |
assert.EqualError(t, err, assert.AnError.Error()) |
| 40 |
} else { |
| 41 |
t.Fail() |
| 42 |
} |
| 43 |
} |
| 44 |
|
| 45 |
func TestTimedCallSlowNoError(t *testing.T) { |
| 46 |
err := TimedCall( |
| 47 |
"slow no error", timeToWait, |
| 48 |
func() error { time.Sleep(tooSlow); return nil }) |
| 49 |
if assert.Error(t, err) { |
| 50 |
assert.EqualError(t, err, errMsg("slow no error")) |
| 51 |
} else { |
| 52 |
t.Fail() |
| 53 |
} |
| 54 |
} |
| 55 |
|
| 56 |
func TestTimedCallSlowWithError(t *testing.T) { |
| 57 |
err := TimedCall( |
| 58 |
"slow with error", timeToWait, |
| 59 |
func() error { time.Sleep(tooSlow); return assert.AnError }) |
| 60 |
if assert.Error(t, err) { |
| 61 |
assert.EqualError(t, err, errMsg("slow with error")) |
| 62 |
} else { |
| 63 |
t.Fail() |
| 64 |
} |
| 65 |
} |
| 66 |
|
| 67 |
func TestTimedCallGoroutineLeak(t *testing.T) { |
| 68 |
defer goleak.VerifyNone(t) |
| 69 |
err := TimedCall("function done, no goroutine leaks", timeToWait, func() error { |
| 70 |
time.Sleep(tooSlow) |
| 71 |
return fmt.Errorf("function done") |
| 72 |
}) |
| 73 |
if assert.Error(t, err) { |
| 74 |
assert.EqualError(t, err, errMsg("function done, no goroutine leaks")) |
| 75 |
} else { |
| 76 |
t.Fail() |
| 77 |
} |
| 78 |
|
| 79 |
// The code introduces a 2-second sleep to allow the goroutine to complete its execution. |
| 80 |
// Subsequently, it verifies if the goroutine created by the function exits as expected. |
| 81 |
time.Sleep(tooSlow) |
| 82 |
} |