mirror of
https://github.com/elastic/elasticsearch.git
synced 2025-04-24 23:27:25 -04:00
Securemock is a wrapper around Mockito that monkey patches internals of Mockito to work with the SecurityManager. However, the library has not been updated in several years due to the complicated nature of this monkey patching. This has left us with an ancient version of Mockito, missing out on updates to the library in the last half decade. While Securemock currently works with Mockito 1.x, in 2.x an official means of plugging into mockito was added, MockMaker. This commit removes securemock as a dependnecy of the test framework, replacing it with a modern version of Mockito, and implementing a MockMaker that integrates with SecurityManager. Note that while there is a newer version of Mockito available, 4.0, it has several deprecations removed that are used throughout Elasticsearch. Those can be addressed in followups, and then a subsequent upgrade to 4.0 should be possible. relates #79567 closes #40334
This commit is contained in:
parent
262db33192
commit
09c88797d2
86 changed files with 509 additions and 312 deletions
|
@ -40,7 +40,6 @@ httpasyncclient = 4.1.4
|
||||||
commonslogging = 1.1.3
|
commonslogging = 1.1.3
|
||||||
commonscodec = 1.11
|
commonscodec = 1.11
|
||||||
hamcrest = 2.1
|
hamcrest = 2.1
|
||||||
securemock = 1.2
|
|
||||||
mocksocket = 1.2
|
mocksocket = 1.2
|
||||||
|
|
||||||
# benchmark dependencies
|
# benchmark dependencies
|
||||||
|
|
|
@ -68,13 +68,13 @@ public class CustomRestHighLevelClientTests extends ESTestCase {
|
||||||
|
|
||||||
doAnswer(inv -> mockPerformRequest((Request) inv.getArguments()[0]))
|
doAnswer(inv -> mockPerformRequest((Request) inv.getArguments()[0]))
|
||||||
.when(restClient)
|
.when(restClient)
|
||||||
.performRequest(argThat(new RequestMatcher("GET", ENDPOINT)));
|
.performRequest(argThat(new RequestMatcher("GET", ENDPOINT)::matches));
|
||||||
|
|
||||||
doAnswer(inv -> mockPerformRequestAsync(
|
doAnswer(inv -> mockPerformRequestAsync(
|
||||||
((Request) inv.getArguments()[0]),
|
((Request) inv.getArguments()[0]),
|
||||||
(ResponseListener) inv.getArguments()[1]))
|
(ResponseListener) inv.getArguments()[1]))
|
||||||
.when(restClient)
|
.when(restClient)
|
||||||
.performRequestAsync(argThat(new RequestMatcher("GET", ENDPOINT)), any(ResponseListener.class));
|
.performRequestAsync(argThat(new RequestMatcher("GET", ENDPOINT)::matches), any(ResponseListener.class));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -236,7 +236,7 @@ public class RestHighLevelClientTests extends ESTestCase {
|
||||||
}
|
}
|
||||||
|
|
||||||
when(restClient
|
when(restClient
|
||||||
.performRequestAsync(argThat(new RequestMatcher("GET", "/")), any()))
|
.performRequestAsync(argThat(new RequestMatcher("GET", "/")::matches), any()))
|
||||||
.thenAnswer(i -> {
|
.thenAnswer(i -> {
|
||||||
((ResponseListener)i.getArguments()[1]).onSuccess(response);
|
((ResponseListener)i.getArguments()[1]).onSuccess(response);
|
||||||
return Cancellable.NO_OP;
|
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);
|
Build build = new Build(Build.Flavor.DEFAULT, Build.Type.UNKNOWN, "hash", "date", false, version);
|
||||||
mockGetRoot(restClient, build, setProductHeader);
|
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());
|
RestHighLevelClient highLevelClient = new RestHighLevelClient(restClient, RestClient::close, Collections.emptyList());
|
||||||
|
|
||||||
|
@ -1086,7 +1087,8 @@ public class RestHighLevelClientTests extends ESTestCase {
|
||||||
when(apiStatus.getStatusCode()).thenReturn(200);
|
when(apiStatus.getStatusCode()).thenReturn(200);
|
||||||
Response apiResponse = mock(Response.class);
|
Response apiResponse = mock(Response.class);
|
||||||
when(apiResponse.getStatusLine()).thenReturn(apiStatus);
|
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());
|
RestHighLevelClient highLevelClient = new RestHighLevelClient(restClient, RestClient::close, Collections.emptyList());
|
||||||
|
|
||||||
|
@ -1124,7 +1126,8 @@ public class RestHighLevelClientTests extends ESTestCase {
|
||||||
when(apiStatus.getStatusCode()).thenReturn(200);
|
when(apiStatus.getStatusCode()).thenReturn(200);
|
||||||
Response apiResponse = mock(Response.class);
|
Response apiResponse = mock(Response.class);
|
||||||
when(apiResponse.getStatusLine()).thenReturn(apiStatus);
|
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());
|
RestHighLevelClient highLevelClient = new RestHighLevelClient(restClient, RestClient::close, Collections.emptyList());
|
||||||
|
|
||||||
|
@ -1166,10 +1169,11 @@ public class RestHighLevelClientTests extends ESTestCase {
|
||||||
when(apiStatus.getStatusCode()).thenReturn(200);
|
when(apiStatus.getStatusCode()).thenReturn(200);
|
||||||
Response apiResponse = mock(Response.class);
|
Response apiResponse = mock(Response.class);
|
||||||
when(apiResponse.getStatusLine()).thenReturn(apiStatus);
|
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
|
// Have the verification request fail
|
||||||
when(restClient.performRequestAsync(argThat(new RequestMatcher("GET", "/")), any()))
|
when(restClient.performRequestAsync(argThat(new RequestMatcher("GET", "/")::matches), any()))
|
||||||
.thenAnswer(i -> {
|
.thenAnswer(i -> {
|
||||||
((ResponseListener)i.getArguments()[1]).onFailure(new IOException("Something bad happened"));
|
((ResponseListener)i.getArguments()[1]).onFailure(new IOException("Something bad happened"));
|
||||||
return Cancellable.NO_OP;
|
return Cancellable.NO_OP;
|
||||||
|
@ -1198,10 +1202,11 @@ public class RestHighLevelClientTests extends ESTestCase {
|
||||||
when(apiStatus.getStatusCode()).thenReturn(200);
|
when(apiStatus.getStatusCode()).thenReturn(200);
|
||||||
Response apiResponse = mock(Response.class);
|
Response apiResponse = mock(Response.class);
|
||||||
when(apiResponse.getStatusLine()).thenReturn(apiStatus);
|
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)
|
// 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 -> {
|
.thenAnswer(i -> {
|
||||||
StatusLine infoStatus = mock(StatusLine.class);
|
StatusLine infoStatus = mock(StatusLine.class);
|
||||||
when(apiStatus.getStatusCode()).thenReturn(HttpStatus.SC_FORBIDDEN);
|
when(apiStatus.getStatusCode()).thenReturn(HttpStatus.SC_FORBIDDEN);
|
||||||
|
@ -1224,7 +1229,8 @@ public class RestHighLevelClientTests extends ESTestCase {
|
||||||
|
|
||||||
mockGetRoot(restClient);
|
mockGetRoot(restClient);
|
||||||
Cancellable cancellable = mock(Cancellable.class);
|
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(
|
Cancellable result = restHighLevelClient.existsSourceAsync(
|
||||||
new GetSourceRequest("foo", "bar"),
|
new GetSourceRequest("foo", "bar"),
|
||||||
|
|
|
@ -44,7 +44,6 @@ dependencies {
|
||||||
testImplementation "com.carrotsearch.randomizedtesting:randomizedtesting-runner:${versions.randomizedrunner}"
|
testImplementation "com.carrotsearch.randomizedtesting:randomizedtesting-runner:${versions.randomizedrunner}"
|
||||||
testImplementation "junit:junit:${versions.junit}"
|
testImplementation "junit:junit:${versions.junit}"
|
||||||
testImplementation "org.hamcrest:hamcrest:${versions.hamcrest}"
|
testImplementation "org.hamcrest:hamcrest:${versions.hamcrest}"
|
||||||
testImplementation "org.elasticsearch:securemock:${versions.securemock}"
|
|
||||||
testImplementation "org.elasticsearch:mocksocket:${versions.mocksocket}"
|
testImplementation "org.elasticsearch:mocksocket:${versions.mocksocket}"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -54,7 +54,6 @@ import org.junit.Before;
|
||||||
import org.mockito.ArgumentCaptor;
|
import org.mockito.ArgumentCaptor;
|
||||||
import org.mockito.stubbing.Answer;
|
import org.mockito.stubbing.Answer;
|
||||||
|
|
||||||
import javax.net.ssl.SSLHandshakeException;
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.io.PrintWriter;
|
import java.io.PrintWriter;
|
||||||
import java.io.StringWriter;
|
import java.io.StringWriter;
|
||||||
|
@ -72,6 +71,7 @@ import java.util.concurrent.ExecutorService;
|
||||||
import java.util.concurrent.Executors;
|
import java.util.concurrent.Executors;
|
||||||
import java.util.concurrent.Future;
|
import java.util.concurrent.Future;
|
||||||
import java.util.concurrent.atomic.AtomicReference;
|
import java.util.concurrent.atomic.AtomicReference;
|
||||||
|
import javax.net.ssl.SSLHandshakeException;
|
||||||
|
|
||||||
import static java.util.Collections.singletonList;
|
import static java.util.Collections.singletonList;
|
||||||
import static org.elasticsearch.client.RestClientTestUtil.getAllErrorStatusCodes;
|
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.assertThat;
|
||||||
import static org.junit.Assert.assertTrue;
|
import static org.junit.Assert.assertTrue;
|
||||||
import static org.junit.Assert.fail;
|
import static org.junit.Assert.fail;
|
||||||
|
import static org.mockito.ArgumentMatchers.nullable;
|
||||||
import static org.mockito.Matchers.any;
|
import static org.mockito.Matchers.any;
|
||||||
import static org.mockito.Mockito.mock;
|
import static org.mockito.Mockito.mock;
|
||||||
import static org.mockito.Mockito.times;
|
import static org.mockito.Mockito.times;
|
||||||
|
@ -124,7 +125,7 @@ public class RestClientSingleHostTests extends RestClientTestCase {
|
||||||
static CloseableHttpAsyncClient mockHttpClient(final ExecutorService exec) {
|
static CloseableHttpAsyncClient mockHttpClient(final ExecutorService exec) {
|
||||||
CloseableHttpAsyncClient httpClient = mock(CloseableHttpAsyncClient.class);
|
CloseableHttpAsyncClient httpClient = mock(CloseableHttpAsyncClient.class);
|
||||||
when(httpClient.<HttpResponse>execute(any(HttpAsyncRequestProducer.class), any(HttpAsyncResponseConsumer.class),
|
when(httpClient.<HttpResponse>execute(any(HttpAsyncRequestProducer.class), any(HttpAsyncResponseConsumer.class),
|
||||||
any(HttpClientContext.class), any(FutureCallback.class))).thenAnswer((Answer<Future<HttpResponse>>) invocationOnMock -> {
|
any(HttpClientContext.class), nullable(FutureCallback.class))).thenAnswer((Answer<Future<HttpResponse>>) invocationOnMock -> {
|
||||||
final HttpAsyncRequestProducer requestProducer = (HttpAsyncRequestProducer) invocationOnMock.getArguments()[0];
|
final HttpAsyncRequestProducer requestProducer = (HttpAsyncRequestProducer) invocationOnMock.getArguments()[0];
|
||||||
final FutureCallback<HttpResponse> futureCallback =
|
final FutureCallback<HttpResponse> futureCallback =
|
||||||
(FutureCallback<HttpResponse>) invocationOnMock.getArguments()[3];
|
(FutureCallback<HttpResponse>) invocationOnMock.getArguments()[3];
|
||||||
|
@ -202,7 +203,7 @@ public class RestClientSingleHostTests extends RestClientTestCase {
|
||||||
for (String httpMethod : getHttpMethods()) {
|
for (String httpMethod : getHttpMethods()) {
|
||||||
HttpUriRequest expectedRequest = performRandomRequest(httpMethod);
|
HttpUriRequest expectedRequest = performRandomRequest(httpMethod);
|
||||||
verify(httpClient, times(++times)).<HttpResponse>execute(requestArgumentCaptor.capture(),
|
verify(httpClient, times(++times)).<HttpResponse>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();
|
HttpUriRequest actualRequest = (HttpUriRequest)requestArgumentCaptor.getValue().generateRequest();
|
||||||
assertEquals(expectedRequest.getURI(), actualRequest.getURI());
|
assertEquals(expectedRequest.getURI(), actualRequest.getURI());
|
||||||
assertEquals(expectedRequest.getClass(), actualRequest.getClass());
|
assertEquals(expectedRequest.getClass(), actualRequest.getClass());
|
||||||
|
|
|
@ -42,7 +42,6 @@ dependencies {
|
||||||
testImplementation project(":client:test")
|
testImplementation project(":client:test")
|
||||||
testImplementation "com.carrotsearch.randomizedtesting:randomizedtesting-runner:${versions.randomizedrunner}"
|
testImplementation "com.carrotsearch.randomizedtesting:randomizedtesting-runner:${versions.randomizedrunner}"
|
||||||
testImplementation "junit:junit:${versions.junit}"
|
testImplementation "junit:junit:${versions.junit}"
|
||||||
testImplementation "org.elasticsearch:securemock:${versions.securemock}"
|
|
||||||
testImplementation "org.elasticsearch:mocksocket:${versions.mocksocket}"
|
testImplementation "org.elasticsearch:mocksocket:${versions.mocksocket}"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -23,6 +23,11 @@ dependencies {
|
||||||
api "com.carrotsearch.randomizedtesting:randomizedtesting-runner:${versions.randomizedrunner}"
|
api "com.carrotsearch.randomizedtesting:randomizedtesting-runner:${versions.randomizedrunner}"
|
||||||
api "junit:junit:${versions.junit}"
|
api "junit:junit:${versions.junit}"
|
||||||
api "org.hamcrest:hamcrest:${versions.hamcrest}"
|
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 {
|
tasks.named('forbiddenApisMain').configure {
|
||||||
|
@ -38,6 +43,9 @@ tasks.named('forbiddenApisTest').configure {
|
||||||
replaceSignatureFiles 'jdk-signatures'
|
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
|
// JarHell is part of es server, which we don't want to pull in
|
||||||
// TODO: Not anymore. Now in :libs:elasticsearch-core
|
// TODO: Not anymore. Now in :libs:elasticsearch-core
|
||||||
tasks.named("jarHell").configure { enabled = false }
|
tasks.named("jarHell").configure { enabled = false }
|
||||||
|
|
|
@ -8,9 +8,9 @@
|
||||||
|
|
||||||
package org.elasticsearch.nio;
|
package org.elasticsearch.nio;
|
||||||
|
|
||||||
|
import org.elasticsearch.common.util.concurrent.AbstractRunnable;
|
||||||
import org.elasticsearch.core.CheckedRunnable;
|
import org.elasticsearch.core.CheckedRunnable;
|
||||||
import org.elasticsearch.core.TimeValue;
|
import org.elasticsearch.core.TimeValue;
|
||||||
import org.elasticsearch.common.util.concurrent.AbstractRunnable;
|
|
||||||
import org.elasticsearch.test.ESTestCase;
|
import org.elasticsearch.test.ESTestCase;
|
||||||
import org.junit.Before;
|
import org.junit.Before;
|
||||||
import org.mockito.ArgumentCaptor;
|
import org.mockito.ArgumentCaptor;
|
||||||
|
@ -27,8 +27,8 @@ import java.util.concurrent.TimeUnit;
|
||||||
import java.util.concurrent.atomic.AtomicBoolean;
|
import java.util.concurrent.atomic.AtomicBoolean;
|
||||||
import java.util.function.BiConsumer;
|
import java.util.function.BiConsumer;
|
||||||
|
|
||||||
|
import static org.mockito.ArgumentMatchers.anyLong;
|
||||||
import static org.mockito.Matchers.any;
|
import static org.mockito.Matchers.any;
|
||||||
import static org.mockito.Matchers.anyInt;
|
|
||||||
import static org.mockito.Matchers.isNull;
|
import static org.mockito.Matchers.isNull;
|
||||||
import static org.mockito.Matchers.same;
|
import static org.mockito.Matchers.same;
|
||||||
import static org.mockito.Mockito.doAnswer;
|
import static org.mockito.Mockito.doAnswer;
|
||||||
|
@ -168,7 +168,7 @@ public class NioSelectorTests extends ESTestCase {
|
||||||
|
|
||||||
public void testSelectorClosedExceptionIsNotCaughtWhileRunning() throws IOException {
|
public void testSelectorClosedExceptionIsNotCaughtWhileRunning() throws IOException {
|
||||||
boolean closedSelectorExceptionCaught = false;
|
boolean closedSelectorExceptionCaught = false;
|
||||||
when(rawSelector.select(anyInt())).thenThrow(new ClosedSelectorException());
|
when(rawSelector.select(anyLong())).thenThrow(new ClosedSelectorException());
|
||||||
try {
|
try {
|
||||||
this.selector.singleLoop();
|
this.selector.singleLoop();
|
||||||
} catch (ClosedSelectorException e) {
|
} catch (ClosedSelectorException e) {
|
||||||
|
@ -181,7 +181,7 @@ public class NioSelectorTests extends ESTestCase {
|
||||||
public void testIOExceptionWhileSelect() throws IOException {
|
public void testIOExceptionWhileSelect() throws IOException {
|
||||||
IOException ioException = new IOException();
|
IOException ioException = new IOException();
|
||||||
|
|
||||||
when(rawSelector.select(anyInt())).thenThrow(ioException);
|
when(rawSelector.select(anyLong())).thenThrow(ioException);
|
||||||
|
|
||||||
this.selector.singleLoop();
|
this.selector.singleLoop();
|
||||||
|
|
||||||
|
|
|
@ -30,7 +30,7 @@ import org.elasticsearch.index.mapper.MapperBuilderContext;
|
||||||
import org.elasticsearch.index.mapper.TestDocumentParserContext;
|
import org.elasticsearch.index.mapper.TestDocumentParserContext;
|
||||||
import org.elasticsearch.index.query.SearchExecutionContext;
|
import org.elasticsearch.index.query.SearchExecutionContext;
|
||||||
import org.elasticsearch.index.query.TermQueryBuilder;
|
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.SearchModule;
|
||||||
import org.elasticsearch.search.aggregations.support.CoreValuesSourceType;
|
import org.elasticsearch.search.aggregations.support.CoreValuesSourceType;
|
||||||
import org.elasticsearch.test.ESTestCase;
|
import org.elasticsearch.test.ESTestCase;
|
||||||
|
|
|
@ -10,7 +10,7 @@
|
||||||
//// These are mock objects and test management that we allow test framework libs
|
//// 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!
|
//// 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)
|
// needed to access ReflectionFactory (see below)
|
||||||
permission java.lang.RuntimePermission "accessClassInPackage.sun.reflect";
|
permission java.lang.RuntimePermission "accessClassInPackage.sun.reflect";
|
||||||
// needed for reflection in ibm jdk
|
// needed for reflection in ibm jdk
|
||||||
|
@ -20,6 +20,27 @@ grant codeBase "${codebase.securemock}" {
|
||||||
// needed for spy interception, etc
|
// needed for spy interception, etc
|
||||||
permission java.lang.RuntimePermission "accessDeclaredMembers";
|
permission java.lang.RuntimePermission "accessDeclaredMembers";
|
||||||
permission java.lang.reflect.ReflectPermission "suppressAccessChecks";
|
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}" {
|
grant codeBase "${codebase.lucene-test-framework}" {
|
||||||
|
|
|
@ -165,7 +165,7 @@ public class TransportBulkActionIngestTests extends ESTestCase {
|
||||||
// initialize captors, which must be members to use @Capture because of generics
|
// initialize captors, which must be members to use @Capture because of generics
|
||||||
threadPool = mock(ThreadPool.class);
|
threadPool = mock(ThreadPool.class);
|
||||||
when(threadPool.executor(anyString())).thenReturn(EsExecutors.DIRECT_EXECUTOR_SERVICE);
|
when(threadPool.executor(anyString())).thenReturn(EsExecutors.DIRECT_EXECUTOR_SERVICE);
|
||||||
MockitoAnnotations.initMocks(this);
|
MockitoAnnotations.openMocks(this);
|
||||||
// setup services that will be called by action
|
// setup services that will be called by action
|
||||||
transportService = mock(TransportService.class);
|
transportService = mock(TransportService.class);
|
||||||
clusterService = mock(ClusterService.class);
|
clusterService = mock(ClusterService.class);
|
||||||
|
|
|
@ -54,6 +54,7 @@ import static java.util.Collections.emptySet;
|
||||||
import static org.elasticsearch.common.UUIDs.randomBase64UUID;
|
import static org.elasticsearch.common.UUIDs.randomBase64UUID;
|
||||||
import static org.hamcrest.Matchers.equalTo;
|
import static org.hamcrest.Matchers.equalTo;
|
||||||
import static org.hamcrest.Matchers.instanceOf;
|
import static org.hamcrest.Matchers.instanceOf;
|
||||||
|
import static org.mockito.ArgumentMatchers.nullable;
|
||||||
import static org.mockito.Matchers.anyString;
|
import static org.mockito.Matchers.anyString;
|
||||||
import static org.mockito.Matchers.eq;
|
import static org.mockito.Matchers.eq;
|
||||||
import static org.mockito.Mockito.mock;
|
import static org.mockito.Mockito.mock;
|
||||||
|
@ -121,13 +122,15 @@ public class TransportMultiGetActionTests extends ESTestCase {
|
||||||
when(index2ShardIterator.shardId()).thenReturn(new ShardId(index2, randomInt()));
|
when(index2ShardIterator.shardId()).thenReturn(new ShardId(index2, randomInt()));
|
||||||
|
|
||||||
final OperationRouting operationRouting = mock(OperationRouting.class);
|
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);
|
.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()));
|
.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);
|
.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()));
|
.thenReturn(new ShardId(index2, randomInt()));
|
||||||
|
|
||||||
clusterService = mock(ClusterService.class);
|
clusterService = mock(ClusterService.class);
|
||||||
|
|
|
@ -55,6 +55,7 @@ import static java.util.Collections.emptySet;
|
||||||
import static org.elasticsearch.common.UUIDs.randomBase64UUID;
|
import static org.elasticsearch.common.UUIDs.randomBase64UUID;
|
||||||
import static org.hamcrest.Matchers.equalTo;
|
import static org.hamcrest.Matchers.equalTo;
|
||||||
import static org.hamcrest.Matchers.instanceOf;
|
import static org.hamcrest.Matchers.instanceOf;
|
||||||
|
import static org.mockito.ArgumentMatchers.nullable;
|
||||||
import static org.mockito.Matchers.anyString;
|
import static org.mockito.Matchers.anyString;
|
||||||
import static org.mockito.Matchers.eq;
|
import static org.mockito.Matchers.eq;
|
||||||
import static org.mockito.Mockito.mock;
|
import static org.mockito.Mockito.mock;
|
||||||
|
@ -122,13 +123,15 @@ public class TransportMultiTermVectorsActionTests extends ESTestCase {
|
||||||
when(index2ShardIterator.shardId()).thenReturn(new ShardId(index2, randomInt()));
|
when(index2ShardIterator.shardId()).thenReturn(new ShardId(index2, randomInt()));
|
||||||
|
|
||||||
final OperationRouting operationRouting = mock(OperationRouting.class);
|
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);
|
.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()));
|
.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);
|
.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()));
|
.thenReturn(new ShardId(index2, randomInt()));
|
||||||
|
|
||||||
clusterService = mock(ClusterService.class);
|
clusterService = mock(ClusterService.class);
|
||||||
|
|
|
@ -11,7 +11,7 @@ package org.elasticsearch.common.settings;
|
||||||
import org.elasticsearch.cluster.ClusterState;
|
import org.elasticsearch.cluster.ClusterState;
|
||||||
import org.elasticsearch.cluster.ClusterStateUpdateTask;
|
import org.elasticsearch.cluster.ClusterStateUpdateTask;
|
||||||
import org.elasticsearch.cluster.service.ClusterService;
|
import org.elasticsearch.cluster.service.ClusterService;
|
||||||
import org.elasticsearch.mock.orig.Mockito;
|
import org.mockito.Mockito;
|
||||||
import org.elasticsearch.test.ESTestCase;
|
import org.elasticsearch.test.ESTestCase;
|
||||||
import org.junit.Before;
|
import org.junit.Before;
|
||||||
import org.mockito.stubbing.Answer;
|
import org.mockito.stubbing.Answer;
|
||||||
|
|
|
@ -20,11 +20,11 @@ import org.elasticsearch.common.network.NetworkService;
|
||||||
import org.elasticsearch.common.settings.Settings;
|
import org.elasticsearch.common.settings.Settings;
|
||||||
import org.elasticsearch.common.transport.BoundTransportAddress;
|
import org.elasticsearch.common.transport.BoundTransportAddress;
|
||||||
import org.elasticsearch.common.transport.TransportAddress;
|
import org.elasticsearch.common.transport.TransportAddress;
|
||||||
import org.elasticsearch.core.TimeValue;
|
|
||||||
import org.elasticsearch.common.util.CancellableThreads;
|
import org.elasticsearch.common.util.CancellableThreads;
|
||||||
import org.elasticsearch.common.util.PageCacheRecycler;
|
import org.elasticsearch.common.util.PageCacheRecycler;
|
||||||
import org.elasticsearch.common.util.concurrent.EsExecutors;
|
import org.elasticsearch.common.util.concurrent.EsExecutors;
|
||||||
import org.elasticsearch.common.util.concurrent.FutureUtils;
|
import org.elasticsearch.common.util.concurrent.FutureUtils;
|
||||||
|
import org.elasticsearch.core.TimeValue;
|
||||||
import org.elasticsearch.core.internal.io.IOUtils;
|
import org.elasticsearch.core.internal.io.IOUtils;
|
||||||
import org.elasticsearch.indices.breaker.NoneCircuitBreakerService;
|
import org.elasticsearch.indices.breaker.NoneCircuitBreakerService;
|
||||||
import org.elasticsearch.test.ESTestCase;
|
import org.elasticsearch.test.ESTestCase;
|
||||||
|
@ -49,7 +49,6 @@ import java.util.List;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
import java.util.Stack;
|
import java.util.Stack;
|
||||||
import java.util.concurrent.CountDownLatch;
|
import java.util.concurrent.CountDownLatch;
|
||||||
import java.util.concurrent.ExecutionException;
|
|
||||||
import java.util.concurrent.ExecutorService;
|
import java.util.concurrent.ExecutorService;
|
||||||
import java.util.concurrent.ThreadFactory;
|
import java.util.concurrent.ThreadFactory;
|
||||||
import java.util.concurrent.TimeUnit;
|
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, 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).getAddress(), equalTo("127.0.0.1"));
|
||||||
assertThat(transportAddresses.get(0).getPort(), equalTo(9301));
|
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));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -28,8 +28,8 @@ import org.elasticsearch.transport.TransportService;
|
||||||
|
|
||||||
import java.util.Collections;
|
import java.util.Collections;
|
||||||
|
|
||||||
import static org.elasticsearch.mock.orig.Mockito.never;
|
import static org.mockito.Mockito.never;
|
||||||
import static org.elasticsearch.mock.orig.Mockito.when;
|
import static org.mockito.Mockito.when;
|
||||||
import static org.elasticsearch.test.ClusterServiceUtils.createClusterService;
|
import static org.elasticsearch.test.ClusterServiceUtils.createClusterService;
|
||||||
import static org.mockito.Mockito.mock;
|
import static org.mockito.Mockito.mock;
|
||||||
import static org.mockito.Mockito.verify;
|
import static org.mockito.Mockito.verify;
|
||||||
|
|
|
@ -34,7 +34,7 @@ import java.util.Collections;
|
||||||
import java.util.concurrent.CountDownLatch;
|
import java.util.concurrent.CountDownLatch;
|
||||||
import java.util.concurrent.atomic.AtomicBoolean;
|
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.elasticsearch.test.ClusterServiceUtils.createClusterService;
|
||||||
import static org.hamcrest.Matchers.sameInstance;
|
import static org.hamcrest.Matchers.sameInstance;
|
||||||
import static org.mockito.Mockito.mock;
|
import static org.mockito.Mockito.mock;
|
||||||
|
|
|
@ -33,7 +33,7 @@ import org.elasticsearch.transport.TransportService;
|
||||||
import java.util.Collections;
|
import java.util.Collections;
|
||||||
import java.util.concurrent.atomic.AtomicBoolean;
|
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.elasticsearch.test.ClusterServiceUtils.createClusterService;
|
||||||
import static org.hamcrest.Matchers.sameInstance;
|
import static org.hamcrest.Matchers.sameInstance;
|
||||||
import static org.mockito.Mockito.mock;
|
import static org.mockito.Mockito.mock;
|
||||||
|
|
|
@ -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.NO_OPS_PERFORMED;
|
||||||
import static org.elasticsearch.index.seqno.SequenceNumbers.UNASSIGNED_SEQ_NO;
|
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.containsString;
|
||||||
import static org.hamcrest.Matchers.equalTo;
|
import static org.hamcrest.Matchers.equalTo;
|
||||||
import static org.hamcrest.Matchers.hasToString;
|
import static org.hamcrest.Matchers.hasToString;
|
||||||
import static org.hamcrest.Matchers.instanceOf;
|
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.doAnswer;
|
||||||
import static org.mockito.Mockito.mock;
|
import static org.mockito.Mockito.mock;
|
||||||
import static org.mockito.Mockito.reset;
|
import static org.mockito.Mockito.reset;
|
||||||
|
@ -622,7 +621,7 @@ public class GlobalCheckpointListenersTests extends ESTestCase {
|
||||||
doAnswer(invocationOnMock -> {
|
doAnswer(invocationOnMock -> {
|
||||||
latch.countDown();
|
latch.countDown();
|
||||||
return null;
|
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 =
|
final GlobalCheckpointListeners globalCheckpointListeners =
|
||||||
new GlobalCheckpointListeners(shardId, scheduler, mockLogger);
|
new GlobalCheckpointListeners(shardId, scheduler, mockLogger);
|
||||||
final TimeValue timeout = TimeValue.timeValueMillis(randomIntBetween(1, 50));
|
final TimeValue timeout = TimeValue.timeValueMillis(randomIntBetween(1, 50));
|
||||||
|
|
|
@ -134,7 +134,7 @@ import static org.hamcrest.Matchers.lessThanOrEqualTo;
|
||||||
import static org.hamcrest.Matchers.not;
|
import static org.hamcrest.Matchers.not;
|
||||||
import static org.hamcrest.Matchers.nullValue;
|
import static org.hamcrest.Matchers.nullValue;
|
||||||
import static org.mockito.Mockito.mock;
|
import static org.mockito.Mockito.mock;
|
||||||
import static org.mockito.Mockito.stub;
|
import static org.mockito.Mockito.when;
|
||||||
|
|
||||||
@LuceneTestCase.SuppressFileSystems("ExtrasFS")
|
@LuceneTestCase.SuppressFileSystems("ExtrasFS")
|
||||||
public class TranslogTests extends ESTestCase {
|
public class TranslogTests extends ESTestCase {
|
||||||
|
@ -385,7 +385,7 @@ public class TranslogTests extends ESTestCase {
|
||||||
long period = randomLongBetween(10000, 1000000);
|
long period = randomLongBetween(10000, 1000000);
|
||||||
periods[numberOfReaders] = period;
|
periods[numberOfReaders] = period;
|
||||||
TranslogWriter w = mock(TranslogWriter.class);
|
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));
|
assertThat(Translog.findEarliestLastModifiedAge(fixedTime, new ArrayList<>(), w), equalTo(period));
|
||||||
|
|
||||||
for (int i = 0; i < numberOfReaders; i++) {
|
for (int i = 0; i < numberOfReaders; i++) {
|
||||||
|
@ -394,7 +394,7 @@ public class TranslogTests extends ESTestCase {
|
||||||
List<TranslogReader> readers = new ArrayList<>();
|
List<TranslogReader> readers = new ArrayList<>();
|
||||||
for (long l : periods) {
|
for (long l : periods) {
|
||||||
TranslogReader r = mock(TranslogReader.class);
|
TranslogReader r = mock(TranslogReader.class);
|
||||||
stub(r.getLastModifiedTime()).toReturn(fixedTime - l);
|
when(r.getLastModifiedTime()).thenReturn(fixedTime - l);
|
||||||
readers.add(r);
|
readers.add(r);
|
||||||
}
|
}
|
||||||
assertThat(Translog.findEarliestLastModifiedAge(fixedTime, readers, w), equalTo
|
assertThat(Translog.findEarliestLastModifiedAge(fixedTime, readers, w), equalTo
|
||||||
|
|
|
@ -60,7 +60,6 @@ import org.elasticsearch.threadpool.ThreadPool.Names;
|
||||||
import org.elasticsearch.xcontent.XContentBuilder;
|
import org.elasticsearch.xcontent.XContentBuilder;
|
||||||
import org.elasticsearch.xcontent.XContentType;
|
import org.elasticsearch.xcontent.XContentType;
|
||||||
import org.elasticsearch.xcontent.cbor.CborXContent;
|
import org.elasticsearch.xcontent.cbor.CborXContent;
|
||||||
import org.hamcrest.CustomTypeSafeMatcher;
|
|
||||||
import org.junit.Before;
|
import org.junit.Before;
|
||||||
import org.mockito.ArgumentMatcher;
|
import org.mockito.ArgumentMatcher;
|
||||||
import org.mockito.invocation.InvocationOnMock;
|
import org.mockito.invocation.InvocationOnMock;
|
||||||
|
@ -853,19 +852,8 @@ public class IngestServiceTests extends ESTestCase {
|
||||||
ingestService.executeBulkRequest(bulkRequest.numberOfActions(), bulkRequest.requests(), failureHandler,
|
ingestService.executeBulkRequest(bulkRequest.numberOfActions(), bulkRequest.requests(), failureHandler,
|
||||||
completionHandler, indexReq -> {}, Names.WRITE);
|
completionHandler, indexReq -> {}, Names.WRITE);
|
||||||
verify(failureHandler, times(1)).accept(
|
verify(failureHandler, times(1)).accept(
|
||||||
argThat(new CustomTypeSafeMatcher<Integer>("failure handler was not called with the expected arguments") {
|
argThat(item -> item == 2),
|
||||||
@Override
|
argThat(iae -> "pipeline with id [does_not_exist] does not exist".equals(iae.getMessage()))
|
||||||
protected boolean matchesSafely(Integer item) {
|
|
||||||
return item == 2;
|
|
||||||
}
|
|
||||||
|
|
||||||
}),
|
|
||||||
argThat(new CustomTypeSafeMatcher<IllegalArgumentException>("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());
|
|
||||||
}
|
|
||||||
})
|
|
||||||
);
|
);
|
||||||
verify(completionHandler, times(1)).accept(Thread.currentThread(), null);
|
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 -> {},
|
ingestService.executeBulkRequest(numRequest, bulkRequest.requests(), requestItemErrorHandler, completionHandler, indexReq -> {},
|
||||||
Names.WRITE);
|
Names.WRITE);
|
||||||
|
|
||||||
verify(requestItemErrorHandler, times(numIndexRequests)).accept(anyInt(), argThat(new ArgumentMatcher<Exception>() {
|
verify(requestItemErrorHandler, times(numIndexRequests)).accept(anyInt(), argThat(e -> e.getCause().equals(error)));
|
||||||
@Override
|
|
||||||
public boolean matches(final Object o) {
|
|
||||||
return ((Exception)o).getCause().equals(error);
|
|
||||||
}
|
|
||||||
}));
|
|
||||||
verify(completionHandler, times(1)).accept(Thread.currentThread(), null);
|
verify(completionHandler, times(1)).accept(Thread.currentThread(), null);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -1856,7 +1839,7 @@ public class IngestServiceTests extends ESTestCase {
|
||||||
return processor;
|
return processor;
|
||||||
}
|
}
|
||||||
|
|
||||||
private class IngestDocumentMatcher extends ArgumentMatcher<IngestDocument> {
|
private class IngestDocumentMatcher implements ArgumentMatcher<IngestDocument> {
|
||||||
|
|
||||||
private final IngestDocument ingestDocument;
|
private final IngestDocument ingestDocument;
|
||||||
|
|
||||||
|
@ -1869,13 +1852,9 @@ public class IngestServiceTests extends ESTestCase {
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean matches(Object o) {
|
public boolean matches(IngestDocument other) {
|
||||||
if (o.getClass() == IngestDocument.class) {
|
//ingest metadata will not be the same (timestamp differs every time)
|
||||||
IngestDocument otherIngestDocument = (IngestDocument) o;
|
return Objects.equals(ingestDocument.getSourceAndMetadata(), other.getSourceAndMetadata());
|
||||||
//ingest metadata will not be the same (timestamp differs every time)
|
|
||||||
return Objects.equals(ingestDocument.getSourceAndMetadata(), otherIngestDocument.getSourceAndMetadata());
|
|
||||||
}
|
|
||||||
return false;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -16,8 +16,8 @@ import org.elasticsearch.cluster.routing.RecoverySource.SnapshotRecoverySource;
|
||||||
import org.elasticsearch.cluster.routing.TestShardRouting;
|
import org.elasticsearch.cluster.routing.TestShardRouting;
|
||||||
import org.elasticsearch.common.Randomness;
|
import org.elasticsearch.common.Randomness;
|
||||||
import org.elasticsearch.common.Table;
|
import org.elasticsearch.common.Table;
|
||||||
import org.elasticsearch.core.TimeValue;
|
|
||||||
import org.elasticsearch.common.xcontent.XContentElasticsearchExtension;
|
import org.elasticsearch.common.xcontent.XContentElasticsearchExtension;
|
||||||
|
import org.elasticsearch.core.TimeValue;
|
||||||
import org.elasticsearch.index.Index;
|
import org.elasticsearch.index.Index;
|
||||||
import org.elasticsearch.index.shard.ShardId;
|
import org.elasticsearch.index.shard.ShardId;
|
||||||
import org.elasticsearch.indices.recovery.RecoveryState;
|
import org.elasticsearch.indices.recovery.RecoveryState;
|
||||||
|
@ -31,9 +31,9 @@ import java.util.List;
|
||||||
import java.util.Locale;
|
import java.util.Locale;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
|
||||||
import static org.elasticsearch.mock.orig.Mockito.when;
|
|
||||||
import static org.hamcrest.CoreMatchers.equalTo;
|
import static org.hamcrest.CoreMatchers.equalTo;
|
||||||
import static org.mockito.Mockito.mock;
|
import static org.mockito.Mockito.mock;
|
||||||
|
import static org.mockito.Mockito.when;
|
||||||
|
|
||||||
public class RestRecoveryActionTests extends ESTestCase {
|
public class RestRecoveryActionTests extends ESTestCase {
|
||||||
|
|
||||||
|
|
|
@ -54,6 +54,7 @@ import java.util.function.Supplier;
|
||||||
|
|
||||||
import static org.hamcrest.Matchers.equalTo;
|
import static org.hamcrest.Matchers.equalTo;
|
||||||
import static org.hamcrest.Matchers.is;
|
import static org.hamcrest.Matchers.is;
|
||||||
|
import static org.mockito.ArgumentMatchers.nullable;
|
||||||
import static org.mockito.Matchers.anyObject;
|
import static org.mockito.Matchers.anyObject;
|
||||||
import static org.mockito.Matchers.anyString;
|
import static org.mockito.Matchers.anyString;
|
||||||
import static org.mockito.Matchers.eq;
|
import static org.mockito.Matchers.eq;
|
||||||
|
@ -96,7 +97,8 @@ public class DefaultSearchContextTests extends ESTestCase {
|
||||||
when(indexCache.query()).thenReturn(queryCache);
|
when(indexCache.query()).thenReturn(queryCache);
|
||||||
when(indexService.cache()).thenReturn(indexCache);
|
when(indexService.cache()).thenReturn(indexCache);
|
||||||
SearchExecutionContext searchExecutionContext = mock(SearchExecutionContext.class);
|
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);
|
.thenReturn(searchExecutionContext);
|
||||||
MapperService mapperService = mock(MapperService.class);
|
MapperService mapperService = mock(MapperService.class);
|
||||||
when(mapperService.hasNested()).thenReturn(randomBoolean());
|
when(mapperService.hasNested()).thenReturn(randomBoolean());
|
||||||
|
@ -254,7 +256,7 @@ public class DefaultSearchContextTests extends ESTestCase {
|
||||||
eq(shardId.id()),
|
eq(shardId.id()),
|
||||||
anyObject(),
|
anyObject(),
|
||||||
anyObject(),
|
anyObject(),
|
||||||
anyString(),
|
nullable(String.class),
|
||||||
anyObject())
|
anyObject())
|
||||||
).thenReturn(searchExecutionContext);
|
).thenReturn(searchExecutionContext);
|
||||||
|
|
||||||
|
|
|
@ -35,10 +35,10 @@ import java.util.Set;
|
||||||
import java.util.concurrent.TimeUnit;
|
import java.util.concurrent.TimeUnit;
|
||||||
|
|
||||||
import static org.elasticsearch.cluster.metadata.DataStreamTestHelper.createTimestampField;
|
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.any;
|
||||||
import static org.mockito.Matchers.eq;
|
import static org.mockito.Matchers.eq;
|
||||||
import static org.mockito.Mockito.doAnswer;
|
import static org.mockito.Mockito.doAnswer;
|
||||||
|
import static org.mockito.Mockito.doThrow;
|
||||||
import static org.mockito.Mockito.mock;
|
import static org.mockito.Mockito.mock;
|
||||||
import static org.mockito.Mockito.verifyZeroInteractions;
|
import static org.mockito.Mockito.verifyZeroInteractions;
|
||||||
import static org.mockito.Mockito.when;
|
import static org.mockito.Mockito.when;
|
||||||
|
|
|
@ -24,7 +24,12 @@ dependencies {
|
||||||
api "org.apache.lucene:lucene-codecs:${versions.lucene}"
|
api "org.apache.lucene:lucene-codecs:${versions.lucene}"
|
||||||
api "commons-logging:commons-logging:${versions.commonslogging}"
|
api "commons-logging:commons-logging:${versions.commonslogging}"
|
||||||
api "commons-codec:commons-codec:${versions.commonscodec}"
|
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 "org.elasticsearch:mocksocket:${versions.mocksocket}"
|
||||||
api "io.github.nik9000:mapmatcher:0.0.3"
|
api "io.github.nik9000:mapmatcher:0.0.3"
|
||||||
|
|
||||||
|
@ -85,7 +90,17 @@ tasks.named("thirdPartyAudit").configure {
|
||||||
'org.tukaani.xz.X86Options',
|
'org.tukaani.xz.X86Options',
|
||||||
'org.tukaani.xz.XZ',
|
'org.tukaani.xz.XZ',
|
||||||
'org.tukaani.xz.XZInputStream',
|
'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) {
|
if (BuildParams.runtimeJavaVersion > JavaVersion.VERSION_12) {
|
||||||
ignoreMissingClasses(
|
ignoreMissingClasses(
|
||||||
|
|
|
@ -22,6 +22,7 @@ import org.elasticsearch.common.settings.Settings;
|
||||||
import org.elasticsearch.jdk.JarHell;
|
import org.elasticsearch.jdk.JarHell;
|
||||||
import org.elasticsearch.plugins.PluginInfo;
|
import org.elasticsearch.plugins.PluginInfo;
|
||||||
import org.elasticsearch.secure_sm.SecureSM;
|
import org.elasticsearch.secure_sm.SecureSM;
|
||||||
|
import org.elasticsearch.test.mockito.SecureMockMaker;
|
||||||
import org.junit.Assert;
|
import org.junit.Assert;
|
||||||
|
|
||||||
import java.io.InputStream;
|
import java.io.InputStream;
|
||||||
|
@ -91,6 +92,9 @@ public class BootstrapForTesting {
|
||||||
throw new RuntimeException("found jar hell in test classpath", e);
|
throw new RuntimeException("found jar hell in test classpath", e);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// init mockito
|
||||||
|
SecureMockMaker.init();
|
||||||
|
|
||||||
// Log ifconfig output before SecurityManager is installed
|
// Log ifconfig output before SecurityManager is installed
|
||||||
IfConfig.logIfNecessary();
|
IfConfig.logIfNecessary();
|
||||||
|
|
||||||
|
|
|
@ -10,7 +10,7 @@ package org.elasticsearch.test;
|
||||||
|
|
||||||
import org.elasticsearch.action.ActionListener;
|
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.
|
* Test utilities for working with {@link ActionListener}s.
|
||||||
|
|
|
@ -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));
|
||||||
|
}
|
||||||
|
}
|
|
@ -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> T createMock(MockCreationSettings<T> mockCreationSettings, MockHandler mockHandler) {
|
||||||
|
return wrap(() -> delegate.createMock(mockCreationSettings, mockHandler));
|
||||||
|
}
|
||||||
|
|
||||||
|
@SuppressWarnings("rawtypes")
|
||||||
|
@Override
|
||||||
|
public <T> Optional<T> createSpy(MockCreationSettings<T> 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 <T> StaticMockControl<T> createStaticMock(Class<T> type, MockCreationSettings<T> settings, MockHandler handler) {
|
||||||
|
return delegate.createStaticMock(type, settings, handler);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public <T> ConstructionMockControl<T> createConstructionMock(
|
||||||
|
Class<T> type,
|
||||||
|
Function<MockedConstruction.Context, MockCreationSettings<T>> settingsFactory,
|
||||||
|
Function<MockedConstruction.Context, MockHandler<T>> handlerFactory,
|
||||||
|
MockedConstruction.MockInitializer<T> mockInitializer) {
|
||||||
|
return delegate.createConstructionMock(type, settingsFactory, handlerFactory, mockInitializer);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void clearAllCaches() {
|
||||||
|
delegate.clearAllCaches();
|
||||||
|
}
|
||||||
|
}
|
|
@ -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<AccessControlContext>) AccessController::getContext, acc);
|
||||||
|
}
|
||||||
|
|
||||||
|
// forces static init to run
|
||||||
|
public static void init() {}
|
||||||
|
|
||||||
|
// wrap the given call to play nice with SecurityManager
|
||||||
|
static <T> T wrap(Supplier<T> call) {
|
||||||
|
return AccessController.doPrivileged((PrivilegedAction<T>) call::get, context);
|
||||||
|
}
|
||||||
|
|
||||||
|
// no construction
|
||||||
|
private SecureMockUtil() {}
|
||||||
|
}
|
|
@ -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> T newInstance(Class<T> cls) {
|
||||||
|
return SecureMockUtil.wrap(() -> delegate.newInstance(cls));
|
||||||
|
}
|
||||||
|
}
|
|
@ -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));
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1 @@
|
||||||
|
org.elasticsearch.test.mockito.SecureAnnotationEngine
|
|
@ -0,0 +1 @@
|
||||||
|
org.elasticsearch.test.mockito.SecureObjectInstantiatorProvider
|
|
@ -0,0 +1 @@
|
||||||
|
org.elasticsearch.test.mockito.SecureMockMaker
|
|
@ -45,7 +45,6 @@ dependencies {
|
||||||
exclude group: "org.elasticsearch", module: "elasticsearch-core"
|
exclude group: "org.elasticsearch", module: "elasticsearch-core"
|
||||||
}
|
}
|
||||||
|
|
||||||
testImplementation 'org.elasticsearch:securemock:1.2'
|
|
||||||
testImplementation "org.elasticsearch:mocksocket:${versions.mocksocket}"
|
testImplementation "org.elasticsearch:mocksocket:${versions.mocksocket}"
|
||||||
testImplementation "org.apache.logging.log4j:log4j-slf4j-impl:${versions.log4j}"
|
testImplementation "org.apache.logging.log4j:log4j-slf4j-impl:${versions.log4j}"
|
||||||
testImplementation "org.slf4j:slf4j-api:${versions.slf4j}"
|
testImplementation "org.slf4j:slf4j-api:${versions.slf4j}"
|
||||||
|
|
|
@ -458,7 +458,7 @@ public final class RemoteClusterLicenseCheckerTests extends ESTestCase {
|
||||||
threadPool,
|
threadPool,
|
||||||
client -> {
|
client -> {
|
||||||
when(client.getRemoteClusterClient(clusterAlias)).thenThrow(new IllegalArgumentException());
|
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);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -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_REPLICAS;
|
||||||
import static org.elasticsearch.cluster.metadata.IndexMetadata.SETTING_NUMBER_OF_SHARDS;
|
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.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_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_PIPELINE_MISSING_VALIDATION;
|
||||||
import static org.elasticsearch.xpack.core.common.validation.SourceDestValidator.DESTINATION_SINGLE_INDEX_VALIDATION;
|
import static org.elasticsearch.xpack.core.common.validation.SourceDestValidator.DESTINATION_SINGLE_INDEX_VALIDATION;
|
||||||
|
|
|
@ -26,12 +26,11 @@ import java.util.concurrent.TimeUnit;
|
||||||
import java.util.concurrent.atomic.AtomicBoolean;
|
import java.util.concurrent.atomic.AtomicBoolean;
|
||||||
import java.util.concurrent.atomic.AtomicInteger;
|
import java.util.concurrent.atomic.AtomicInteger;
|
||||||
|
|
||||||
import static org.hamcrest.Matchers.any;
|
|
||||||
import static org.hamcrest.Matchers.arrayWithSize;
|
import static org.hamcrest.Matchers.arrayWithSize;
|
||||||
import static org.hamcrest.Matchers.equalTo;
|
import static org.hamcrest.Matchers.equalTo;
|
||||||
import static org.hamcrest.Matchers.instanceOf;
|
import static org.hamcrest.Matchers.instanceOf;
|
||||||
import static org.hamcrest.Matchers.is;
|
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.doAnswer;
|
||||||
import static org.mockito.Mockito.mock;
|
import static org.mockito.Mockito.mock;
|
||||||
import static org.mockito.Mockito.times;
|
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
|
// this happens after the listener has been notified, threw an exception, and then mock logged the exception
|
||||||
latch.countDown();
|
latch.countDown();
|
||||||
return null;
|
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));
|
listeners.add(Tuple.tuple(listener, trigger));
|
||||||
}
|
}
|
||||||
|
|
|
@ -59,7 +59,7 @@ import java.util.Map;
|
||||||
import java.util.concurrent.atomic.AtomicInteger;
|
import java.util.concurrent.atomic.AtomicInteger;
|
||||||
import java.util.stream.Collectors;
|
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.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.INDEX_TEMPLATE_VERSION;
|
||||||
import static org.elasticsearch.xpack.core.slm.history.SnapshotLifecycleTemplateRegistry.SLM_POLICY_NAME;
|
import static org.elasticsearch.xpack.core.slm.history.SnapshotLifecycleTemplateRegistry.SLM_POLICY_NAME;
|
||||||
|
|
|
@ -45,7 +45,6 @@ dependencies {
|
||||||
api "org.apache.httpcomponents:httpclient-cache:${versions.httpclient}"
|
api "org.apache.httpcomponents:httpclient-cache:${versions.httpclient}"
|
||||||
runtimeOnly 'com.google.guava:guava:19.0'
|
runtimeOnly 'com.google.guava:guava:19.0'
|
||||||
|
|
||||||
testImplementation 'org.elasticsearch:securemock:1.2'
|
|
||||||
testImplementation "org.elasticsearch:mocksocket:${versions.mocksocket}"
|
testImplementation "org.elasticsearch:mocksocket:${versions.mocksocket}"
|
||||||
testImplementation(testArtifact(project(xpackModule('core'))))
|
testImplementation(testArtifact(project(xpackModule('core'))))
|
||||||
// So that we can extend LocalStateCompositeXPackPlugin
|
// So that we can extend LocalStateCompositeXPackPlugin
|
||||||
|
|
|
@ -116,18 +116,19 @@ public class TransportSamlInitiateSingleSignOnAction
|
||||||
ActionListener<UserServiceAuthentication> listener) {
|
ActionListener<UserServiceAuthentication> listener) {
|
||||||
User user = secondaryAuthentication.getUser();
|
User user = secondaryAuthentication.getUser();
|
||||||
secondaryAuthentication.execute(ignore -> {
|
secondaryAuthentication.execute(ignore -> {
|
||||||
privilegeResolver.resolve(serviceProvider.getPrivileges(), ActionListener.wrap(
|
ActionListener<UserPrivilegeResolver.UserPrivileges> wrapped = ActionListener.wrap(
|
||||||
userPrivileges -> {
|
userPrivileges -> {
|
||||||
if (userPrivileges.hasAccess == false) {
|
if (userPrivileges.hasAccess == false) {
|
||||||
listener.onResponse(null);
|
listener.onResponse(null);
|
||||||
} else {
|
} else {
|
||||||
logger.debug("Resolved [{}] for [{}]", userPrivileges, user);
|
logger.debug("Resolved [{}] for [{}]", userPrivileges, user);
|
||||||
listener.onResponse(new UserServiceAuthentication(user.principal(), user.fullName(), user.email(),
|
listener.onResponse(new UserServiceAuthentication(user.principal(), user.fullName(), user.email(),
|
||||||
userPrivileges.roles, serviceProvider));
|
userPrivileges.roles, serviceProvider));
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
listener::onFailure
|
listener::onFailure
|
||||||
));
|
);
|
||||||
|
privilegeResolver.resolve(serviceProvider.getPrivileges(), wrapped);
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
|
|
|
@ -46,7 +46,8 @@ import java.util.HashSet;
|
||||||
import static org.hamcrest.CoreMatchers.containsString;
|
import static org.hamcrest.CoreMatchers.containsString;
|
||||||
import static org.hamcrest.CoreMatchers.equalTo;
|
import static org.hamcrest.CoreMatchers.equalTo;
|
||||||
import static org.hamcrest.Matchers.arrayWithSize;
|
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.doAnswer;
|
||||||
import static org.mockito.Mockito.mock;
|
import static org.mockito.Mockito.mock;
|
||||||
import static org.mockito.Mockito.when;
|
import static org.mockito.Mockito.when;
|
||||||
|
@ -180,17 +181,15 @@ public class TransportSamlInitiateSingleSignOnActionTests extends IdpSamlTestCas
|
||||||
final SamlFactory factory = new SamlFactory();
|
final SamlFactory factory = new SamlFactory();
|
||||||
final UserPrivilegeResolver privilegeResolver = Mockito.mock(UserPrivilegeResolver.class);
|
final UserPrivilegeResolver privilegeResolver = Mockito.mock(UserPrivilegeResolver.class);
|
||||||
doAnswer(inv -> {
|
doAnswer(inv -> {
|
||||||
final Object[] args = inv.getArguments();
|
assertThat(inv.getArguments(), arrayWithSize(2));
|
||||||
assertThat(args, arrayWithSize(2));
|
ActionListener<UserPrivilegeResolver.UserPrivileges> listener = inv.getArgument(1);
|
||||||
ActionListener<UserPrivilegeResolver.UserPrivileges> listener
|
|
||||||
= (ActionListener<UserPrivilegeResolver.UserPrivileges>) args[args.length - 1];
|
|
||||||
final UserPrivilegeResolver.UserPrivileges privileges = new UserPrivilegeResolver.UserPrivileges(
|
final UserPrivilegeResolver.UserPrivileges privileges = new UserPrivilegeResolver.UserPrivileges(
|
||||||
"saml_enduser", true,
|
"saml_enduser", true,
|
||||||
new HashSet<>(Arrays.asList(generateRandomStringArray(5, 8, false, false))
|
new HashSet<>(Arrays.asList(generateRandomStringArray(5, 8, false, false))
|
||||||
));
|
));
|
||||||
listener.onResponse(privileges);
|
listener.onResponse(privileges);
|
||||||
return null;
|
return null;
|
||||||
}).when(privilegeResolver).resolve(any(ServiceProviderPrivileges.class), any(ActionListener.class));
|
}).when(privilegeResolver).resolve(nullable(ServiceProviderPrivileges.class), any());
|
||||||
return new TransportSamlInitiateSingleSignOnAction(transportService, actionFilters, securityContext,
|
return new TransportSamlInitiateSingleSignOnAction(transportService, actionFilters, securityContext,
|
||||||
idp, factory, privilegeResolver);
|
idp, factory, privilegeResolver);
|
||||||
}
|
}
|
||||||
|
|
|
@ -56,6 +56,7 @@ import javax.xml.transform.TransformerException;
|
||||||
import javax.xml.transform.dom.DOMSource;
|
import javax.xml.transform.dom.DOMSource;
|
||||||
import javax.xml.transform.stream.StreamResult;
|
import javax.xml.transform.stream.StreamResult;
|
||||||
|
|
||||||
|
import static org.mockito.ArgumentMatchers.nullable;
|
||||||
import static org.opensaml.core.xml.config.XMLObjectProviderRegistrySupport.getUnmarshallerFactory;
|
import static org.opensaml.core.xml.config.XMLObjectProviderRegistrySupport.getUnmarshallerFactory;
|
||||||
|
|
||||||
public abstract class IdpSamlTestCase extends ESTestCase {
|
public abstract class IdpSamlTestCase extends ESTestCase {
|
||||||
|
@ -98,7 +99,7 @@ public abstract class IdpSamlTestCase extends ESTestCase {
|
||||||
|
|
||||||
listener.onResponse(sp);
|
listener.onResponse(sp);
|
||||||
return null;
|
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));
|
Mockito.any(ActionListener.class));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -1066,7 +1066,7 @@ public class IndexLifecycleRunnerTests extends ESTestCase {
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private static class SetStepInfoUpdateTaskMatcher extends ArgumentMatcher<SetStepInfoUpdateTask> {
|
private static class SetStepInfoUpdateTaskMatcher implements ArgumentMatcher<SetStepInfoUpdateTask> {
|
||||||
|
|
||||||
private Index index;
|
private Index index;
|
||||||
private String policy;
|
private String policy;
|
||||||
|
@ -1081,15 +1081,14 @@ public class IndexLifecycleRunnerTests extends ESTestCase {
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean matches(Object argument) {
|
public boolean matches(SetStepInfoUpdateTask other) {
|
||||||
if (argument == null || argument instanceof SetStepInfoUpdateTask == false) {
|
if (other == null) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
SetStepInfoUpdateTask task = (SetStepInfoUpdateTask) argument;
|
return Objects.equals(index, other.getIndex()) &&
|
||||||
return Objects.equals(index, task.getIndex()) &&
|
Objects.equals(policy, other.getPolicy())&&
|
||||||
Objects.equals(policy, task.getPolicy())&&
|
Objects.equals(currentStepKey, other.getCurrentStepKey()) &&
|
||||||
Objects.equals(currentStepKey, task.getCurrentStepKey()) &&
|
Objects.equals(xContentToString(stepInfo), xContentToString(other.getStepInfo()));
|
||||||
Objects.equals(xContentToString(stepInfo), xContentToString(task.getStepInfo()));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private String xContentToString(ToXContentObject xContent) {
|
private String xContentToString(ToXContentObject xContent) {
|
||||||
|
@ -1104,7 +1103,7 @@ public class IndexLifecycleRunnerTests extends ESTestCase {
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private static class ExecuteStepsUpdateTaskMatcher extends ArgumentMatcher<ExecuteStepsUpdateTask> {
|
private static class ExecuteStepsUpdateTaskMatcher implements ArgumentMatcher<ExecuteStepsUpdateTask> {
|
||||||
|
|
||||||
private Index index;
|
private Index index;
|
||||||
private String policy;
|
private String policy;
|
||||||
|
@ -1117,14 +1116,13 @@ public class IndexLifecycleRunnerTests extends ESTestCase {
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean matches(Object argument) {
|
public boolean matches(ExecuteStepsUpdateTask other) {
|
||||||
if (argument == null || argument instanceof ExecuteStepsUpdateTask == false) {
|
if (other == null) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
ExecuteStepsUpdateTask task = (ExecuteStepsUpdateTask) argument;
|
return Objects.equals(index, other.getIndex()) &&
|
||||||
return Objects.equals(index, task.getIndex()) &&
|
Objects.equals(policy, other.getPolicy()) &&
|
||||||
Objects.equals(policy, task.getPolicy()) &&
|
Objects.equals(startStep, other.getStartStep());
|
||||||
Objects.equals(startStep, task.getStartStep());
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -50,7 +50,6 @@ import org.elasticsearch.xpack.core.ilm.ShrinkStep;
|
||||||
import org.elasticsearch.xpack.core.ilm.ShrunkShardsAllocatedStep;
|
import org.elasticsearch.xpack.core.ilm.ShrunkShardsAllocatedStep;
|
||||||
import org.elasticsearch.xpack.core.ilm.Step;
|
import org.elasticsearch.xpack.core.ilm.Step;
|
||||||
import org.elasticsearch.xpack.core.scheduler.SchedulerEngine;
|
import org.elasticsearch.xpack.core.scheduler.SchedulerEngine;
|
||||||
import org.hamcrest.Description;
|
|
||||||
import org.junit.After;
|
import org.junit.After;
|
||||||
import org.junit.Before;
|
import org.junit.Before;
|
||||||
import org.mockito.ArgumentMatcher;
|
import org.mockito.ArgumentMatcher;
|
||||||
|
@ -345,19 +344,10 @@ public class IndexLifecycleServiceTests extends ESTestCase {
|
||||||
Priority actualPriority = null;
|
Priority actualPriority = null;
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean matches(Object argument) {
|
public boolean matches(OperationModeUpdateTask other) {
|
||||||
if (argument instanceof OperationModeUpdateTask == false) {
|
actualPriority = other.priority();
|
||||||
return false;
|
|
||||||
}
|
|
||||||
actualPriority = ((OperationModeUpdateTask) argument).priority();
|
|
||||||
return actualPriority == expectedPriority;
|
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());
|
|
||||||
}
|
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
|
@ -19,7 +19,6 @@ import org.elasticsearch.test.ESTestCase;
|
||||||
import org.elasticsearch.threadpool.ThreadPool;
|
import org.elasticsearch.threadpool.ThreadPool;
|
||||||
import org.elasticsearch.transport.TransportService;
|
import org.elasticsearch.transport.TransportService;
|
||||||
import org.elasticsearch.xpack.core.ilm.StopILMRequest;
|
import org.elasticsearch.xpack.core.ilm.StopILMRequest;
|
||||||
import org.hamcrest.Description;
|
|
||||||
import org.mockito.ArgumentMatcher;
|
import org.mockito.ArgumentMatcher;
|
||||||
|
|
||||||
import static org.mockito.Matchers.argThat;
|
import static org.mockito.Matchers.argThat;
|
||||||
|
@ -56,19 +55,10 @@ public class TransportStopILMActionTests extends ESTestCase {
|
||||||
Priority actualPriority = null;
|
Priority actualPriority = null;
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean matches(Object argument) {
|
public boolean matches(AckedClusterStateUpdateTask other) {
|
||||||
if (argument instanceof AckedClusterStateUpdateTask == false) {
|
actualPriority = other.priority();
|
||||||
return false;
|
|
||||||
}
|
|
||||||
actualPriority = ((AckedClusterStateUpdateTask) argument).priority();
|
|
||||||
return actualPriority == Priority.IMMEDIATE;
|
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());
|
|
||||||
}
|
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
|
@ -57,7 +57,7 @@ public class MlAssignmentNotifierTests extends ESTestCase {
|
||||||
threadPool = mock(ThreadPool.class);
|
threadPool = mock(ThreadPool.class);
|
||||||
|
|
||||||
ExecutorService executorService = mock(ExecutorService.class);
|
ExecutorService executorService = mock(ExecutorService.class);
|
||||||
org.elasticsearch.mock.orig.Mockito.doAnswer(invocation -> {
|
org.mockito.Mockito.doAnswer(invocation -> {
|
||||||
((Runnable) invocation.getArguments()[0]).run();
|
((Runnable) invocation.getArguments()[0]).run();
|
||||||
return null;
|
return null;
|
||||||
}).when(executorService).execute(any(Runnable.class));
|
}).when(executorService).execute(any(Runnable.class));
|
||||||
|
|
|
@ -40,7 +40,7 @@ import java.util.Collections;
|
||||||
import java.util.concurrent.CountDownLatch;
|
import java.util.concurrent.CountDownLatch;
|
||||||
import java.util.concurrent.TimeUnit;
|
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.any;
|
||||||
import static org.mockito.Matchers.same;
|
import static org.mockito.Matchers.same;
|
||||||
import static org.mockito.Mockito.doAnswer;
|
import static org.mockito.Mockito.doAnswer;
|
||||||
|
|
|
@ -37,8 +37,8 @@ import org.junit.Before;
|
||||||
import org.mockito.ArgumentCaptor;
|
import org.mockito.ArgumentCaptor;
|
||||||
import org.mockito.stubbing.Answer;
|
import org.mockito.stubbing.Answer;
|
||||||
|
|
||||||
import static org.elasticsearch.mock.orig.Mockito.verify;
|
import static org.mockito.Mockito.verify;
|
||||||
import static org.elasticsearch.mock.orig.Mockito.when;
|
import static org.mockito.Mockito.when;
|
||||||
import static org.hamcrest.Matchers.equalTo;
|
import static org.hamcrest.Matchers.equalTo;
|
||||||
import static org.mockito.Matchers.any;
|
import static org.mockito.Matchers.any;
|
||||||
import static org.mockito.Matchers.anyObject;
|
import static org.mockito.Matchers.anyObject;
|
||||||
|
|
|
@ -17,7 +17,7 @@ import org.junit.Before;
|
||||||
|
|
||||||
import java.util.concurrent.ExecutorService;
|
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.hamcrest.Matchers.is;
|
||||||
import static org.mockito.Matchers.any;
|
import static org.mockito.Matchers.any;
|
||||||
import static org.mockito.Mockito.mock;
|
import static org.mockito.Mockito.mock;
|
||||||
|
|
|
@ -47,7 +47,7 @@ public class TransportFinalizeJobExecutionActionTests extends ESTestCase {
|
||||||
private void setupMocks() {
|
private void setupMocks() {
|
||||||
ExecutorService executorService = mock(ExecutorService.class);
|
ExecutorService executorService = mock(ExecutorService.class);
|
||||||
threadPool = mock(ThreadPool.class);
|
threadPool = mock(ThreadPool.class);
|
||||||
org.elasticsearch.mock.orig.Mockito.doAnswer(invocation -> {
|
org.mockito.Mockito.doAnswer(invocation -> {
|
||||||
((Runnable) invocation.getArguments()[0]).run();
|
((Runnable) invocation.getArguments()[0]).run();
|
||||||
return null;
|
return null;
|
||||||
}).when(executorService).execute(any(Runnable.class));
|
}).when(executorService).execute(any(Runnable.class));
|
||||||
|
|
|
@ -27,7 +27,7 @@ import org.elasticsearch.xcontent.XContentFactory;
|
||||||
import org.elasticsearch.xcontent.XContentType;
|
import org.elasticsearch.xcontent.XContentType;
|
||||||
import org.elasticsearch.core.TimeValue;
|
import org.elasticsearch.core.TimeValue;
|
||||||
import org.elasticsearch.index.shard.ShardId;
|
import org.elasticsearch.index.shard.ShardId;
|
||||||
import org.elasticsearch.mock.orig.Mockito;
|
import org.mockito.Mockito;
|
||||||
import org.elasticsearch.test.ESTestCase;
|
import org.elasticsearch.test.ESTestCase;
|
||||||
import org.elasticsearch.threadpool.ThreadPool;
|
import org.elasticsearch.threadpool.ThreadPool;
|
||||||
import org.elasticsearch.xpack.core.ClientHelper;
|
import org.elasticsearch.xpack.core.ClientHelper;
|
||||||
|
|
|
@ -19,8 +19,8 @@ import org.elasticsearch.cluster.node.DiscoveryNodes;
|
||||||
import org.elasticsearch.cluster.service.ClusterService;
|
import org.elasticsearch.cluster.service.ClusterService;
|
||||||
import org.elasticsearch.common.settings.Settings;
|
import org.elasticsearch.common.settings.Settings;
|
||||||
import org.elasticsearch.common.transport.TransportAddress;
|
import org.elasticsearch.common.transport.TransportAddress;
|
||||||
import org.elasticsearch.core.TimeValue;
|
|
||||||
import org.elasticsearch.common.util.concurrent.ThreadContext;
|
import org.elasticsearch.common.util.concurrent.ThreadContext;
|
||||||
|
import org.elasticsearch.core.TimeValue;
|
||||||
import org.elasticsearch.persistent.PersistentTasksCustomMetadata;
|
import org.elasticsearch.persistent.PersistentTasksCustomMetadata;
|
||||||
import org.elasticsearch.persistent.PersistentTasksCustomMetadata.PersistentTask;
|
import org.elasticsearch.persistent.PersistentTasksCustomMetadata.PersistentTask;
|
||||||
import org.elasticsearch.test.ESTestCase;
|
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.elasticsearch.xpack.ml.job.task.OpenJobPersistentTasksExecutorTests.addJobTask;
|
||||||
import static org.hamcrest.Matchers.equalTo;
|
import static org.hamcrest.Matchers.equalTo;
|
||||||
import static org.hamcrest.Matchers.is;
|
import static org.hamcrest.Matchers.is;
|
||||||
|
import static org.mockito.ArgumentMatchers.nullable;
|
||||||
import static org.mockito.Matchers.any;
|
import static org.mockito.Matchers.any;
|
||||||
import static org.mockito.Matchers.anyLong;
|
import static org.mockito.Matchers.anyLong;
|
||||||
import static org.mockito.Matchers.anyString;
|
import static org.mockito.Matchers.anyString;
|
||||||
|
@ -105,8 +106,6 @@ public class DatafeedRunnerTests extends ESTestCase {
|
||||||
DiscoveryNode dNode = mock(DiscoveryNode.class);
|
DiscoveryNode dNode = mock(DiscoveryNode.class);
|
||||||
when(dNode.getName()).thenReturn("this_node_has_a_name");
|
when(dNode.getName()).thenReturn("this_node_has_a_name");
|
||||||
when(clusterService.localNode()).thenReturn(dNode);
|
when(clusterService.localNode()).thenReturn(dNode);
|
||||||
auditor = mock(AnomalyDetectionAuditor.class);
|
|
||||||
|
|
||||||
auditor = mock(AnomalyDetectionAuditor.class);
|
auditor = mock(AnomalyDetectionAuditor.class);
|
||||||
threadPool = mock(ThreadPool.class);
|
threadPool = mock(ThreadPool.class);
|
||||||
when(threadPool.getThreadContext()).thenReturn(new ThreadContext(Settings.EMPTY));
|
when(threadPool.getThreadContext()).thenReturn(new ThreadContext(Settings.EMPTY));
|
||||||
|
@ -203,7 +202,7 @@ public class DatafeedRunnerTests extends ESTestCase {
|
||||||
|
|
||||||
public void testRealTime_GivenStoppingAnalysisProblem() throws Exception {
|
public void testRealTime_GivenStoppingAnalysisProblem() throws Exception {
|
||||||
Exception cause = new RuntimeException("stopping");
|
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<Exception> handler = mockConsumer();
|
Consumer<Exception> handler = mockConsumer();
|
||||||
StartDatafeedAction.DatafeedParams params = new StartDatafeedAction.DatafeedParams(DATAFEED_ID, 0L);
|
StartDatafeedAction.DatafeedParams params = new StartDatafeedAction.DatafeedParams(DATAFEED_ID, 0L);
|
||||||
|
@ -222,7 +221,8 @@ public class DatafeedRunnerTests extends ESTestCase {
|
||||||
|
|
||||||
public void testRealTime_GivenNonStoppingAnalysisProblem() throws Exception {
|
public void testRealTime_GivenNonStoppingAnalysisProblem() throws Exception {
|
||||||
Exception cause = new RuntimeException("non-stopping");
|
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<Exception> handler = mockConsumer();
|
Consumer<Exception> handler = mockConsumer();
|
||||||
StartDatafeedAction.DatafeedParams params = new StartDatafeedAction.DatafeedParams(DATAFEED_ID, 0L);
|
StartDatafeedAction.DatafeedParams params = new StartDatafeedAction.DatafeedParams(DATAFEED_ID, 0L);
|
||||||
|
|
|
@ -20,7 +20,7 @@ import org.mockito.InOrder;
|
||||||
import java.sql.Date;
|
import java.sql.Date;
|
||||||
import java.time.Instant;
|
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.equalTo;
|
||||||
import static org.hamcrest.Matchers.is;
|
import static org.hamcrest.Matchers.is;
|
||||||
import static org.mockito.Matchers.any;
|
import static org.mockito.Matchers.any;
|
||||||
|
|
|
@ -16,7 +16,7 @@ import org.elasticsearch.client.Client;
|
||||||
import org.elasticsearch.core.TimeValue;
|
import org.elasticsearch.core.TimeValue;
|
||||||
import org.elasticsearch.index.query.QueryBuilder;
|
import org.elasticsearch.index.query.QueryBuilder;
|
||||||
import org.elasticsearch.index.query.QueryBuilders;
|
import org.elasticsearch.index.query.QueryBuilders;
|
||||||
import org.elasticsearch.mock.orig.Mockito;
|
import org.mockito.Mockito;
|
||||||
import org.elasticsearch.rest.RestStatus;
|
import org.elasticsearch.rest.RestStatus;
|
||||||
import org.elasticsearch.search.SearchHit;
|
import org.elasticsearch.search.SearchHit;
|
||||||
import org.elasticsearch.search.SearchHits;
|
import org.elasticsearch.search.SearchHits;
|
||||||
|
|
|
@ -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.inference.trainedmodel.tree.TreeNode;
|
||||||
import org.elasticsearch.xpack.core.ml.job.messages.Messages;
|
import org.elasticsearch.xpack.core.ml.job.messages.Messages;
|
||||||
import org.elasticsearch.xpack.ml.inference.TrainedModelStatsService;
|
import org.elasticsearch.xpack.ml.inference.TrainedModelStatsService;
|
||||||
import org.mockito.ArgumentMatcher;
|
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.util.Arrays;
|
import java.util.Arrays;
|
||||||
|
@ -290,12 +289,7 @@ public class LocalModelTests extends ESTestCase {
|
||||||
assertThat(result.valueAsString(), is("0"));
|
assertThat(result.valueAsString(), is("0"));
|
||||||
// Should have reset after persistence, so only 2 docs have been seen since last persistence
|
// Should have reset after persistence, so only 2 docs have been seen since last persistence
|
||||||
assertThat(model.getLatestStatsAndReset().getInferenceCount(), equalTo(2L));
|
assertThat(model.getLatestStatsAndReset().getInferenceCount(), equalTo(2L));
|
||||||
verify(modelStatsService, times(1)).queueStats(argThat(new ArgumentMatcher<InferenceStats>() {
|
verify(modelStatsService, times(1)).queueStats(argThat(o -> o.getInferenceCount() == 99L), anyBoolean());
|
||||||
@Override
|
|
||||||
public boolean matches(Object o) {
|
|
||||||
return ((InferenceStats)o).getInferenceCount() == 99L;
|
|
||||||
}
|
|
||||||
}), anyBoolean());
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public void testMapFieldsIfNecessary() {
|
public void testMapFieldsIfNecessary() {
|
||||||
|
|
|
@ -22,14 +22,11 @@ import org.elasticsearch.cluster.service.ClusterService;
|
||||||
import org.elasticsearch.common.breaker.CircuitBreaker;
|
import org.elasticsearch.common.breaker.CircuitBreaker;
|
||||||
import org.elasticsearch.common.breaker.CircuitBreakingException;
|
import org.elasticsearch.common.breaker.CircuitBreakingException;
|
||||||
import org.elasticsearch.common.bytes.BytesReference;
|
import org.elasticsearch.common.bytes.BytesReference;
|
||||||
import org.elasticsearch.core.Tuple;
|
|
||||||
import org.elasticsearch.common.settings.Settings;
|
import org.elasticsearch.common.settings.Settings;
|
||||||
import org.elasticsearch.common.transport.TransportAddress;
|
import org.elasticsearch.common.transport.TransportAddress;
|
||||||
import org.elasticsearch.common.unit.ByteSizeValue;
|
import org.elasticsearch.common.unit.ByteSizeValue;
|
||||||
import org.elasticsearch.core.TimeValue;
|
import org.elasticsearch.core.TimeValue;
|
||||||
import org.elasticsearch.xcontent.XContentBuilder;
|
import org.elasticsearch.core.Tuple;
|
||||||
import org.elasticsearch.xcontent.XContentFactory;
|
|
||||||
import org.elasticsearch.xcontent.XContentType;
|
|
||||||
import org.elasticsearch.ingest.IngestMetadata;
|
import org.elasticsearch.ingest.IngestMetadata;
|
||||||
import org.elasticsearch.ingest.PipelineConfiguration;
|
import org.elasticsearch.ingest.PipelineConfiguration;
|
||||||
import org.elasticsearch.license.XPackLicenseState;
|
import org.elasticsearch.license.XPackLicenseState;
|
||||||
|
@ -37,7 +34,11 @@ import org.elasticsearch.test.ESTestCase;
|
||||||
import org.elasticsearch.threadpool.ScalingExecutorBuilder;
|
import org.elasticsearch.threadpool.ScalingExecutorBuilder;
|
||||||
import org.elasticsearch.threadpool.TestThreadPool;
|
import org.elasticsearch.threadpool.TestThreadPool;
|
||||||
import org.elasticsearch.threadpool.ThreadPool;
|
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.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.TrainedModelConfig;
|
||||||
import org.elasticsearch.xpack.core.ml.inference.TrainedModelInput;
|
import org.elasticsearch.xpack.core.ml.inference.TrainedModelInput;
|
||||||
import org.elasticsearch.xpack.core.ml.inference.results.InferenceResults;
|
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.inference.trainedmodel.inference.InferenceDefinition;
|
||||||
import org.elasticsearch.xpack.core.ml.job.messages.Messages;
|
import org.elasticsearch.xpack.core.ml.job.messages.Messages;
|
||||||
import org.elasticsearch.xpack.ml.MachineLearning;
|
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.TrainedModelStatsService;
|
||||||
import org.elasticsearch.xpack.ml.inference.ingest.InferenceProcessor;
|
import org.elasticsearch.xpack.ml.inference.ingest.InferenceProcessor;
|
||||||
import org.elasticsearch.xpack.ml.inference.persistence.TrainedModelProvider;
|
import org.elasticsearch.xpack.ml.inference.persistence.TrainedModelProvider;
|
||||||
import org.elasticsearch.xpack.ml.notifications.InferenceAuditor;
|
import org.elasticsearch.xpack.ml.notifications.InferenceAuditor;
|
||||||
import org.junit.After;
|
import org.junit.After;
|
||||||
import org.junit.Before;
|
import org.junit.Before;
|
||||||
import org.mockito.ArgumentMatcher;
|
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.net.InetAddress;
|
import java.net.InetAddress;
|
||||||
|
@ -224,12 +223,7 @@ public class ModelLoadingServiceTests extends ESTestCase {
|
||||||
verify(trainedModelProvider, times(1)).getTrainedModelForInference(eq(model3), eq(false), any());
|
verify(trainedModelProvider, times(1)).getTrainedModelForInference(eq(model3), eq(false), any());
|
||||||
|
|
||||||
// model 3 has been loaded and evicted exactly once
|
// model 3 has been loaded and evicted exactly once
|
||||||
verify(trainedModelStatsService, times(1)).queueStats(argThat(new ArgumentMatcher<InferenceStats>() {
|
verify(trainedModelStatsService, times(1)).queueStats(argThat(o -> o.getModelId().equals(model3)), anyBoolean());
|
||||||
@Override
|
|
||||||
public boolean matches(final Object o) {
|
|
||||||
return ((InferenceStats)o).getModelId().equals(model3);
|
|
||||||
}
|
|
||||||
}), anyBoolean());
|
|
||||||
|
|
||||||
// Load model 3, should invalidate 1 and 2
|
// Load model 3, should invalidate 1 and 2
|
||||||
for(int i = 0; i < 10; i++) {
|
for(int i = 0; i < 10; i++) {
|
||||||
|
@ -238,19 +232,8 @@ public class ModelLoadingServiceTests extends ESTestCase {
|
||||||
assertThat(future3.get(), is(not(nullValue())));
|
assertThat(future3.get(), is(not(nullValue())));
|
||||||
}
|
}
|
||||||
verify(trainedModelProvider, times(2)).getTrainedModelForInference(eq(model3), eq(false), any());
|
verify(trainedModelProvider, times(2)).getTrainedModelForInference(eq(model3), eq(false), any());
|
||||||
|
verify(trainedModelStatsService, atMost(2)).queueStats(argThat(o -> o.getModelId().equals(model1)), anyBoolean());
|
||||||
verify(trainedModelStatsService, atMost(2)).queueStats(argThat(new ArgumentMatcher<InferenceStats>() {
|
verify(trainedModelStatsService, atMost(2)).queueStats(argThat(o -> o.getModelId().equals(model2)), anyBoolean());
|
||||||
@Override
|
|
||||||
public boolean matches(final Object o) {
|
|
||||||
return ((InferenceStats)o).getModelId().equals(model1);
|
|
||||||
}
|
|
||||||
}), anyBoolean());
|
|
||||||
verify(trainedModelStatsService, atMost(2)).queueStats(argThat(new ArgumentMatcher<InferenceStats>() {
|
|
||||||
@Override
|
|
||||||
public boolean matches(final Object o) {
|
|
||||||
return ((InferenceStats)o).getModelId().equals(model2);
|
|
||||||
}
|
|
||||||
}), anyBoolean());
|
|
||||||
|
|
||||||
// Load model 1, should invalidate 3
|
// Load model 1, should invalidate 3
|
||||||
for(int i = 0; i < 10; i++) {
|
for(int i = 0; i < 10; i++) {
|
||||||
|
@ -259,12 +242,7 @@ public class ModelLoadingServiceTests extends ESTestCase {
|
||||||
assertThat(future1.get(), is(not(nullValue())));
|
assertThat(future1.get(), is(not(nullValue())));
|
||||||
}
|
}
|
||||||
verify(trainedModelProvider, atMost(3)).getTrainedModelForInference(eq(model1), eq(false), any());
|
verify(trainedModelProvider, atMost(3)).getTrainedModelForInference(eq(model1), eq(false), any());
|
||||||
verify(trainedModelStatsService, times(2)).queueStats(argThat(new ArgumentMatcher<InferenceStats>() {
|
verify(trainedModelStatsService, times(2)).queueStats(argThat(o -> o.getModelId().equals(model3)), anyBoolean());
|
||||||
@Override
|
|
||||||
public boolean matches(final Object o) {
|
|
||||||
return ((InferenceStats)o).getModelId().equals(model3);
|
|
||||||
}
|
|
||||||
}), anyBoolean());
|
|
||||||
|
|
||||||
// Load model 2
|
// Load model 2
|
||||||
for(int i = 0; i < 10; i++) {
|
for(int i = 0; i < 10; i++) {
|
||||||
|
|
|
@ -135,7 +135,7 @@ public class JobManagerTests extends ESTestCase {
|
||||||
|
|
||||||
ExecutorService executorService = mock(ExecutorService.class);
|
ExecutorService executorService = mock(ExecutorService.class);
|
||||||
threadPool = mock(ThreadPool.class);
|
threadPool = mock(ThreadPool.class);
|
||||||
org.elasticsearch.mock.orig.Mockito.doAnswer(invocation -> {
|
org.mockito.Mockito.doAnswer(invocation -> {
|
||||||
((Runnable) invocation.getArguments()[0]).run();
|
((Runnable) invocation.getArguments()[0]).run();
|
||||||
return null;
|
return null;
|
||||||
}).when(executorService).execute(any(Runnable.class));
|
}).when(executorService).execute(any(Runnable.class));
|
||||||
|
|
|
@ -13,7 +13,7 @@ import org.elasticsearch.common.bytes.BytesReference;
|
||||||
import org.elasticsearch.xcontent.XContentFactory;
|
import org.elasticsearch.xcontent.XContentFactory;
|
||||||
import org.elasticsearch.index.query.QueryBuilder;
|
import org.elasticsearch.index.query.QueryBuilder;
|
||||||
import org.elasticsearch.index.query.QueryBuilders;
|
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.SearchHit;
|
||||||
import org.elasticsearch.search.SearchHits;
|
import org.elasticsearch.search.SearchHits;
|
||||||
import org.elasticsearch.search.sort.SortBuilder;
|
import org.elasticsearch.search.sort.SortBuilder;
|
||||||
|
|
|
@ -49,7 +49,8 @@ import java.util.concurrent.atomic.AtomicBoolean;
|
||||||
import java.util.concurrent.atomic.AtomicReference;
|
import java.util.concurrent.atomic.AtomicReference;
|
||||||
import java.util.function.BiConsumer;
|
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.hamcrest.Matchers.equalTo;
|
||||||
import static org.mockito.Matchers.any;
|
import static org.mockito.Matchers.any;
|
||||||
import static org.mockito.Matchers.anyBoolean;
|
import static org.mockito.Matchers.anyBoolean;
|
||||||
|
@ -109,10 +110,9 @@ public class AutodetectCommunicatorTests extends ESTestCase {
|
||||||
|
|
||||||
public void testFlushJob() throws Exception {
|
public void testFlushJob() throws Exception {
|
||||||
AutodetectProcess process = mockAutodetectProcessWithOutputStream();
|
AutodetectProcess process = mockAutodetectProcessWithOutputStream();
|
||||||
when(process.isProcessAlive()).thenReturn(true);
|
|
||||||
AutodetectResultProcessor processor = mock(AutodetectResultProcessor.class);
|
AutodetectResultProcessor processor = mock(AutodetectResultProcessor.class);
|
||||||
FlushAcknowledgement flushAcknowledgement = mock(FlushAcknowledgement.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)) {
|
try (AutodetectCommunicator communicator = createAutodetectCommunicator(process, processor)) {
|
||||||
FlushJobParams params = FlushJobParams.builder().build();
|
FlushJobParams params = FlushJobParams.builder().build();
|
||||||
AtomicReference<FlushAcknowledgement> flushAcknowledgementHolder = new AtomicReference<>();
|
AtomicReference<FlushAcknowledgement> flushAcknowledgementHolder = new AtomicReference<>();
|
||||||
|
@ -145,10 +145,9 @@ public class AutodetectCommunicatorTests extends ESTestCase {
|
||||||
|
|
||||||
public void testFlushJob_givenFlushWaitReturnsTrueOnSecondCall() throws Exception {
|
public void testFlushJob_givenFlushWaitReturnsTrueOnSecondCall() throws Exception {
|
||||||
AutodetectProcess process = mockAutodetectProcessWithOutputStream();
|
AutodetectProcess process = mockAutodetectProcessWithOutputStream();
|
||||||
when(process.isProcessAlive()).thenReturn(true);
|
|
||||||
AutodetectResultProcessor autodetectResultProcessor = mock(AutodetectResultProcessor.class);
|
AutodetectResultProcessor autodetectResultProcessor = mock(AutodetectResultProcessor.class);
|
||||||
FlushAcknowledgement flushAcknowledgement = mock(FlushAcknowledgement.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);
|
.thenReturn(null).thenReturn(flushAcknowledgement);
|
||||||
FlushJobParams params = FlushJobParams.builder().build();
|
FlushJobParams params = FlushJobParams.builder().build();
|
||||||
|
|
||||||
|
@ -156,7 +155,7 @@ public class AutodetectCommunicatorTests extends ESTestCase {
|
||||||
communicator.flushJob(params, (aVoid, e) -> {});
|
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()
|
// First in checkAndRun, second due to check between calls to waitForFlushAcknowledgement and third due to close()
|
||||||
verify(process, times(3)).isProcessAlive();
|
verify(process, times(3)).isProcessAlive();
|
||||||
}
|
}
|
||||||
|
@ -244,12 +243,11 @@ public class AutodetectCommunicatorTests extends ESTestCase {
|
||||||
private AutodetectCommunicator createAutodetectCommunicator(AutodetectProcess autodetectProcess,
|
private AutodetectCommunicator createAutodetectCommunicator(AutodetectProcess autodetectProcess,
|
||||||
AutodetectResultProcessor autodetectResultProcessor) throws IOException {
|
AutodetectResultProcessor autodetectResultProcessor) throws IOException {
|
||||||
ExecutorService executorService = mock(ExecutorService.class);
|
ExecutorService executorService = mock(ExecutorService.class);
|
||||||
when(executorService.submit(any(Callable.class))).thenReturn(mock(Future.class));
|
|
||||||
doAnswer(invocationOnMock -> {
|
doAnswer(invocationOnMock -> {
|
||||||
Callable<Void> runnable = (Callable<Void>) invocationOnMock.getArguments()[0];
|
Callable<?> runnable = (Callable<?>) invocationOnMock.getArguments()[0];
|
||||||
runnable.call();
|
runnable.call();
|
||||||
return mock(Future.class);
|
return mock(Future.class);
|
||||||
}).when(executorService).submit(any(Callable.class));
|
}).when(executorService).submit((Callable<Future<?>>) any());
|
||||||
doAnswer(invocation -> {
|
doAnswer(invocation -> {
|
||||||
((Runnable) invocation.getArguments()[0]).run();
|
((Runnable) invocation.getArguments()[0]).run();
|
||||||
return null;
|
return null;
|
||||||
|
|
|
@ -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_REPLICAS;
|
||||||
import static org.elasticsearch.cluster.metadata.IndexMetadata.SETTING_NUMBER_OF_SHARDS;
|
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.cluster.metadata.IndexMetadata.SETTING_VERSION_CREATED;
|
||||||
import static org.elasticsearch.mock.orig.Mockito.doAnswer;
|
import static org.mockito.Mockito.doAnswer;
|
||||||
import static org.elasticsearch.mock.orig.Mockito.doReturn;
|
import static org.mockito.Mockito.doReturn;
|
||||||
import static org.elasticsearch.mock.orig.Mockito.doThrow;
|
import static org.mockito.Mockito.doThrow;
|
||||||
import static org.elasticsearch.mock.orig.Mockito.times;
|
import static org.mockito.Mockito.times;
|
||||||
import static org.elasticsearch.mock.orig.Mockito.verify;
|
import static org.mockito.Mockito.verify;
|
||||||
import static org.elasticsearch.mock.orig.Mockito.verifyNoMoreInteractions;
|
import static org.mockito.Mockito.verifyNoMoreInteractions;
|
||||||
import static org.elasticsearch.mock.orig.Mockito.when;
|
import static org.mockito.Mockito.when;
|
||||||
import static org.hamcrest.Matchers.is;
|
import static org.hamcrest.Matchers.is;
|
||||||
import static org.hamcrest.Matchers.notNullValue;
|
import static org.hamcrest.Matchers.notNullValue;
|
||||||
import static org.hamcrest.Matchers.nullValue;
|
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
|
// let the communicator throw, simulating a problem with the underlying
|
||||||
// autodetect, e.g. a crash
|
// autodetect, e.g. a crash
|
||||||
doThrow(Exception.class).when(autodetectCommunicator).close();
|
doThrow(RuntimeException.class).when(autodetectCommunicator).close();
|
||||||
|
|
||||||
// create a jobtask
|
// create a jobtask
|
||||||
JobTask jobTask = mock(JobTask.class);
|
JobTask jobTask = mock(JobTask.class);
|
||||||
|
|
|
@ -50,7 +50,7 @@ class AsyncHttpResourceHelper {
|
||||||
doAnswer(invocation -> {
|
doAnswer(invocation -> {
|
||||||
((ResponseListener)invocation.getArguments()[1]).onSuccess(response);
|
((ResponseListener)invocation.getArguments()[1]).onSuccess(response);
|
||||||
return null;
|
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> request, final List<Response> responses) {
|
static void whenPerformRequestAsyncWith(final RestClient client, final Matcher<Request> request, final List<Response> 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) {
|
static void whenPerformRequestAsyncWith(final RestClient client, final Request request, final Response response) {
|
||||||
|
@ -115,7 +115,7 @@ class AsyncHttpResourceHelper {
|
||||||
doAnswer(invocation -> {
|
doAnswer(invocation -> {
|
||||||
((ResponseListener)invocation.getArguments()[1]).onFailure(exception);
|
((ResponseListener)invocation.getArguments()[1]).onFailure(exception);
|
||||||
return null;
|
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) {
|
static void whenPerformRequestAsyncWith(final RestClient client, final Request request, final Exception exception) {
|
||||||
|
|
|
@ -16,7 +16,7 @@ import org.elasticsearch.xcontent.XContent;
|
||||||
import org.elasticsearch.xcontent.XContentParser;
|
import org.elasticsearch.xcontent.XContentParser;
|
||||||
import org.elasticsearch.xcontent.XContentParser.Token;
|
import org.elasticsearch.xcontent.XContentParser.Token;
|
||||||
import org.elasticsearch.xcontent.XContentType;
|
import org.elasticsearch.xcontent.XContentType;
|
||||||
import org.elasticsearch.mock.orig.Mockito;
|
import org.mockito.Mockito;
|
||||||
import org.elasticsearch.test.ESTestCase;
|
import org.elasticsearch.test.ESTestCase;
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
|
|
|
@ -856,47 +856,49 @@ public class HttpExporterResourceTests extends AbstractPublishableHttpResourceTe
|
||||||
}
|
}
|
||||||
|
|
||||||
private void verifyVersionCheck() {
|
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) {
|
private void verifyGetTemplates(final int called) {
|
||||||
verify(client, times(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) {
|
private void verifyPutTemplates(final int called) {
|
||||||
verify(client, times(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) {
|
private void verifyGetPipelines(final int called) {
|
||||||
verify(client, times(called))
|
verify(client, times(called)).performRequestAsync(
|
||||||
.performRequestAsync(argThat(new RequestMatcher(is("GET"), startsWith("/_ingest/pipeline/"))), any(ResponseListener.class));
|
argThat(new RequestMatcher(is("GET"), startsWith("/_ingest/pipeline/"))::matches), any(ResponseListener.class));
|
||||||
}
|
}
|
||||||
|
|
||||||
private void verifyPutPipelines(final int called) {
|
private void verifyPutPipelines(final int called) {
|
||||||
verify(client, times(called))
|
verify(client, times(called)).performRequestAsync(
|
||||||
.performRequestAsync(argThat(new RequestMatcher(is("PUT"), startsWith("/_ingest/pipeline/"))), any(ResponseListener.class));
|
argThat(new RequestMatcher(is("PUT"), startsWith("/_ingest/pipeline/"))::matches), any(ResponseListener.class));
|
||||||
}
|
}
|
||||||
|
|
||||||
private void verifyWatcherCheck() {
|
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) {
|
private void verifyDeleteWatches(final int called) {
|
||||||
verify(client, times(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));
|
any(ResponseListener.class));
|
||||||
}
|
}
|
||||||
|
|
||||||
private void verifyGetWatches(final int called) {
|
private void verifyGetWatches(final int called) {
|
||||||
verify(client, times(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) {
|
private void verifyPutWatches(final int called) {
|
||||||
verify(client, times(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) {
|
private ClusterService mockClusterService(final ClusterState state) {
|
||||||
|
|
|
@ -6,8 +6,6 @@
|
||||||
*/
|
*/
|
||||||
package org.elasticsearch.xpack.monitoring.exporter.http;
|
package org.elasticsearch.xpack.monitoring.exporter.http;
|
||||||
|
|
||||||
import java.util.Collections;
|
|
||||||
import java.util.Map;
|
|
||||||
import org.apache.http.HttpEntity;
|
import org.apache.http.HttpEntity;
|
||||||
import org.apache.http.entity.ContentType;
|
import org.apache.http.entity.ContentType;
|
||||||
import org.apache.http.entity.StringEntity;
|
import org.apache.http.entity.StringEntity;
|
||||||
|
@ -17,16 +15,17 @@ import org.elasticsearch.client.Response;
|
||||||
import org.elasticsearch.client.ResponseException;
|
import org.elasticsearch.client.ResponseException;
|
||||||
import org.elasticsearch.client.ResponseListener;
|
import org.elasticsearch.client.ResponseListener;
|
||||||
import org.elasticsearch.client.RestClient;
|
import org.elasticsearch.client.RestClient;
|
||||||
import org.elasticsearch.core.CheckedFunction;
|
|
||||||
import org.elasticsearch.common.SuppressLoggerChecks;
|
import org.elasticsearch.common.SuppressLoggerChecks;
|
||||||
|
import org.elasticsearch.core.CheckedFunction;
|
||||||
|
import org.elasticsearch.rest.RestStatus;
|
||||||
import org.elasticsearch.xcontent.XContent;
|
import org.elasticsearch.xcontent.XContent;
|
||||||
import org.elasticsearch.xcontent.XContentType;
|
import org.elasticsearch.xcontent.XContentType;
|
||||||
import org.elasticsearch.rest.RestStatus;
|
|
||||||
|
|
||||||
import org.elasticsearch.xpack.monitoring.exporter.http.HttpResource.ResourcePublishResult;
|
import org.elasticsearch.xpack.monitoring.exporter.http.HttpResource.ResourcePublishResult;
|
||||||
import org.mockito.ArgumentCaptor;
|
import org.mockito.ArgumentCaptor;
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.Map;
|
||||||
import java.util.function.Supplier;
|
import java.util.function.Supplier;
|
||||||
|
|
||||||
import static org.elasticsearch.xpack.monitoring.exporter.http.AsyncHttpResourceHelper.whenPerformRequestAsyncWith;
|
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).trace("checking if {} [{}] exists on the [{}] {}", resourceType, resourceName, owner, ownerType);
|
||||||
verify(logger).debug("{} [{}] found 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(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);
|
verifyNoMoreInteractions(client, logger);
|
||||||
}
|
}
|
||||||
|
|
|
@ -793,7 +793,7 @@ public class BufferOnMarkInputStreamTests extends ESTestCase {
|
||||||
}
|
}
|
||||||
int bytesSkipped = 1 + Randomness.get().nextInt(Math.toIntExact(n));
|
int bytesSkipped = 1 + Randomness.get().nextInt(Math.toIntExact(n));
|
||||||
bytesRead.addAndGet(bytesSkipped);
|
bytesRead.addAndGet(bytesSkipped);
|
||||||
return bytesSkipped;
|
return (long) bytesSkipped;
|
||||||
});
|
});
|
||||||
when(mockSource.available()).thenReturn(1 + Randomness.get().nextInt(32));
|
when(mockSource.available()).thenReturn(1 + Randomness.get().nextInt(32));
|
||||||
when(mockSource.markSupported()).thenReturn(false);
|
when(mockSource.markSupported()).thenReturn(false);
|
||||||
|
|
|
@ -186,11 +186,11 @@ public class PrefixInputStreamTests extends ESTestCase {
|
||||||
when(mockSource.skip(org.mockito.Matchers.anyLong())).thenAnswer(invocationOnMock -> {
|
when(mockSource.skip(org.mockito.Matchers.anyLong())).thenAnswer(invocationOnMock -> {
|
||||||
final long n = (long) invocationOnMock.getArguments()[0];
|
final long n = (long) invocationOnMock.getArguments()[0];
|
||||||
if (n <= 0 || bytesRemaining.get() <= 0) {
|
if (n <= 0 || bytesRemaining.get() <= 0) {
|
||||||
return 0;
|
return 0L;
|
||||||
}
|
}
|
||||||
int bytesSkipped = 1 + Randomness.get().nextInt(Math.min(bytesRemaining.get(), Math.toIntExact(n)));
|
int bytesSkipped = 1 + Randomness.get().nextInt(Math.min(bytesRemaining.get(), Math.toIntExact(n)));
|
||||||
bytesRemaining.addAndGet(-bytesSkipped);
|
bytesRemaining.addAndGet(-bytesSkipped);
|
||||||
return bytesSkipped;
|
return (long) bytesSkipped;
|
||||||
});
|
});
|
||||||
when(mockSource.available()).thenAnswer(invocationOnMock -> {
|
when(mockSource.available()).thenAnswer(invocationOnMock -> {
|
||||||
if (bytesRemaining.get() <= 0) {
|
if (bytesRemaining.get() <= 0) {
|
||||||
|
|
|
@ -38,7 +38,6 @@ import static org.hamcrest.Matchers.lessThan;
|
||||||
import static org.hamcrest.Matchers.lessThanOrEqualTo;
|
import static org.hamcrest.Matchers.lessThanOrEqualTo;
|
||||||
import static org.hamcrest.Matchers.startsWith;
|
import static org.hamcrest.Matchers.startsWith;
|
||||||
import static org.mockito.Matchers.any;
|
import static org.mockito.Matchers.any;
|
||||||
import static org.mockito.Matchers.anyInt;
|
|
||||||
import static org.mockito.Matchers.anyLong;
|
import static org.mockito.Matchers.anyLong;
|
||||||
import static org.mockito.Matchers.anyString;
|
import static org.mockito.Matchers.anyString;
|
||||||
import static org.mockito.Mockito.mock;
|
import static org.mockito.Mockito.mock;
|
||||||
|
@ -80,7 +79,7 @@ public class DirectBlobContainerIndexInputTests extends ESIndexInputTestCase {
|
||||||
);
|
);
|
||||||
|
|
||||||
final BlobContainer blobContainer = mock(BlobContainer.class);
|
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];
|
String name = (String) invocationOnMock.getArguments()[0];
|
||||||
long position = (long) invocationOnMock.getArguments()[1];
|
long position = (long) invocationOnMock.getArguments()[1];
|
||||||
long length = (long) invocationOnMock.getArguments()[2];
|
long length = (long) invocationOnMock.getArguments()[2];
|
||||||
|
|
|
@ -75,7 +75,6 @@ dependencies {
|
||||||
api "net.minidev:accessors-smart:2.4.2"
|
api "net.minidev:accessors-smart:2.4.2"
|
||||||
api "org.ow2.asm:asm:9.1"
|
api "org.ow2.asm:asm:9.1"
|
||||||
|
|
||||||
testImplementation 'org.elasticsearch:securemock:1.2'
|
|
||||||
testImplementation "org.elasticsearch:mocksocket:${versions.mocksocket}"
|
testImplementation "org.elasticsearch:mocksocket:${versions.mocksocket}"
|
||||||
|
|
||||||
// Test dependencies for Kerberos (MiniKdc)
|
// Test dependencies for Kerberos (MiniKdc)
|
||||||
|
|
|
@ -74,8 +74,8 @@ import static org.hamcrest.Matchers.hasSize;
|
||||||
import static org.hamcrest.Matchers.instanceOf;
|
import static org.hamcrest.Matchers.instanceOf;
|
||||||
import static org.hamcrest.Matchers.notNullValue;
|
import static org.hamcrest.Matchers.notNullValue;
|
||||||
import static org.hamcrest.Matchers.startsWith;
|
import static org.hamcrest.Matchers.startsWith;
|
||||||
|
import static org.mockito.ArgumentMatchers.nullable;
|
||||||
import static org.mockito.Matchers.any;
|
import static org.mockito.Matchers.any;
|
||||||
import static org.mockito.Matchers.anyString;
|
|
||||||
import static org.mockito.Matchers.eq;
|
import static org.mockito.Matchers.eq;
|
||||||
import static org.mockito.Mockito.doAnswer;
|
import static org.mockito.Mockito.doAnswer;
|
||||||
import static org.mockito.Mockito.mock;
|
import static org.mockito.Mockito.mock;
|
||||||
|
@ -119,21 +119,21 @@ public class TransportOpenIdConnectLogoutActionTests extends OpenIdConnectTestCa
|
||||||
.setType((String) invocationOnMock.getArguments()[1])
|
.setType((String) invocationOnMock.getArguments()[1])
|
||||||
.setId((String) invocationOnMock.getArguments()[2]);
|
.setId((String) invocationOnMock.getArguments()[2]);
|
||||||
return builder;
|
return builder;
|
||||||
}).when(client).prepareGet(anyString(), anyString(), anyString());
|
}).when(client).prepareGet(nullable(String.class), nullable(String.class), nullable(String.class));
|
||||||
doAnswer(invocationOnMock -> {
|
doAnswer(invocationOnMock -> {
|
||||||
IndexRequestBuilder builder = new IndexRequestBuilder(client, IndexAction.INSTANCE);
|
IndexRequestBuilder builder = new IndexRequestBuilder(client, IndexAction.INSTANCE);
|
||||||
builder.setIndex((String) invocationOnMock.getArguments()[0])
|
builder.setIndex((String) invocationOnMock.getArguments()[0])
|
||||||
.setType((String) invocationOnMock.getArguments()[1])
|
.setType((String) invocationOnMock.getArguments()[1])
|
||||||
.setId((String) invocationOnMock.getArguments()[2]);
|
.setId((String) invocationOnMock.getArguments()[2]);
|
||||||
return builder;
|
return builder;
|
||||||
}).when(client).prepareIndex(anyString(), anyString(), anyString());
|
}).when(client).prepareIndex(nullable(String.class), nullable(String.class), nullable(String.class));
|
||||||
doAnswer(invocationOnMock -> {
|
doAnswer(invocationOnMock -> {
|
||||||
UpdateRequestBuilder builder = new UpdateRequestBuilder(client, UpdateAction.INSTANCE);
|
UpdateRequestBuilder builder = new UpdateRequestBuilder(client, UpdateAction.INSTANCE);
|
||||||
builder.setIndex((String) invocationOnMock.getArguments()[0])
|
builder.setIndex((String) invocationOnMock.getArguments()[0])
|
||||||
.setType((String) invocationOnMock.getArguments()[1])
|
.setType((String) invocationOnMock.getArguments()[1])
|
||||||
.setId((String) invocationOnMock.getArguments()[2]);
|
.setId((String) invocationOnMock.getArguments()[2]);
|
||||||
return builder;
|
return builder;
|
||||||
}).when(client).prepareUpdate(anyString(), anyString(), anyString());
|
}).when(client).prepareUpdate(nullable(String.class), nullable(String.class), nullable(String.class));
|
||||||
doAnswer(invocationOnMock -> {
|
doAnswer(invocationOnMock -> {
|
||||||
BulkRequestBuilder builder = new BulkRequestBuilder(client, BulkAction.INSTANCE);
|
BulkRequestBuilder builder = new BulkRequestBuilder(client, BulkAction.INSTANCE);
|
||||||
return builder;
|
return builder;
|
||||||
|
|
|
@ -32,6 +32,7 @@ import static org.hamcrest.Matchers.arrayContaining;
|
||||||
import static org.hamcrest.Matchers.arrayContainingInAnyOrder;
|
import static org.hamcrest.Matchers.arrayContainingInAnyOrder;
|
||||||
import static org.hamcrest.Matchers.containsInAnyOrder;
|
import static org.hamcrest.Matchers.containsInAnyOrder;
|
||||||
import static org.hamcrest.Matchers.notNullValue;
|
import static org.hamcrest.Matchers.notNullValue;
|
||||||
|
import static org.mockito.ArgumentMatchers.nullable;
|
||||||
import static org.mockito.Matchers.any;
|
import static org.mockito.Matchers.any;
|
||||||
import static org.mockito.Mockito.doAnswer;
|
import static org.mockito.Mockito.doAnswer;
|
||||||
import static org.mockito.Mockito.mock;
|
import static org.mockito.Mockito.mock;
|
||||||
|
@ -61,7 +62,7 @@ public class TransportGetRoleMappingsActionTests extends ESTestCase {
|
||||||
ActionListener<List<ExpressionRoleMapping>> listener = (ActionListener<List<ExpressionRoleMapping>>) args[1];
|
ActionListener<List<ExpressionRoleMapping>> listener = (ActionListener<List<ExpressionRoleMapping>>) args[1];
|
||||||
listener.onResponse(result);
|
listener.onResponse(result);
|
||||||
return null;
|
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 {
|
public void testGetSingleRole() throws Exception {
|
||||||
|
|
|
@ -84,8 +84,8 @@ import static org.hamcrest.Matchers.hasSize;
|
||||||
import static org.hamcrest.Matchers.instanceOf;
|
import static org.hamcrest.Matchers.instanceOf;
|
||||||
import static org.hamcrest.Matchers.notNullValue;
|
import static org.hamcrest.Matchers.notNullValue;
|
||||||
import static org.hamcrest.Matchers.startsWith;
|
import static org.hamcrest.Matchers.startsWith;
|
||||||
|
import static org.mockito.ArgumentMatchers.nullable;
|
||||||
import static org.mockito.Matchers.any;
|
import static org.mockito.Matchers.any;
|
||||||
import static org.mockito.Matchers.anyString;
|
|
||||||
import static org.mockito.Matchers.eq;
|
import static org.mockito.Matchers.eq;
|
||||||
import static org.mockito.Mockito.doAnswer;
|
import static org.mockito.Mockito.doAnswer;
|
||||||
import static org.mockito.Mockito.mock;
|
import static org.mockito.Mockito.mock;
|
||||||
|
@ -133,21 +133,21 @@ public class TransportSamlLogoutActionTests extends SamlTestCase {
|
||||||
.setType((String) invocationOnMock.getArguments()[1])
|
.setType((String) invocationOnMock.getArguments()[1])
|
||||||
.setId((String) invocationOnMock.getArguments()[2]);
|
.setId((String) invocationOnMock.getArguments()[2]);
|
||||||
return builder;
|
return builder;
|
||||||
}).when(client).prepareGet(anyString(), anyString(), anyString());
|
}).when(client).prepareGet(nullable(String.class), nullable(String.class), nullable(String.class));
|
||||||
doAnswer(invocationOnMock -> {
|
doAnswer(invocationOnMock -> {
|
||||||
IndexRequestBuilder builder = new IndexRequestBuilder(client, IndexAction.INSTANCE);
|
IndexRequestBuilder builder = new IndexRequestBuilder(client, IndexAction.INSTANCE);
|
||||||
builder.setIndex((String) invocationOnMock.getArguments()[0])
|
builder.setIndex((String) invocationOnMock.getArguments()[0])
|
||||||
.setType((String) invocationOnMock.getArguments()[1])
|
.setType((String) invocationOnMock.getArguments()[1])
|
||||||
.setId((String) invocationOnMock.getArguments()[2]);
|
.setId((String) invocationOnMock.getArguments()[2]);
|
||||||
return builder;
|
return builder;
|
||||||
}).when(client).prepareIndex(anyString(), anyString(), anyString());
|
}).when(client).prepareIndex(nullable(String.class), nullable(String.class), nullable(String.class));
|
||||||
doAnswer(invocationOnMock -> {
|
doAnswer(invocationOnMock -> {
|
||||||
UpdateRequestBuilder builder = new UpdateRequestBuilder(client, UpdateAction.INSTANCE);
|
UpdateRequestBuilder builder = new UpdateRequestBuilder(client, UpdateAction.INSTANCE);
|
||||||
builder.setIndex((String) invocationOnMock.getArguments()[0])
|
builder.setIndex((String) invocationOnMock.getArguments()[0])
|
||||||
.setType((String) invocationOnMock.getArguments()[1])
|
.setType((String) invocationOnMock.getArguments()[1])
|
||||||
.setId((String) invocationOnMock.getArguments()[2]);
|
.setId((String) invocationOnMock.getArguments()[2]);
|
||||||
return builder;
|
return builder;
|
||||||
}).when(client).prepareUpdate(anyString(), anyString(), anyString());
|
}).when(client).prepareUpdate(nullable(String.class), nullable(String.class), nullable(String.class));
|
||||||
doAnswer(invocationOnMock -> {
|
doAnswer(invocationOnMock -> {
|
||||||
BulkRequestBuilder builder = new BulkRequestBuilder(client, BulkAction.INSTANCE);
|
BulkRequestBuilder builder = new BulkRequestBuilder(client, BulkAction.INSTANCE);
|
||||||
return builder;
|
return builder;
|
||||||
|
|
|
@ -34,7 +34,6 @@ import org.elasticsearch.common.settings.SecureString;
|
||||||
import org.elasticsearch.common.settings.Settings;
|
import org.elasticsearch.common.settings.Settings;
|
||||||
import org.elasticsearch.index.shard.ShardId;
|
import org.elasticsearch.index.shard.ShardId;
|
||||||
import org.elasticsearch.license.MockLicenseState;
|
import org.elasticsearch.license.MockLicenseState;
|
||||||
import org.elasticsearch.mock.orig.Mockito;
|
|
||||||
import org.elasticsearch.node.Node;
|
import org.elasticsearch.node.Node;
|
||||||
import org.elasticsearch.rest.RestStatus;
|
import org.elasticsearch.rest.RestStatus;
|
||||||
import org.elasticsearch.test.ClusterServiceUtils;
|
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.elasticsearch.xpack.security.support.SecurityIndexManager;
|
||||||
import org.junit.After;
|
import org.junit.After;
|
||||||
import org.junit.Before;
|
import org.junit.Before;
|
||||||
|
import org.mockito.Mockito;
|
||||||
|
|
||||||
import java.nio.charset.StandardCharsets;
|
import java.nio.charset.StandardCharsets;
|
||||||
import java.time.Clock;
|
import java.time.Clock;
|
||||||
|
@ -71,8 +71,8 @@ import java.util.function.Consumer;
|
||||||
import static org.elasticsearch.test.ActionListenerUtils.anyActionListener;
|
import static org.elasticsearch.test.ActionListenerUtils.anyActionListener;
|
||||||
import static org.hamcrest.Matchers.containsString;
|
import static org.hamcrest.Matchers.containsString;
|
||||||
import static org.hamcrest.Matchers.is;
|
import static org.hamcrest.Matchers.is;
|
||||||
|
import static org.mockito.ArgumentMatchers.nullable;
|
||||||
import static org.mockito.Matchers.any;
|
import static org.mockito.Matchers.any;
|
||||||
import static org.mockito.Matchers.anyString;
|
|
||||||
import static org.mockito.Matchers.eq;
|
import static org.mockito.Matchers.eq;
|
||||||
import static org.mockito.Mockito.doAnswer;
|
import static org.mockito.Mockito.doAnswer;
|
||||||
import static org.mockito.Mockito.mock;
|
import static org.mockito.Mockito.mock;
|
||||||
|
@ -106,7 +106,7 @@ public class TransportCreateTokenActionTests extends ESTestCase {
|
||||||
.setType((String) invocationOnMock.getArguments()[1])
|
.setType((String) invocationOnMock.getArguments()[1])
|
||||||
.setId((String) invocationOnMock.getArguments()[2]);
|
.setId((String) invocationOnMock.getArguments()[2]);
|
||||||
return builder;
|
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));
|
when(client.prepareMultiGet()).thenReturn(new MultiGetRequestBuilder(client, MultiGetAction.INSTANCE));
|
||||||
doAnswer(invocationOnMock -> {
|
doAnswer(invocationOnMock -> {
|
||||||
@SuppressWarnings("unchecked")
|
@SuppressWarnings("unchecked")
|
||||||
|
@ -125,9 +125,9 @@ public class TransportCreateTokenActionTests extends ESTestCase {
|
||||||
listener.onResponse(response);
|
listener.onResponse(response);
|
||||||
return Void.TYPE;
|
return Void.TYPE;
|
||||||
}).when(client).multiGet(any(MultiGetRequest.class), anyActionListener());
|
}).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));
|
.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));
|
.thenReturn(new UpdateRequestBuilder(client, UpdateAction.INSTANCE));
|
||||||
doAnswer(invocationOnMock -> {
|
doAnswer(invocationOnMock -> {
|
||||||
idxReqReference.set((IndexRequest) invocationOnMock.getArguments()[1]);
|
idxReqReference.set((IndexRequest) invocationOnMock.getArguments()[1]);
|
||||||
|
|
|
@ -18,16 +18,15 @@ import org.elasticsearch.common.settings.ClusterSettings;
|
||||||
import org.elasticsearch.common.settings.Setting;
|
import org.elasticsearch.common.settings.Setting;
|
||||||
import org.elasticsearch.common.settings.Settings;
|
import org.elasticsearch.common.settings.Settings;
|
||||||
import org.elasticsearch.common.util.concurrent.ThreadContext;
|
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.license.XPackLicenseState;
|
||||||
import org.elasticsearch.mock.orig.Mockito;
|
|
||||||
import org.elasticsearch.rest.RestRequest;
|
import org.elasticsearch.rest.RestRequest;
|
||||||
import org.elasticsearch.test.ESTestCase;
|
import org.elasticsearch.test.ESTestCase;
|
||||||
import org.elasticsearch.test.rest.FakeRestRequest;
|
import org.elasticsearch.test.rest.FakeRestRequest;
|
||||||
import org.elasticsearch.test.rest.FakeRestRequest.Builder;
|
import org.elasticsearch.test.rest.FakeRestRequest.Builder;
|
||||||
import org.elasticsearch.threadpool.ThreadPool;
|
import org.elasticsearch.threadpool.ThreadPool;
|
||||||
import org.elasticsearch.transport.TransportRequest;
|
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.audit.logfile.CapturingLogger;
|
||||||
import org.elasticsearch.xpack.core.security.authc.Authentication;
|
import org.elasticsearch.xpack.core.security.authc.Authentication;
|
||||||
import org.elasticsearch.xpack.core.security.authc.Authentication.RealmRef;
|
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.support.SecurityIndexManager;
|
||||||
import org.elasticsearch.xpack.security.transport.filter.SecurityIpFilterRule;
|
import org.elasticsearch.xpack.security.transport.filter.SecurityIpFilterRule;
|
||||||
import org.junit.Before;
|
import org.junit.Before;
|
||||||
|
import org.mockito.Mockito;
|
||||||
import org.mockito.stubbing.Answer;
|
import org.mockito.stubbing.Answer;
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
|
|
|
@ -21,7 +21,6 @@ import org.elasticsearch.common.Strings;
|
||||||
import org.elasticsearch.common.bytes.BytesArray;
|
import org.elasticsearch.common.bytes.BytesArray;
|
||||||
import org.elasticsearch.common.bytes.BytesReference;
|
import org.elasticsearch.common.bytes.BytesReference;
|
||||||
import org.elasticsearch.common.collect.MapBuilder;
|
import org.elasticsearch.common.collect.MapBuilder;
|
||||||
import org.elasticsearch.core.Tuple;
|
|
||||||
import org.elasticsearch.common.io.stream.StreamOutput;
|
import org.elasticsearch.common.io.stream.StreamOutput;
|
||||||
import org.elasticsearch.common.logging.Loggers;
|
import org.elasticsearch.common.logging.Loggers;
|
||||||
import org.elasticsearch.common.network.NetworkAddress;
|
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.Setting;
|
||||||
import org.elasticsearch.common.settings.Settings;
|
import org.elasticsearch.common.settings.Settings;
|
||||||
import org.elasticsearch.common.transport.TransportAddress;
|
import org.elasticsearch.common.transport.TransportAddress;
|
||||||
import org.elasticsearch.core.TimeValue;
|
|
||||||
import org.elasticsearch.common.util.concurrent.ThreadContext;
|
import org.elasticsearch.common.util.concurrent.ThreadContext;
|
||||||
import org.elasticsearch.xcontent.NamedXContentRegistry;
|
import org.elasticsearch.core.TimeValue;
|
||||||
import org.elasticsearch.xcontent.XContentBuilder;
|
import org.elasticsearch.core.Tuple;
|
||||||
import org.elasticsearch.xcontent.XContentType;
|
|
||||||
import org.elasticsearch.license.XPackLicenseState;
|
import org.elasticsearch.license.XPackLicenseState;
|
||||||
import org.elasticsearch.mock.orig.Mockito;
|
|
||||||
import org.elasticsearch.rest.RestRequest;
|
import org.elasticsearch.rest.RestRequest;
|
||||||
import org.elasticsearch.tasks.Task;
|
import org.elasticsearch.tasks.Task;
|
||||||
import org.elasticsearch.test.ESTestCase;
|
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.test.rest.FakeRestRequest.Builder;
|
||||||
import org.elasticsearch.threadpool.ThreadPool;
|
import org.elasticsearch.threadpool.ThreadPool;
|
||||||
import org.elasticsearch.transport.TransportRequest;
|
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.XPackSettings;
|
||||||
import org.elasticsearch.xpack.core.security.action.CreateApiKeyAction;
|
import org.elasticsearch.xpack.core.security.action.CreateApiKeyAction;
|
||||||
import org.elasticsearch.xpack.core.security.action.CreateApiKeyRequest;
|
import org.elasticsearch.xpack.core.security.action.CreateApiKeyRequest;
|
||||||
|
@ -113,6 +112,7 @@ import org.junit.After;
|
||||||
import org.junit.AfterClass;
|
import org.junit.AfterClass;
|
||||||
import org.junit.Before;
|
import org.junit.Before;
|
||||||
import org.junit.BeforeClass;
|
import org.junit.BeforeClass;
|
||||||
|
import org.mockito.Mockito;
|
||||||
import org.mockito.stubbing.Answer;
|
import org.mockito.stubbing.Answer;
|
||||||
|
|
||||||
import java.io.BufferedInputStream;
|
import java.io.BufferedInputStream;
|
||||||
|
|
|
@ -100,7 +100,6 @@ import org.elasticsearch.xpack.security.support.CacheInvalidatorRegistry;
|
||||||
import org.elasticsearch.xpack.security.support.SecurityIndexManager;
|
import org.elasticsearch.xpack.security.support.SecurityIndexManager;
|
||||||
import org.junit.After;
|
import org.junit.After;
|
||||||
import org.junit.Before;
|
import org.junit.Before;
|
||||||
import org.mockito.ArgumentMatcher;
|
|
||||||
import org.mockito.Mockito;
|
import org.mockito.Mockito;
|
||||||
|
|
||||||
import java.io.IOException;
|
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.notNullValue;
|
||||||
import static org.hamcrest.Matchers.nullValue;
|
import static org.hamcrest.Matchers.nullValue;
|
||||||
import static org.hamcrest.Matchers.sameInstance;
|
import static org.hamcrest.Matchers.sameInstance;
|
||||||
|
import static org.mockito.ArgumentMatchers.nullable;
|
||||||
import static org.mockito.Matchers.any;
|
import static org.mockito.Matchers.any;
|
||||||
import static org.mockito.Matchers.anyString;
|
import static org.mockito.Matchers.anyString;
|
||||||
import static org.mockito.Matchers.argThat;
|
import static org.mockito.Matchers.argThat;
|
||||||
|
@ -255,9 +255,9 @@ public class AuthenticationServiceTests extends ESTestCase {
|
||||||
threadContext = threadPool.getThreadContext();
|
threadContext = threadPool.getThreadContext();
|
||||||
when(client.threadPool()).thenReturn(threadPool);
|
when(client.threadPool()).thenReturn(threadPool);
|
||||||
when(client.settings()).thenReturn(settings);
|
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));
|
.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));
|
.thenReturn(new UpdateRequestBuilder(client, UpdateAction.INSTANCE));
|
||||||
doAnswer(invocationOnMock -> {
|
doAnswer(invocationOnMock -> {
|
||||||
@SuppressWarnings("unchecked")
|
@SuppressWarnings("unchecked")
|
||||||
|
@ -272,7 +272,7 @@ public class AuthenticationServiceTests extends ESTestCase {
|
||||||
.setType((String) invocationOnMock.getArguments()[1])
|
.setType((String) invocationOnMock.getArguments()[1])
|
||||||
.setId((String) invocationOnMock.getArguments()[2]);
|
.setId((String) invocationOnMock.getArguments()[2]);
|
||||||
return builder;
|
return builder;
|
||||||
}).when(client).prepareGet(anyString(), anyString(), anyString());
|
}).when(client).prepareGet(nullable(String.class), nullable(String.class), nullable(String.class));
|
||||||
securityIndex = mock(SecurityIndexManager.class);
|
securityIndex = mock(SecurityIndexManager.class);
|
||||||
doAnswer(invocationOnMock -> {
|
doAnswer(invocationOnMock -> {
|
||||||
Runnable runnable = (Runnable) invocationOnMock.getArguments()[1];
|
Runnable runnable = (Runnable) invocationOnMock.getArguments()[1];
|
||||||
|
@ -2021,12 +2021,7 @@ public class AuthenticationServiceTests extends ESTestCase {
|
||||||
verifyZeroInteractions(operatorPrivilegesService);
|
verifyZeroInteractions(operatorPrivilegesService);
|
||||||
final ServiceAccountToken serviceToken = ServiceAccountToken.fromBearerString(new SecureString(bearerString.toCharArray()));
|
final ServiceAccountToken serviceToken = ServiceAccountToken.fromBearerString(new SecureString(bearerString.toCharArray()));
|
||||||
verify(auditTrail).authenticationFailed(eq(reqId.get()),
|
verify(auditTrail).authenticationFailed(eq(reqId.get()),
|
||||||
argThat(new ArgumentMatcher<AuthenticationToken>() {
|
argThat(o -> ((ServiceAccountToken) o).getTokenId().equals(serviceToken.getTokenId())),
|
||||||
@Override
|
|
||||||
public boolean matches(Object o) {
|
|
||||||
return ((ServiceAccountToken) o).getTokenId().equals(serviceToken.getTokenId());
|
|
||||||
}
|
|
||||||
}),
|
|
||||||
eq("_action"), eq(transportRequest));
|
eq("_action"), eq(transportRequest));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -28,7 +28,7 @@ import org.elasticsearch.xpack.security.support.SecurityIndexManager;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.function.BiConsumer;
|
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.CoreMatchers.nullValue;
|
||||||
import static org.hamcrest.Matchers.any;
|
import static org.hamcrest.Matchers.any;
|
||||||
import static org.hamcrest.Matchers.hasEntry;
|
import static org.hamcrest.Matchers.hasEntry;
|
||||||
|
|
|
@ -959,7 +959,7 @@ public class TokenServiceTests extends ESTestCase {
|
||||||
when(response.getSource()).thenReturn(sourceMap);
|
when(response.getSource()).thenReturn(sourceMap);
|
||||||
}
|
}
|
||||||
listener.onResponse(response);
|
listener.onResponse(response);
|
||||||
return Void.TYPE;
|
return null;
|
||||||
}).when(client).get(any(GetRequest.class), anyActionListener());
|
}).when(client).get(any(GetRequest.class), anyActionListener());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -1063,7 +1063,7 @@ public class TokenServiceTests extends ESTestCase {
|
||||||
when(response.getHits()).thenReturn(hits);
|
when(response.getHits()).thenReturn(hits);
|
||||||
listener.onResponse(response);
|
listener.onResponse(response);
|
||||||
return Void.TYPE;
|
return Void.TYPE;
|
||||||
}).when(client).search(any(SearchRequest.class), anyActionListener());
|
}).when(client).search(any(SearchRequest.class), any());
|
||||||
}
|
}
|
||||||
|
|
||||||
private void mockGetTokenAsyncForDecryptedToken(String accessToken) {
|
private void mockGetTokenAsyncForDecryptedToken(String accessToken) {
|
||||||
|
|
|
@ -166,7 +166,6 @@ import org.elasticsearch.xpack.security.authz.store.NativePrivilegeStore;
|
||||||
import org.elasticsearch.xpack.security.operator.OperatorPrivileges;
|
import org.elasticsearch.xpack.security.operator.OperatorPrivileges;
|
||||||
import org.elasticsearch.xpack.sql.action.SqlQueryAction;
|
import org.elasticsearch.xpack.sql.action.SqlQueryAction;
|
||||||
import org.elasticsearch.xpack.sql.action.SqlQueryRequest;
|
import org.elasticsearch.xpack.sql.action.SqlQueryRequest;
|
||||||
import org.hamcrest.Description;
|
|
||||||
import org.junit.Before;
|
import org.junit.Before;
|
||||||
import org.mockito.ArgumentMatcher;
|
import org.mockito.ArgumentMatcher;
|
||||||
import org.mockito.Matchers;
|
import org.mockito.Matchers;
|
||||||
|
@ -2096,7 +2095,7 @@ public class AuthorizationServiceTests extends ESTestCase {
|
||||||
return Matchers.argThat(new RBACAuthorizationInfoRoleMatcher(expectedRoles));
|
return Matchers.argThat(new RBACAuthorizationInfoRoleMatcher(expectedRoles));
|
||||||
}
|
}
|
||||||
|
|
||||||
private static class RBACAuthorizationInfoRoleMatcher extends ArgumentMatcher<AuthorizationInfo> {
|
private static class RBACAuthorizationInfoRoleMatcher implements ArgumentMatcher<AuthorizationInfo> {
|
||||||
|
|
||||||
private final String[] wanted;
|
private final String[] wanted;
|
||||||
|
|
||||||
|
@ -2105,17 +2104,9 @@ public class AuthorizationServiceTests extends ESTestCase {
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean matches(Object item) {
|
public boolean matches(AuthorizationInfo other) {
|
||||||
if (item instanceof AuthorizationInfo) {
|
final String[] found = (String[]) other.asMap().get(PRINCIPAL_ROLES_FIELD_NAME);
|
||||||
final String[] found = (String[]) ((AuthorizationInfo) item).asMap().get(PRINCIPAL_ROLES_FIELD_NAME);
|
return Arrays.equals(wanted, found);
|
||||||
return Arrays.equals(wanted, found);
|
|
||||||
}
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void describeTo(Description description) {
|
|
||||||
description.appendText("RBAC AuthorizationInfo Roles[").appendText(Strings.arrayToCommaDelimitedString(wanted)).appendText("]");
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -94,8 +94,8 @@ import java.util.function.Consumer;
|
||||||
import java.util.function.Function;
|
import java.util.function.Function;
|
||||||
import java.util.function.Predicate;
|
import java.util.function.Predicate;
|
||||||
|
|
||||||
import static org.elasticsearch.mock.orig.Mockito.times;
|
import static org.mockito.Mockito.times;
|
||||||
import static org.elasticsearch.mock.orig.Mockito.verifyNoMoreInteractions;
|
import static org.mockito.Mockito.verifyNoMoreInteractions;
|
||||||
import static org.elasticsearch.test.ActionListenerUtils.anyActionListener;
|
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.SecurityField.DOCUMENT_LEVEL_SECURITY_FEATURE;
|
||||||
import static org.elasticsearch.xpack.core.security.authc.AuthenticationField.API_KEY_LIMITED_ROLE_DESCRIPTORS_KEY;
|
import static org.elasticsearch.xpack.core.security.authc.AuthenticationField.API_KEY_LIMITED_ROLE_DESCRIPTORS_KEY;
|
||||||
|
|
|
@ -17,7 +17,7 @@ import org.elasticsearch.common.logging.DeprecationCategory;
|
||||||
import org.elasticsearch.common.logging.DeprecationLogger;
|
import org.elasticsearch.common.logging.DeprecationLogger;
|
||||||
import org.elasticsearch.common.settings.Settings;
|
import org.elasticsearch.common.settings.Settings;
|
||||||
import org.elasticsearch.common.util.concurrent.ThreadContext;
|
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.ESTestCase;
|
||||||
import org.elasticsearch.test.VersionUtils;
|
import org.elasticsearch.test.VersionUtils;
|
||||||
import org.elasticsearch.threadpool.ThreadPool;
|
import org.elasticsearch.threadpool.ThreadPool;
|
||||||
|
|
|
@ -63,7 +63,6 @@ import java.util.Map;
|
||||||
import java.util.concurrent.atomic.AtomicInteger;
|
import java.util.concurrent.atomic.AtomicInteger;
|
||||||
import java.util.stream.Collectors;
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
import static org.elasticsearch.mock.orig.Mockito.when;
|
|
||||||
import static org.hamcrest.Matchers.anyOf;
|
import static org.hamcrest.Matchers.anyOf;
|
||||||
import static org.hamcrest.Matchers.equalTo;
|
import static org.hamcrest.Matchers.equalTo;
|
||||||
import static org.hamcrest.Matchers.greaterThan;
|
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.hamcrest.Matchers.instanceOf;
|
||||||
import static org.mockito.Mockito.mock;
|
import static org.mockito.Mockito.mock;
|
||||||
import static org.mockito.Mockito.spy;
|
import static org.mockito.Mockito.spy;
|
||||||
|
import static org.mockito.Mockito.when;
|
||||||
|
|
||||||
public class StackTemplateRegistryTests extends ESTestCase {
|
public class StackTemplateRegistryTests extends ESTestCase {
|
||||||
private StackTemplateRegistry registry;
|
private StackTemplateRegistry registry;
|
||||||
|
|
|
@ -21,18 +21,12 @@ import org.elasticsearch.client.Client;
|
||||||
import org.elasticsearch.cluster.node.DiscoveryNode;
|
import org.elasticsearch.cluster.node.DiscoveryNode;
|
||||||
import org.elasticsearch.cluster.node.DiscoveryNodeRole;
|
import org.elasticsearch.cluster.node.DiscoveryNodeRole;
|
||||||
import org.elasticsearch.cluster.service.ClusterService;
|
import org.elasticsearch.cluster.service.ClusterService;
|
||||||
import org.elasticsearch.core.Tuple;
|
|
||||||
import org.elasticsearch.common.settings.Settings;
|
import org.elasticsearch.common.settings.Settings;
|
||||||
import org.elasticsearch.core.TimeValue;
|
|
||||||
import org.elasticsearch.common.util.concurrent.EsExecutors;
|
import org.elasticsearch.common.util.concurrent.EsExecutors;
|
||||||
import org.elasticsearch.common.util.concurrent.EsRejectedExecutionException;
|
import org.elasticsearch.common.util.concurrent.EsRejectedExecutionException;
|
||||||
import org.elasticsearch.common.util.concurrent.ThreadContext;
|
import org.elasticsearch.common.util.concurrent.ThreadContext;
|
||||||
import org.elasticsearch.xcontent.DeprecationHandler;
|
import org.elasticsearch.core.TimeValue;
|
||||||
import org.elasticsearch.xcontent.NamedXContentRegistry;
|
import org.elasticsearch.core.Tuple;
|
||||||
import org.elasticsearch.xcontent.ObjectPath;
|
|
||||||
import org.elasticsearch.xcontent.XContentFactory;
|
|
||||||
import org.elasticsearch.xcontent.XContentParser;
|
|
||||||
import org.elasticsearch.xcontent.XContentType;
|
|
||||||
import org.elasticsearch.index.Index;
|
import org.elasticsearch.index.Index;
|
||||||
import org.elasticsearch.index.IndexNotFoundException;
|
import org.elasticsearch.index.IndexNotFoundException;
|
||||||
import org.elasticsearch.index.engine.VersionConflictEngineException;
|
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.index.shard.ShardId;
|
||||||
import org.elasticsearch.test.ESTestCase;
|
import org.elasticsearch.test.ESTestCase;
|
||||||
import org.elasticsearch.threadpool.ThreadPool;
|
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.Authentication;
|
||||||
import org.elasticsearch.xpack.core.security.authc.AuthenticationField;
|
import org.elasticsearch.xpack.core.security.authc.AuthenticationField;
|
||||||
import org.elasticsearch.xpack.core.security.user.User;
|
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.notNullValue;
|
||||||
import static org.hamcrest.Matchers.nullValue;
|
import static org.hamcrest.Matchers.nullValue;
|
||||||
import static org.hamcrest.Matchers.sameInstance;
|
import static org.hamcrest.Matchers.sameInstance;
|
||||||
|
import static org.mockito.ArgumentMatchers.nullable;
|
||||||
import static org.mockito.Matchers.any;
|
import static org.mockito.Matchers.any;
|
||||||
import static org.mockito.Matchers.anyLong;
|
import static org.mockito.Matchers.anyLong;
|
||||||
import static org.mockito.Matchers.anyObject;
|
import static org.mockito.Matchers.anyObject;
|
||||||
|
@ -142,7 +143,7 @@ public class ExecutionServiceTests extends ESTestCase {
|
||||||
inputResult = mock(Input.Result.class);
|
inputResult = mock(Input.Result.class);
|
||||||
when(inputResult.status()).thenReturn(Input.Result.Status.SUCCESS);
|
when(inputResult.status()).thenReturn(Input.Result.Status.SUCCESS);
|
||||||
when(inputResult.payload()).thenReturn(payload);
|
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);
|
triggeredWatchStore = mock(TriggeredWatchStore.class);
|
||||||
historyStore = mock(HistoryStore.class);
|
historyStore = mock(HistoryStore.class);
|
||||||
|
@ -286,7 +287,7 @@ public class ExecutionServiceTests extends ESTestCase {
|
||||||
Input.Result inputResult = mock(Input.Result.class);
|
Input.Result inputResult = mock(Input.Result.class);
|
||||||
when(inputResult.status()).thenReturn(Input.Result.Status.FAILURE);
|
when(inputResult.status()).thenReturn(Input.Result.Status.FAILURE);
|
||||||
when(inputResult.getException()).thenReturn(new IOException());
|
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;
|
Condition.Result conditionResult = InternalAlwaysCondition.RESULT_INSTANCE;
|
||||||
ExecutableCondition condition = mock(ExecutableCondition.class);
|
ExecutableCondition condition = mock(ExecutableCondition.class);
|
||||||
|
|
|
@ -59,8 +59,8 @@ import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.stream.Collectors;
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
import static org.elasticsearch.mock.orig.Mockito.verify;
|
import static org.mockito.Mockito.verify;
|
||||||
import static org.elasticsearch.mock.orig.Mockito.when;
|
import static org.mockito.Mockito.when;
|
||||||
import static org.elasticsearch.xpack.core.watcher.support.WatcherIndexTemplateRegistryField.INDEX_TEMPLATE_VERSION;
|
import static org.elasticsearch.xpack.core.watcher.support.WatcherIndexTemplateRegistryField.INDEX_TEMPLATE_VERSION;
|
||||||
import static org.hamcrest.Matchers.equalTo;
|
import static org.hamcrest.Matchers.equalTo;
|
||||||
import static org.hamcrest.Matchers.hasSize;
|
import static org.hamcrest.Matchers.hasSize;
|
||||||
|
|
|
@ -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.boolQuery;
|
||||||
import static org.elasticsearch.index.query.QueryBuilders.matchQuery;
|
import static org.elasticsearch.index.query.QueryBuilders.matchQuery;
|
||||||
import static org.elasticsearch.index.query.QueryBuilders.rangeQuery;
|
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.search.builder.SearchSourceBuilder.searchSource;
|
||||||
import static org.elasticsearch.xpack.watcher.test.WatcherTestUtils.getRandomSupportedSearchType;
|
import static org.elasticsearch.xpack.watcher.test.WatcherTestUtils.getRandomSupportedSearchType;
|
||||||
import static org.hamcrest.Matchers.arrayContainingInAnyOrder;
|
import static org.hamcrest.Matchers.arrayContainingInAnyOrder;
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue