Improve closing mock webserver when failed to start (#52943)

Fix NPE when closing a webserver that hasn't started correctly.

This can happen when ssl context isn't initialized. The server instance is then never set,
which causes an NPE that masks the actual failure.

Example stacktrace that would mask an actual failure:

```
java.lang.NullPointerException
	at org.elasticsearch.test.http.MockWebServer.close(MockWebServer.java:271)
	at org.elasticsearch.xpack.watcher.test.integration.HttpSecretsIntegrationTests.cleanup(HttpSecretsIntegrationTests.java:70)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:498)
```
This commit is contained in:
Martijn van Groningen 2020-03-02 07:16:34 +01:00
parent 712191f2af
commit d102158e6f
No known key found for this signature in database
GPG Key ID: AB236F4FCF2AF12A
2 changed files with 8 additions and 4 deletions

View File

@ -268,11 +268,13 @@ public class MockWebServer implements Closeable {
logger.debug("[{}:{}] Counting down all latches before terminating executor", getHostName(), getPort());
latches.forEach(CountDownLatch::countDown);
if (server != null) {
if (server.getExecutor() instanceof ExecutorService) {
terminate((ExecutorService) server.getExecutor());
}
server.stop(0);
}
}
/**
* Helper method to return the first 20 chars of a request's body

View File

@ -72,8 +72,10 @@ public class WebhookHttpsIntegrationTests extends AbstractWatcherIntegrationTest
@After
public void stopWebservice() throws Exception {
if (webServer != null) {
webServer.close();
}
}
public void testHttps() throws Exception {
webServer.enqueue(new MockResponse().setResponseCode(200).setBody("body"));