diff --git a/build-tools-internal/version.properties b/build-tools-internal/version.properties index aa90f3e450bf..0ab9eadc725b 100644 --- a/build-tools-internal/version.properties +++ b/build-tools-internal/version.properties @@ -40,7 +40,6 @@ httpasyncclient = 4.1.4 commonslogging = 1.1.3 commonscodec = 1.11 hamcrest = 2.1 -securemock = 1.2 mocksocket = 1.2 # benchmark dependencies diff --git a/client/rest-high-level/src/test/java/org/elasticsearch/client/CustomRestHighLevelClientTests.java b/client/rest-high-level/src/test/java/org/elasticsearch/client/CustomRestHighLevelClientTests.java index d65a2c677069..2b2b76465608 100644 --- a/client/rest-high-level/src/test/java/org/elasticsearch/client/CustomRestHighLevelClientTests.java +++ b/client/rest-high-level/src/test/java/org/elasticsearch/client/CustomRestHighLevelClientTests.java @@ -68,13 +68,13 @@ public class CustomRestHighLevelClientTests extends ESTestCase { doAnswer(inv -> mockPerformRequest((Request) inv.getArguments()[0])) .when(restClient) - .performRequest(argThat(new RequestMatcher("GET", ENDPOINT))); + .performRequest(argThat(new RequestMatcher("GET", ENDPOINT)::matches)); doAnswer(inv -> mockPerformRequestAsync( ((Request) inv.getArguments()[0]), (ResponseListener) inv.getArguments()[1])) .when(restClient) - .performRequestAsync(argThat(new RequestMatcher("GET", ENDPOINT)), any(ResponseListener.class)); + .performRequestAsync(argThat(new RequestMatcher("GET", ENDPOINT)::matches), any(ResponseListener.class)); } } diff --git a/client/rest-high-level/src/test/java/org/elasticsearch/client/RestHighLevelClientTests.java b/client/rest-high-level/src/test/java/org/elasticsearch/client/RestHighLevelClientTests.java index 711e0cbea4c4..f5adb65ffd09 100644 --- a/client/rest-high-level/src/test/java/org/elasticsearch/client/RestHighLevelClientTests.java +++ b/client/rest-high-level/src/test/java/org/elasticsearch/client/RestHighLevelClientTests.java @@ -236,7 +236,7 @@ public class RestHighLevelClientTests extends ESTestCase { } when(restClient - .performRequestAsync(argThat(new RequestMatcher("GET", "/")), any())) + .performRequestAsync(argThat(new RequestMatcher("GET", "/")::matches), any())) .thenAnswer(i -> { ((ResponseListener)i.getArguments()[1]).onSuccess(response); return Cancellable.NO_OP; @@ -1039,7 +1039,8 @@ public class RestHighLevelClientTests extends ESTestCase { Build build = new Build(Build.Flavor.DEFAULT, Build.Type.UNKNOWN, "hash", "date", false, version); mockGetRoot(restClient, build, setProductHeader); - when(restClient.performRequest(argThat(new RequestMatcher("HEAD", "/foo/_source/bar")))).thenReturn(apiResponse); + when(restClient.performRequest(argThat(new RequestMatcher("HEAD", "/foo/_source/bar")::matches))) + .thenReturn(apiResponse); RestHighLevelClient highLevelClient = new RestHighLevelClient(restClient, RestClient::close, Collections.emptyList()); @@ -1086,7 +1087,8 @@ public class RestHighLevelClientTests extends ESTestCase { when(apiStatus.getStatusCode()).thenReturn(200); Response apiResponse = mock(Response.class); when(apiResponse.getStatusLine()).thenReturn(apiStatus); - when(restClient.performRequest(argThat(new RequestMatcher("HEAD", "/foo/_source/bar")))).thenReturn(apiResponse); + when(restClient.performRequest(argThat(new RequestMatcher("HEAD", "/foo/_source/bar")::matches))) + .thenReturn(apiResponse); RestHighLevelClient highLevelClient = new RestHighLevelClient(restClient, RestClient::close, Collections.emptyList()); @@ -1124,7 +1126,8 @@ public class RestHighLevelClientTests extends ESTestCase { when(apiStatus.getStatusCode()).thenReturn(200); Response apiResponse = mock(Response.class); when(apiResponse.getStatusLine()).thenReturn(apiStatus); - when(restClient.performRequest(argThat(new RequestMatcher("HEAD", "/foo/_source/bar")))).thenReturn(apiResponse); + when(restClient.performRequest(argThat(new RequestMatcher("HEAD", "/foo/_source/bar")::matches))) + .thenReturn(apiResponse); RestHighLevelClient highLevelClient = new RestHighLevelClient(restClient, RestClient::close, Collections.emptyList()); @@ -1166,10 +1169,11 @@ public class RestHighLevelClientTests extends ESTestCase { when(apiStatus.getStatusCode()).thenReturn(200); Response apiResponse = mock(Response.class); when(apiResponse.getStatusLine()).thenReturn(apiStatus); - when(restClient.performRequest(argThat(new RequestMatcher("HEAD", "/foo/_source/bar")))).thenReturn(apiResponse); + when(restClient.performRequest(argThat(new RequestMatcher("HEAD", "/foo/_source/bar")::matches))) + .thenReturn(apiResponse); // Have the verification request fail - when(restClient.performRequestAsync(argThat(new RequestMatcher("GET", "/")), any())) + when(restClient.performRequestAsync(argThat(new RequestMatcher("GET", "/")::matches), any())) .thenAnswer(i -> { ((ResponseListener)i.getArguments()[1]).onFailure(new IOException("Something bad happened")); return Cancellable.NO_OP; @@ -1198,10 +1202,11 @@ public class RestHighLevelClientTests extends ESTestCase { when(apiStatus.getStatusCode()).thenReturn(200); Response apiResponse = mock(Response.class); when(apiResponse.getStatusLine()).thenReturn(apiStatus); - when(restClient.performRequest(argThat(new RequestMatcher("HEAD", "/foo/_source/bar")))).thenReturn(apiResponse); + when(restClient.performRequest(argThat(new RequestMatcher("HEAD", "/foo/_source/bar")::matches))) + .thenReturn(apiResponse); // Have the info endpoint used for verification return a 403 (forbidden) - when(restClient.performRequestAsync(argThat(new RequestMatcher("GET", "/")), any())) + when(restClient.performRequestAsync(argThat(new RequestMatcher("GET", "/")::matches), any())) .thenAnswer(i -> { StatusLine infoStatus = mock(StatusLine.class); when(apiStatus.getStatusCode()).thenReturn(HttpStatus.SC_FORBIDDEN); @@ -1224,7 +1229,8 @@ public class RestHighLevelClientTests extends ESTestCase { mockGetRoot(restClient); Cancellable cancellable = mock(Cancellable.class); - when(restClient.performRequestAsync(argThat(new RequestMatcher("HEAD", "/foo/_source/bar")), any())).thenReturn(cancellable); + when(restClient.performRequestAsync(argThat(new RequestMatcher("HEAD", "/foo/_source/bar")::matches), any())) + .thenReturn(cancellable); Cancellable result = restHighLevelClient.existsSourceAsync( new GetSourceRequest("foo", "bar"), diff --git a/client/rest/build.gradle b/client/rest/build.gradle index 3fa58b997c9e..4fc00d0b6589 100644 --- a/client/rest/build.gradle +++ b/client/rest/build.gradle @@ -44,7 +44,6 @@ dependencies { testImplementation "com.carrotsearch.randomizedtesting:randomizedtesting-runner:${versions.randomizedrunner}" testImplementation "junit:junit:${versions.junit}" testImplementation "org.hamcrest:hamcrest:${versions.hamcrest}" - testImplementation "org.elasticsearch:securemock:${versions.securemock}" testImplementation "org.elasticsearch:mocksocket:${versions.mocksocket}" } diff --git a/client/rest/src/test/java/org/elasticsearch/client/RestClientSingleHostTests.java b/client/rest/src/test/java/org/elasticsearch/client/RestClientSingleHostTests.java index e15e4cb23993..7846758fc087 100644 --- a/client/rest/src/test/java/org/elasticsearch/client/RestClientSingleHostTests.java +++ b/client/rest/src/test/java/org/elasticsearch/client/RestClientSingleHostTests.java @@ -54,7 +54,6 @@ import org.junit.Before; import org.mockito.ArgumentCaptor; import org.mockito.stubbing.Answer; -import javax.net.ssl.SSLHandshakeException; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; @@ -72,6 +71,7 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.atomic.AtomicReference; +import javax.net.ssl.SSLHandshakeException; import static java.util.Collections.singletonList; import static org.elasticsearch.client.RestClientTestUtil.getAllErrorStatusCodes; @@ -87,6 +87,7 @@ import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; +import static org.mockito.ArgumentMatchers.nullable; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; @@ -124,7 +125,7 @@ public class RestClientSingleHostTests extends RestClientTestCase { static CloseableHttpAsyncClient mockHttpClient(final ExecutorService exec) { CloseableHttpAsyncClient httpClient = mock(CloseableHttpAsyncClient.class); when(httpClient.execute(any(HttpAsyncRequestProducer.class), any(HttpAsyncResponseConsumer.class), - any(HttpClientContext.class), any(FutureCallback.class))).thenAnswer((Answer>) invocationOnMock -> { + any(HttpClientContext.class), nullable(FutureCallback.class))).thenAnswer((Answer>) invocationOnMock -> { final HttpAsyncRequestProducer requestProducer = (HttpAsyncRequestProducer) invocationOnMock.getArguments()[0]; final FutureCallback futureCallback = (FutureCallback) invocationOnMock.getArguments()[3]; @@ -202,7 +203,7 @@ public class RestClientSingleHostTests extends RestClientTestCase { for (String httpMethod : getHttpMethods()) { HttpUriRequest expectedRequest = performRandomRequest(httpMethod); verify(httpClient, times(++times)).execute(requestArgumentCaptor.capture(), - any(HttpAsyncResponseConsumer.class), any(HttpClientContext.class), any(FutureCallback.class)); + any(HttpAsyncResponseConsumer.class), any(HttpClientContext.class), nullable(FutureCallback.class)); HttpUriRequest actualRequest = (HttpUriRequest)requestArgumentCaptor.getValue().generateRequest(); assertEquals(expectedRequest.getURI(), actualRequest.getURI()); assertEquals(expectedRequest.getClass(), actualRequest.getClass()); diff --git a/client/sniffer/build.gradle b/client/sniffer/build.gradle index a04984ecb593..6d673f5e986f 100644 --- a/client/sniffer/build.gradle +++ b/client/sniffer/build.gradle @@ -42,7 +42,6 @@ dependencies { testImplementation project(":client:test") testImplementation "com.carrotsearch.randomizedtesting:randomizedtesting-runner:${versions.randomizedrunner}" testImplementation "junit:junit:${versions.junit}" - testImplementation "org.elasticsearch:securemock:${versions.securemock}" testImplementation "org.elasticsearch:mocksocket:${versions.mocksocket}" } diff --git a/client/test/build.gradle b/client/test/build.gradle index e8d5ca53c9c1..ae7a983422bc 100644 --- a/client/test/build.gradle +++ b/client/test/build.gradle @@ -23,6 +23,11 @@ dependencies { api "com.carrotsearch.randomizedtesting:randomizedtesting-runner:${versions.randomizedrunner}" api "junit:junit:${versions.junit}" api "org.hamcrest:hamcrest:${versions.hamcrest}" + + // mockito + api 'org.mockito:mockito-core:3.12.4' + api 'net.bytebuddy:byte-buddy:1.11.13' + api 'org.objenesis:objenesis:3.2' } tasks.named('forbiddenApisMain').configure { @@ -38,6 +43,9 @@ tasks.named('forbiddenApisTest').configure { replaceSignatureFiles 'jdk-signatures' } +// since this client implementation is going away, third party audit is pointless +tasks.named("thirdPartyAudit").configure { enabled = false } + // JarHell is part of es server, which we don't want to pull in // TODO: Not anymore. Now in :libs:elasticsearch-core tasks.named("jarHell").configure { enabled = false } diff --git a/libs/nio/src/test/java/org/elasticsearch/nio/NioSelectorTests.java b/libs/nio/src/test/java/org/elasticsearch/nio/NioSelectorTests.java index e9a9be78f311..d4020b0a7ef4 100644 --- a/libs/nio/src/test/java/org/elasticsearch/nio/NioSelectorTests.java +++ b/libs/nio/src/test/java/org/elasticsearch/nio/NioSelectorTests.java @@ -8,9 +8,9 @@ package org.elasticsearch.nio; +import org.elasticsearch.common.util.concurrent.AbstractRunnable; import org.elasticsearch.core.CheckedRunnable; import org.elasticsearch.core.TimeValue; -import org.elasticsearch.common.util.concurrent.AbstractRunnable; import org.elasticsearch.test.ESTestCase; import org.junit.Before; import org.mockito.ArgumentCaptor; @@ -27,8 +27,8 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.BiConsumer; +import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.Matchers.any; -import static org.mockito.Matchers.anyInt; import static org.mockito.Matchers.isNull; import static org.mockito.Matchers.same; import static org.mockito.Mockito.doAnswer; @@ -168,7 +168,7 @@ public class NioSelectorTests extends ESTestCase { public void testSelectorClosedExceptionIsNotCaughtWhileRunning() throws IOException { boolean closedSelectorExceptionCaught = false; - when(rawSelector.select(anyInt())).thenThrow(new ClosedSelectorException()); + when(rawSelector.select(anyLong())).thenThrow(new ClosedSelectorException()); try { this.selector.singleLoop(); } catch (ClosedSelectorException e) { @@ -181,7 +181,7 @@ public class NioSelectorTests extends ESTestCase { public void testIOExceptionWhileSelect() throws IOException { IOException ioException = new IOException(); - when(rawSelector.select(anyInt())).thenThrow(ioException); + when(rawSelector.select(anyLong())).thenThrow(ioException); this.selector.singleLoop(); diff --git a/modules/percolator/src/test/java/org/elasticsearch/percolator/QueryBuilderStoreTests.java b/modules/percolator/src/test/java/org/elasticsearch/percolator/QueryBuilderStoreTests.java index d2e4f0dd8231..8e05a777a2a8 100644 --- a/modules/percolator/src/test/java/org/elasticsearch/percolator/QueryBuilderStoreTests.java +++ b/modules/percolator/src/test/java/org/elasticsearch/percolator/QueryBuilderStoreTests.java @@ -30,7 +30,7 @@ import org.elasticsearch.index.mapper.MapperBuilderContext; import org.elasticsearch.index.mapper.TestDocumentParserContext; import org.elasticsearch.index.query.SearchExecutionContext; import org.elasticsearch.index.query.TermQueryBuilder; -import org.elasticsearch.mock.orig.Mockito; +import org.mockito.Mockito; import org.elasticsearch.search.SearchModule; import org.elasticsearch.search.aggregations.support.CoreValuesSourceType; import org.elasticsearch.test.ESTestCase; diff --git a/server/src/main/resources/org/elasticsearch/bootstrap/test-framework.policy b/server/src/main/resources/org/elasticsearch/bootstrap/test-framework.policy index 80c2f3af16f4..abd9b80c96b7 100644 --- a/server/src/main/resources/org/elasticsearch/bootstrap/test-framework.policy +++ b/server/src/main/resources/org/elasticsearch/bootstrap/test-framework.policy @@ -10,7 +10,7 @@ //// These are mock objects and test management that we allow test framework libs //// to provide on our behalf. But tests themselves cannot do this stuff! -grant codeBase "${codebase.securemock}" { +grant codeBase "${codebase.mockito-core}" { // needed to access ReflectionFactory (see below) permission java.lang.RuntimePermission "accessClassInPackage.sun.reflect"; // needed for reflection in ibm jdk @@ -20,6 +20,27 @@ grant codeBase "${codebase.securemock}" { // needed for spy interception, etc permission java.lang.RuntimePermission "accessDeclaredMembers"; permission java.lang.reflect.ReflectPermission "suppressAccessChecks"; + permission java.lang.RuntimePermission "getClassLoader"; +}; + +grant codeBase "${codebase.byte-buddy}" { + permission java.lang.RuntimePermission "getClassLoader"; + permission java.lang.RuntimePermission "createClassLoader"; + permission java.lang.RuntimePermission "accessDeclaredMembers"; + permission java.lang.RuntimePermission "net.bytebuddy.createJavaDispatcher"; + permission java.lang.RuntimePermission "accessClassInPackage.sun.misc"; + permission java.lang.reflect.ReflectPermission "suppressAccessChecks"; + permission java.lang.reflect.ReflectPermission "newProxyInPackage.net.bytebuddy.utility"; + permission java.lang.reflect.ReflectPermission "newProxyInPackage.net.bytebuddy.dynamic.loading"; + permission java.lang.reflect.ReflectPermission "newProxyInPackage.net.bytebuddy.description.type"; + permission java.lang.reflect.ReflectPermission "newProxyInPackage.net.bytebuddy.description.method"; +}; + +grant codeBase "${codebase.objenesis}" { + permission java.lang.RuntimePermission "reflectionFactoryAccess"; + permission java.lang.RuntimePermission "accessClassInPackage.sun.reflect"; + permission java.lang.RuntimePermission "accessDeclaredMembers"; + permission java.lang.reflect.ReflectPermission "suppressAccessChecks"; }; grant codeBase "${codebase.lucene-test-framework}" { diff --git a/server/src/test/java/org/elasticsearch/action/bulk/TransportBulkActionIngestTests.java b/server/src/test/java/org/elasticsearch/action/bulk/TransportBulkActionIngestTests.java index 3a836a753afd..af4a4c658c39 100644 --- a/server/src/test/java/org/elasticsearch/action/bulk/TransportBulkActionIngestTests.java +++ b/server/src/test/java/org/elasticsearch/action/bulk/TransportBulkActionIngestTests.java @@ -165,7 +165,7 @@ public class TransportBulkActionIngestTests extends ESTestCase { // initialize captors, which must be members to use @Capture because of generics threadPool = mock(ThreadPool.class); when(threadPool.executor(anyString())).thenReturn(EsExecutors.DIRECT_EXECUTOR_SERVICE); - MockitoAnnotations.initMocks(this); + MockitoAnnotations.openMocks(this); // setup services that will be called by action transportService = mock(TransportService.class); clusterService = mock(ClusterService.class); diff --git a/server/src/test/java/org/elasticsearch/action/get/TransportMultiGetActionTests.java b/server/src/test/java/org/elasticsearch/action/get/TransportMultiGetActionTests.java index 13cd7d27bd44..8737862f47dc 100644 --- a/server/src/test/java/org/elasticsearch/action/get/TransportMultiGetActionTests.java +++ b/server/src/test/java/org/elasticsearch/action/get/TransportMultiGetActionTests.java @@ -54,6 +54,7 @@ import static java.util.Collections.emptySet; import static org.elasticsearch.common.UUIDs.randomBase64UUID; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.instanceOf; +import static org.mockito.ArgumentMatchers.nullable; import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.mock; @@ -121,13 +122,15 @@ public class TransportMultiGetActionTests extends ESTestCase { when(index2ShardIterator.shardId()).thenReturn(new ShardId(index2, randomInt())); final OperationRouting operationRouting = mock(OperationRouting.class); - when(operationRouting.getShards(eq(clusterState), eq(index1.getName()), anyString(), anyString(), anyString())) + when(operationRouting.getShards(eq(clusterState), eq(index1.getName()), + anyString(), nullable(String.class), nullable(String.class))) .thenReturn(index1ShardIterator); - when(operationRouting.shardId(eq(clusterState), eq(index1.getName()), anyString(), anyString())) + when(operationRouting.shardId(eq(clusterState), eq(index1.getName()), nullable(String.class), nullable(String.class))) .thenReturn(new ShardId(index1, randomInt())); - when(operationRouting.getShards(eq(clusterState), eq(index2.getName()), anyString(), anyString(), anyString())) + when(operationRouting.getShards(eq(clusterState), eq(index2.getName()), + anyString(), nullable(String.class), nullable(String.class))) .thenReturn(index2ShardIterator); - when(operationRouting.shardId(eq(clusterState), eq(index2.getName()), anyString(), anyString())) + when(operationRouting.shardId(eq(clusterState), eq(index2.getName()), nullable(String.class), nullable(String.class))) .thenReturn(new ShardId(index2, randomInt())); clusterService = mock(ClusterService.class); diff --git a/server/src/test/java/org/elasticsearch/action/termvectors/TransportMultiTermVectorsActionTests.java b/server/src/test/java/org/elasticsearch/action/termvectors/TransportMultiTermVectorsActionTests.java index 1b5744490eaa..43ee50312b71 100644 --- a/server/src/test/java/org/elasticsearch/action/termvectors/TransportMultiTermVectorsActionTests.java +++ b/server/src/test/java/org/elasticsearch/action/termvectors/TransportMultiTermVectorsActionTests.java @@ -55,6 +55,7 @@ import static java.util.Collections.emptySet; import static org.elasticsearch.common.UUIDs.randomBase64UUID; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.instanceOf; +import static org.mockito.ArgumentMatchers.nullable; import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.mock; @@ -122,13 +123,15 @@ public class TransportMultiTermVectorsActionTests extends ESTestCase { when(index2ShardIterator.shardId()).thenReturn(new ShardId(index2, randomInt())); final OperationRouting operationRouting = mock(OperationRouting.class); - when(operationRouting.getShards(eq(clusterState), eq(index1.getName()), anyString(), anyString(), anyString())) + when(operationRouting.getShards(eq(clusterState), eq(index1.getName()), + anyString(), nullable(String.class), nullable(String.class))) .thenReturn(index1ShardIterator); - when(operationRouting.shardId(eq(clusterState), eq(index1.getName()), anyString(), anyString())) + when(operationRouting.shardId(eq(clusterState), eq(index1.getName()), nullable(String.class), nullable(String.class))) .thenReturn(new ShardId(index1, randomInt())); - when(operationRouting.getShards(eq(clusterState), eq(index2.getName()), anyString(), anyString(), anyString())) + when(operationRouting.getShards(eq(clusterState), eq(index2.getName()), + anyString(), nullable(String.class), nullable(String.class))) .thenReturn(index2ShardIterator); - when(operationRouting.shardId(eq(clusterState), eq(index2.getName()), anyString(), anyString())) + when(operationRouting.shardId(eq(clusterState), eq(index2.getName()), nullable(String.class), nullable(String.class))) .thenReturn(new ShardId(index2, randomInt())); clusterService = mock(ClusterService.class); diff --git a/server/src/test/java/org/elasticsearch/common/settings/ConsistentSettingsServiceTests.java b/server/src/test/java/org/elasticsearch/common/settings/ConsistentSettingsServiceTests.java index b25b02da667f..48df8de79bdb 100644 --- a/server/src/test/java/org/elasticsearch/common/settings/ConsistentSettingsServiceTests.java +++ b/server/src/test/java/org/elasticsearch/common/settings/ConsistentSettingsServiceTests.java @@ -11,7 +11,7 @@ package org.elasticsearch.common.settings; import org.elasticsearch.cluster.ClusterState; import org.elasticsearch.cluster.ClusterStateUpdateTask; import org.elasticsearch.cluster.service.ClusterService; -import org.elasticsearch.mock.orig.Mockito; +import org.mockito.Mockito; import org.elasticsearch.test.ESTestCase; import org.junit.Before; import org.mockito.stubbing.Answer; diff --git a/server/src/test/java/org/elasticsearch/discovery/SeedHostsResolverTests.java b/server/src/test/java/org/elasticsearch/discovery/SeedHostsResolverTests.java index 6ba114db2285..c972d9c2aa4a 100644 --- a/server/src/test/java/org/elasticsearch/discovery/SeedHostsResolverTests.java +++ b/server/src/test/java/org/elasticsearch/discovery/SeedHostsResolverTests.java @@ -20,11 +20,11 @@ import org.elasticsearch.common.network.NetworkService; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.transport.BoundTransportAddress; import org.elasticsearch.common.transport.TransportAddress; -import org.elasticsearch.core.TimeValue; import org.elasticsearch.common.util.CancellableThreads; import org.elasticsearch.common.util.PageCacheRecycler; import org.elasticsearch.common.util.concurrent.EsExecutors; import org.elasticsearch.common.util.concurrent.FutureUtils; +import org.elasticsearch.core.TimeValue; import org.elasticsearch.core.internal.io.IOUtils; import org.elasticsearch.indices.breaker.NoneCircuitBreakerService; import org.elasticsearch.test.ESTestCase; @@ -49,7 +49,6 @@ import java.util.List; import java.util.Set; import java.util.Stack; import java.util.concurrent.CountDownLatch; -import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; @@ -403,6 +402,6 @@ public class SeedHostsResolverTests extends ESTestCase { assertThat(transportAddresses, hasSize(1)); // only one of the two is valid and will be used assertThat(transportAddresses.get(0).getAddress(), equalTo("127.0.0.1")); assertThat(transportAddresses.get(0).getPort(), equalTo(9301)); - verify(logger).warn(eq("failed to resolve host [127.0.0.1:9300:9300]"), any(ExecutionException.class)); + verify(logger).warn(eq("failed to resolve host [127.0.0.1:9300:9300]"), any(Exception.class)); } } diff --git a/server/src/test/java/org/elasticsearch/index/seqno/GlobalCheckpointSyncActionTests.java b/server/src/test/java/org/elasticsearch/index/seqno/GlobalCheckpointSyncActionTests.java index 0c854e9c0060..865c87bc34ab 100644 --- a/server/src/test/java/org/elasticsearch/index/seqno/GlobalCheckpointSyncActionTests.java +++ b/server/src/test/java/org/elasticsearch/index/seqno/GlobalCheckpointSyncActionTests.java @@ -28,8 +28,8 @@ import org.elasticsearch.transport.TransportService; import java.util.Collections; -import static org.elasticsearch.mock.orig.Mockito.never; -import static org.elasticsearch.mock.orig.Mockito.when; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.when; import static org.elasticsearch.test.ClusterServiceUtils.createClusterService; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; diff --git a/server/src/test/java/org/elasticsearch/index/seqno/RetentionLeaseBackgroundSyncActionTests.java b/server/src/test/java/org/elasticsearch/index/seqno/RetentionLeaseBackgroundSyncActionTests.java index 28c3f8db9f96..54588d7a85e4 100644 --- a/server/src/test/java/org/elasticsearch/index/seqno/RetentionLeaseBackgroundSyncActionTests.java +++ b/server/src/test/java/org/elasticsearch/index/seqno/RetentionLeaseBackgroundSyncActionTests.java @@ -34,7 +34,7 @@ import java.util.Collections; import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicBoolean; -import static org.elasticsearch.mock.orig.Mockito.when; +import static org.mockito.Mockito.when; import static org.elasticsearch.test.ClusterServiceUtils.createClusterService; import static org.hamcrest.Matchers.sameInstance; import static org.mockito.Mockito.mock; diff --git a/server/src/test/java/org/elasticsearch/index/seqno/RetentionLeaseSyncActionTests.java b/server/src/test/java/org/elasticsearch/index/seqno/RetentionLeaseSyncActionTests.java index 6b9946af469f..6490ae21503b 100644 --- a/server/src/test/java/org/elasticsearch/index/seqno/RetentionLeaseSyncActionTests.java +++ b/server/src/test/java/org/elasticsearch/index/seqno/RetentionLeaseSyncActionTests.java @@ -33,7 +33,7 @@ import org.elasticsearch.transport.TransportService; import java.util.Collections; import java.util.concurrent.atomic.AtomicBoolean; -import static org.elasticsearch.mock.orig.Mockito.when; +import static org.mockito.Mockito.when; import static org.elasticsearch.test.ClusterServiceUtils.createClusterService; import static org.hamcrest.Matchers.sameInstance; import static org.mockito.Mockito.mock; diff --git a/server/src/test/java/org/elasticsearch/index/shard/GlobalCheckpointListenersTests.java b/server/src/test/java/org/elasticsearch/index/shard/GlobalCheckpointListenersTests.java index c605900a8c72..cf465b0cfc00 100644 --- a/server/src/test/java/org/elasticsearch/index/shard/GlobalCheckpointListenersTests.java +++ b/server/src/test/java/org/elasticsearch/index/shard/GlobalCheckpointListenersTests.java @@ -42,12 +42,11 @@ import java.util.concurrent.atomic.AtomicLong; import static org.elasticsearch.index.seqno.SequenceNumbers.NO_OPS_PERFORMED; import static org.elasticsearch.index.seqno.SequenceNumbers.UNASSIGNED_SEQ_NO; -import static org.hamcrest.Matchers.any; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasToString; import static org.hamcrest.Matchers.instanceOf; -import static org.mockito.Matchers.argThat; +import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.reset; @@ -622,7 +621,7 @@ public class GlobalCheckpointListenersTests extends ESTestCase { doAnswer(invocationOnMock -> { latch.countDown(); return null; - }).when(mockLogger).warn(argThat(any(String.class)), argThat(any(RuntimeException.class))); + }).when(mockLogger).warn(any(String.class), any(RuntimeException.class)); final GlobalCheckpointListeners globalCheckpointListeners = new GlobalCheckpointListeners(shardId, scheduler, mockLogger); final TimeValue timeout = TimeValue.timeValueMillis(randomIntBetween(1, 50)); diff --git a/server/src/test/java/org/elasticsearch/index/translog/TranslogTests.java b/server/src/test/java/org/elasticsearch/index/translog/TranslogTests.java index 3f3175671af0..29e92e1434af 100644 --- a/server/src/test/java/org/elasticsearch/index/translog/TranslogTests.java +++ b/server/src/test/java/org/elasticsearch/index/translog/TranslogTests.java @@ -134,7 +134,7 @@ import static org.hamcrest.Matchers.lessThanOrEqualTo; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.nullValue; import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.stub; +import static org.mockito.Mockito.when; @LuceneTestCase.SuppressFileSystems("ExtrasFS") public class TranslogTests extends ESTestCase { @@ -385,7 +385,7 @@ public class TranslogTests extends ESTestCase { long period = randomLongBetween(10000, 1000000); periods[numberOfReaders] = period; TranslogWriter w = mock(TranslogWriter.class); - stub(w.getLastModifiedTime()).toReturn(fixedTime - period); + when(w.getLastModifiedTime()).thenReturn(fixedTime - period); assertThat(Translog.findEarliestLastModifiedAge(fixedTime, new ArrayList<>(), w), equalTo(period)); for (int i = 0; i < numberOfReaders; i++) { @@ -394,7 +394,7 @@ public class TranslogTests extends ESTestCase { List readers = new ArrayList<>(); for (long l : periods) { TranslogReader r = mock(TranslogReader.class); - stub(r.getLastModifiedTime()).toReturn(fixedTime - l); + when(r.getLastModifiedTime()).thenReturn(fixedTime - l); readers.add(r); } assertThat(Translog.findEarliestLastModifiedAge(fixedTime, readers, w), equalTo diff --git a/server/src/test/java/org/elasticsearch/ingest/IngestServiceTests.java b/server/src/test/java/org/elasticsearch/ingest/IngestServiceTests.java index ffbf35fbff61..e89692097246 100644 --- a/server/src/test/java/org/elasticsearch/ingest/IngestServiceTests.java +++ b/server/src/test/java/org/elasticsearch/ingest/IngestServiceTests.java @@ -60,7 +60,6 @@ import org.elasticsearch.threadpool.ThreadPool.Names; import org.elasticsearch.xcontent.XContentBuilder; import org.elasticsearch.xcontent.XContentType; import org.elasticsearch.xcontent.cbor.CborXContent; -import org.hamcrest.CustomTypeSafeMatcher; import org.junit.Before; import org.mockito.ArgumentMatcher; import org.mockito.invocation.InvocationOnMock; @@ -853,19 +852,8 @@ public class IngestServiceTests extends ESTestCase { ingestService.executeBulkRequest(bulkRequest.numberOfActions(), bulkRequest.requests(), failureHandler, completionHandler, indexReq -> {}, Names.WRITE); verify(failureHandler, times(1)).accept( - argThat(new CustomTypeSafeMatcher("failure handler was not called with the expected arguments") { - @Override - protected boolean matchesSafely(Integer item) { - return item == 2; - } - - }), - argThat(new CustomTypeSafeMatcher("failure handler was not called with the expected arguments") { - @Override - protected boolean matchesSafely(IllegalArgumentException iae) { - return "pipeline with id [does_not_exist] does not exist".equals(iae.getMessage()); - } - }) + argThat(item -> item == 2), + argThat(iae -> "pipeline with id [does_not_exist] does not exist".equals(iae.getMessage())) ); verify(completionHandler, times(1)).accept(Thread.currentThread(), null); } @@ -1150,12 +1138,7 @@ public class IngestServiceTests extends ESTestCase { ingestService.executeBulkRequest(numRequest, bulkRequest.requests(), requestItemErrorHandler, completionHandler, indexReq -> {}, Names.WRITE); - verify(requestItemErrorHandler, times(numIndexRequests)).accept(anyInt(), argThat(new ArgumentMatcher() { - @Override - public boolean matches(final Object o) { - return ((Exception)o).getCause().equals(error); - } - })); + verify(requestItemErrorHandler, times(numIndexRequests)).accept(anyInt(), argThat(e -> e.getCause().equals(error))); verify(completionHandler, times(1)).accept(Thread.currentThread(), null); } @@ -1856,7 +1839,7 @@ public class IngestServiceTests extends ESTestCase { return processor; } - private class IngestDocumentMatcher extends ArgumentMatcher { + private class IngestDocumentMatcher implements ArgumentMatcher { private final IngestDocument ingestDocument; @@ -1869,13 +1852,9 @@ public class IngestServiceTests extends ESTestCase { } @Override - public boolean matches(Object o) { - if (o.getClass() == IngestDocument.class) { - IngestDocument otherIngestDocument = (IngestDocument) o; - //ingest metadata will not be the same (timestamp differs every time) - return Objects.equals(ingestDocument.getSourceAndMetadata(), otherIngestDocument.getSourceAndMetadata()); - } - return false; + public boolean matches(IngestDocument other) { + //ingest metadata will not be the same (timestamp differs every time) + return Objects.equals(ingestDocument.getSourceAndMetadata(), other.getSourceAndMetadata()); } } diff --git a/server/src/test/java/org/elasticsearch/rest/action/cat/RestRecoveryActionTests.java b/server/src/test/java/org/elasticsearch/rest/action/cat/RestRecoveryActionTests.java index 74456b594891..ff1d0cbebc0f 100644 --- a/server/src/test/java/org/elasticsearch/rest/action/cat/RestRecoveryActionTests.java +++ b/server/src/test/java/org/elasticsearch/rest/action/cat/RestRecoveryActionTests.java @@ -16,8 +16,8 @@ import org.elasticsearch.cluster.routing.RecoverySource.SnapshotRecoverySource; import org.elasticsearch.cluster.routing.TestShardRouting; import org.elasticsearch.common.Randomness; import org.elasticsearch.common.Table; -import org.elasticsearch.core.TimeValue; import org.elasticsearch.common.xcontent.XContentElasticsearchExtension; +import org.elasticsearch.core.TimeValue; import org.elasticsearch.index.Index; import org.elasticsearch.index.shard.ShardId; import org.elasticsearch.indices.recovery.RecoveryState; @@ -31,9 +31,9 @@ import java.util.List; import java.util.Locale; import java.util.Map; -import static org.elasticsearch.mock.orig.Mockito.when; import static org.hamcrest.CoreMatchers.equalTo; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; public class RestRecoveryActionTests extends ESTestCase { diff --git a/server/src/test/java/org/elasticsearch/search/DefaultSearchContextTests.java b/server/src/test/java/org/elasticsearch/search/DefaultSearchContextTests.java index 1430da81cccb..b434da3fbaa6 100644 --- a/server/src/test/java/org/elasticsearch/search/DefaultSearchContextTests.java +++ b/server/src/test/java/org/elasticsearch/search/DefaultSearchContextTests.java @@ -54,6 +54,7 @@ import java.util.function.Supplier; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; +import static org.mockito.ArgumentMatchers.nullable; import static org.mockito.Matchers.anyObject; import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.eq; @@ -96,7 +97,8 @@ public class DefaultSearchContextTests extends ESTestCase { when(indexCache.query()).thenReturn(queryCache); when(indexService.cache()).thenReturn(indexCache); SearchExecutionContext searchExecutionContext = mock(SearchExecutionContext.class); - when(indexService.newSearchExecutionContext(eq(shardId.id()), eq(shardId.id()), anyObject(), anyObject(), anyString(), anyObject())) + when(indexService.newSearchExecutionContext(eq(shardId.id()), eq(shardId.id()), anyObject(), + anyObject(), nullable(String.class), anyObject())) .thenReturn(searchExecutionContext); MapperService mapperService = mock(MapperService.class); when(mapperService.hasNested()).thenReturn(randomBoolean()); @@ -254,7 +256,7 @@ public class DefaultSearchContextTests extends ESTestCase { eq(shardId.id()), anyObject(), anyObject(), - anyString(), + nullable(String.class), anyObject()) ).thenReturn(searchExecutionContext); diff --git a/server/src/test/java/org/elasticsearch/snapshots/RestoreServiceTests.java b/server/src/test/java/org/elasticsearch/snapshots/RestoreServiceTests.java index 5739ed0e58d8..21d21231dd9d 100644 --- a/server/src/test/java/org/elasticsearch/snapshots/RestoreServiceTests.java +++ b/server/src/test/java/org/elasticsearch/snapshots/RestoreServiceTests.java @@ -35,10 +35,10 @@ import java.util.Set; import java.util.concurrent.TimeUnit; import static org.elasticsearch.cluster.metadata.DataStreamTestHelper.createTimestampField; -import static org.elasticsearch.mock.orig.Mockito.doThrow; import static org.mockito.Matchers.any; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verifyZeroInteractions; import static org.mockito.Mockito.when; diff --git a/test/framework/build.gradle b/test/framework/build.gradle index f8b3f54e60a0..2aa092429d4b 100644 --- a/test/framework/build.gradle +++ b/test/framework/build.gradle @@ -24,7 +24,12 @@ dependencies { api "org.apache.lucene:lucene-codecs:${versions.lucene}" api "commons-logging:commons-logging:${versions.commonslogging}" api "commons-codec:commons-codec:${versions.commonscodec}" - api "org.elasticsearch:securemock:${versions.securemock}" + + // mockito + api 'org.mockito:mockito-core:3.12.4' + api 'net.bytebuddy:byte-buddy:1.11.13' + api 'org.objenesis:objenesis:3.2' + api "org.elasticsearch:mocksocket:${versions.mocksocket}" api "io.github.nik9000:mapmatcher:0.0.3" @@ -85,7 +90,17 @@ tasks.named("thirdPartyAudit").configure { 'org.tukaani.xz.X86Options', 'org.tukaani.xz.XZ', 'org.tukaani.xz.XZInputStream', - 'org.tukaani.xz.XZOutputStream' + 'org.tukaani.xz.XZOutputStream', + + // mockito + 'net.bytebuddy.agent.ByteBuddyAgent', + 'org.mockito.internal.creation.bytebuddy.inject.MockMethodDispatcher', + 'org.opentest4j.AssertionFailedError' + ) + + ignoreViolations( + 'org.objenesis.instantiator.sun.UnsafeFactoryInstantiator', + 'org.objenesis.instantiator.util.UnsafeUtils' ) if (BuildParams.runtimeJavaVersion > JavaVersion.VERSION_12) { ignoreMissingClasses( diff --git a/test/framework/src/main/java/org/elasticsearch/bootstrap/BootstrapForTesting.java b/test/framework/src/main/java/org/elasticsearch/bootstrap/BootstrapForTesting.java index 5e3b0f7bc40b..3ca3369e80e1 100644 --- a/test/framework/src/main/java/org/elasticsearch/bootstrap/BootstrapForTesting.java +++ b/test/framework/src/main/java/org/elasticsearch/bootstrap/BootstrapForTesting.java @@ -22,6 +22,7 @@ import org.elasticsearch.common.settings.Settings; import org.elasticsearch.jdk.JarHell; import org.elasticsearch.plugins.PluginInfo; import org.elasticsearch.secure_sm.SecureSM; +import org.elasticsearch.test.mockito.SecureMockMaker; import org.junit.Assert; import java.io.InputStream; @@ -91,6 +92,9 @@ public class BootstrapForTesting { throw new RuntimeException("found jar hell in test classpath", e); } + // init mockito + SecureMockMaker.init(); + // Log ifconfig output before SecurityManager is installed IfConfig.logIfNecessary(); diff --git a/test/framework/src/main/java/org/elasticsearch/test/ActionListenerUtils.java b/test/framework/src/main/java/org/elasticsearch/test/ActionListenerUtils.java index bef547a0a0ce..8c69cde694a8 100644 --- a/test/framework/src/main/java/org/elasticsearch/test/ActionListenerUtils.java +++ b/test/framework/src/main/java/org/elasticsearch/test/ActionListenerUtils.java @@ -10,7 +10,7 @@ package org.elasticsearch.test; import org.elasticsearch.action.ActionListener; -import static org.mockito.Matchers.any; +import static org.mockito.ArgumentMatchers.any; /** * Test utilities for working with {@link ActionListener}s. diff --git a/test/framework/src/main/java/org/elasticsearch/test/mockito/SecureAnnotationEngine.java b/test/framework/src/main/java/org/elasticsearch/test/mockito/SecureAnnotationEngine.java new file mode 100644 index 000000000000..f8ff482b0a49 --- /dev/null +++ b/test/framework/src/main/java/org/elasticsearch/test/mockito/SecureAnnotationEngine.java @@ -0,0 +1,27 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +package org.elasticsearch.test.mockito; + +import org.mockito.internal.configuration.InjectingAnnotationEngine; +import org.mockito.plugins.AnnotationEngine; + +import static org.elasticsearch.test.mockito.SecureMockUtil.wrap; + +public class SecureAnnotationEngine implements AnnotationEngine { + private final AnnotationEngine delegate; + + public SecureAnnotationEngine() { + delegate = wrap(InjectingAnnotationEngine::new); + } + + @Override + public AutoCloseable process(Class clazz, Object testInstance) { + return wrap(() -> delegate.process(clazz, testInstance)); + } +} diff --git a/test/framework/src/main/java/org/elasticsearch/test/mockito/SecureMockMaker.java b/test/framework/src/main/java/org/elasticsearch/test/mockito/SecureMockMaker.java new file mode 100644 index 000000000000..3815fc7277da --- /dev/null +++ b/test/framework/src/main/java/org/elasticsearch/test/mockito/SecureMockMaker.java @@ -0,0 +1,96 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +package org.elasticsearch.test.mockito; + +import org.mockito.MockedConstruction; +import org.mockito.internal.creation.bytebuddy.SubclassByteBuddyMockMaker; +import org.mockito.internal.util.reflection.LenientCopyTool; +import org.mockito.invocation.MockHandler; +import org.mockito.mock.MockCreationSettings; +import org.mockito.plugins.MockMaker; + +import java.util.Optional; +import java.util.function.Function; + +import static org.elasticsearch.test.mockito.SecureMockUtil.wrap; + +/** + * A {@link MockMaker} that works with {@link SecurityManager}. + */ +public class SecureMockMaker implements MockMaker { + + // delegates to initializing util, which we don't want to have public + public static void init() { + SecureMockUtil.init(); + } + + // TODO: consider using InlineByteBuddyMockMaker, but this requires using a java agent for instrumentation + private final SubclassByteBuddyMockMaker delegate; + + public SecureMockMaker() { + delegate = wrap(SubclassByteBuddyMockMaker::new); + } + + @SuppressWarnings("rawtypes") + @Override + public T createMock(MockCreationSettings mockCreationSettings, MockHandler mockHandler) { + return wrap(() -> delegate.createMock(mockCreationSettings, mockHandler)); + } + + @SuppressWarnings("rawtypes") + @Override + public Optional createSpy(MockCreationSettings settings, MockHandler handler, T object) { + // spies are not implemented by the bytebuddy delegate implementation + return wrap(() -> { + T instance = delegate.createMock(settings, handler); + new LenientCopyTool().copyToMock(object, instance); + return Optional.of(instance); + }); + } + + @SuppressWarnings("rawtypes") + @Override + public MockHandler getHandler(Object o) { + return delegate.getHandler(o); + } + + @SuppressWarnings("rawtypes") + @Override + public void resetMock(Object o, MockHandler mockHandler, MockCreationSettings mockCreationSettings) { + wrap(() -> { + delegate.resetMock(o, mockHandler, mockCreationSettings); + return (Void) null; + }); + } + + @Override + public TypeMockability isTypeMockable(Class type) { + return delegate.isTypeMockable(type); + } + + @SuppressWarnings("rawtypes") + @Override + public StaticMockControl createStaticMock(Class type, MockCreationSettings settings, MockHandler handler) { + return delegate.createStaticMock(type, settings, handler); + } + + @Override + public ConstructionMockControl createConstructionMock( + Class type, + Function> settingsFactory, + Function> handlerFactory, + MockedConstruction.MockInitializer mockInitializer) { + return delegate.createConstructionMock(type, settingsFactory, handlerFactory, mockInitializer); + } + + @Override + public void clearAllCaches() { + delegate.clearAllCaches(); + } +} diff --git a/test/framework/src/main/java/org/elasticsearch/test/mockito/SecureMockUtil.java b/test/framework/src/main/java/org/elasticsearch/test/mockito/SecureMockUtil.java new file mode 100644 index 000000000000..4793183b487c --- /dev/null +++ b/test/framework/src/main/java/org/elasticsearch/test/mockito/SecureMockUtil.java @@ -0,0 +1,43 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +package org.elasticsearch.test.mockito; + +import org.mockito.plugins.MockMaker; + +import java.security.AccessControlContext; +import java.security.AccessController; +import java.security.DomainCombiner; +import java.security.PrivilegedAction; +import java.security.ProtectionDomain; +import java.util.function.Supplier; + +class SecureMockUtil { + + // we use the protection domain of mockito for wrapped calls so that + // Elasticsearch server jar does not need additional permissions + private static final AccessControlContext context = getContext(); + private static AccessControlContext getContext() { + ProtectionDomain[] pda = new ProtectionDomain[] { wrap(MockMaker.class::getProtectionDomain) }; + DomainCombiner combiner = (current, assigned) -> pda; + AccessControlContext acc = new AccessControlContext(AccessController.getContext(), combiner); + // getContext must be called with the new acc so that a combined context will be created + return AccessController.doPrivileged((PrivilegedAction) AccessController::getContext, acc); + } + + // forces static init to run + public static void init() {} + + // wrap the given call to play nice with SecurityManager + static T wrap(Supplier call) { + return AccessController.doPrivileged((PrivilegedAction) call::get, context); + } + + // no construction + private SecureMockUtil() {} +} diff --git a/test/framework/src/main/java/org/elasticsearch/test/mockito/SecureObjectInstantiator.java b/test/framework/src/main/java/org/elasticsearch/test/mockito/SecureObjectInstantiator.java new file mode 100644 index 000000000000..77c783cee077 --- /dev/null +++ b/test/framework/src/main/java/org/elasticsearch/test/mockito/SecureObjectInstantiator.java @@ -0,0 +1,27 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +package org.elasticsearch.test.mockito; + +import org.mockito.creation.instance.Instantiator; + +/** + * A wrapper for instantiating objects reflectively, but plays nice with SecurityManager. + */ +class SecureObjectInstantiator implements Instantiator { + private final Instantiator delegate; + + SecureObjectInstantiator(Instantiator delegate) { + this.delegate = delegate; + } + + @Override + public T newInstance(Class cls) { + return SecureMockUtil.wrap(() -> delegate.newInstance(cls)); + } +} diff --git a/test/framework/src/main/java/org/elasticsearch/test/mockito/SecureObjectInstantiatorProvider.java b/test/framework/src/main/java/org/elasticsearch/test/mockito/SecureObjectInstantiatorProvider.java new file mode 100644 index 000000000000..5dca61186f1a --- /dev/null +++ b/test/framework/src/main/java/org/elasticsearch/test/mockito/SecureObjectInstantiatorProvider.java @@ -0,0 +1,31 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +package org.elasticsearch.test.mockito; + +import org.mockito.creation.instance.Instantiator; +import org.mockito.internal.creation.instance.DefaultInstantiatorProvider; +import org.mockito.mock.MockCreationSettings; +import org.mockito.plugins.InstantiatorProvider2; + +/** + * A wrapper around the default provider which itself just wraps + * {@link Instantiator} instances to play nice with {@link SecurityManager}. + */ +public class SecureObjectInstantiatorProvider implements InstantiatorProvider2 { + private final DefaultInstantiatorProvider delegate; + + public SecureObjectInstantiatorProvider() { + delegate = new DefaultInstantiatorProvider(); + } + + @Override + public Instantiator getInstantiator(MockCreationSettings settings) { + return new SecureObjectInstantiator(delegate.getInstantiator(settings)); + } +} diff --git a/test/framework/src/main/resources/mockito-extensions/org.mockito.plugins.AnnotationEngine b/test/framework/src/main/resources/mockito-extensions/org.mockito.plugins.AnnotationEngine new file mode 100644 index 000000000000..be695fd30f50 --- /dev/null +++ b/test/framework/src/main/resources/mockito-extensions/org.mockito.plugins.AnnotationEngine @@ -0,0 +1 @@ +org.elasticsearch.test.mockito.SecureAnnotationEngine diff --git a/test/framework/src/main/resources/mockito-extensions/org.mockito.plugins.InstantiatorProvider2 b/test/framework/src/main/resources/mockito-extensions/org.mockito.plugins.InstantiatorProvider2 new file mode 100644 index 000000000000..ba41d233143f --- /dev/null +++ b/test/framework/src/main/resources/mockito-extensions/org.mockito.plugins.InstantiatorProvider2 @@ -0,0 +1 @@ +org.elasticsearch.test.mockito.SecureObjectInstantiatorProvider diff --git a/test/framework/src/main/resources/mockito-extensions/org.mockito.plugins.MockMaker b/test/framework/src/main/resources/mockito-extensions/org.mockito.plugins.MockMaker new file mode 100644 index 000000000000..e19b9d550f81 --- /dev/null +++ b/test/framework/src/main/resources/mockito-extensions/org.mockito.plugins.MockMaker @@ -0,0 +1 @@ +org.elasticsearch.test.mockito.SecureMockMaker diff --git a/x-pack/plugin/core/build.gradle b/x-pack/plugin/core/build.gradle index b75c6d4909aa..d930c094c048 100644 --- a/x-pack/plugin/core/build.gradle +++ b/x-pack/plugin/core/build.gradle @@ -45,7 +45,6 @@ dependencies { exclude group: "org.elasticsearch", module: "elasticsearch-core" } - testImplementation 'org.elasticsearch:securemock:1.2' testImplementation "org.elasticsearch:mocksocket:${versions.mocksocket}" testImplementation "org.apache.logging.log4j:log4j-slf4j-impl:${versions.log4j}" testImplementation "org.slf4j:slf4j-api:${versions.slf4j}" diff --git a/x-pack/plugin/core/src/test/java/org/elasticsearch/license/RemoteClusterLicenseCheckerTests.java b/x-pack/plugin/core/src/test/java/org/elasticsearch/license/RemoteClusterLicenseCheckerTests.java index a6fd09f0103e..1e1340041297 100644 --- a/x-pack/plugin/core/src/test/java/org/elasticsearch/license/RemoteClusterLicenseCheckerTests.java +++ b/x-pack/plugin/core/src/test/java/org/elasticsearch/license/RemoteClusterLicenseCheckerTests.java @@ -458,7 +458,7 @@ public final class RemoteClusterLicenseCheckerTests extends ESTestCase { threadPool, client -> { when(client.getRemoteClusterClient(clusterAlias)).thenThrow(new IllegalArgumentException()); - when(client.getRemoteClusterClient(argThat(not(clusterAlias)))).thenReturn(client); + when(client.getRemoteClusterClient(argThat(a -> not(clusterAlias).matches(a)))).thenReturn(client); }); } diff --git a/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/common/validation/SourceDestValidatorTests.java b/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/common/validation/SourceDestValidatorTests.java index 57dd2345cccf..8486a1201bae 100644 --- a/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/common/validation/SourceDestValidatorTests.java +++ b/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/common/validation/SourceDestValidatorTests.java @@ -62,7 +62,7 @@ import static org.elasticsearch.cluster.metadata.IndexMetadata.SETTING_CREATION_ import static org.elasticsearch.cluster.metadata.IndexMetadata.SETTING_NUMBER_OF_REPLICAS; import static org.elasticsearch.cluster.metadata.IndexMetadata.SETTING_NUMBER_OF_SHARDS; import static org.elasticsearch.cluster.metadata.IndexMetadata.SETTING_VERSION_CREATED; -import static org.elasticsearch.mock.orig.Mockito.when; +import static org.mockito.Mockito.when; import static org.elasticsearch.xpack.core.common.validation.SourceDestValidator.DESTINATION_IN_SOURCE_VALIDATION; import static org.elasticsearch.xpack.core.common.validation.SourceDestValidator.DESTINATION_PIPELINE_MISSING_VALIDATION; import static org.elasticsearch.xpack.core.common.validation.SourceDestValidator.DESTINATION_SINGLE_INDEX_VALIDATION; diff --git a/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/scheduler/SchedulerEngineTests.java b/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/scheduler/SchedulerEngineTests.java index 42bbde3c5e7f..06e54195167d 100644 --- a/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/scheduler/SchedulerEngineTests.java +++ b/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/scheduler/SchedulerEngineTests.java @@ -26,12 +26,11 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; -import static org.hamcrest.Matchers.any; import static org.hamcrest.Matchers.arrayWithSize; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.is; -import static org.mockito.Matchers.argThat; +import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; @@ -74,7 +73,7 @@ public class SchedulerEngineTests extends ESTestCase { // this happens after the listener has been notified, threw an exception, and then mock logged the exception latch.countDown(); return null; - }).when(mockLogger).warn(argThat(any(ParameterizedMessage.class)), argThat(any(RuntimeException.class))); + }).when(mockLogger).warn(any(ParameterizedMessage.class), any(RuntimeException.class)); } listeners.add(Tuple.tuple(listener, trigger)); } diff --git a/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/slm/history/SnapshotLifecycleTemplateRegistryTests.java b/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/slm/history/SnapshotLifecycleTemplateRegistryTests.java index af31fd11d965..3b942ca85399 100644 --- a/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/slm/history/SnapshotLifecycleTemplateRegistryTests.java +++ b/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/slm/history/SnapshotLifecycleTemplateRegistryTests.java @@ -59,7 +59,7 @@ import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors; -import static org.elasticsearch.mock.orig.Mockito.when; +import static org.mockito.Mockito.when; import static org.elasticsearch.xpack.core.ilm.LifecycleSettings.SLM_HISTORY_INDEX_ENABLED_SETTING; import static org.elasticsearch.xpack.core.slm.history.SnapshotLifecycleTemplateRegistry.INDEX_TEMPLATE_VERSION; import static org.elasticsearch.xpack.core.slm.history.SnapshotLifecycleTemplateRegistry.SLM_POLICY_NAME; diff --git a/x-pack/plugin/identity-provider/build.gradle b/x-pack/plugin/identity-provider/build.gradle index 6ab2382d420a..06eca697da0a 100644 --- a/x-pack/plugin/identity-provider/build.gradle +++ b/x-pack/plugin/identity-provider/build.gradle @@ -45,7 +45,6 @@ dependencies { api "org.apache.httpcomponents:httpclient-cache:${versions.httpclient}" runtimeOnly 'com.google.guava:guava:19.0' - testImplementation 'org.elasticsearch:securemock:1.2' testImplementation "org.elasticsearch:mocksocket:${versions.mocksocket}" testImplementation(testArtifact(project(xpackModule('core')))) // So that we can extend LocalStateCompositeXPackPlugin diff --git a/x-pack/plugin/identity-provider/src/main/java/org/elasticsearch/xpack/idp/action/TransportSamlInitiateSingleSignOnAction.java b/x-pack/plugin/identity-provider/src/main/java/org/elasticsearch/xpack/idp/action/TransportSamlInitiateSingleSignOnAction.java index e8c5d6faec58..d179b8952644 100644 --- a/x-pack/plugin/identity-provider/src/main/java/org/elasticsearch/xpack/idp/action/TransportSamlInitiateSingleSignOnAction.java +++ b/x-pack/plugin/identity-provider/src/main/java/org/elasticsearch/xpack/idp/action/TransportSamlInitiateSingleSignOnAction.java @@ -116,18 +116,19 @@ public class TransportSamlInitiateSingleSignOnAction ActionListener listener) { User user = secondaryAuthentication.getUser(); secondaryAuthentication.execute(ignore -> { - privilegeResolver.resolve(serviceProvider.getPrivileges(), ActionListener.wrap( - userPrivileges -> { - if (userPrivileges.hasAccess == false) { - listener.onResponse(null); - } else { - logger.debug("Resolved [{}] for [{}]", userPrivileges, user); - listener.onResponse(new UserServiceAuthentication(user.principal(), user.fullName(), user.email(), - userPrivileges.roles, serviceProvider)); - } - }, - listener::onFailure - )); + ActionListener wrapped = ActionListener.wrap( + userPrivileges -> { + if (userPrivileges.hasAccess == false) { + listener.onResponse(null); + } else { + logger.debug("Resolved [{}] for [{}]", userPrivileges, user); + listener.onResponse(new UserServiceAuthentication(user.principal(), user.fullName(), user.email(), + userPrivileges.roles, serviceProvider)); + } + }, + listener::onFailure + ); + privilegeResolver.resolve(serviceProvider.getPrivileges(), wrapped); return null; } ); diff --git a/x-pack/plugin/identity-provider/src/test/java/org/elasticsearch/xpack/idp/action/TransportSamlInitiateSingleSignOnActionTests.java b/x-pack/plugin/identity-provider/src/test/java/org/elasticsearch/xpack/idp/action/TransportSamlInitiateSingleSignOnActionTests.java index a335ce32917b..3fa5e38fa7df 100644 --- a/x-pack/plugin/identity-provider/src/test/java/org/elasticsearch/xpack/idp/action/TransportSamlInitiateSingleSignOnActionTests.java +++ b/x-pack/plugin/identity-provider/src/test/java/org/elasticsearch/xpack/idp/action/TransportSamlInitiateSingleSignOnActionTests.java @@ -46,7 +46,8 @@ import java.util.HashSet; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.Matchers.arrayWithSize; -import static org.mockito.Matchers.any; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.nullable; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -180,17 +181,15 @@ public class TransportSamlInitiateSingleSignOnActionTests extends IdpSamlTestCas final SamlFactory factory = new SamlFactory(); final UserPrivilegeResolver privilegeResolver = Mockito.mock(UserPrivilegeResolver.class); doAnswer(inv -> { - final Object[] args = inv.getArguments(); - assertThat(args, arrayWithSize(2)); - ActionListener listener - = (ActionListener) args[args.length - 1]; + assertThat(inv.getArguments(), arrayWithSize(2)); + ActionListener listener = inv.getArgument(1); final UserPrivilegeResolver.UserPrivileges privileges = new UserPrivilegeResolver.UserPrivileges( "saml_enduser", true, new HashSet<>(Arrays.asList(generateRandomStringArray(5, 8, false, false)) )); listener.onResponse(privileges); return null; - }).when(privilegeResolver).resolve(any(ServiceProviderPrivileges.class), any(ActionListener.class)); + }).when(privilegeResolver).resolve(nullable(ServiceProviderPrivileges.class), any()); return new TransportSamlInitiateSingleSignOnAction(transportService, actionFilters, securityContext, idp, factory, privilegeResolver); } diff --git a/x-pack/plugin/identity-provider/src/test/java/org/elasticsearch/xpack/idp/saml/test/IdpSamlTestCase.java b/x-pack/plugin/identity-provider/src/test/java/org/elasticsearch/xpack/idp/saml/test/IdpSamlTestCase.java index 908051e84ced..43eba4e9c397 100644 --- a/x-pack/plugin/identity-provider/src/test/java/org/elasticsearch/xpack/idp/saml/test/IdpSamlTestCase.java +++ b/x-pack/plugin/identity-provider/src/test/java/org/elasticsearch/xpack/idp/saml/test/IdpSamlTestCase.java @@ -56,6 +56,7 @@ import javax.xml.transform.TransformerException; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; +import static org.mockito.ArgumentMatchers.nullable; import static org.opensaml.core.xml.config.XMLObjectProviderRegistrySupport.getUnmarshallerFactory; public abstract class IdpSamlTestCase extends ESTestCase { @@ -98,7 +99,7 @@ public abstract class IdpSamlTestCase extends ESTestCase { listener.onResponse(sp); return null; - }).when(idp).resolveServiceProvider(Mockito.eq(entityId), Mockito.anyString(), Mockito.anyBoolean(), + }).when(idp).resolveServiceProvider(Mockito.eq(entityId), nullable(String.class), Mockito.anyBoolean(), Mockito.any(ActionListener.class)); } diff --git a/x-pack/plugin/ilm/src/test/java/org/elasticsearch/xpack/ilm/IndexLifecycleRunnerTests.java b/x-pack/plugin/ilm/src/test/java/org/elasticsearch/xpack/ilm/IndexLifecycleRunnerTests.java index 2d14829ff10f..1330eb8fa0d6 100644 --- a/x-pack/plugin/ilm/src/test/java/org/elasticsearch/xpack/ilm/IndexLifecycleRunnerTests.java +++ b/x-pack/plugin/ilm/src/test/java/org/elasticsearch/xpack/ilm/IndexLifecycleRunnerTests.java @@ -1066,7 +1066,7 @@ public class IndexLifecycleRunnerTests extends ESTestCase { } - private static class SetStepInfoUpdateTaskMatcher extends ArgumentMatcher { + private static class SetStepInfoUpdateTaskMatcher implements ArgumentMatcher { private Index index; private String policy; @@ -1081,15 +1081,14 @@ public class IndexLifecycleRunnerTests extends ESTestCase { } @Override - public boolean matches(Object argument) { - if (argument == null || argument instanceof SetStepInfoUpdateTask == false) { + public boolean matches(SetStepInfoUpdateTask other) { + if (other == null) { return false; } - SetStepInfoUpdateTask task = (SetStepInfoUpdateTask) argument; - return Objects.equals(index, task.getIndex()) && - Objects.equals(policy, task.getPolicy())&& - Objects.equals(currentStepKey, task.getCurrentStepKey()) && - Objects.equals(xContentToString(stepInfo), xContentToString(task.getStepInfo())); + return Objects.equals(index, other.getIndex()) && + Objects.equals(policy, other.getPolicy())&& + Objects.equals(currentStepKey, other.getCurrentStepKey()) && + Objects.equals(xContentToString(stepInfo), xContentToString(other.getStepInfo())); } private String xContentToString(ToXContentObject xContent) { @@ -1104,7 +1103,7 @@ public class IndexLifecycleRunnerTests extends ESTestCase { } - private static class ExecuteStepsUpdateTaskMatcher extends ArgumentMatcher { + private static class ExecuteStepsUpdateTaskMatcher implements ArgumentMatcher { private Index index; private String policy; @@ -1117,14 +1116,13 @@ public class IndexLifecycleRunnerTests extends ESTestCase { } @Override - public boolean matches(Object argument) { - if (argument == null || argument instanceof ExecuteStepsUpdateTask == false) { + public boolean matches(ExecuteStepsUpdateTask other) { + if (other == null) { return false; } - ExecuteStepsUpdateTask task = (ExecuteStepsUpdateTask) argument; - return Objects.equals(index, task.getIndex()) && - Objects.equals(policy, task.getPolicy()) && - Objects.equals(startStep, task.getStartStep()); + return Objects.equals(index, other.getIndex()) && + Objects.equals(policy, other.getPolicy()) && + Objects.equals(startStep, other.getStartStep()); } } diff --git a/x-pack/plugin/ilm/src/test/java/org/elasticsearch/xpack/ilm/IndexLifecycleServiceTests.java b/x-pack/plugin/ilm/src/test/java/org/elasticsearch/xpack/ilm/IndexLifecycleServiceTests.java index 7d3f498e906d..86b5c51f7ba1 100644 --- a/x-pack/plugin/ilm/src/test/java/org/elasticsearch/xpack/ilm/IndexLifecycleServiceTests.java +++ b/x-pack/plugin/ilm/src/test/java/org/elasticsearch/xpack/ilm/IndexLifecycleServiceTests.java @@ -50,7 +50,6 @@ import org.elasticsearch.xpack.core.ilm.ShrinkStep; import org.elasticsearch.xpack.core.ilm.ShrunkShardsAllocatedStep; import org.elasticsearch.xpack.core.ilm.Step; import org.elasticsearch.xpack.core.scheduler.SchedulerEngine; -import org.hamcrest.Description; import org.junit.After; import org.junit.Before; import org.mockito.ArgumentMatcher; @@ -345,19 +344,10 @@ public class IndexLifecycleServiceTests extends ESTestCase { Priority actualPriority = null; @Override - public boolean matches(Object argument) { - if (argument instanceof OperationModeUpdateTask == false) { - return false; - } - actualPriority = ((OperationModeUpdateTask) argument).priority(); + public boolean matches(OperationModeUpdateTask other) { + actualPriority = other.priority(); return actualPriority == expectedPriority; } - - @Override - public void describeTo(Description description) { - description.appendText("the cluster state update task priority must be "+ expectedPriority+" but got: ") - .appendText(actualPriority.name()); - } }) ); } diff --git a/x-pack/plugin/ilm/src/test/java/org/elasticsearch/xpack/ilm/action/TransportStopILMActionTests.java b/x-pack/plugin/ilm/src/test/java/org/elasticsearch/xpack/ilm/action/TransportStopILMActionTests.java index e4fad189e945..1c923089e407 100644 --- a/x-pack/plugin/ilm/src/test/java/org/elasticsearch/xpack/ilm/action/TransportStopILMActionTests.java +++ b/x-pack/plugin/ilm/src/test/java/org/elasticsearch/xpack/ilm/action/TransportStopILMActionTests.java @@ -19,7 +19,6 @@ import org.elasticsearch.test.ESTestCase; import org.elasticsearch.threadpool.ThreadPool; import org.elasticsearch.transport.TransportService; import org.elasticsearch.xpack.core.ilm.StopILMRequest; -import org.hamcrest.Description; import org.mockito.ArgumentMatcher; import static org.mockito.Matchers.argThat; @@ -56,19 +55,10 @@ public class TransportStopILMActionTests extends ESTestCase { Priority actualPriority = null; @Override - public boolean matches(Object argument) { - if (argument instanceof AckedClusterStateUpdateTask == false) { - return false; - } - actualPriority = ((AckedClusterStateUpdateTask) argument).priority(); + public boolean matches(AckedClusterStateUpdateTask other) { + actualPriority = other.priority(); return actualPriority == Priority.IMMEDIATE; } - - @Override - public void describeTo(Description description) { - description.appendText("the cluster state update task priority must be URGENT but got: ") - .appendText(actualPriority.name()); - } }) ); } diff --git a/x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/MlAssignmentNotifierTests.java b/x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/MlAssignmentNotifierTests.java index faabd0b67a94..a91b88d99363 100644 --- a/x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/MlAssignmentNotifierTests.java +++ b/x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/MlAssignmentNotifierTests.java @@ -57,7 +57,7 @@ public class MlAssignmentNotifierTests extends ESTestCase { threadPool = mock(ThreadPool.class); ExecutorService executorService = mock(ExecutorService.class); - org.elasticsearch.mock.orig.Mockito.doAnswer(invocation -> { + org.mockito.Mockito.doAnswer(invocation -> { ((Runnable) invocation.getArguments()[0]).run(); return null; }).when(executorService).execute(any(Runnable.class)); diff --git a/x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/MlDailyMaintenanceServiceTests.java b/x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/MlDailyMaintenanceServiceTests.java index 4e3bb953b35c..1357abae8771 100644 --- a/x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/MlDailyMaintenanceServiceTests.java +++ b/x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/MlDailyMaintenanceServiceTests.java @@ -40,7 +40,7 @@ import java.util.Collections; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; -import static org.elasticsearch.mock.orig.Mockito.verify; +import static org.mockito.Mockito.verify; import static org.mockito.Matchers.any; import static org.mockito.Matchers.same; import static org.mockito.Mockito.doAnswer; diff --git a/x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/MlIndexTemplateRegistryTests.java b/x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/MlIndexTemplateRegistryTests.java index 3e6590a3143f..2fd6f1179ba9 100644 --- a/x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/MlIndexTemplateRegistryTests.java +++ b/x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/MlIndexTemplateRegistryTests.java @@ -37,8 +37,8 @@ import org.junit.Before; import org.mockito.ArgumentCaptor; import org.mockito.stubbing.Answer; -import static org.elasticsearch.mock.orig.Mockito.verify; -import static org.elasticsearch.mock.orig.Mockito.when; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; import static org.hamcrest.Matchers.equalTo; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyObject; diff --git a/x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/MlInitializationServiceTests.java b/x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/MlInitializationServiceTests.java index eed3eef2050d..933b72b54909 100644 --- a/x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/MlInitializationServiceTests.java +++ b/x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/MlInitializationServiceTests.java @@ -17,7 +17,7 @@ import org.junit.Before; import java.util.concurrent.ExecutorService; -import static org.elasticsearch.mock.orig.Mockito.doAnswer; +import static org.mockito.Mockito.doAnswer; import static org.hamcrest.Matchers.is; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; diff --git a/x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/action/TransportFinalizeJobExecutionActionTests.java b/x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/action/TransportFinalizeJobExecutionActionTests.java index e74b4ae1c0d4..a4367d072faa 100644 --- a/x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/action/TransportFinalizeJobExecutionActionTests.java +++ b/x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/action/TransportFinalizeJobExecutionActionTests.java @@ -47,7 +47,7 @@ public class TransportFinalizeJobExecutionActionTests extends ESTestCase { private void setupMocks() { ExecutorService executorService = mock(ExecutorService.class); threadPool = mock(ThreadPool.class); - org.elasticsearch.mock.orig.Mockito.doAnswer(invocation -> { + org.mockito.Mockito.doAnswer(invocation -> { ((Runnable) invocation.getArguments()[0]).run(); return null; }).when(executorService).execute(any(Runnable.class)); diff --git a/x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/datafeed/DatafeedJobTests.java b/x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/datafeed/DatafeedJobTests.java index c0407a062dd6..990927a4936b 100644 --- a/x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/datafeed/DatafeedJobTests.java +++ b/x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/datafeed/DatafeedJobTests.java @@ -27,7 +27,7 @@ import org.elasticsearch.xcontent.XContentFactory; import org.elasticsearch.xcontent.XContentType; import org.elasticsearch.core.TimeValue; import org.elasticsearch.index.shard.ShardId; -import org.elasticsearch.mock.orig.Mockito; +import org.mockito.Mockito; import org.elasticsearch.test.ESTestCase; import org.elasticsearch.threadpool.ThreadPool; import org.elasticsearch.xpack.core.ClientHelper; diff --git a/x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/datafeed/DatafeedRunnerTests.java b/x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/datafeed/DatafeedRunnerTests.java index c56624183f3c..11adff41a349 100644 --- a/x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/datafeed/DatafeedRunnerTests.java +++ b/x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/datafeed/DatafeedRunnerTests.java @@ -19,8 +19,8 @@ import org.elasticsearch.cluster.node.DiscoveryNodes; import org.elasticsearch.cluster.service.ClusterService; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.transport.TransportAddress; -import org.elasticsearch.core.TimeValue; import org.elasticsearch.common.util.concurrent.ThreadContext; +import org.elasticsearch.core.TimeValue; import org.elasticsearch.persistent.PersistentTasksCustomMetadata; import org.elasticsearch.persistent.PersistentTasksCustomMetadata.PersistentTask; import org.elasticsearch.test.ESTestCase; @@ -55,6 +55,7 @@ import java.util.function.Consumer; import static org.elasticsearch.xpack.ml.job.task.OpenJobPersistentTasksExecutorTests.addJobTask; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; +import static org.mockito.ArgumentMatchers.nullable; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyLong; import static org.mockito.Matchers.anyString; @@ -105,8 +106,6 @@ public class DatafeedRunnerTests extends ESTestCase { DiscoveryNode dNode = mock(DiscoveryNode.class); when(dNode.getName()).thenReturn("this_node_has_a_name"); when(clusterService.localNode()).thenReturn(dNode); - auditor = mock(AnomalyDetectionAuditor.class); - auditor = mock(AnomalyDetectionAuditor.class); threadPool = mock(ThreadPool.class); when(threadPool.getThreadContext()).thenReturn(new ThreadContext(Settings.EMPTY)); @@ -203,7 +202,7 @@ public class DatafeedRunnerTests extends ESTestCase { public void testRealTime_GivenStoppingAnalysisProblem() throws Exception { Exception cause = new RuntimeException("stopping"); - when(datafeedJob.runLookBack(anyLong(), anyLong())).thenThrow(new DatafeedJob.AnalysisProblemException(0L, true, cause)); + when(datafeedJob.runLookBack(anyLong(), nullable(Long.class))).thenThrow(new DatafeedJob.AnalysisProblemException(0L, true, cause)); Consumer handler = mockConsumer(); StartDatafeedAction.DatafeedParams params = new StartDatafeedAction.DatafeedParams(DATAFEED_ID, 0L); @@ -222,7 +221,8 @@ public class DatafeedRunnerTests extends ESTestCase { public void testRealTime_GivenNonStoppingAnalysisProblem() throws Exception { Exception cause = new RuntimeException("non-stopping"); - when(datafeedJob.runLookBack(anyLong(), anyLong())).thenThrow(new DatafeedJob.AnalysisProblemException(0L, false, cause)); + when(datafeedJob.runLookBack(anyLong(), nullable(Long.class))) + .thenThrow(new DatafeedJob.AnalysisProblemException(0L, false, cause)); Consumer handler = mockConsumer(); StartDatafeedAction.DatafeedParams params = new StartDatafeedAction.DatafeedParams(DATAFEED_ID, 0L); diff --git a/x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/datafeed/DatafeedTimingStatsReporterTests.java b/x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/datafeed/DatafeedTimingStatsReporterTests.java index a43cee90b8be..b31e6c6d0427 100644 --- a/x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/datafeed/DatafeedTimingStatsReporterTests.java +++ b/x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/datafeed/DatafeedTimingStatsReporterTests.java @@ -20,7 +20,7 @@ import org.mockito.InOrder; import java.sql.Date; import java.time.Instant; -import static org.elasticsearch.mock.orig.Mockito.doThrow; +import static org.mockito.Mockito.doThrow; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; import static org.mockito.Matchers.any; diff --git a/x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/datafeed/extractor/chunked/ChunkedDataExtractorTests.java b/x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/datafeed/extractor/chunked/ChunkedDataExtractorTests.java index 537c62e48cf1..7f4affe3b994 100644 --- a/x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/datafeed/extractor/chunked/ChunkedDataExtractorTests.java +++ b/x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/datafeed/extractor/chunked/ChunkedDataExtractorTests.java @@ -16,7 +16,7 @@ import org.elasticsearch.client.Client; import org.elasticsearch.core.TimeValue; import org.elasticsearch.index.query.QueryBuilder; import org.elasticsearch.index.query.QueryBuilders; -import org.elasticsearch.mock.orig.Mockito; +import org.mockito.Mockito; import org.elasticsearch.rest.RestStatus; import org.elasticsearch.search.SearchHit; import org.elasticsearch.search.SearchHits; diff --git a/x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/inference/loadingservice/LocalModelTests.java b/x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/inference/loadingservice/LocalModelTests.java index 11ad263905d3..9cdd6b699569 100644 --- a/x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/inference/loadingservice/LocalModelTests.java +++ b/x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/inference/loadingservice/LocalModelTests.java @@ -35,7 +35,6 @@ import org.elasticsearch.xpack.core.ml.inference.trainedmodel.tree.Tree; import org.elasticsearch.xpack.core.ml.inference.trainedmodel.tree.TreeNode; import org.elasticsearch.xpack.core.ml.job.messages.Messages; import org.elasticsearch.xpack.ml.inference.TrainedModelStatsService; -import org.mockito.ArgumentMatcher; import java.io.IOException; import java.util.Arrays; @@ -290,12 +289,7 @@ public class LocalModelTests extends ESTestCase { assertThat(result.valueAsString(), is("0")); // Should have reset after persistence, so only 2 docs have been seen since last persistence assertThat(model.getLatestStatsAndReset().getInferenceCount(), equalTo(2L)); - verify(modelStatsService, times(1)).queueStats(argThat(new ArgumentMatcher() { - @Override - public boolean matches(Object o) { - return ((InferenceStats)o).getInferenceCount() == 99L; - } - }), anyBoolean()); + verify(modelStatsService, times(1)).queueStats(argThat(o -> o.getInferenceCount() == 99L), anyBoolean()); } public void testMapFieldsIfNecessary() { diff --git a/x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/inference/loadingservice/ModelLoadingServiceTests.java b/x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/inference/loadingservice/ModelLoadingServiceTests.java index 024c8f8d130b..2bc21c8f215b 100644 --- a/x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/inference/loadingservice/ModelLoadingServiceTests.java +++ b/x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/inference/loadingservice/ModelLoadingServiceTests.java @@ -22,14 +22,11 @@ import org.elasticsearch.cluster.service.ClusterService; import org.elasticsearch.common.breaker.CircuitBreaker; import org.elasticsearch.common.breaker.CircuitBreakingException; import org.elasticsearch.common.bytes.BytesReference; -import org.elasticsearch.core.Tuple; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.transport.TransportAddress; import org.elasticsearch.common.unit.ByteSizeValue; import org.elasticsearch.core.TimeValue; -import org.elasticsearch.xcontent.XContentBuilder; -import org.elasticsearch.xcontent.XContentFactory; -import org.elasticsearch.xcontent.XContentType; +import org.elasticsearch.core.Tuple; import org.elasticsearch.ingest.IngestMetadata; import org.elasticsearch.ingest.PipelineConfiguration; import org.elasticsearch.license.XPackLicenseState; @@ -37,7 +34,11 @@ import org.elasticsearch.test.ESTestCase; import org.elasticsearch.threadpool.ScalingExecutorBuilder; import org.elasticsearch.threadpool.TestThreadPool; import org.elasticsearch.threadpool.ThreadPool; +import org.elasticsearch.xcontent.XContentBuilder; +import org.elasticsearch.xcontent.XContentFactory; +import org.elasticsearch.xcontent.XContentType; import org.elasticsearch.xpack.core.ml.action.GetTrainedModelsAction; +import org.elasticsearch.xpack.core.ml.inference.ModelAliasMetadata; import org.elasticsearch.xpack.core.ml.inference.TrainedModelConfig; import org.elasticsearch.xpack.core.ml.inference.TrainedModelInput; import org.elasticsearch.xpack.core.ml.inference.results.InferenceResults; @@ -46,14 +47,12 @@ import org.elasticsearch.xpack.core.ml.inference.trainedmodel.InferenceStats; import org.elasticsearch.xpack.core.ml.inference.trainedmodel.inference.InferenceDefinition; import org.elasticsearch.xpack.core.ml.job.messages.Messages; import org.elasticsearch.xpack.ml.MachineLearning; -import org.elasticsearch.xpack.core.ml.inference.ModelAliasMetadata; import org.elasticsearch.xpack.ml.inference.TrainedModelStatsService; import org.elasticsearch.xpack.ml.inference.ingest.InferenceProcessor; import org.elasticsearch.xpack.ml.inference.persistence.TrainedModelProvider; import org.elasticsearch.xpack.ml.notifications.InferenceAuditor; import org.junit.After; import org.junit.Before; -import org.mockito.ArgumentMatcher; import java.io.IOException; import java.net.InetAddress; @@ -224,12 +223,7 @@ public class ModelLoadingServiceTests extends ESTestCase { verify(trainedModelProvider, times(1)).getTrainedModelForInference(eq(model3), eq(false), any()); // model 3 has been loaded and evicted exactly once - verify(trainedModelStatsService, times(1)).queueStats(argThat(new ArgumentMatcher() { - @Override - public boolean matches(final Object o) { - return ((InferenceStats)o).getModelId().equals(model3); - } - }), anyBoolean()); + verify(trainedModelStatsService, times(1)).queueStats(argThat(o -> o.getModelId().equals(model3)), anyBoolean()); // Load model 3, should invalidate 1 and 2 for(int i = 0; i < 10; i++) { @@ -238,19 +232,8 @@ public class ModelLoadingServiceTests extends ESTestCase { assertThat(future3.get(), is(not(nullValue()))); } verify(trainedModelProvider, times(2)).getTrainedModelForInference(eq(model3), eq(false), any()); - - verify(trainedModelStatsService, atMost(2)).queueStats(argThat(new ArgumentMatcher() { - @Override - public boolean matches(final Object o) { - return ((InferenceStats)o).getModelId().equals(model1); - } - }), anyBoolean()); - verify(trainedModelStatsService, atMost(2)).queueStats(argThat(new ArgumentMatcher() { - @Override - public boolean matches(final Object o) { - return ((InferenceStats)o).getModelId().equals(model2); - } - }), anyBoolean()); + verify(trainedModelStatsService, atMost(2)).queueStats(argThat(o -> o.getModelId().equals(model1)), anyBoolean()); + verify(trainedModelStatsService, atMost(2)).queueStats(argThat(o -> o.getModelId().equals(model2)), anyBoolean()); // Load model 1, should invalidate 3 for(int i = 0; i < 10; i++) { @@ -259,12 +242,7 @@ public class ModelLoadingServiceTests extends ESTestCase { assertThat(future1.get(), is(not(nullValue()))); } verify(trainedModelProvider, atMost(3)).getTrainedModelForInference(eq(model1), eq(false), any()); - verify(trainedModelStatsService, times(2)).queueStats(argThat(new ArgumentMatcher() { - @Override - public boolean matches(final Object o) { - return ((InferenceStats)o).getModelId().equals(model3); - } - }), anyBoolean()); + verify(trainedModelStatsService, times(2)).queueStats(argThat(o -> o.getModelId().equals(model3)), anyBoolean()); // Load model 2 for(int i = 0; i < 10; i++) { diff --git a/x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/job/JobManagerTests.java b/x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/job/JobManagerTests.java index 210ae0ee645c..5a22c8ca5580 100644 --- a/x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/job/JobManagerTests.java +++ b/x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/job/JobManagerTests.java @@ -135,7 +135,7 @@ public class JobManagerTests extends ESTestCase { ExecutorService executorService = mock(ExecutorService.class); threadPool = mock(ThreadPool.class); - org.elasticsearch.mock.orig.Mockito.doAnswer(invocation -> { + org.mockito.Mockito.doAnswer(invocation -> { ((Runnable) invocation.getArguments()[0]).run(); return null; }).when(executorService).execute(any(Runnable.class)); diff --git a/x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/job/persistence/StateStreamerTests.java b/x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/job/persistence/StateStreamerTests.java index c6b034c7d4cf..ec31f68560a3 100644 --- a/x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/job/persistence/StateStreamerTests.java +++ b/x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/job/persistence/StateStreamerTests.java @@ -13,7 +13,7 @@ import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.xcontent.XContentFactory; import org.elasticsearch.index.query.QueryBuilder; import org.elasticsearch.index.query.QueryBuilders; -import org.elasticsearch.mock.orig.Mockito; +import org.mockito.Mockito; import org.elasticsearch.search.SearchHit; import org.elasticsearch.search.SearchHits; import org.elasticsearch.search.sort.SortBuilder; diff --git a/x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/job/process/autodetect/AutodetectCommunicatorTests.java b/x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/job/process/autodetect/AutodetectCommunicatorTests.java index 165e2553ccf2..03ef2caf06ec 100644 --- a/x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/job/process/autodetect/AutodetectCommunicatorTests.java +++ b/x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/job/process/autodetect/AutodetectCommunicatorTests.java @@ -49,7 +49,8 @@ import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import java.util.function.BiConsumer; -import static org.elasticsearch.mock.orig.Mockito.doAnswer; +import static org.mockito.ArgumentMatchers.nullable; +import static org.mockito.Mockito.doAnswer; import static org.hamcrest.Matchers.equalTo; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyBoolean; @@ -109,10 +110,9 @@ public class AutodetectCommunicatorTests extends ESTestCase { public void testFlushJob() throws Exception { AutodetectProcess process = mockAutodetectProcessWithOutputStream(); - when(process.isProcessAlive()).thenReturn(true); AutodetectResultProcessor processor = mock(AutodetectResultProcessor.class); FlushAcknowledgement flushAcknowledgement = mock(FlushAcknowledgement.class); - when(processor.waitForFlushAcknowledgement(anyString(), any())).thenReturn(flushAcknowledgement); + when(processor.waitForFlushAcknowledgement(nullable(String.class), any())).thenReturn(flushAcknowledgement); try (AutodetectCommunicator communicator = createAutodetectCommunicator(process, processor)) { FlushJobParams params = FlushJobParams.builder().build(); AtomicReference flushAcknowledgementHolder = new AtomicReference<>(); @@ -145,10 +145,9 @@ public class AutodetectCommunicatorTests extends ESTestCase { public void testFlushJob_givenFlushWaitReturnsTrueOnSecondCall() throws Exception { AutodetectProcess process = mockAutodetectProcessWithOutputStream(); - when(process.isProcessAlive()).thenReturn(true); AutodetectResultProcessor autodetectResultProcessor = mock(AutodetectResultProcessor.class); FlushAcknowledgement flushAcknowledgement = mock(FlushAcknowledgement.class); - when(autodetectResultProcessor.waitForFlushAcknowledgement(anyString(), eq(Duration.ofSeconds(1)))) + when(autodetectResultProcessor.waitForFlushAcknowledgement(nullable(String.class), eq(Duration.ofSeconds(1)))) .thenReturn(null).thenReturn(flushAcknowledgement); FlushJobParams params = FlushJobParams.builder().build(); @@ -156,7 +155,7 @@ public class AutodetectCommunicatorTests extends ESTestCase { communicator.flushJob(params, (aVoid, e) -> {}); } - verify(autodetectResultProcessor, times(2)).waitForFlushAcknowledgement(anyString(), eq(Duration.ofSeconds(1))); + verify(autodetectResultProcessor, times(2)).waitForFlushAcknowledgement(nullable(String.class), eq(Duration.ofSeconds(1))); // First in checkAndRun, second due to check between calls to waitForFlushAcknowledgement and third due to close() verify(process, times(3)).isProcessAlive(); } @@ -244,12 +243,11 @@ public class AutodetectCommunicatorTests extends ESTestCase { private AutodetectCommunicator createAutodetectCommunicator(AutodetectProcess autodetectProcess, AutodetectResultProcessor autodetectResultProcessor) throws IOException { ExecutorService executorService = mock(ExecutorService.class); - when(executorService.submit(any(Callable.class))).thenReturn(mock(Future.class)); doAnswer(invocationOnMock -> { - Callable runnable = (Callable) invocationOnMock.getArguments()[0]; + Callable runnable = (Callable) invocationOnMock.getArguments()[0]; runnable.call(); return mock(Future.class); - }).when(executorService).submit(any(Callable.class)); + }).when(executorService).submit((Callable>) any()); doAnswer(invocation -> { ((Runnable) invocation.getArguments()[0]).run(); return null; diff --git a/x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/job/process/autodetect/AutodetectProcessManagerTests.java b/x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/job/process/autodetect/AutodetectProcessManagerTests.java index 80f0d89addc1..1fd0238caeb5 100644 --- a/x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/job/process/autodetect/AutodetectProcessManagerTests.java +++ b/x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/job/process/autodetect/AutodetectProcessManagerTests.java @@ -95,13 +95,13 @@ import static org.elasticsearch.action.support.master.MasterNodeRequest.DEFAULT_ import static org.elasticsearch.cluster.metadata.IndexMetadata.SETTING_NUMBER_OF_REPLICAS; import static org.elasticsearch.cluster.metadata.IndexMetadata.SETTING_NUMBER_OF_SHARDS; import static org.elasticsearch.cluster.metadata.IndexMetadata.SETTING_VERSION_CREATED; -import static org.elasticsearch.mock.orig.Mockito.doAnswer; -import static org.elasticsearch.mock.orig.Mockito.doReturn; -import static org.elasticsearch.mock.orig.Mockito.doThrow; -import static org.elasticsearch.mock.orig.Mockito.times; -import static org.elasticsearch.mock.orig.Mockito.verify; -import static org.elasticsearch.mock.orig.Mockito.verifyNoMoreInteractions; -import static org.elasticsearch.mock.orig.Mockito.when; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.Matchers.nullValue; @@ -515,7 +515,7 @@ public class AutodetectProcessManagerTests extends ESTestCase { // let the communicator throw, simulating a problem with the underlying // autodetect, e.g. a crash - doThrow(Exception.class).when(autodetectCommunicator).close(); + doThrow(RuntimeException.class).when(autodetectCommunicator).close(); // create a jobtask JobTask jobTask = mock(JobTask.class); diff --git a/x-pack/plugin/monitoring/src/test/java/org/elasticsearch/xpack/monitoring/exporter/http/AsyncHttpResourceHelper.java b/x-pack/plugin/monitoring/src/test/java/org/elasticsearch/xpack/monitoring/exporter/http/AsyncHttpResourceHelper.java index f8d06e08ab42..74257fa2af39 100644 --- a/x-pack/plugin/monitoring/src/test/java/org/elasticsearch/xpack/monitoring/exporter/http/AsyncHttpResourceHelper.java +++ b/x-pack/plugin/monitoring/src/test/java/org/elasticsearch/xpack/monitoring/exporter/http/AsyncHttpResourceHelper.java @@ -50,7 +50,7 @@ class AsyncHttpResourceHelper { doAnswer(invocation -> { ((ResponseListener)invocation.getArguments()[1]).onSuccess(response); return null; - }).when(client).performRequestAsync(argThat(request), any(ResponseListener.class)); + }).when(client).performRequestAsync(argThat(request::matches), any(ResponseListener.class)); } static void whenPerformRequestAsyncWith(final RestClient client, final Matcher request, final List responses) { @@ -94,7 +94,7 @@ class AsyncHttpResourceHelper { }); } - stub.when(client).performRequestAsync(argThat(request), any(ResponseListener.class)); + stub.when(client).performRequestAsync(argThat(request::matches), any(ResponseListener.class)); } static void whenPerformRequestAsyncWith(final RestClient client, final Request request, final Response response) { @@ -115,7 +115,7 @@ class AsyncHttpResourceHelper { doAnswer(invocation -> { ((ResponseListener)invocation.getArguments()[1]).onFailure(exception); return null; - }).when(client).performRequestAsync(argThat(request), any(ResponseListener.class)); + }).when(client).performRequestAsync(argThat(request::matches), any(ResponseListener.class)); } static void whenPerformRequestAsyncWith(final RestClient client, final Request request, final Exception exception) { diff --git a/x-pack/plugin/monitoring/src/test/java/org/elasticsearch/xpack/monitoring/exporter/http/HttpExportBulkResponseListenerTests.java b/x-pack/plugin/monitoring/src/test/java/org/elasticsearch/xpack/monitoring/exporter/http/HttpExportBulkResponseListenerTests.java index b13172a97a0d..2e28ea405826 100644 --- a/x-pack/plugin/monitoring/src/test/java/org/elasticsearch/xpack/monitoring/exporter/http/HttpExportBulkResponseListenerTests.java +++ b/x-pack/plugin/monitoring/src/test/java/org/elasticsearch/xpack/monitoring/exporter/http/HttpExportBulkResponseListenerTests.java @@ -16,7 +16,7 @@ import org.elasticsearch.xcontent.XContent; import org.elasticsearch.xcontent.XContentParser; import org.elasticsearch.xcontent.XContentParser.Token; import org.elasticsearch.xcontent.XContentType; -import org.elasticsearch.mock.orig.Mockito; +import org.mockito.Mockito; import org.elasticsearch.test.ESTestCase; import java.io.IOException; diff --git a/x-pack/plugin/monitoring/src/test/java/org/elasticsearch/xpack/monitoring/exporter/http/HttpExporterResourceTests.java b/x-pack/plugin/monitoring/src/test/java/org/elasticsearch/xpack/monitoring/exporter/http/HttpExporterResourceTests.java index 398b28354bea..e795fcef1f1f 100644 --- a/x-pack/plugin/monitoring/src/test/java/org/elasticsearch/xpack/monitoring/exporter/http/HttpExporterResourceTests.java +++ b/x-pack/plugin/monitoring/src/test/java/org/elasticsearch/xpack/monitoring/exporter/http/HttpExporterResourceTests.java @@ -856,47 +856,49 @@ public class HttpExporterResourceTests extends AbstractPublishableHttpResourceTe } private void verifyVersionCheck() { - verify(client).performRequestAsync(argThat(new RequestMatcher(is("GET"), is("/"))), any(ResponseListener.class)); + verify(client).performRequestAsync(argThat(new RequestMatcher(is("GET"), is("/"))::matches), any(ResponseListener.class)); } private void verifyGetTemplates(final int called) { verify(client, times(called)) - .performRequestAsync(argThat(new RequestMatcher(is("GET"), startsWith("/_template/"))), any(ResponseListener.class)); + .performRequestAsync(argThat(new RequestMatcher(is("GET"), startsWith("/_template/"))::matches), any(ResponseListener.class)); } private void verifyPutTemplates(final int called) { verify(client, times(called)) - .performRequestAsync(argThat(new RequestMatcher(is("PUT"), startsWith("/_template/"))), any(ResponseListener.class)); + .performRequestAsync(argThat(new RequestMatcher(is("PUT"), startsWith("/_template/"))::matches), any(ResponseListener.class)); } private void verifyGetPipelines(final int called) { - verify(client, times(called)) - .performRequestAsync(argThat(new RequestMatcher(is("GET"), startsWith("/_ingest/pipeline/"))), any(ResponseListener.class)); + verify(client, times(called)).performRequestAsync( + argThat(new RequestMatcher(is("GET"), startsWith("/_ingest/pipeline/"))::matches), any(ResponseListener.class)); } private void verifyPutPipelines(final int called) { - verify(client, times(called)) - .performRequestAsync(argThat(new RequestMatcher(is("PUT"), startsWith("/_ingest/pipeline/"))), any(ResponseListener.class)); + verify(client, times(called)).performRequestAsync( + argThat(new RequestMatcher(is("PUT"), startsWith("/_ingest/pipeline/"))::matches), any(ResponseListener.class)); } private void verifyWatcherCheck() { - verify(client).performRequestAsync(argThat(new RequestMatcher(is("GET"), is("/_xpack"))), any(ResponseListener.class)); + verify(client).performRequestAsync(argThat(new RequestMatcher(is("GET"), is("/_xpack"))::matches), any(ResponseListener.class)); } private void verifyDeleteWatches(final int called) { verify(client, times(called)) - .performRequestAsync(argThat(new RequestMatcher(is("DELETE"), startsWith("/_watcher/watch/"))), + .performRequestAsync(argThat(new RequestMatcher(is("DELETE"), startsWith("/_watcher/watch/"))::matches), any(ResponseListener.class)); } private void verifyGetWatches(final int called) { verify(client, times(called)) - .performRequestAsync(argThat(new RequestMatcher(is("GET"), startsWith("/_watcher/watch/"))), any(ResponseListener.class)); + .performRequestAsync(argThat(new RequestMatcher(is("GET"), startsWith("/_watcher/watch/"))::matches), + any(ResponseListener.class)); } private void verifyPutWatches(final int called) { verify(client, times(called)) - .performRequestAsync(argThat(new RequestMatcher(is("PUT"), startsWith("/_watcher/watch/"))), any(ResponseListener.class)); + .performRequestAsync(argThat(new RequestMatcher(is("PUT"), startsWith("/_watcher/watch/"))::matches), + any(ResponseListener.class)); } private ClusterService mockClusterService(final ClusterState state) { diff --git a/x-pack/plugin/monitoring/src/test/java/org/elasticsearch/xpack/monitoring/exporter/http/PublishableHttpResourceTests.java b/x-pack/plugin/monitoring/src/test/java/org/elasticsearch/xpack/monitoring/exporter/http/PublishableHttpResourceTests.java index 5a8b7223cd3d..12d9ff5b2ca9 100644 --- a/x-pack/plugin/monitoring/src/test/java/org/elasticsearch/xpack/monitoring/exporter/http/PublishableHttpResourceTests.java +++ b/x-pack/plugin/monitoring/src/test/java/org/elasticsearch/xpack/monitoring/exporter/http/PublishableHttpResourceTests.java @@ -6,8 +6,6 @@ */ package org.elasticsearch.xpack.monitoring.exporter.http; -import java.util.Collections; -import java.util.Map; import org.apache.http.HttpEntity; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; @@ -17,16 +15,17 @@ import org.elasticsearch.client.Response; import org.elasticsearch.client.ResponseException; import org.elasticsearch.client.ResponseListener; import org.elasticsearch.client.RestClient; -import org.elasticsearch.core.CheckedFunction; import org.elasticsearch.common.SuppressLoggerChecks; +import org.elasticsearch.core.CheckedFunction; +import org.elasticsearch.rest.RestStatus; import org.elasticsearch.xcontent.XContent; import org.elasticsearch.xcontent.XContentType; -import org.elasticsearch.rest.RestStatus; - import org.elasticsearch.xpack.monitoring.exporter.http.HttpResource.ResourcePublishResult; import org.mockito.ArgumentCaptor; import java.io.IOException; +import java.util.Collections; +import java.util.Map; import java.util.function.Supplier; import static org.elasticsearch.xpack.monitoring.exporter.http.AsyncHttpResourceHelper.whenPerformRequestAsyncWith; @@ -142,7 +141,7 @@ public class PublishableHttpResourceTests extends AbstractPublishableHttpResourc verify(logger).trace("checking if {} [{}] exists on the [{}] {}", resourceType, resourceName, owner, ownerType); verify(logger).debug("{} [{}] found on the [{}] {}", resourceType, resourceName, owner, ownerType); verify(client).performRequestAsync(eq(request), any(ResponseListener.class)); - verify(logger, times(2)).error(any(org.apache.logging.log4j.util.Supplier.class), any(ResponseException.class)); + verify(logger, times(2)).error(any(org.apache.logging.log4j.util.Supplier.class), any(Exception.class)); verifyNoMoreInteractions(client, logger); } diff --git a/x-pack/plugin/repository-encrypted/src/test/java/org/elasticsearch/repositories/encrypted/BufferOnMarkInputStreamTests.java b/x-pack/plugin/repository-encrypted/src/test/java/org/elasticsearch/repositories/encrypted/BufferOnMarkInputStreamTests.java index 3114c03301e0..df11d6514e1c 100644 --- a/x-pack/plugin/repository-encrypted/src/test/java/org/elasticsearch/repositories/encrypted/BufferOnMarkInputStreamTests.java +++ b/x-pack/plugin/repository-encrypted/src/test/java/org/elasticsearch/repositories/encrypted/BufferOnMarkInputStreamTests.java @@ -793,7 +793,7 @@ public class BufferOnMarkInputStreamTests extends ESTestCase { } int bytesSkipped = 1 + Randomness.get().nextInt(Math.toIntExact(n)); bytesRead.addAndGet(bytesSkipped); - return bytesSkipped; + return (long) bytesSkipped; }); when(mockSource.available()).thenReturn(1 + Randomness.get().nextInt(32)); when(mockSource.markSupported()).thenReturn(false); diff --git a/x-pack/plugin/repository-encrypted/src/test/java/org/elasticsearch/repositories/encrypted/PrefixInputStreamTests.java b/x-pack/plugin/repository-encrypted/src/test/java/org/elasticsearch/repositories/encrypted/PrefixInputStreamTests.java index 6ca42d8d1409..fa70996001bc 100644 --- a/x-pack/plugin/repository-encrypted/src/test/java/org/elasticsearch/repositories/encrypted/PrefixInputStreamTests.java +++ b/x-pack/plugin/repository-encrypted/src/test/java/org/elasticsearch/repositories/encrypted/PrefixInputStreamTests.java @@ -186,11 +186,11 @@ public class PrefixInputStreamTests extends ESTestCase { when(mockSource.skip(org.mockito.Matchers.anyLong())).thenAnswer(invocationOnMock -> { final long n = (long) invocationOnMock.getArguments()[0]; if (n <= 0 || bytesRemaining.get() <= 0) { - return 0; + return 0L; } int bytesSkipped = 1 + Randomness.get().nextInt(Math.min(bytesRemaining.get(), Math.toIntExact(n))); bytesRemaining.addAndGet(-bytesSkipped); - return bytesSkipped; + return (long) bytesSkipped; }); when(mockSource.available()).thenAnswer(invocationOnMock -> { if (bytesRemaining.get() <= 0) { diff --git a/x-pack/plugin/searchable-snapshots/src/test/java/org/elasticsearch/xpack/searchablesnapshots/store/input/DirectBlobContainerIndexInputTests.java b/x-pack/plugin/searchable-snapshots/src/test/java/org/elasticsearch/xpack/searchablesnapshots/store/input/DirectBlobContainerIndexInputTests.java index bef6d3ea2962..4d0cfb326a2e 100644 --- a/x-pack/plugin/searchable-snapshots/src/test/java/org/elasticsearch/xpack/searchablesnapshots/store/input/DirectBlobContainerIndexInputTests.java +++ b/x-pack/plugin/searchable-snapshots/src/test/java/org/elasticsearch/xpack/searchablesnapshots/store/input/DirectBlobContainerIndexInputTests.java @@ -38,7 +38,6 @@ import static org.hamcrest.Matchers.lessThan; import static org.hamcrest.Matchers.lessThanOrEqualTo; import static org.hamcrest.Matchers.startsWith; import static org.mockito.Matchers.any; -import static org.mockito.Matchers.anyInt; import static org.mockito.Matchers.anyLong; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.mock; @@ -80,7 +79,7 @@ public class DirectBlobContainerIndexInputTests extends ESIndexInputTestCase { ); final BlobContainer blobContainer = mock(BlobContainer.class); - when(blobContainer.readBlob(anyString(), anyLong(), anyInt())).thenAnswer(invocationOnMock -> { + when(blobContainer.readBlob(anyString(), anyLong(), anyLong())).thenAnswer(invocationOnMock -> { String name = (String) invocationOnMock.getArguments()[0]; long position = (long) invocationOnMock.getArguments()[1]; long length = (long) invocationOnMock.getArguments()[2]; diff --git a/x-pack/plugin/security/build.gradle b/x-pack/plugin/security/build.gradle index ab3bd8ecc876..a61ae04cd854 100644 --- a/x-pack/plugin/security/build.gradle +++ b/x-pack/plugin/security/build.gradle @@ -75,7 +75,6 @@ dependencies { api "net.minidev:accessors-smart:2.4.2" api "org.ow2.asm:asm:9.1" - testImplementation 'org.elasticsearch:securemock:1.2' testImplementation "org.elasticsearch:mocksocket:${versions.mocksocket}" // Test dependencies for Kerberos (MiniKdc) diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/oidc/TransportOpenIdConnectLogoutActionTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/oidc/TransportOpenIdConnectLogoutActionTests.java index 37151c9ae664..8382dbfdd482 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/oidc/TransportOpenIdConnectLogoutActionTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/oidc/TransportOpenIdConnectLogoutActionTests.java @@ -74,8 +74,8 @@ import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.Matchers.startsWith; +import static org.mockito.ArgumentMatchers.nullable; import static org.mockito.Matchers.any; -import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; @@ -119,21 +119,21 @@ public class TransportOpenIdConnectLogoutActionTests extends OpenIdConnectTestCa .setType((String) invocationOnMock.getArguments()[1]) .setId((String) invocationOnMock.getArguments()[2]); return builder; - }).when(client).prepareGet(anyString(), anyString(), anyString()); + }).when(client).prepareGet(nullable(String.class), nullable(String.class), nullable(String.class)); doAnswer(invocationOnMock -> { IndexRequestBuilder builder = new IndexRequestBuilder(client, IndexAction.INSTANCE); builder.setIndex((String) invocationOnMock.getArguments()[0]) .setType((String) invocationOnMock.getArguments()[1]) .setId((String) invocationOnMock.getArguments()[2]); return builder; - }).when(client).prepareIndex(anyString(), anyString(), anyString()); + }).when(client).prepareIndex(nullable(String.class), nullable(String.class), nullable(String.class)); doAnswer(invocationOnMock -> { UpdateRequestBuilder builder = new UpdateRequestBuilder(client, UpdateAction.INSTANCE); builder.setIndex((String) invocationOnMock.getArguments()[0]) .setType((String) invocationOnMock.getArguments()[1]) .setId((String) invocationOnMock.getArguments()[2]); return builder; - }).when(client).prepareUpdate(anyString(), anyString(), anyString()); + }).when(client).prepareUpdate(nullable(String.class), nullable(String.class), nullable(String.class)); doAnswer(invocationOnMock -> { BulkRequestBuilder builder = new BulkRequestBuilder(client, BulkAction.INSTANCE); return builder; diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/rolemapping/TransportGetRoleMappingsActionTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/rolemapping/TransportGetRoleMappingsActionTests.java index 4a455d7349ff..a74fe289872e 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/rolemapping/TransportGetRoleMappingsActionTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/rolemapping/TransportGetRoleMappingsActionTests.java @@ -32,6 +32,7 @@ import static org.hamcrest.Matchers.arrayContaining; import static org.hamcrest.Matchers.arrayContainingInAnyOrder; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.notNullValue; +import static org.mockito.ArgumentMatchers.nullable; import static org.mockito.Matchers.any; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; @@ -61,7 +62,7 @@ public class TransportGetRoleMappingsActionTests extends ESTestCase { ActionListener> listener = (ActionListener>) args[1]; listener.onResponse(result); return null; - }).when(store).getRoleMappings(any(Set.class), any(ActionListener.class)); + }).when(store).getRoleMappings(nullable(Set.class), any(ActionListener.class)); } public void testGetSingleRole() throws Exception { diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/saml/TransportSamlLogoutActionTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/saml/TransportSamlLogoutActionTests.java index e2dfdcc407af..729f2148c8d0 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/saml/TransportSamlLogoutActionTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/saml/TransportSamlLogoutActionTests.java @@ -84,8 +84,8 @@ import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.Matchers.startsWith; +import static org.mockito.ArgumentMatchers.nullable; import static org.mockito.Matchers.any; -import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; @@ -133,21 +133,21 @@ public class TransportSamlLogoutActionTests extends SamlTestCase { .setType((String) invocationOnMock.getArguments()[1]) .setId((String) invocationOnMock.getArguments()[2]); return builder; - }).when(client).prepareGet(anyString(), anyString(), anyString()); + }).when(client).prepareGet(nullable(String.class), nullable(String.class), nullable(String.class)); doAnswer(invocationOnMock -> { IndexRequestBuilder builder = new IndexRequestBuilder(client, IndexAction.INSTANCE); builder.setIndex((String) invocationOnMock.getArguments()[0]) .setType((String) invocationOnMock.getArguments()[1]) .setId((String) invocationOnMock.getArguments()[2]); return builder; - }).when(client).prepareIndex(anyString(), anyString(), anyString()); + }).when(client).prepareIndex(nullable(String.class), nullable(String.class), nullable(String.class)); doAnswer(invocationOnMock -> { UpdateRequestBuilder builder = new UpdateRequestBuilder(client, UpdateAction.INSTANCE); builder.setIndex((String) invocationOnMock.getArguments()[0]) .setType((String) invocationOnMock.getArguments()[1]) .setId((String) invocationOnMock.getArguments()[2]); return builder; - }).when(client).prepareUpdate(anyString(), anyString(), anyString()); + }).when(client).prepareUpdate(nullable(String.class), nullable(String.class), nullable(String.class)); doAnswer(invocationOnMock -> { BulkRequestBuilder builder = new BulkRequestBuilder(client, BulkAction.INSTANCE); return builder; diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/token/TransportCreateTokenActionTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/token/TransportCreateTokenActionTests.java index 10535f65901a..948154c6f6eb 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/token/TransportCreateTokenActionTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/token/TransportCreateTokenActionTests.java @@ -34,7 +34,6 @@ import org.elasticsearch.common.settings.SecureString; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.index.shard.ShardId; import org.elasticsearch.license.MockLicenseState; -import org.elasticsearch.mock.orig.Mockito; import org.elasticsearch.node.Node; import org.elasticsearch.rest.RestStatus; import org.elasticsearch.test.ClusterServiceUtils; @@ -58,6 +57,7 @@ import org.elasticsearch.xpack.security.authc.kerberos.KerberosAuthenticationTok import org.elasticsearch.xpack.security.support.SecurityIndexManager; import org.junit.After; import org.junit.Before; +import org.mockito.Mockito; import java.nio.charset.StandardCharsets; import java.time.Clock; @@ -71,8 +71,8 @@ import java.util.function.Consumer; import static org.elasticsearch.test.ActionListenerUtils.anyActionListener; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.is; +import static org.mockito.ArgumentMatchers.nullable; import static org.mockito.Matchers.any; -import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; @@ -106,7 +106,7 @@ public class TransportCreateTokenActionTests extends ESTestCase { .setType((String) invocationOnMock.getArguments()[1]) .setId((String) invocationOnMock.getArguments()[2]); return builder; - }).when(client).prepareGet(anyString(), anyString(), anyString()); + }).when(client).prepareGet(nullable(String.class), nullable(String.class), nullable(String.class)); when(client.prepareMultiGet()).thenReturn(new MultiGetRequestBuilder(client, MultiGetAction.INSTANCE)); doAnswer(invocationOnMock -> { @SuppressWarnings("unchecked") @@ -125,9 +125,9 @@ public class TransportCreateTokenActionTests extends ESTestCase { listener.onResponse(response); return Void.TYPE; }).when(client).multiGet(any(MultiGetRequest.class), anyActionListener()); - when(client.prepareIndex(any(String.class), any(String.class), any(String.class))) + when(client.prepareIndex(nullable(String.class), nullable(String.class), nullable(String.class))) .thenReturn(new IndexRequestBuilder(client, IndexAction.INSTANCE)); - when(client.prepareUpdate(any(String.class), any(String.class), any(String.class))) + when(client.prepareUpdate(nullable(String.class), nullable(String.class), nullable(String.class))) .thenReturn(new UpdateRequestBuilder(client, UpdateAction.INSTANCE)); doAnswer(invocationOnMock -> { idxReqReference.set((IndexRequest) invocationOnMock.getArguments()[1]); diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/audit/logfile/LoggingAuditTrailFilterTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/audit/logfile/LoggingAuditTrailFilterTests.java index fca9a16abc10..9d109f422cd6 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/audit/logfile/LoggingAuditTrailFilterTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/audit/logfile/LoggingAuditTrailFilterTests.java @@ -18,16 +18,15 @@ import org.elasticsearch.common.settings.ClusterSettings; import org.elasticsearch.common.settings.Setting; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.util.concurrent.ThreadContext; -import org.elasticsearch.xcontent.NamedXContentRegistry; -import org.elasticsearch.xcontent.XContentType; import org.elasticsearch.license.XPackLicenseState; -import org.elasticsearch.mock.orig.Mockito; import org.elasticsearch.rest.RestRequest; import org.elasticsearch.test.ESTestCase; import org.elasticsearch.test.rest.FakeRestRequest; import org.elasticsearch.test.rest.FakeRestRequest.Builder; import org.elasticsearch.threadpool.ThreadPool; import org.elasticsearch.transport.TransportRequest; +import org.elasticsearch.xcontent.NamedXContentRegistry; +import org.elasticsearch.xcontent.XContentType; import org.elasticsearch.xpack.core.security.audit.logfile.CapturingLogger; import org.elasticsearch.xpack.core.security.authc.Authentication; import org.elasticsearch.xpack.core.security.authc.Authentication.RealmRef; @@ -44,6 +43,7 @@ import org.elasticsearch.xpack.security.support.CacheInvalidatorRegistry; import org.elasticsearch.xpack.security.support.SecurityIndexManager; import org.elasticsearch.xpack.security.transport.filter.SecurityIpFilterRule; import org.junit.Before; +import org.mockito.Mockito; import org.mockito.stubbing.Answer; import java.io.IOException; diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/audit/logfile/LoggingAuditTrailTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/audit/logfile/LoggingAuditTrailTests.java index 16d15cd6ac92..9a0c12ce052f 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/audit/logfile/LoggingAuditTrailTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/audit/logfile/LoggingAuditTrailTests.java @@ -21,7 +21,6 @@ import org.elasticsearch.common.Strings; import org.elasticsearch.common.bytes.BytesArray; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.collect.MapBuilder; -import org.elasticsearch.core.Tuple; import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.common.logging.Loggers; import org.elasticsearch.common.network.NetworkAddress; @@ -30,13 +29,10 @@ import org.elasticsearch.common.settings.SecureString; import org.elasticsearch.common.settings.Setting; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.transport.TransportAddress; -import org.elasticsearch.core.TimeValue; import org.elasticsearch.common.util.concurrent.ThreadContext; -import org.elasticsearch.xcontent.NamedXContentRegistry; -import org.elasticsearch.xcontent.XContentBuilder; -import org.elasticsearch.xcontent.XContentType; +import org.elasticsearch.core.TimeValue; +import org.elasticsearch.core.Tuple; import org.elasticsearch.license.XPackLicenseState; -import org.elasticsearch.mock.orig.Mockito; import org.elasticsearch.rest.RestRequest; import org.elasticsearch.tasks.Task; import org.elasticsearch.test.ESTestCase; @@ -44,6 +40,9 @@ import org.elasticsearch.test.rest.FakeRestRequest; import org.elasticsearch.test.rest.FakeRestRequest.Builder; import org.elasticsearch.threadpool.ThreadPool; import org.elasticsearch.transport.TransportRequest; +import org.elasticsearch.xcontent.NamedXContentRegistry; +import org.elasticsearch.xcontent.XContentBuilder; +import org.elasticsearch.xcontent.XContentType; import org.elasticsearch.xpack.core.XPackSettings; import org.elasticsearch.xpack.core.security.action.CreateApiKeyAction; import org.elasticsearch.xpack.core.security.action.CreateApiKeyRequest; @@ -113,6 +112,7 @@ import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; +import org.mockito.Mockito; import org.mockito.stubbing.Answer; import java.io.BufferedInputStream; diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/AuthenticationServiceTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/AuthenticationServiceTests.java index b1c8faa6f353..b4c495465c03 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/AuthenticationServiceTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/AuthenticationServiceTests.java @@ -100,7 +100,6 @@ import org.elasticsearch.xpack.security.support.CacheInvalidatorRegistry; import org.elasticsearch.xpack.security.support.SecurityIndexManager; import org.junit.After; import org.junit.Before; -import org.mockito.ArgumentMatcher; import org.mockito.Mockito; import java.io.IOException; @@ -141,6 +140,7 @@ import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.Matchers.nullValue; import static org.hamcrest.Matchers.sameInstance; +import static org.mockito.ArgumentMatchers.nullable; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.argThat; @@ -255,9 +255,9 @@ public class AuthenticationServiceTests extends ESTestCase { threadContext = threadPool.getThreadContext(); when(client.threadPool()).thenReturn(threadPool); when(client.settings()).thenReturn(settings); - when(client.prepareIndex(any(String.class), any(String.class), any(String.class))) + when(client.prepareIndex(nullable(String.class), nullable(String.class), nullable(String.class))) .thenReturn(new IndexRequestBuilder(client, IndexAction.INSTANCE)); - when(client.prepareUpdate(any(String.class), any(String.class), any(String.class))) + when(client.prepareUpdate(nullable(String.class), nullable(String.class), nullable(String.class))) .thenReturn(new UpdateRequestBuilder(client, UpdateAction.INSTANCE)); doAnswer(invocationOnMock -> { @SuppressWarnings("unchecked") @@ -272,7 +272,7 @@ public class AuthenticationServiceTests extends ESTestCase { .setType((String) invocationOnMock.getArguments()[1]) .setId((String) invocationOnMock.getArguments()[2]); return builder; - }).when(client).prepareGet(anyString(), anyString(), anyString()); + }).when(client).prepareGet(nullable(String.class), nullable(String.class), nullable(String.class)); securityIndex = mock(SecurityIndexManager.class); doAnswer(invocationOnMock -> { Runnable runnable = (Runnable) invocationOnMock.getArguments()[1]; @@ -2021,12 +2021,7 @@ public class AuthenticationServiceTests extends ESTestCase { verifyZeroInteractions(operatorPrivilegesService); final ServiceAccountToken serviceToken = ServiceAccountToken.fromBearerString(new SecureString(bearerString.toCharArray())); verify(auditTrail).authenticationFailed(eq(reqId.get()), - argThat(new ArgumentMatcher() { - @Override - public boolean matches(Object o) { - return ((ServiceAccountToken) o).getTokenId().equals(serviceToken.getTokenId()); - } - }), + argThat(o -> ((ServiceAccountToken) o).getTokenId().equals(serviceToken.getTokenId())), eq("_action"), eq(transportRequest)); } } diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/InternalRealmsTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/InternalRealmsTests.java index 6ed0288f8055..1a9a5c0460ae 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/InternalRealmsTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/InternalRealmsTests.java @@ -28,7 +28,7 @@ import org.elasticsearch.xpack.security.support.SecurityIndexManager; import java.util.Map; import java.util.function.BiConsumer; -import static org.elasticsearch.mock.orig.Mockito.times; +import static org.mockito.Mockito.times; import static org.hamcrest.CoreMatchers.nullValue; import static org.hamcrest.Matchers.any; import static org.hamcrest.Matchers.hasEntry; diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/TokenServiceTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/TokenServiceTests.java index b570f9860602..ea2049bbcff4 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/TokenServiceTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/TokenServiceTests.java @@ -959,7 +959,7 @@ public class TokenServiceTests extends ESTestCase { when(response.getSource()).thenReturn(sourceMap); } listener.onResponse(response); - return Void.TYPE; + return null; }).when(client).get(any(GetRequest.class), anyActionListener()); } @@ -1063,7 +1063,7 @@ public class TokenServiceTests extends ESTestCase { when(response.getHits()).thenReturn(hits); listener.onResponse(response); return Void.TYPE; - }).when(client).search(any(SearchRequest.class), anyActionListener()); + }).when(client).search(any(SearchRequest.class), any()); } private void mockGetTokenAsyncForDecryptedToken(String accessToken) { diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authz/AuthorizationServiceTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authz/AuthorizationServiceTests.java index 8e47079edd32..1d6d8bede9c7 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authz/AuthorizationServiceTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authz/AuthorizationServiceTests.java @@ -166,7 +166,6 @@ import org.elasticsearch.xpack.security.authz.store.NativePrivilegeStore; import org.elasticsearch.xpack.security.operator.OperatorPrivileges; import org.elasticsearch.xpack.sql.action.SqlQueryAction; import org.elasticsearch.xpack.sql.action.SqlQueryRequest; -import org.hamcrest.Description; import org.junit.Before; import org.mockito.ArgumentMatcher; import org.mockito.Matchers; @@ -2096,7 +2095,7 @@ public class AuthorizationServiceTests extends ESTestCase { return Matchers.argThat(new RBACAuthorizationInfoRoleMatcher(expectedRoles)); } - private static class RBACAuthorizationInfoRoleMatcher extends ArgumentMatcher { + private static class RBACAuthorizationInfoRoleMatcher implements ArgumentMatcher { private final String[] wanted; @@ -2105,17 +2104,9 @@ public class AuthorizationServiceTests extends ESTestCase { } @Override - public boolean matches(Object item) { - if (item instanceof AuthorizationInfo) { - final String[] found = (String[]) ((AuthorizationInfo) item).asMap().get(PRINCIPAL_ROLES_FIELD_NAME); - return Arrays.equals(wanted, found); - } - return false; - } - - @Override - public void describeTo(Description description) { - description.appendText("RBAC AuthorizationInfo Roles[").appendText(Strings.arrayToCommaDelimitedString(wanted)).appendText("]"); + public boolean matches(AuthorizationInfo other) { + final String[] found = (String[]) other.asMap().get(PRINCIPAL_ROLES_FIELD_NAME); + return Arrays.equals(wanted, found); } } diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authz/store/CompositeRolesStoreTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authz/store/CompositeRolesStoreTests.java index d732e701bb5a..9b1ef0d9495c 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authz/store/CompositeRolesStoreTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authz/store/CompositeRolesStoreTests.java @@ -94,8 +94,8 @@ import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; -import static org.elasticsearch.mock.orig.Mockito.times; -import static org.elasticsearch.mock.orig.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.elasticsearch.test.ActionListenerUtils.anyActionListener; import static org.elasticsearch.xpack.core.security.SecurityField.DOCUMENT_LEVEL_SECURITY_FEATURE; import static org.elasticsearch.xpack.core.security.authc.AuthenticationField.API_KEY_LIMITED_ROLE_DESCRIPTORS_KEY; diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authz/store/DeprecationRoleDescriptorConsumerTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authz/store/DeprecationRoleDescriptorConsumerTests.java index 76e8ad63d2f8..33e2fc98ce55 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authz/store/DeprecationRoleDescriptorConsumerTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authz/store/DeprecationRoleDescriptorConsumerTests.java @@ -17,7 +17,7 @@ import org.elasticsearch.common.logging.DeprecationCategory; import org.elasticsearch.common.logging.DeprecationLogger; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.util.concurrent.ThreadContext; -import org.elasticsearch.mock.orig.Mockito; +import org.mockito.Mockito; import org.elasticsearch.test.ESTestCase; import org.elasticsearch.test.VersionUtils; import org.elasticsearch.threadpool.ThreadPool; diff --git a/x-pack/plugin/stack/src/test/java/org/elasticsearch/xpack/stack/StackTemplateRegistryTests.java b/x-pack/plugin/stack/src/test/java/org/elasticsearch/xpack/stack/StackTemplateRegistryTests.java index 3972f8ce2d48..27db7aeadb7a 100644 --- a/x-pack/plugin/stack/src/test/java/org/elasticsearch/xpack/stack/StackTemplateRegistryTests.java +++ b/x-pack/plugin/stack/src/test/java/org/elasticsearch/xpack/stack/StackTemplateRegistryTests.java @@ -63,7 +63,6 @@ import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors; -import static org.elasticsearch.mock.orig.Mockito.when; import static org.hamcrest.Matchers.anyOf; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.greaterThan; @@ -71,6 +70,7 @@ import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.instanceOf; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.when; public class StackTemplateRegistryTests extends ESTestCase { private StackTemplateRegistry registry; diff --git a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/execution/ExecutionServiceTests.java b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/execution/ExecutionServiceTests.java index fe7d94308914..99c2f513c1f3 100644 --- a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/execution/ExecutionServiceTests.java +++ b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/execution/ExecutionServiceTests.java @@ -21,18 +21,12 @@ import org.elasticsearch.client.Client; import org.elasticsearch.cluster.node.DiscoveryNode; import org.elasticsearch.cluster.node.DiscoveryNodeRole; import org.elasticsearch.cluster.service.ClusterService; -import org.elasticsearch.core.Tuple; import org.elasticsearch.common.settings.Settings; -import org.elasticsearch.core.TimeValue; import org.elasticsearch.common.util.concurrent.EsExecutors; import org.elasticsearch.common.util.concurrent.EsRejectedExecutionException; import org.elasticsearch.common.util.concurrent.ThreadContext; -import org.elasticsearch.xcontent.DeprecationHandler; -import org.elasticsearch.xcontent.NamedXContentRegistry; -import org.elasticsearch.xcontent.ObjectPath; -import org.elasticsearch.xcontent.XContentFactory; -import org.elasticsearch.xcontent.XContentParser; -import org.elasticsearch.xcontent.XContentType; +import org.elasticsearch.core.TimeValue; +import org.elasticsearch.core.Tuple; import org.elasticsearch.index.Index; import org.elasticsearch.index.IndexNotFoundException; import org.elasticsearch.index.engine.VersionConflictEngineException; @@ -40,6 +34,12 @@ import org.elasticsearch.index.get.GetResult; import org.elasticsearch.index.shard.ShardId; import org.elasticsearch.test.ESTestCase; import org.elasticsearch.threadpool.ThreadPool; +import org.elasticsearch.xcontent.DeprecationHandler; +import org.elasticsearch.xcontent.NamedXContentRegistry; +import org.elasticsearch.xcontent.ObjectPath; +import org.elasticsearch.xcontent.XContentFactory; +import org.elasticsearch.xcontent.XContentParser; +import org.elasticsearch.xcontent.XContentType; import org.elasticsearch.xpack.core.security.authc.Authentication; import org.elasticsearch.xpack.core.security.authc.AuthenticationField; import org.elasticsearch.xpack.core.security.user.User; @@ -108,6 +108,7 @@ import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.Matchers.nullValue; import static org.hamcrest.Matchers.sameInstance; +import static org.mockito.ArgumentMatchers.nullable; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyLong; import static org.mockito.Matchers.anyObject; @@ -142,7 +143,7 @@ public class ExecutionServiceTests extends ESTestCase { inputResult = mock(Input.Result.class); when(inputResult.status()).thenReturn(Input.Result.Status.SUCCESS); when(inputResult.payload()).thenReturn(payload); - when(input.execute(any(WatchExecutionContext.class), any(Payload.class))).thenReturn(inputResult); + when(input.execute(any(WatchExecutionContext.class), nullable(Payload.class))).thenReturn(inputResult); triggeredWatchStore = mock(TriggeredWatchStore.class); historyStore = mock(HistoryStore.class); @@ -286,7 +287,7 @@ public class ExecutionServiceTests extends ESTestCase { Input.Result inputResult = mock(Input.Result.class); when(inputResult.status()).thenReturn(Input.Result.Status.FAILURE); when(inputResult.getException()).thenReturn(new IOException()); - when(input.execute(eq(context), any(Payload.class))).thenReturn(inputResult); + when(input.execute(eq(context), nullable(Payload.class))).thenReturn(inputResult); Condition.Result conditionResult = InternalAlwaysCondition.RESULT_INSTANCE; ExecutableCondition condition = mock(ExecutableCondition.class); diff --git a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/support/WatcherIndexTemplateRegistryTests.java b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/support/WatcherIndexTemplateRegistryTests.java index 9ddaf3cabe5c..6165c31fbabe 100644 --- a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/support/WatcherIndexTemplateRegistryTests.java +++ b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/support/WatcherIndexTemplateRegistryTests.java @@ -59,8 +59,8 @@ import java.util.List; import java.util.Map; import java.util.stream.Collectors; -import static org.elasticsearch.mock.orig.Mockito.verify; -import static org.elasticsearch.mock.orig.Mockito.when; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; import static org.elasticsearch.xpack.core.watcher.support.WatcherIndexTemplateRegistryField.INDEX_TEMPLATE_VERSION; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasSize; diff --git a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/test/integration/SearchInputTests.java b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/test/integration/SearchInputTests.java index 2bbd052059ad..bbc74ab75fee 100644 --- a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/test/integration/SearchInputTests.java +++ b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/test/integration/SearchInputTests.java @@ -55,7 +55,7 @@ import static org.elasticsearch.xcontent.XContentFactory.jsonBuilder; import static org.elasticsearch.index.query.QueryBuilders.boolQuery; import static org.elasticsearch.index.query.QueryBuilders.matchQuery; import static org.elasticsearch.index.query.QueryBuilders.rangeQuery; -import static org.elasticsearch.mock.orig.Mockito.when; +import static org.mockito.Mockito.when; import static org.elasticsearch.search.builder.SearchSourceBuilder.searchSource; import static org.elasticsearch.xpack.watcher.test.WatcherTestUtils.getRandomSupportedSearchType; import static org.hamcrest.Matchers.arrayContainingInAnyOrder;