Debian Codegraph @

test/helper_test.go

raw
1 // Copyright 2015-2026 The NATS Authors
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 package test
15
16 import (
17 "errors"
18 "fmt"
19 "runtime"
20 "strings"
21 "testing"
22 "time"
23 )
24
25 // Dumb wait program to sync on callbacks, etc... Will timeout
26 func Wait(ch chan bool) error {
27 return WaitTime(ch, 5*time.Second)
28 }
29
30 // Wait for a chan with a timeout.
31 func WaitTime(ch chan bool, timeout time.Duration) error {
32 select {
33 case <-ch:
34 return nil
35 case <-time.After(timeout):
36 }
37 return errors.New("timeout")
38 }
39
40 func WaitOnChannel[T comparable](t *testing.T, ch <-chan T, expected T) {
41 t.Helper()
42 select {
43 case s := <-ch:
44 if s != expected {
45 t.Fatalf("Expected result: %v; got: %v", expected, s)
46 }
47 case <-time.After(5 * time.Second):
48 t.Fatalf("Timeout waiting for result %v", expected)
49 }
50 }
51
52 func stackFatalf(t testing.TB, f string, args ...any) {
53 t.Helper()
54 lines := make([]string, 0, 32)
55 msg := fmt.Sprintf(f, args...)
56 lines = append(lines, msg)
57
58 // Generate the Stack of callers: Skip us and verify* frames.
59 for i := 1; true; i++ {
60 _, file, line, ok := runtime.Caller(i)
61 if !ok {
62 break
63 }
64 msg := fmt.Sprintf("%d - %s:%d", i, file, line)
65 lines = append(lines, msg)
66 }
67 t.Fatalf("%s", strings.Join(lines, "\n"))
68 }
69
70 // getStableNumGoroutine returns runtime.NumGoroutine() once the count is
71 // observed stable for several consecutive samples. Used by goroutine-leak
72 // tests to take a stable baseline.
73 func getStableNumGoroutine(t *testing.T) int {
74 t.Helper()
75 timeout := time.Now().Add(2 * time.Second)
76 var base, old, same int
77 for time.Now().Before(timeout) {
78 base = runtime.NumGoroutine()
79 if old == base {
80 same++
81 if same == 5 {
82 return base
83 }
84 } else {
85 same = 0
86 }
87 old = base
88 time.Sleep(50 * time.Millisecond)
89 }
90 t.Fatalf("Unable to get stable number of go routines")
91 return 0
92 }
93
94 // checkNoGoroutineLeak asserts the goroutine count returns to base within
95 // 2 seconds; otherwise reports the delta.
96 func checkNoGoroutineLeak(t *testing.T, base int, action string) {
97 t.Helper()
98 waitFor(t, 2*time.Second, 100*time.Millisecond, func() error {
99 delta := (runtime.NumGoroutine() - base)
100 if delta > 0 {
101 return fmt.Errorf("%d Go routines still exist after %s", delta, action)
102 }
103 return nil
104 })
105 }
106
107 // checkErrChannel polls the error channel non-blockingly; if an error is
108 // present, fails the test with it. Supports patterns where the producer may
109 // send nil to signal absence-of-error.
110 func checkErrChannel(t *testing.T, errCh chan error) {
111 t.Helper()
112 select {
113 case e := <-errCh:
114 if e != nil {
115 t.Fatal(e.Error())
116 }
117 default:
118 }
119 }
120
121 // waitFor retries f every sleepDur up to totalWait, failing the test with the
122 // last non-nil error if f never returns nil.
123 func waitFor(t *testing.T, totalWait, sleepDur time.Duration, f func() error) {
124 t.Helper()
125 timeout := time.Now().Add(totalWait)
126 var err error
127 for time.Now().Before(timeout) {
128 err = f()
129 if err == nil {
130 return
131 }
132 time.Sleep(sleepDur)
133 }
134 if err != nil {
135 t.Fatal(err.Error())
136 }
137 }
138
139 // checkFor is an alias for waitFor used by JetStream-flavored tests; both
140 // signatures exist in the historical code base, kept for callers'
141 // convenience.
142 func checkFor(t *testing.T, totalWait, sleepDur time.Duration, f func() error) {
143 t.Helper()
144 waitFor(t, totalWait, sleepDur, f)
145 }