File: timedcall_test.go

package info (click to toggle)
golang-k8s-sigs-kustomize-api 0.20.1%2Bds-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 3,768 kB
  • sloc: makefile: 206; sh: 67
file content (82 lines) | stat: -rw-r--r-- 1,930 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
// Copyright 2020 The Kubernetes Authors.
// SPDX-License-Identifier: Apache-2.0

package utils_test

import (
	"fmt"
	"testing"
	"time"

	"github.com/stretchr/testify/assert"
	"go.uber.org/goleak"
	. "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()
	}
}

func TestTimedCallGoroutineLeak(t *testing.T) {
	defer goleak.VerifyNone(t)
	err := TimedCall("function done, no goroutine leaks", timeToWait, func() error {
		time.Sleep(tooSlow)
		return fmt.Errorf("function done")
	})
	if assert.Error(t, err) {
		assert.EqualError(t, err, errMsg("function done, no goroutine leaks"))
	} else {
		t.Fail()
	}

	// The code introduces a 2-second sleep to allow the goroutine to complete its execution.
	// Subsequently, it verifies if the goroutine created by the function exits as expected.
	time.Sleep(tooSlow)
}