@@ -23,6 +23,7 @@ import (
23
23
"net/http"
24
24
"net/url"
25
25
"os"
26
+ "sync"
26
27
"time"
27
28
28
29
"github.com/kubernetes-incubator/cri-tools/pkg/framework"
@@ -190,20 +191,42 @@ func createDefaultAttach(c internalapi.RuntimeService, containerID string) strin
190
191
return resp .Url
191
192
}
192
193
194
+ // safeBuffer is a goroutine safe bytes.Buffer
195
+ type safeBuffer struct {
196
+ mu sync.Mutex
197
+ buffer bytes.Buffer
198
+ }
199
+
200
+ // Write appends the contents of p to the buffer, growing the buffer as needed. It returns
201
+ // the number of bytes written.
202
+ func (s * safeBuffer ) Write (p []byte ) (n int , err error ) {
203
+ s .mu .Lock ()
204
+ defer s .mu .Unlock ()
205
+ return s .buffer .Write (p )
206
+ }
207
+
208
+ // String returns the contents of the unread portion of the buffer
209
+ // as a string. If the Buffer is a nil pointer, it returns "<nil>".
210
+ func (s * safeBuffer ) String () string {
211
+ s .mu .Lock ()
212
+ defer s .mu .Unlock ()
213
+ return s .buffer .String ()
214
+ }
215
+
193
216
func checkAttach (c internalapi.RuntimeService , attachServerURL string ) {
194
- localOut := & bytes.Buffer {}
217
+ localOut := & safeBuffer { buffer : bytes.Buffer {} }
195
218
localErr := & bytes.Buffer {}
196
219
reader , writer := io .Pipe ()
197
- var out string
198
-
199
220
go func () {
200
221
defer GinkgoRecover ()
222
+ defer writer .Close ()
201
223
writer .Write ([]byte ("echo hello\n " ))
202
224
Eventually (func () string {
203
- out = localOut .String ()
204
- return out
205
- }, time .Minute , time .Second ).ShouldNot (BeEmpty ())
206
- writer .Close ()
225
+ return localOut .String ()
226
+ }, time .Minute , time .Second ).Should (Equal ("hello\n " ), "The stdout of attach should be hello" )
227
+ Consistently (func () string {
228
+ return localOut .String ()
229
+ }, 3 * time .Second , time .Second ).Should (Equal ("hello\n " ), "The stdout of attach should not contain other things" )
207
230
}()
208
231
209
232
// Only http is supported now.
@@ -220,7 +243,6 @@ func checkAttach(c internalapi.RuntimeService, attachServerURL string) {
220
243
})
221
244
framework .ExpectNoError (err , "failed to open streamer for %q" , attachServerURL )
222
245
223
- Expect (out ).To (Equal ("hello\n " ), "The stdout of exec should be hello" )
224
246
Expect (localErr .String ()).To (BeEmpty (), "The stderr of attach should be empty" )
225
247
framework .Logf ("Check attach url %q succeed" , attachServerURL )
226
248
}
0 commit comments