...
1
16
17 package ktesting
18
19 import (
20 "context"
21 "time"
22
23 "github.com/onsi/gomega"
24 "k8s.io/klog/v2"
25 )
26
27
28
29
30 func WithCancel(tCtx TContext) TContext {
31 ctx, cancel := context.WithCancelCause(tCtx)
32 tCtx.Cleanup(func() {
33 cancel(cleanupErr(tCtx.Name()))
34 })
35
36 return withContext{
37 TContext: tCtx,
38 Context: ctx,
39 cancel: func(cause string) {
40 var cancelCause error
41 if cause != "" {
42 cancelCause = canceledError(cause)
43 }
44 cancel(cancelCause)
45 },
46 }
47 }
48
49
50
51
52
53
54 func WithTimeout(tCtx TContext, timeout time.Duration, timeoutCause string) TContext {
55 tCtx.Helper()
56 ctx, cancel := withTimeout(tCtx, tCtx.TB(), timeout, timeoutCause)
57
58 return withContext{
59 TContext: tCtx,
60 Context: ctx,
61 cancel: cancel,
62 }
63 }
64
65
66 func WithLogger(tCtx TContext, logger klog.Logger) TContext {
67 ctx := klog.NewContext(tCtx, logger)
68
69 return withContext{
70 TContext: tCtx,
71 Context: ctx,
72 cancel: tCtx.Cancel,
73 }
74 }
75
76
77
78
79 type withContext struct {
80 TContext
81 context.Context
82
83 cancel func(cause string)
84 }
85
86 func (wCtx withContext) Cancel(cause string) {
87 wCtx.cancel(cause)
88 }
89
90 func (wCtx withContext) CleanupCtx(cb func(TContext)) {
91 wCtx.Helper()
92 cleanupCtx(wCtx, cb)
93 }
94
95 func (wCtx withContext) Expect(actual interface{}, extra ...interface{}) gomega.Assertion {
96 wCtx.Helper()
97 return expect(wCtx, actual, extra...)
98 }
99
100 func (wCtx withContext) ExpectNoError(err error, explain ...interface{}) {
101 wCtx.Helper()
102 expectNoError(wCtx, err, explain...)
103 }
104
105 func (wCtx withContext) Logger() klog.Logger {
106 return klog.FromContext(wCtx)
107 }
108
109 func (wCtx withContext) Deadline() (time.Time, bool) {
110 return wCtx.Context.Deadline()
111 }
112
113 func (wCtx withContext) Done() <-chan struct{} {
114 return wCtx.Context.Done()
115 }
116
117 func (wCtx withContext) Err() error {
118 return wCtx.Context.Err()
119 }
120
121 func (wCtx withContext) Value(key any) any {
122 return wCtx.Context.Value(key)
123 }
124
View as plain text