1818import static com .github .tomakehurst .wiremock .client .WireMock .getRequestedFor ;
1919import static com .github .tomakehurst .wiremock .client .WireMock .urlPathEqualTo ;
2020import static com .github .tomakehurst .wiremock .core .WireMockConfiguration .wireMockConfig ;
21+ import static org .awaitility .Awaitility .await ;
2122
22- import com .github .tomakehurst .wiremock .core .Admin ;
23- import com .github .tomakehurst .wiremock .extension .Parameters ;
24- import com .github .tomakehurst .wiremock .extension .PostServeAction ;
2523import com .github .tomakehurst .wiremock .junit5 .WireMockExtension ;
2624import com .github .tomakehurst .wiremock .matching .AnythingPattern ;
27- import com .github .tomakehurst .wiremock .stubbing . ServeEvent ;
25+ import com .github .tomakehurst .wiremock .matching . RequestPatternBuilder ;
2826import io .kubernetes .client .openapi .ApiClient ;
2927import io .kubernetes .client .openapi .ApiException ;
3028import io .kubernetes .client .openapi .models .V1ObjectMeta ;
4038import java .nio .file .Paths ;
4139import java .util .HashMap ;
4240import java .util .Map ;
43- import java .util .concurrent .CountDownLatch ;
4441import java .util .concurrent .TimeUnit ;
4542import org .junit .jupiter .api .BeforeEach ;
4643import org .junit .jupiter .api .Test ;
@@ -125,25 +122,59 @@ public InputStream copyFileFromPod(String namespace, String pod, String srcPath)
125122 }
126123 }
127124
128- public static class CountDownLatchAction extends PostServeAction {
129- @ Override
130- public String getName () {
131- return "countdown" ;
132- }
133-
134- @ Override
135- public void doAction (ServeEvent serveEvent , Admin admin , Parameters parameters ) {
136- CountDownLatch latch = (CountDownLatch ) parameters .get ("latch" );
137- latch .countDown ();
138- }
139- }
140-
141125 @ RegisterExtension
142126 static WireMockExtension apiServer =
143127 WireMockExtension .newInstance ()
144- .options (wireMockConfig ().dynamicPort (). extensions ( new CountDownLatchAction ()) )
128+ .options (wireMockConfig ().dynamicPort ())
145129 .build ();
146130
131+ private RequestPatternBuilder execRequest () {
132+ return getRequestedFor (
133+ urlPathEqualTo ("/api/v1/namespaces/" + namespace + "/pods/" + podName + "/exec" ));
134+ }
135+
136+ private void stubExecNotFound () {
137+ apiServer .stubFor (
138+ get (urlPathEqualTo ("/api/v1/namespaces/" + namespace + "/pods/" + podName + "/exec" ))
139+ .willReturn (
140+ aResponse ()
141+ .withStatus (404 )
142+ .withHeader ("Content-Type" , "application/json" )
143+ .withBody ("{}" )));
144+ }
145+
146+ /**
147+ * Runs the given action on a background thread, waits until WireMock has recorded an exec
148+ * request, then stops the thread and waits for it to terminate so it cannot leak into later
149+ * tests.
150+ */
151+ private void runUntilExecRequested (ThrowingRunnable action ) throws InterruptedException {
152+ Thread t =
153+ new Thread (
154+ () -> {
155+ try {
156+ action .run ();
157+ } catch (Exception ex ) {
158+ // Expected: the mock server rejects the websocket upgrade.
159+ }
160+ });
161+ t .start ();
162+ try {
163+ await ()
164+ .atMost (30 , TimeUnit .SECONDS )
165+ .until (() -> !apiServer .findAll (execRequest ()).isEmpty ());
166+ } finally {
167+ t .interrupt ();
168+ t .join (TimeUnit .SECONDS .toMillis (30 ));
169+ }
170+ assertFalse (t .isAlive (), "background copy thread did not terminate" );
171+ }
172+
173+ @ FunctionalInterface
174+ private interface ThrowingRunnable {
175+ void run () throws Exception ;
176+ }
177+
147178 @ BeforeEach
148179 void setup () {
149180 client = new ClientBuilder ().setBasePath ("http://localhost:" + apiServer .getPort ()).build ();
@@ -187,46 +218,19 @@ void url() {
187218
188219 @ Test
189220 void copyFileToPod (@ TempDir Path tempDir ) throws Exception {
190-
191221 Path testFile = Files .createTempFile (tempDir , "testfile" , null );
192222
193223 Copy copy = new Copy (client );
194224
195- CountDownLatch latch = new CountDownLatch (1 );
196- Parameters params = new Parameters ();
197- params .put ("latch" , latch );
225+ stubExecNotFound ();
198226
199- apiServer .stubFor (
200- get (urlPathEqualTo ("/api/v1/namespaces/" + namespace + "/pods/" + podName + "/exec" ))
201- .withPostServeAction ("countdown" , params )
202- .willReturn (
203- aResponse ()
204- .withStatus (404 )
205- .withHeader ("Content-Type" , "application/json" )
206- .withBody ("{}" )));
207-
208- // When attempting to write to the process outputstream in copyFileToPod, the
209- // WebSocketStreamHandler is in a wait state because no websocket is created by mock, which
210- // blocks the main thread. So here we execute the method in a thread.
211- Thread t =
212- new Thread (
213- new Runnable () {
214- public void run () {
215- try {
216- copy .copyFileToPod (
217- namespace , podName , "" , testFile , Paths .get ("/copied-testfile" ));
218- } catch (IOException | ApiException ex ) {
219- ex .printStackTrace ();
220- }
221- }
222- });
223- t .start ();
224- assertTrue (latch .await (30 , TimeUnit .SECONDS ));
225- t .interrupt ();
227+ // The mock server never upgrades to a websocket, so run the copy in the background and only
228+ // wait for the exec request to reach the server.
229+ runUntilExecRequested (
230+ () -> copy .copyFileToPod (namespace , podName , "" , testFile , Paths .get ("/copied-testfile" )));
226231
227232 apiServer .verify (
228- getRequestedFor (
229- urlPathEqualTo ("/api/v1/namespaces/" + namespace + "/pods/" + podName + "/exec" ))
233+ execRequest ()
230234 .withQueryParam ("stdin" , equalTo ("true" ))
231235 .withQueryParam ("stdout" , equalTo ("true" ))
232236 .withQueryParam ("stderr" , equalTo ("true" ))
@@ -238,46 +242,17 @@ public void run() {
238242
239243 @ Test
240244 void copyBinaryDataToPod () throws InterruptedException {
241-
242245 byte [] testSrc = new byte [0 ];
243246
244247 Copy copy = new Copy (client );
245248
246- CountDownLatch latch = new CountDownLatch (1 );
247- Parameters params = new Parameters ();
248- params .put ("latch" , latch );
249-
250- apiServer .stubFor (
251- get (urlPathEqualTo ("/api/v1/namespaces/" + namespace + "/pods/" + podName + "/exec" ))
252- .withPostServeAction ("countdown" , params )
253- .willReturn (
254- aResponse ()
255- .withStatus (404 )
256- .withHeader ("Content-Type" , "application/json" )
257- .withBody ("{}" )));
249+ stubExecNotFound ();
258250
259- // When attempting to write to the process outputstream in copyFileToPod, the
260- // WebSocketStreamHandler is in a wait state because no websocket is created by mock, which
261- // blocks the main thread. So here we execute the method in a thread.
262- Thread t =
263- new Thread (
264- new Runnable () {
265- public void run () {
266- try {
267- copy .copyFileToPod (
268- namespace , podName , "" , testSrc , Paths .get ("/copied-binarydata" ));
269- } catch (IOException | ApiException ex ) {
270- ex .printStackTrace ();
271- }
272- }
273- });
274- t .start ();
275- assertTrue (latch .await (30 , TimeUnit .SECONDS ));
276- t .interrupt ();
251+ runUntilExecRequested (
252+ () -> copy .copyFileToPod (namespace , podName , "" , testSrc , Paths .get ("/copied-binarydata" )));
277253
278254 apiServer .verify (
279- getRequestedFor (
280- urlPathEqualTo ("/api/v1/namespaces/" + namespace + "/pods/" + podName + "/exec" ))
255+ execRequest ()
281256 .withQueryParam ("stdin" , equalTo ("true" ))
282257 .withQueryParam ("stdout" , equalTo ("true" ))
283258 .withQueryParam ("stderr" , equalTo ("true" ))
@@ -291,42 +266,15 @@ public void run() {
291266 void testCopyDirectoryFromPod (@ TempDir Path tempDir ) throws Exception {
292267 Copy copy = new Copy (client );
293268
294- CountDownLatch latch = new CountDownLatch (1 );
295- Parameters params = new Parameters ();
296- params .put ("latch" , latch );
297-
298- apiServer .stubFor (
299- get (urlPathEqualTo ("/api/v1/namespaces/" + namespace + "/pods/" + podName + "/exec" ))
300- .withPostServeAction ("countdown" , params )
301- .willReturn (
302- aResponse ()
303- .withStatus (404 )
304- .withHeader ("Content-Type" , "application/json" )
305- .withBody ("{}" )));
269+ stubExecNotFound ();
306270
307- Thread t =
308- new Thread (
309- new Runnable () {
310- public void run () {
311- try {
312- copy .copyDirectoryFromPod (
313- namespace ,
314- podName ,
315- "" ,
316- tempDir .toString (),
317- Paths .get ("/copied-testDir" ));
318- } catch (IOException | ApiException | CopyNotSupportedException ex ) {
319- ex .printStackTrace ();
320- }
321- }
322- });
323- t .start ();
324- assertTrue (latch .await (30 , TimeUnit .SECONDS ));
325- t .interrupt ();
271+ runUntilExecRequested (
272+ () ->
273+ copy .copyDirectoryFromPod (
274+ namespace , podName , "" , tempDir .toString (), Paths .get ("/copied-testDir" )));
326275
327276 apiServer .verify (
328- getRequestedFor (
329- urlPathEqualTo ("/api/v1/namespaces/" + namespace + "/pods/" + podName + "/exec" ))
277+ execRequest ()
330278 .withQueryParam ("stdin" , equalTo ("false" ))
331279 .withQueryParam ("stdout" , equalTo ("true" ))
332280 .withQueryParam ("stderr" , equalTo ("true" ))
0 commit comments