Browse Source

Rename assertThrows to prevent naming clash (#52582)

This commit renames ElasticsearchAssertions#assertThrows to
assertRequestBuilderThrows and assertFutureThrows to avoid a
naming clash with JUnit 4.13+ and static imports of these methods.
Additionally, these methods have been updated to make use of
expectThrows internally to avoid duplicating the logic there.

Relates #51787
Jay Modi 5 years ago
parent
commit
f83d75d255
18 changed files with 138 additions and 141 deletions
  1. 2 2
      server/src/test/java/org/elasticsearch/action/admin/cluster/node/tasks/TasksIT.java
  2. 2 2
      server/src/test/java/org/elasticsearch/action/admin/indices/create/CreateIndexIT.java
  3. 2 2
      server/src/test/java/org/elasticsearch/action/termvectors/GetTermVectorsIT.java
  4. 9 9
      server/src/test/java/org/elasticsearch/cluster/NoMasterNodeIT.java
  5. 3 2
      server/src/test/java/org/elasticsearch/indices/settings/UpdateSettingsIT.java
  6. 3 3
      server/src/test/java/org/elasticsearch/indices/template/SimpleIndexTemplateIT.java
  7. 10 10
      server/src/test/java/org/elasticsearch/persistent/PersistentTasksExecutorIT.java
  8. 2 2
      server/src/test/java/org/elasticsearch/repositories/blobstore/BlobStoreRepositoryCleanupIT.java
  9. 7 7
      server/src/test/java/org/elasticsearch/search/morelikethis/MoreLikeThisIT.java
  10. 6 6
      server/src/test/java/org/elasticsearch/search/scroll/SearchScrollIT.java
  11. 4 4
      server/src/test/java/org/elasticsearch/search/suggest/SuggestSearchIT.java
  12. 4 3
      server/src/test/java/org/elasticsearch/snapshots/DedicatedClusterSnapshotRestoreIT.java
  13. 5 5
      server/src/test/java/org/elasticsearch/snapshots/RepositoriesIT.java
  14. 6 6
      server/src/test/java/org/elasticsearch/snapshots/SharedClusterSnapshotRestoreIT.java
  15. 2 2
      server/src/test/java/org/elasticsearch/update/UpdateIT.java
  16. 34 24
      server/src/test/java/org/elasticsearch/versioning/SimpleVersioningIT.java
  17. 35 50
      test/framework/src/main/java/org/elasticsearch/test/hamcrest/ElasticsearchAssertions.java
  18. 2 2
      x-pack/plugin/security/src/test/java/org/elasticsearch/integration/SecurityClearScrollTests.java

+ 2 - 2
server/src/test/java/org/elasticsearch/action/admin/cluster/node/tasks/TasksIT.java

@@ -85,9 +85,9 @@ import static java.util.Collections.singleton;
 import static org.elasticsearch.common.unit.TimeValue.timeValueMillis;
 import static org.elasticsearch.common.unit.TimeValue.timeValueSeconds;
 import static org.elasticsearch.http.HttpTransportSettings.SETTING_HTTP_MAX_HEADER_SIZE;
+import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertFutureThrows;
 import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertNoFailures;
 import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertSearchResponse;
-import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertThrows;
 import static org.hamcrest.Matchers.allOf;
 import static org.hamcrest.Matchers.containsString;
 import static org.hamcrest.Matchers.empty;
@@ -786,7 +786,7 @@ public class TasksIT extends ESIntegTestCase {
         request.setShouldBlock(false);
 
         // Start non-blocking test task that should fail
-        assertThrows(
+        assertFutureThrows(
             client().execute(TestTaskPlugin.TestTaskAction.INSTANCE, request),
             IllegalStateException.class
         );

+ 2 - 2
server/src/test/java/org/elasticsearch/action/admin/indices/create/CreateIndexIT.java

@@ -52,7 +52,7 @@ import java.util.function.BiFunction;
 import static org.elasticsearch.cluster.metadata.IndexMetaData.SETTING_WAIT_FOR_ACTIVE_SHARDS;
 import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked;
 import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertBlocked;
-import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertThrows;
+import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertRequestBuilderThrows;
 import static org.hamcrest.Matchers.allOf;
 import static org.hamcrest.Matchers.equalTo;
 import static org.hamcrest.Matchers.greaterThanOrEqualTo;
@@ -303,7 +303,7 @@ public class CreateIndexIT extends ESIntegTestCase {
             .addAlias(new Alias("alias1").writeIndex(true))
             .get());
 
-        assertThrows(client().admin().indices().prepareCreate("test-idx-2")
+        assertRequestBuilderThrows(client().admin().indices().prepareCreate("test-idx-2")
                 .setSettings(settings)
                 .addAlias(new Alias("alias1").writeIndex(true)),
             IllegalStateException.class);

+ 2 - 2
server/src/test/java/org/elasticsearch/action/termvectors/GetTermVectorsIT.java

@@ -55,7 +55,7 @@ import java.util.stream.Collectors;
 
 import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;
 import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked;
-import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertThrows;
+import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertRequestBuilderThrows;
 import static org.hamcrest.Matchers.equalTo;
 import static org.hamcrest.Matchers.notNullValue;
 import static org.hamcrest.Matchers.nullValue;
@@ -368,7 +368,7 @@ public class GetTermVectorsIT extends AbstractTermVectorsTestCase {
         for (TestConfig test : testConfigs) {
             TermVectorsRequestBuilder request = getRequestForConfig(test);
             if (test.expectedException != null) {
-                assertThrows(request, test.expectedException);
+                assertRequestBuilderThrows(request, test.expectedException);
                 continue;
             }
 

+ 9 - 9
server/src/test/java/org/elasticsearch/cluster/NoMasterNodeIT.java

@@ -53,7 +53,7 @@ import java.util.List;
 
 import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertExists;
 import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertHitCount;
-import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertThrows;
+import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertRequestBuilderThrows;
 import static org.hamcrest.Matchers.equalTo;
 import static org.hamcrest.Matchers.greaterThan;
 
@@ -96,35 +96,35 @@ public class NoMasterNodeIT extends ESIntegTestCase {
             assertTrue(state.blocks().hasGlobalBlockWithId(NoMasterBlockService.NO_MASTER_BLOCK_ID));
         });
 
-        assertThrows(clientToMasterlessNode.prepareGet("test", "1"),
+        assertRequestBuilderThrows(clientToMasterlessNode.prepareGet("test", "1"),
             ClusterBlockException.class, RestStatus.SERVICE_UNAVAILABLE
         );
 
-        assertThrows(clientToMasterlessNode.prepareGet("no_index", "1"),
+        assertRequestBuilderThrows(clientToMasterlessNode.prepareGet("no_index", "1"),
             ClusterBlockException.class, RestStatus.SERVICE_UNAVAILABLE
         );
 
-        assertThrows(clientToMasterlessNode.prepareMultiGet().add("test", "1"),
+        assertRequestBuilderThrows(clientToMasterlessNode.prepareMultiGet().add("test", "1"),
             ClusterBlockException.class, RestStatus.SERVICE_UNAVAILABLE
         );
 
-        assertThrows(clientToMasterlessNode.prepareMultiGet().add("no_index", "1"),
+        assertRequestBuilderThrows(clientToMasterlessNode.prepareMultiGet().add("no_index", "1"),
             ClusterBlockException.class, RestStatus.SERVICE_UNAVAILABLE
         );
 
-        assertThrows(clientToMasterlessNode.admin().indices().prepareAnalyze("test", "this is a test"),
+        assertRequestBuilderThrows(clientToMasterlessNode.admin().indices().prepareAnalyze("test", "this is a test"),
             ClusterBlockException.class, RestStatus.SERVICE_UNAVAILABLE
         );
 
-        assertThrows(clientToMasterlessNode.admin().indices().prepareAnalyze("no_index", "this is a test"),
+        assertRequestBuilderThrows(clientToMasterlessNode.admin().indices().prepareAnalyze("no_index", "this is a test"),
             ClusterBlockException.class, RestStatus.SERVICE_UNAVAILABLE
         );
 
-        assertThrows(clientToMasterlessNode.prepareSearch("test").setSize(0),
+        assertRequestBuilderThrows(clientToMasterlessNode.prepareSearch("test").setSize(0),
             ClusterBlockException.class, RestStatus.SERVICE_UNAVAILABLE
         );
 
-        assertThrows(clientToMasterlessNode.prepareSearch("no_index").setSize(0),
+        assertRequestBuilderThrows(clientToMasterlessNode.prepareSearch("no_index").setSize(0),
             ClusterBlockException.class, RestStatus.SERVICE_UNAVAILABLE
         );
 

+ 3 - 2
server/src/test/java/org/elasticsearch/indices/settings/UpdateSettingsIT.java

@@ -45,7 +45,7 @@ import static org.elasticsearch.cluster.metadata.IndexMetaData.SETTING_BLOCKS_WR
 import static org.elasticsearch.cluster.metadata.IndexMetaData.SETTING_READ_ONLY;
 import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked;
 import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertBlocked;
-import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertThrows;
+import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertRequestBuilderThrows;
 import static org.hamcrest.Matchers.containsString;
 import static org.hamcrest.Matchers.equalTo;
 import static org.hamcrest.Matchers.greaterThan;
@@ -452,7 +452,8 @@ public class UpdateSettingsIT extends ESIntegTestCase {
         client().prepareIndex("test").setId("1").setSource("f", 1).setVersionType(VersionType.EXTERNAL).setVersion(1).get();
         client().prepareDelete("test", "1").setVersionType(VersionType.EXTERNAL).setVersion(2).get();
         // delete is still in cache this should fail
-        assertThrows(client().prepareIndex("test").setId("1").setSource("f", 3).setVersionType(VersionType.EXTERNAL).setVersion(1),
+        assertRequestBuilderThrows(
+            client().prepareIndex("test").setId("1").setSource("f", 3).setVersionType(VersionType.EXTERNAL).setVersion(1),
             VersionConflictEngineException.class);
 
         assertAcked(client().admin().indices().prepareUpdateSettings("test").setSettings(Settings.builder().put("index.gc_deletes", 0)));

+ 3 - 3
server/src/test/java/org/elasticsearch/indices/template/SimpleIndexTemplateIT.java

@@ -56,7 +56,7 @@ import static org.elasticsearch.action.support.WriteRequest.RefreshPolicy.IMMEDI
 import static org.elasticsearch.index.query.QueryBuilders.termQuery;
 import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked;
 import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertHitCount;
-import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertThrows;
+import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertRequestBuilderThrows;
 import static org.hamcrest.Matchers.anyOf;
 import static org.hamcrest.Matchers.containsInAnyOrder;
 import static org.hamcrest.Matchers.containsString;
@@ -109,7 +109,7 @@ public class SimpleIndexTemplateIT extends ESIntegTestCase {
                 .get();
 
         // test create param
-        assertThrows(client().admin().indices().preparePutTemplate("template_2")
+        assertRequestBuilderThrows(client().admin().indices().preparePutTemplate("template_2")
                 .setPatterns(Collections.singletonList("test*"))
                 .setSettings(indexSettings())
                 .setCreate(true)
@@ -329,7 +329,7 @@ public class SimpleIndexTemplateIT extends ESIntegTestCase {
     }
 
     private void testExpectActionRequestValidationException(String... names) {
-        assertThrows(client().admin().indices().prepareGetTemplates(names),
+        assertRequestBuilderThrows(client().admin().indices().prepareGetTemplates(names),
                 ActionRequestValidationException.class,
                 "get template with " + Arrays.toString(names));
     }

+ 10 - 10
server/src/test/java/org/elasticsearch/persistent/PersistentTasksExecutorIT.java

@@ -25,16 +25,16 @@ import org.elasticsearch.action.support.PlainActionFuture;
 import org.elasticsearch.common.UUIDs;
 import org.elasticsearch.common.settings.Settings;
 import org.elasticsearch.common.unit.TimeValue;
-import org.elasticsearch.plugins.Plugin;
-import org.elasticsearch.tasks.TaskId;
-import org.elasticsearch.tasks.TaskInfo;
-import org.elasticsearch.test.ESIntegTestCase;
 import org.elasticsearch.persistent.PersistentTasksCustomMetaData.PersistentTask;
 import org.elasticsearch.persistent.PersistentTasksService.WaitForPersistentTaskListener;
 import org.elasticsearch.persistent.TestPersistentTasksPlugin.State;
-import org.elasticsearch.persistent.TestPersistentTasksPlugin.TestPersistentTasksExecutor;
 import org.elasticsearch.persistent.TestPersistentTasksPlugin.TestParams;
+import org.elasticsearch.persistent.TestPersistentTasksPlugin.TestPersistentTasksExecutor;
 import org.elasticsearch.persistent.TestPersistentTasksPlugin.TestTasksRequestBuilder;
+import org.elasticsearch.plugins.Plugin;
+import org.elasticsearch.tasks.TaskId;
+import org.elasticsearch.tasks.TaskInfo;
+import org.elasticsearch.test.ESIntegTestCase;
 import org.junit.After;
 import org.junit.Before;
 
@@ -43,7 +43,7 @@ import java.util.Collections;
 import java.util.List;
 import java.util.Objects;
 
-import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertThrows;
+import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertFutureThrows;
 import static org.hamcrest.Matchers.empty;
 import static org.hamcrest.Matchers.equalTo;
 import static org.hamcrest.Matchers.hasSize;
@@ -132,7 +132,7 @@ public class PersistentTasksExecutorIT extends ESIntegTestCase {
             //try sending completion request with incorrect allocation id
             PlainActionFuture<PersistentTask<?>> failedCompletionNotificationFuture = new PlainActionFuture<>();
             persistentTasksService.sendCompletionRequest(taskId, Long.MAX_VALUE, null, failedCompletionNotificationFuture);
-            assertThrows(failedCompletionNotificationFuture, ResourceNotFoundException.class);
+            assertFutureThrows(failedCompletionNotificationFuture, ResourceNotFoundException.class);
             // Make sure that the task is still running
             assertThat(client().admin().cluster().prepareListTasks().setActions(TestPersistentTasksExecutor.NAME + "[c]")
                     .setDetailed(true).get().getTasks().size(), equalTo(1));
@@ -240,11 +240,11 @@ public class PersistentTasksExecutorIT extends ESIntegTestCase {
         persistentTasksService.waitForPersistentTaskCondition(taskId,
                 task -> false, TimeValue.timeValueMillis(10), future1);
 
-        assertThrows(future1, IllegalStateException.class, "timed out after 10ms");
+        assertFutureThrows(future1, IllegalStateException.class, "timed out after 10ms");
 
         PlainActionFuture<PersistentTask<?>> failedUpdateFuture = new PlainActionFuture<>();
         persistentTasksService.sendUpdateStateRequest(taskId, -2, new State("should fail"), failedUpdateFuture);
-        assertThrows(failedUpdateFuture, ResourceNotFoundException.class, "the task with id " + taskId +
+        assertFutureThrows(failedUpdateFuture, ResourceNotFoundException.class, "the task with id " + taskId +
                 " and allocation id -2 doesn't exist");
 
         // Wait for the task to disappear
@@ -268,7 +268,7 @@ public class PersistentTasksExecutorIT extends ESIntegTestCase {
 
         PlainActionFuture<PersistentTask<TestParams>> future2 = new PlainActionFuture<>();
         persistentTasksService.sendStartRequest(taskId, TestPersistentTasksExecutor.NAME, new TestParams("Blah"), future2);
-        assertThrows(future2, ResourceAlreadyExistsException.class);
+        assertFutureThrows(future2, ResourceAlreadyExistsException.class);
 
         assertBusy(() -> {
             // Wait for the task to start

+ 2 - 2
server/src/test/java/org/elasticsearch/repositories/blobstore/BlobStoreRepositoryCleanupIT.java

@@ -35,7 +35,7 @@ import java.util.concurrent.ExecutionException;
 import java.util.concurrent.TimeUnit;
 
 import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked;
-import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertThrows;
+import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertFutureThrows;
 import static org.hamcrest.Matchers.is;
 
 @ESIntegTestCase.ClusterScope(scope = ESIntegTestCase.Scope.TEST, numDataNodes = 0)
@@ -59,7 +59,7 @@ public class BlobStoreRepositoryCleanupIT extends AbstractSnapshotIntegTestCase
         final String masterNode = startBlockedCleanup("test-repo");
 
         logger.info("-->  sending another cleanup");
-        assertThrows(client().admin().cluster().prepareCleanupRepository("test-repo").execute(), IllegalStateException.class);
+        assertFutureThrows(client().admin().cluster().prepareCleanupRepository("test-repo").execute(), IllegalStateException.class);
 
         logger.info("-->  ensure cleanup is still in progress");
         final RepositoryCleanupInProgress cleanup =

+ 7 - 7
server/src/test/java/org/elasticsearch/search/morelikethis/MoreLikeThisIT.java

@@ -54,9 +54,9 @@ import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcke
 import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertHitCount;
 import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertNoFailures;
 import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertOrderedSearchHits;
+import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertRequestBuilderThrows;
 import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertSearchHits;
 import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertSearchResponse;
-import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertThrows;
 import static org.hamcrest.Matchers.equalTo;
 import static org.hamcrest.Matchers.instanceOf;
 import static org.hamcrest.Matchers.notNullValue;
@@ -319,12 +319,12 @@ public class MoreLikeThisIT extends ESIntegTestCase {
         assertHitCount(searchResponse, 1L);
 
         // Explicit list of fields including numeric fields -> fail
-        assertThrows(client().prepareSearch().setQuery(
+        assertRequestBuilderThrows(client().prepareSearch().setQuery(
                 new MoreLikeThisQueryBuilder(new String[] {"string_value", "int_value"}, null,
                         new Item[] {new Item("test", "1")}).minTermFreq(1).minDocFreq(1)), SearchPhaseExecutionException.class);
 
         // mlt query with no field -> exception because _all is not enabled)
-        assertThrows(client().prepareSearch()
+        assertRequestBuilderThrows(client().prepareSearch()
             .setQuery(moreLikeThisQuery(new String[] {"index"}).minTermFreq(1).minDocFreq(1)),
             SearchPhaseExecutionException.class);
 
@@ -334,12 +334,12 @@ public class MoreLikeThisIT extends ESIntegTestCase {
         assertHitCount(searchResponse, 2L);
 
         // mlt query with at least a numeric field -> fail by default
-        assertThrows(client().prepareSearch().setQuery(
+        assertRequestBuilderThrows(client().prepareSearch().setQuery(
                 moreLikeThisQuery(new String[] {"string_value", "int_value"}, new String[] {"index"}, null)),
                 SearchPhaseExecutionException.class);
 
         // mlt query with at least a numeric field -> fail by command
-        assertThrows(client().prepareSearch().setQuery(
+        assertRequestBuilderThrows(client().prepareSearch().setQuery(
                 moreLikeThisQuery(new String[] {"string_value", "int_value"}, new String[] {"index"}, null).failOnUnsupportedField(true)),
                 SearchPhaseExecutionException.class);
 
@@ -351,12 +351,12 @@ public class MoreLikeThisIT extends ESIntegTestCase {
         assertHitCount(searchResponse, 2L);
 
         // mlt field query on a numeric field -> failure by default
-        assertThrows(client().prepareSearch().setQuery(
+        assertRequestBuilderThrows(client().prepareSearch().setQuery(
                 moreLikeThisQuery(new String[] {"int_value"}, new String[] {"42"}, null).minTermFreq(1).minDocFreq(1)),
                 SearchPhaseExecutionException.class);
 
         // mlt field query on a numeric field -> failure by command
-        assertThrows(client().prepareSearch().setQuery(
+        assertRequestBuilderThrows(client().prepareSearch().setQuery(
                 moreLikeThisQuery(new String[] {"int_value"}, new String[] {"42"}, null).minTermFreq(1).minDocFreq(1)
                 .failOnUnsupportedField(true)),
                 SearchPhaseExecutionException.class);

+ 6 - 6
server/src/test/java/org/elasticsearch/search/scroll/SearchScrollIT.java

@@ -56,9 +56,9 @@ import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcke
 import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertHitCount;
 import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertNoFailures;
 import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertNoSearchHits;
+import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertRequestBuilderThrows;
 import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertSearchHits;
 import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertSearchResponse;
-import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertThrows;
 import static org.hamcrest.Matchers.containsString;
 import static org.hamcrest.Matchers.equalTo;
 import static org.hamcrest.Matchers.greaterThan;
@@ -328,9 +328,9 @@ public class SearchScrollIT extends ESIntegTestCase {
         assertThat(clearResponse.status(), equalTo(RestStatus.OK));
         assertToXContentResponse(clearResponse, true, clearResponse.getNumFreed());
 
-        assertThrows(client().prepareSearchScroll(searchResponse1.getScrollId()).setScroll(TimeValue.timeValueMinutes(2)),
+        assertRequestBuilderThrows(client().prepareSearchScroll(searchResponse1.getScrollId()).setScroll(TimeValue.timeValueMinutes(2)),
                 RestStatus.NOT_FOUND);
-        assertThrows(client().prepareSearchScroll(searchResponse2.getScrollId()).setScroll(TimeValue.timeValueMinutes(2)),
+        assertRequestBuilderThrows(client().prepareSearchScroll(searchResponse2.getScrollId()).setScroll(TimeValue.timeValueMinutes(2)),
                 RestStatus.NOT_FOUND);
     }
 
@@ -436,9 +436,9 @@ public class SearchScrollIT extends ESIntegTestCase {
         assertThat(clearResponse.status(), equalTo(RestStatus.OK));
         assertToXContentResponse(clearResponse, true, clearResponse.getNumFreed());
 
-        assertThrows(internalCluster().client().prepareSearchScroll(searchResponse1.getScrollId())
+        assertRequestBuilderThrows(internalCluster().client().prepareSearchScroll(searchResponse1.getScrollId())
                 .setScroll(TimeValue.timeValueMinutes(2)), RestStatus.NOT_FOUND);
-        assertThrows(internalCluster().client().prepareSearchScroll(searchResponse2.getScrollId())
+        assertRequestBuilderThrows(internalCluster().client().prepareSearchScroll(searchResponse2.getScrollId())
                 .setScroll(TimeValue.timeValueMinutes(2)), RestStatus.NOT_FOUND);
     }
 
@@ -486,7 +486,7 @@ public class SearchScrollIT extends ESIntegTestCase {
         ClearScrollResponse clearScrollResponse = client().prepareClearScroll().addScrollId(searchResponse.getScrollId()).get();
         assertThat(clearScrollResponse.isSucceeded(), is(true));
 
-        assertThrows(internalCluster().client().prepareSearchScroll(searchResponse.getScrollId()), RestStatus.NOT_FOUND);
+        assertRequestBuilderThrows(internalCluster().client().prepareSearchScroll(searchResponse.getScrollId()), RestStatus.NOT_FOUND);
     }
 
     public void testStringSortMissingAscTerminates() throws Exception {

+ 4 - 4
server/src/test/java/org/elasticsearch/search/suggest/SuggestSearchIT.java

@@ -65,10 +65,10 @@ import static org.elasticsearch.search.suggest.SuggestBuilders.phraseSuggestion;
 import static org.elasticsearch.search.suggest.SuggestBuilders.termSuggestion;
 import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked;
 import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertNoFailures;
+import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertRequestBuilderThrows;
 import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertSuggestion;
 import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertSuggestionPhraseCollateMatchExists;
 import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertSuggestionSize;
-import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertThrows;
 import static org.hamcrest.Matchers.anyOf;
 import static org.hamcrest.Matchers.endsWith;
 import static org.hamcrest.Matchers.equalTo;
@@ -293,12 +293,12 @@ public class SuggestSearchIT extends ESIntegTestCase {
         {
             SearchRequestBuilder searchBuilder = client().prepareSearch().setSize(0);
             searchBuilder.suggest(new SuggestBuilder().setGlobalText("tetsting sugestion").addSuggestion("did_you_mean", phraseSuggestion));
-            assertThrows(searchBuilder, SearchPhaseExecutionException.class);
+            assertRequestBuilderThrows(searchBuilder, SearchPhaseExecutionException.class);
         }
         {
             SearchRequestBuilder searchBuilder = client().prepareSearch().setSize(0);
             searchBuilder.suggest(new SuggestBuilder().setGlobalText("tetsting sugestion").addSuggestion("did_you_mean", phraseSuggestion));
-            assertThrows(searchBuilder, SearchPhaseExecutionException.class);
+            assertRequestBuilderThrows(searchBuilder, SearchPhaseExecutionException.class);
         }
     }
 
@@ -748,7 +748,7 @@ public class SuggestSearchIT extends ESIntegTestCase {
                 .suggest(
                         new SuggestBuilder().setGlobalText("tetsting sugestion").addSuggestion("did_you_mean",
                                 phraseSuggestion("fielddoesnotexist").maxErrors(5.0f)));
-        assertThrows(request, SearchPhaseExecutionException.class);
+        assertRequestBuilderThrows(request, SearchPhaseExecutionException.class);
 
         // When searching on a shard which does not hold yet any document of an existing type, we should not fail
         SearchResponse searchResponse = client().prepareSearch().setSize(0)

+ 4 - 3
server/src/test/java/org/elasticsearch/snapshots/DedicatedClusterSnapshotRestoreIT.java

@@ -106,8 +106,9 @@ import java.util.function.Consumer;
 
 import static org.elasticsearch.index.seqno.RetentionLeaseActions.RETAIN_ALL;
 import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked;
+import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertFutureThrows;
 import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertHitCount;
-import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertThrows;
+import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertRequestBuilderThrows;
 import static org.hamcrest.Matchers.allOf;
 import static org.hamcrest.Matchers.containsString;
 import static org.hamcrest.Matchers.equalTo;
@@ -314,7 +315,7 @@ public class DedicatedClusterSnapshotRestoreIT extends AbstractSnapshotIntegTest
             .setWaitForCompletion(true).execute().actionGet();
 
         logger.info("--> make sure old repository wasn't restored");
-        assertThrows(client.admin().cluster().prepareGetRepositories("test-repo"), RepositoryMissingException.class);
+        assertRequestBuilderThrows(client.admin().cluster().prepareGetRepositories("test-repo"), RepositoryMissingException.class);
         assertThat(client.admin().cluster().prepareGetRepositories("test-repo-2").get().repositories().size(), equalTo(1));
 
         logger.info("--> check that custom persistent metadata was restored");
@@ -615,7 +616,7 @@ public class DedicatedClusterSnapshotRestoreIT extends AbstractSnapshotIntegTest
         assertAcked(client().admin().indices().prepareClose("test-idx-all"));
 
         logger.info("--> restore incomplete snapshot - should fail");
-        assertThrows(client().admin().cluster().prepareRestoreSnapshot("test-repo", "test-snap-2").setRestoreGlobalState(false)
+        assertFutureThrows(client().admin().cluster().prepareRestoreSnapshot("test-repo", "test-snap-2").setRestoreGlobalState(false)
                 .setWaitForCompletion(true).execute(),
             SnapshotRestoreException.class);
 

+ 5 - 5
server/src/test/java/org/elasticsearch/snapshots/RepositoriesIT.java

@@ -38,7 +38,7 @@ import java.nio.file.Path;
 import java.util.List;
 
 import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked;
-import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertThrows;
+import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertRequestBuilderThrows;
 import static org.hamcrest.Matchers.containsString;
 import static org.hamcrest.Matchers.equalTo;
 import static org.hamcrest.Matchers.notNullValue;
@@ -196,12 +196,12 @@ public class RepositoriesIT extends AbstractSnapshotIntegTestCase {
         Settings readonlySettings = Settings.builder().put(settings)
             .put("readonly", true).build();
         logger.info("-->  creating repository that cannot write any files - should fail");
-        assertThrows(client.admin().cluster().preparePutRepository("test-repo-1")
+        assertRequestBuilderThrows(client.admin().cluster().preparePutRepository("test-repo-1")
                         .setType("mock").setSettings(settings),
                 RepositoryVerificationException.class);
 
         logger.info("-->  creating read-only repository that cannot read any files - should fail");
-        assertThrows(client.admin().cluster().preparePutRepository("test-repo-2")
+        assertRequestBuilderThrows(client.admin().cluster().preparePutRepository("test-repo-2")
                 .setType("mock").setSettings(readonlySettings),
             RepositoryVerificationException.class);
 
@@ -210,14 +210,14 @@ public class RepositoriesIT extends AbstractSnapshotIntegTestCase {
                 .setType("mock").setSettings(settings).setVerify(false));
 
         logger.info("-->  verifying repository");
-        assertThrows(client.admin().cluster().prepareVerifyRepository("test-repo-1"), RepositoryVerificationException.class);
+        assertRequestBuilderThrows(client.admin().cluster().prepareVerifyRepository("test-repo-1"), RepositoryVerificationException.class);
 
         logger.info("-->  creating read-only repository that cannot read any files, but suppress verification - should be acked");
         assertAcked(client.admin().cluster().preparePutRepository("test-repo-2")
             .setType("mock").setSettings(readonlySettings).setVerify(false));
 
         logger.info("-->  verifying repository");
-        assertThrows(client.admin().cluster().prepareVerifyRepository("test-repo-2"), RepositoryVerificationException.class);
+        assertRequestBuilderThrows(client.admin().cluster().prepareVerifyRepository("test-repo-2"), RepositoryVerificationException.class);
 
         Path location = randomRepoPath();
 

+ 6 - 6
server/src/test/java/org/elasticsearch/snapshots/SharedClusterSnapshotRestoreIT.java

@@ -125,7 +125,7 @@ import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertHitC
 import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertIndexTemplateExists;
 import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertIndexTemplateMissing;
 import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertNoFailures;
-import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertThrows;
+import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertRequestBuilderThrows;
 import static org.hamcrest.Matchers.allOf;
 import static org.hamcrest.Matchers.anyOf;
 import static org.hamcrest.Matchers.containsString;
@@ -1607,7 +1607,7 @@ public class SharedClusterSnapshotRestoreIT extends AbstractSnapshotIntegTestCas
         assertAcked(client().admin().cluster().prepareDeleteSnapshot("test-repo", "test-snap").get());
         expectThrows(SnapshotMissingException.class, () -> client().admin().cluster()
                 .prepareGetSnapshots("test-repo").addSnapshots("test-snap").get().getSnapshots("test-repo"));
-        assertThrows(client().admin().cluster().prepareSnapshotStatus("test-repo").addSnapshots("test-snap"),
+        assertRequestBuilderThrows(client().admin().cluster().prepareSnapshotStatus("test-repo").addSnapshots("test-snap"),
             SnapshotMissingException.class);
 
         createSnapshotResponse = client().admin().cluster().prepareCreateSnapshot("test-repo", "test-snap")
@@ -2018,11 +2018,11 @@ public class SharedClusterSnapshotRestoreIT extends AbstractSnapshotIntegTestCas
         assertThat(getSnapshotsResponse.getSnapshots("readonly-repo").size(), equalTo(1));
 
         logger.info("--> try deleting snapshot");
-        assertThrows(client.admin().cluster().prepareDeleteSnapshot("readonly-repo", "test-snap"), RepositoryException.class,
+        assertRequestBuilderThrows(client.admin().cluster().prepareDeleteSnapshot("readonly-repo", "test-snap"), RepositoryException.class,
             "cannot delete snapshot from a readonly repository");
 
         logger.info("--> try making another snapshot");
-        assertThrows(client.admin().cluster().prepareCreateSnapshot("readonly-repo", "test-snap-2")
+        assertRequestBuilderThrows(client.admin().cluster().prepareCreateSnapshot("readonly-repo", "test-snap-2")
                 .setWaitForCompletion(true).setIndices("test-idx"),
             RepositoryException.class,
             "cannot create snapshot in a readonly repository");
@@ -2388,7 +2388,7 @@ public class SharedClusterSnapshotRestoreIT extends AbstractSnapshotIntegTestCas
                 .build();
 
         logger.info("--> try restoring while changing the number of shards - should fail");
-        assertThrows(client.admin().cluster()
+        assertRequestBuilderThrows(client.admin().cluster()
                 .prepareRestoreSnapshot("test-repo", "test-snap")
                 .setIgnoreIndexSettings("index.analysis.*")
                 .setIndexSettings(newIncorrectIndexSettings)
@@ -2399,7 +2399,7 @@ public class SharedClusterSnapshotRestoreIT extends AbstractSnapshotIntegTestCas
             .put(newIndexSettings)
             .put(SETTING_NUMBER_OF_REPLICAS.substring(IndexMetaData.INDEX_SETTING_PREFIX.length()), randomIntBetween(-10, -1))
             .build();
-        assertThrows(client.admin().cluster()
+        assertRequestBuilderThrows(client.admin().cluster()
             .prepareRestoreSnapshot("test-repo", "test-snap")
             .setIgnoreIndexSettings("index.analysis.*")
             .setIndexSettings(newIncorrectReplicasIndexSettings)

+ 2 - 2
server/src/test/java/org/elasticsearch/update/UpdateIT.java

@@ -62,7 +62,7 @@ import java.util.function.Function;
 
 import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;
 import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked;
-import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertThrows;
+import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertFutureThrows;
 import static org.hamcrest.Matchers.containsString;
 import static org.hamcrest.Matchers.equalTo;
 import static org.hamcrest.Matchers.notNullValue;
@@ -241,7 +241,7 @@ public class UpdateIT extends ESIntegTestCase {
         createTestIndex();
         ensureGreen();
 
-        assertThrows(client().prepareUpdate(indexOrAlias(), "1")
+        assertFutureThrows(client().prepareUpdate(indexOrAlias(), "1")
                 .setDoc(XContentFactory.jsonBuilder().startObject().field("bar", "baz").endObject())
                 .setDocAsUpsert(false)
                 .setFetchSource(true)

+ 34 - 24
server/src/test/java/org/elasticsearch/versioning/SimpleVersioningIT.java

@@ -45,8 +45,9 @@ import java.util.concurrent.atomic.AtomicInteger;
 
 import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery;
 import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked;
+import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertFutureThrows;
 import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertHitCount;
-import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertThrows;
+import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertRequestBuilderThrows;
 import static org.hamcrest.Matchers.equalTo;
 import static org.hamcrest.Matchers.lessThanOrEqualTo;
 
@@ -63,7 +64,7 @@ public class SimpleVersioningIT extends ESIntegTestCase {
         assertEquals(DocWriteResponse.Result.NOT_FOUND, deleteResponse.getResult());
 
         // this should conflict with the delete command transaction which told us that the object was deleted at version 17.
-        assertThrows(
+        assertFutureThrows(
                 client().prepareIndex("test").setId("1").setSource("field1", "value1_1").setVersion(13)
                     .setVersionType(VersionType.EXTERNAL).execute(),
                 VersionConflictEngineException.class
@@ -89,7 +90,7 @@ public class SimpleVersioningIT extends ESIntegTestCase {
             .setVersionType(VersionType.EXTERNAL_GTE).get();
         assertThat(indexResponse.getVersion(), equalTo(14L));
 
-        assertThrows(client().prepareIndex("test").setId("1").setSource("field1", "value1_1").setVersion(13)
+        assertRequestBuilderThrows(client().prepareIndex("test").setId("1").setSource("field1", "value1_1").setVersion(13)
                 .setVersionType(VersionType.EXTERNAL_GTE),
                 VersionConflictEngineException.class);
 
@@ -102,7 +103,7 @@ public class SimpleVersioningIT extends ESIntegTestCase {
         }
 
         // deleting with a lower version fails.
-        assertThrows(
+        assertRequestBuilderThrows(
                 client().prepareDelete("test", "1").setVersion(2).setVersionType(VersionType.EXTERNAL_GTE),
                 VersionConflictEngineException.class);
 
@@ -114,7 +115,7 @@ public class SimpleVersioningIT extends ESIntegTestCase {
         assertThat(deleteResponse.getVersion(), equalTo(v));
 
         // Deleting with a lower version keeps on failing after a delete.
-        assertThrows(
+        assertFutureThrows(
                 client().prepareDelete("test", "1").setVersion(2).setVersionType(VersionType.EXTERNAL_GTE).execute(),
                 VersionConflictEngineException.class);
 
@@ -138,9 +139,9 @@ public class SimpleVersioningIT extends ESIntegTestCase {
             .setVersionType(VersionType.EXTERNAL).execute().actionGet();
         assertThat(indexResponse.getVersion(), equalTo(14L));
 
-        assertThrows(client().prepareIndex("test").setId("1").setSource("field1", "value1_1").setVersion(13)
-                .setVersionType(VersionType.EXTERNAL).execute(),
-                VersionConflictEngineException.class);
+        assertFutureThrows(client().prepareIndex("test").setId("1").setSource("field1", "value1_1").setVersion(13)
+            .setVersionType(VersionType.EXTERNAL).execute(),
+            VersionConflictEngineException.class);
 
         if (randomBoolean()) {
             refresh();
@@ -150,7 +151,7 @@ public class SimpleVersioningIT extends ESIntegTestCase {
         }
 
         // deleting with a lower version fails.
-        assertThrows(
+        assertFutureThrows(
                 client().prepareDelete("test", "1").setVersion(2).setVersionType(VersionType.EXTERNAL).execute(),
                 VersionConflictEngineException.class);
 
@@ -161,7 +162,7 @@ public class SimpleVersioningIT extends ESIntegTestCase {
         assertThat(deleteResponse.getVersion(), equalTo(17L));
 
         // Deleting with a lower version keeps on failing after a delete.
-        assertThrows(
+        assertFutureThrows(
                 client().prepareDelete("test", "1").setVersion(2).setVersionType(VersionType.EXTERNAL).execute(),
                 VersionConflictEngineException.class);
 
@@ -217,7 +218,7 @@ public class SimpleVersioningIT extends ESIntegTestCase {
         createIndex("test");
         ensureGreen();
 
-        assertThrows(client().prepareDelete("test", "1").setIfSeqNo(17).setIfPrimaryTerm(10).execute(),
+        assertFutureThrows(client().prepareDelete("test", "1").setIfSeqNo(17).setIfPrimaryTerm(10).execute(),
                 VersionConflictEngineException.class);
 
         IndexResponse indexResponse = client().prepareIndex("test").setId("1").setSource("field1", "value1_1")
@@ -237,22 +238,25 @@ public class SimpleVersioningIT extends ESIntegTestCase {
         assertThat(indexResponse.getSeqNo(), equalTo(1L));
         assertThat(indexResponse.getPrimaryTerm(), equalTo(1L));
 
-        assertThrows(
+        assertFutureThrows(
             client().prepareIndex("test").setId("1").setSource("field1", "value1_1").setIfSeqNo(10).setIfPrimaryTerm(1).execute(),
             VersionConflictEngineException.class);
 
-        assertThrows(
+        assertFutureThrows(
             client().prepareIndex("test").setId("1").setSource("field1", "value1_1").setIfSeqNo(10).setIfPrimaryTerm(2).execute(),
             VersionConflictEngineException.class);
 
-        assertThrows(
+        assertFutureThrows(
             client().prepareIndex("test").setId("1").setSource("field1", "value1_1").setIfSeqNo(1).setIfPrimaryTerm(2).execute(),
             VersionConflictEngineException.class);
 
 
-        assertThrows(client().prepareDelete("test", "1").setIfSeqNo(10).setIfPrimaryTerm(1), VersionConflictEngineException.class);
-        assertThrows(client().prepareDelete("test", "1").setIfSeqNo(10).setIfPrimaryTerm(2), VersionConflictEngineException.class);
-        assertThrows(client().prepareDelete("test", "1").setIfSeqNo(1).setIfPrimaryTerm(2), VersionConflictEngineException.class);
+        assertRequestBuilderThrows(
+            client().prepareDelete("test", "1").setIfSeqNo(10).setIfPrimaryTerm(1), VersionConflictEngineException.class);
+        assertRequestBuilderThrows(
+            client().prepareDelete("test", "1").setIfSeqNo(10).setIfPrimaryTerm(2), VersionConflictEngineException.class);
+        assertRequestBuilderThrows(
+            client().prepareDelete("test", "1").setIfSeqNo(1).setIfPrimaryTerm(2), VersionConflictEngineException.class);
 
         client().admin().indices().prepareRefresh().execute().actionGet();
         for (int i = 0; i < 10; i++) {
@@ -279,12 +283,16 @@ public class SimpleVersioningIT extends ESIntegTestCase {
         assertThat(deleteResponse.getSeqNo(), equalTo(2L));
         assertThat(deleteResponse.getPrimaryTerm(), equalTo(1L));
 
-        assertThrows(client().prepareDelete("test", "1").setIfSeqNo(1).setIfPrimaryTerm(1), VersionConflictEngineException.class);
-        assertThrows(client().prepareDelete("test", "1").setIfSeqNo(3).setIfPrimaryTerm(12), VersionConflictEngineException.class);
-        assertThrows(client().prepareDelete("test", "1").setIfSeqNo(1).setIfPrimaryTerm(2), VersionConflictEngineException.class);
+        assertRequestBuilderThrows(
+            client().prepareDelete("test", "1").setIfSeqNo(1).setIfPrimaryTerm(1), VersionConflictEngineException.class);
+        assertRequestBuilderThrows(
+            client().prepareDelete("test", "1").setIfSeqNo(3).setIfPrimaryTerm(12), VersionConflictEngineException.class);
+        assertRequestBuilderThrows(
+            client().prepareDelete("test", "1").setIfSeqNo(1).setIfPrimaryTerm(2), VersionConflictEngineException.class);
 
         // the doc is deleted. Even when we hit the deleted seqNo, a conditional delete should fail.
-        assertThrows(client().prepareDelete("test", "1").setIfSeqNo(2).setIfPrimaryTerm(1), VersionConflictEngineException.class);
+        assertRequestBuilderThrows(
+            client().prepareDelete("test", "1").setIfSeqNo(2).setIfPrimaryTerm(1), VersionConflictEngineException.class);
     }
 
     public void testSimpleVersioningWithFlush() throws Exception {
@@ -299,13 +307,15 @@ public class SimpleVersioningIT extends ESIntegTestCase {
         assertThat(indexResponse.getSeqNo(), equalTo(1L));
 
         client().admin().indices().prepareFlush().execute().actionGet();
-        assertThrows(client().prepareIndex("test").setId("1").setSource("field1", "value1_1").setIfSeqNo(0).setIfPrimaryTerm(1),
+        assertRequestBuilderThrows(
+            client().prepareIndex("test").setId("1").setSource("field1", "value1_1").setIfSeqNo(0).setIfPrimaryTerm(1),
                 VersionConflictEngineException.class);
 
-        assertThrows(client().prepareIndex("test").setId("1").setCreate(true).setSource("field1", "value1_1"),
+        assertRequestBuilderThrows(client().prepareIndex("test").setId("1").setCreate(true).setSource("field1", "value1_1"),
                 VersionConflictEngineException.class);
 
-        assertThrows(client().prepareDelete("test", "1").setIfSeqNo(0).setIfPrimaryTerm(1), VersionConflictEngineException.class);
+        assertRequestBuilderThrows(
+            client().prepareDelete("test", "1").setIfSeqNo(0).setIfPrimaryTerm(1), VersionConflictEngineException.class);
 
         for (int i = 0; i < 10; i++) {
             assertThat(client().prepareGet("test", "1").execute().actionGet().getVersion(), equalTo(2L));

+ 35 - 50
test/framework/src/main/java/org/elasticsearch/test/hamcrest/ElasticsearchAssertions.java

@@ -76,6 +76,8 @@ import java.util.concurrent.CountDownLatch;
 import java.util.concurrent.TimeUnit;
 import java.util.function.Function;
 
+import static org.apache.lucene.util.LuceneTestCase.expectThrows;
+import static org.apache.lucene.util.LuceneTestCase.expectThrowsAnyOf;
 import static org.hamcrest.CoreMatchers.equalTo;
 import static org.hamcrest.CoreMatchers.is;
 import static org.hamcrest.MatcherAssert.assertThat;
@@ -493,15 +495,16 @@ public class ElasticsearchAssertions {
     /**
      * Run the request from a given builder and check that it throws an exception of the right type
      */
-    public static <E extends Throwable> void assertThrows(ActionRequestBuilder<?, ?> builder, Class<E> exceptionClass) {
-        assertThrows(builder.execute(), exceptionClass);
+    public static <E extends Throwable> void assertRequestBuilderThrows(ActionRequestBuilder<?, ?> builder, Class<E> exceptionClass) {
+        assertFutureThrows(builder.execute(), exceptionClass);
     }
 
     /**
      * Run the request from a given builder and check that it throws an exception of the right type, with a given {@link RestStatus}
      */
-    public static <E extends Throwable> void assertThrows(ActionRequestBuilder<?, ?> builder, Class<E> exceptionClass, RestStatus status) {
-        assertThrows(builder.execute(), exceptionClass, status);
+    public static <E extends Throwable> void assertRequestBuilderThrows(ActionRequestBuilder<?, ?> builder, Class<E> exceptionClass,
+                                                                        RestStatus status) {
+        assertFutureThrows(builder.execute(), exceptionClass, status);
     }
 
     /**
@@ -509,22 +512,23 @@ public class ElasticsearchAssertions {
      *
      * @param extraInfo extra information to add to the failure message
      */
-    public static <E extends Throwable> void assertThrows(ActionRequestBuilder<?, ?> builder, Class<E> exceptionClass, String extraInfo) {
-        assertThrows(builder.execute(), exceptionClass, extraInfo);
+    public static <E extends Throwable> void assertRequestBuilderThrows(ActionRequestBuilder<?, ?> builder, Class<E> exceptionClass,
+                                                                        String extraInfo) {
+        assertFutureThrows(builder.execute(), exceptionClass, extraInfo);
     }
 
     /**
      * Run future.actionGet() and check that it throws an exception of the right type
      */
-    public static <E extends Throwable> void assertThrows(ActionFuture future, Class<E> exceptionClass) {
-        assertThrows(future, exceptionClass, null, null);
+    public static <E extends Throwable> void assertFutureThrows(ActionFuture<?> future, Class<E> exceptionClass) {
+        assertFutureThrows(future, exceptionClass, null, null);
     }
 
     /**
      * Run future.actionGet() and check that it throws an exception of the right type, with a given {@link RestStatus}
      */
-    public static <E extends Throwable> void assertThrows(ActionFuture future, Class<E> exceptionClass, RestStatus status) {
-        assertThrows(future, exceptionClass, status, null);
+    public static <E extends Throwable> void assertFutureThrows(ActionFuture<?> future, Class<E> exceptionClass, RestStatus status) {
+        assertFutureThrows(future, exceptionClass, status, null);
     }
 
     /**
@@ -532,8 +536,8 @@ public class ElasticsearchAssertions {
      *
      * @param extraInfo extra information to add to the failure message
      */
-    public static <E extends Throwable> void assertThrows(ActionFuture future, Class<E> exceptionClass, String extraInfo) {
-        assertThrows(future, exceptionClass, null, extraInfo);
+    public static <E extends Throwable> void assertFutureThrows(ActionFuture<?> future, Class<E> exceptionClass, String extraInfo) {
+        assertFutureThrows(future, exceptionClass, null, extraInfo);
     }
 
     /**
@@ -543,9 +547,8 @@ public class ElasticsearchAssertions {
      * @param status         {@link org.elasticsearch.rest.RestStatus} to check for. Can be null to disable the check
      * @param extraInfo      extra information to add to the failure message. Can be null.
      */
-    public static <E extends Throwable> void assertThrows(ActionFuture future, Class<E> exceptionClass,
-            @Nullable RestStatus status, @Nullable String extraInfo) {
-        boolean fail = false;
+    public static <E extends Throwable> void assertFutureThrows(ActionFuture<?> future, Class<E> exceptionClass,
+                                                                @Nullable RestStatus status, @Nullable String extraInfo) {
         extraInfo = extraInfo == null || extraInfo.isEmpty() ? "" : extraInfo + ": ";
         extraInfo += "expected a " + exceptionClass + " exception to be thrown";
 
@@ -553,54 +556,36 @@ public class ElasticsearchAssertions {
             extraInfo += " with status [" + status + "]";
         }
 
-        try {
-            future.actionGet();
-            fail = true;
-
-        } catch (ElasticsearchException esException) {
-            assertThat(extraInfo, esException.unwrapCause(), instanceOf(exceptionClass));
-            if (status != null) {
-                assertThat(extraInfo, ExceptionsHelper.status(esException), equalTo(status));
-            }
-        } catch (Exception e) {
-            assertThat(extraInfo, e, instanceOf(exceptionClass));
-            if (status != null) {
-                assertThat(extraInfo, ExceptionsHelper.status(e), equalTo(status));
-            }
+        Throwable expected = expectThrowsAnyOf(List.of(exceptionClass, ElasticsearchException.class), future::actionGet);
+        if (expected instanceof ElasticsearchException) {
+            assertThat(extraInfo, ((ElasticsearchException) expected).unwrapCause(), instanceOf(exceptionClass));
+        } else {
+            assertThat(extraInfo, expected, instanceOf(exceptionClass));
         }
-        // has to be outside catch clause to get a proper message
-        if (fail) {
-            throw new AssertionError(extraInfo);
+
+        if (status != null) {
+            assertThat(extraInfo, ExceptionsHelper.status(expected), equalTo(status));
         }
     }
 
-    public static <E extends Throwable> void assertThrows(ActionRequestBuilder<?, ?> builder, RestStatus status) {
-        assertThrows(builder.execute(), status);
+    public static void assertRequestBuilderThrows(ActionRequestBuilder<?, ?> builder, RestStatus status) {
+        assertFutureThrows(builder.execute(), status);
     }
 
-    public static <E extends Throwable> void assertThrows(ActionRequestBuilder<?, ?> builder, RestStatus status, String extraInfo) {
-        assertThrows(builder.execute(), status, extraInfo);
+    public static void assertRequestBuilderThrows(ActionRequestBuilder<?, ?> builder, RestStatus status, String extraInfo) {
+        assertFutureThrows(builder.execute(), status, extraInfo);
     }
 
-    public static <E extends Throwable> void assertThrows(ActionFuture future, RestStatus status) {
-        assertThrows(future, status, null);
+    public static void assertFutureThrows(ActionFuture<?> future, RestStatus status) {
+        assertFutureThrows(future, status, null);
     }
 
-    public static void assertThrows(ActionFuture future, RestStatus status, String extraInfo) {
-        boolean fail = false;
+    public static void assertFutureThrows(ActionFuture<?> future, RestStatus status, String extraInfo) {
         extraInfo = extraInfo == null || extraInfo.isEmpty() ? "" : extraInfo + ": ";
         extraInfo += "expected a " + status + " status exception to be thrown";
 
-        try {
-            future.actionGet();
-            fail = true;
-        } catch (Exception e) {
-            assertThat(extraInfo, ExceptionsHelper.status(e), equalTo(status));
-        }
-        // has to be outside catch clause to get a proper message
-        if (fail) {
-            throw new AssertionError(extraInfo);
-        }
+        Exception e = expectThrows(Exception.class, future::actionGet);
+        assertThat(extraInfo, ExceptionsHelper.status(e), equalTo(status));
     }
 
     /**

+ 2 - 2
x-pack/plugin/security/src/test/java/org/elasticsearch/integration/SecurityClearScrollTests.java

@@ -25,7 +25,7 @@ import java.util.List;
 import java.util.Map;
 
 import static org.elasticsearch.action.support.WriteRequest.RefreshPolicy.IMMEDIATE;
-import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertThrows;
+import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertRequestBuilderThrows;
 import static org.elasticsearch.xpack.core.security.authc.support.UsernamePasswordToken.BASIC_AUTH_HEADER;
 import static org.elasticsearch.xpack.core.security.authc.support.UsernamePasswordToken.basicAuthHeaderValue;
 import static org.hamcrest.Matchers.containsString;
@@ -107,7 +107,7 @@ public class SecurityClearScrollTests extends SecurityIntegTestCase {
         Map<String, String> headers = new HashMap<>();
         headers.put(SecurityField.USER_SETTING.getKey(), user);
         headers.put(BASIC_AUTH_HEADER, basicAuth);
-        assertThrows(client().filterWithHeader(headers)
+        assertRequestBuilderThrows(client().filterWithHeader(headers)
                 .prepareClearScroll()
                 .addScrollId("_all"), ElasticsearchSecurityException.class,
                 "action [cluster:admin/indices/scroll/clear_all] is unauthorized for user [denied_user]");