Skip to content

Commit 7a2873b

Browse files
committed
better kill testing
1 parent 53e9727 commit 7a2873b

File tree

2 files changed

+47
-1
lines changed

2 files changed

+47
-1
lines changed

src/main/java/org/htmlunit/javascript/background/DefaultJavaScriptExecutor.java

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -102,7 +102,13 @@ private void killThread() {
102102
}
103103

104104
// Stop the thread
105-
eventLoopThread_.stop();
105+
try {
106+
eventLoopThread_.stop();
107+
}
108+
catch (final Exception e) {
109+
LOG.warn("JS thread did not interrupt after 10s, maybe there is an endless loop."
110+
+ "Please consider setting an JavaScriptTimeout for the WebClient.", e);
111+
}
106112
}
107113
}
108114

@@ -174,6 +180,8 @@ public void run() {
174180
catch (final InterruptedException e) {
175181
// restore interrupted status
176182
Thread.currentThread().interrupt();
183+
184+
break;
177185
}
178186
}
179187
}

src/test/java/org/htmlunit/javascript/JavaScriptEngineTest.java

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1182,6 +1182,44 @@ public void shutdownShouldKill() throws Exception {
11821182
+ "</body></html>";
11831183

11841184
try (WebClient webClient = getWebClient()) {
1185+
// there is no way to kill a thread in later JDK's
1186+
// to make the test running we need a final timeout for js stuff
1187+
webClient.setJavaScriptTimeout(DEFAULT_WAIT_TIME * 20);
1188+
1189+
final List<String> collectedAlerts = new ArrayList<>();
1190+
webClient.setAlertHandler(new CollectingAlertHandler(collectedAlerts));
1191+
1192+
loadPage(html);
1193+
Thread.sleep(100);
1194+
assertEquals(getExpectedAlerts(), collectedAlerts);
1195+
1196+
}
1197+
Thread.sleep(400);
1198+
assertTrue(getJavaScriptThreads().isEmpty());
1199+
}
1200+
1201+
/**
1202+
* @throws Exception if the test fails
1203+
*/
1204+
@Test
1205+
@Retry
1206+
@Alerts("starting")
1207+
public void shutdownShouldKillJavaScriptTimeout() throws Exception {
1208+
final String html = "<html>\n"
1209+
+ "<head><title>Test page</title>\n"
1210+
+ "<script>\n"
1211+
+ " function test() {\n"
1212+
+ " alert('starting');\n"
1213+
+ " while(true) { Math.sin(3.14) * Math.sin(3.14);}\n"
1214+
+ " }\n"
1215+
+ "</script>\n"
1216+
+ "</head>\n"
1217+
+ "<body onload='setTimeout(test, 50);'>\n"
1218+
+ "</body></html>";
1219+
1220+
try (WebClient webClient = getWebClient()) {
1221+
webClient.setJavaScriptTimeout(DEFAULT_WAIT_TIME);
1222+
11851223
final List<String> collectedAlerts = new ArrayList<>();
11861224
webClient.setAlertHandler(new CollectingAlertHandler(collectedAlerts));
11871225

0 commit comments

Comments
 (0)