下面列出了怎么用org.mockito.Matchers的API类实例代码及写法,或者点击链接到github查看源代码。
@Test
@WithMockUser(authorities = { "ROLE_SUPER_USER", "ROLE_IOT_USER", "ROLE_ANALYTICS_USER" })
public void shouldDescendingTenantLogs() throws Exception {
ServiceResponse<List<TenantLog>> responseTenantOk = ServiceResponseBuilder.<List<TenantLog>>ok().build();
List<TenantLog> logs = new ArrayList<TenantLog>();
logs.add(TenantLog.builder().time(new Date()).build());
logs.add(TenantLog.builder().time(new Date()).build());
responseTenantOk.setResult(logs);
when(tenantLogService.findByTenant(Matchers.anyObject(), Matchers.eq(false))).thenReturn(responseTenantOk);
when(dateToStringConverter.convert(Matchers.anyObject())).thenReturn("00/00/0000");
ResultActions result = getMockMvc().perform(get("/tenants/log").param("asc", "false"));
result.andExpect(model().attribute("logs", org.hamcrest.Matchers.iterableWithSize(2)));
result.andExpect(model().attribute("asc", org.hamcrest.Matchers.equalTo(false)));
}
@Test
public void testAddSubscription_ko() {
ResponseEntity<Object> response = new ResponseEntity(HttpStatus.CONFLICT);
Subscription subscription = new Subscription();
when(restTemplate.postForEntity(anyString(),anyObject(),Matchers.<Class<Object>>any())).thenReturn(response);
try{
repository.addSubscription(subscription,"alarmid");
verify(restTemplate).postForEntity(DEFAULT_SEYREN_URL + SeyrenRepository.API_ALARMS+"/alarmid/subscriptions/", subscription, Object.class);
fail();
}
catch(SeyrenException e){
assertEquals(e.getHttpStatus(),HttpStatus.CONFLICT.value());
assertEquals(e.getAction(),"addSubscription");
}
}
private ExecutionVertex mockExecutionVertex(
ExecutionAttemptID executionId,
ExecutionState state,
boolean sendSuccess) {
Execution exec = Mockito.mock(Execution.class);
CompletableFuture<StackTraceSampleResponse> failedFuture = new CompletableFuture<>();
failedFuture.completeExceptionally(new Exception("Send failed."));
Mockito.when(exec.getAttemptId()).thenReturn(executionId);
Mockito.when(exec.getState()).thenReturn(state);
Mockito.when(exec.requestStackTraceSample(Matchers.anyInt(), Matchers.anyInt(), Matchers.any(Time.class), Matchers.anyInt(), Matchers.any(Time.class)))
.thenReturn(
sendSuccess ?
CompletableFuture.completedFuture(Mockito.mock(StackTraceSampleResponse.class)) :
failedFuture);
ExecutionVertex vertex = Mockito.mock(ExecutionVertex.class);
Mockito.when(vertex.getJobvertexId()).thenReturn(new JobVertexID());
Mockito.when(vertex.getCurrentExecutionAttempt()).thenReturn(exec);
return vertex;
}
@SuppressWarnings({ "unchecked", "static-access" })
@Test
public void createIndexTest() throws Exception{
HttpEntity jsonEntity = new StringEntity("{}", ContentType.APPLICATION_JSON);
when(response.getEntity()).thenReturn(jsonEntity);
when(restClient.performRequest(anyString(), anyString(), anyMap(), any(HttpEntity.class),
Matchers.<Header>anyVararg())).thenReturn(response);
ReflectionTestUtils.setField(esManager, "restClient", restClient);
when(sl.getStatusCode()).thenReturn(100);
when(response.getStatusLine()).thenReturn(sl);
esManager.createIndex("index", new ArrayList<>());
when(sl.getStatusCode()).thenReturn(200);
when(response.getStatusLine()).thenReturn(sl);
esManager.createIndex("index", new ArrayList<>());
when(restClient.performRequest(anyString(), anyString(), anyMap(), any(HttpEntity.class),
Matchers.<Header>anyVararg())).thenThrow(new IOException());
ReflectionTestUtils.setField(esManager, "restClient", restClient);
esManager.createIndex("index", new ArrayList<>());
}
private void testLookupByDomainInterfaceIsProperlyRejected(DiscoveryError expectedError) throws InterruptedException {
String domain = "domain";
String[] domains = new String[]{ domain };
String interfaceName = "interface";
DiscoveryQos discoveryQos = new DiscoveryQos();
discoveryQos.setDiscoveryScope(DiscoveryScope.GLOBAL_ONLY);
doAnswer(createAddAnswerWithDiscoveryError(expectedError)).when(globalCapabilitiesDirectoryClient)
.lookup(Matchers.<CallbackWithModeledError<List<GlobalDiscoveryEntry>, DiscoveryError>> any(),
eq(domains),
eq(interfaceName),
anyLong(),
Matchers.<String[]> any());
Promise<Lookup1Deferred> promise = localCapabilitiesDirectory.lookup(domains, interfaceName, discoveryQos);
verify(globalCapabilitiesDirectoryClient).lookup(Matchers.<CallbackWithModeledError<List<GlobalDiscoveryEntry>, DiscoveryError>> any(),
eq(domains),
eq(interfaceName),
anyLong(),
Matchers.<String[]> any());
checkPromiseErrorInProviderRuntimeException(promise, expectedError);
}
@Test
public void startClientHandshakeWithOptions() throws Exception {
when(mockStub.send(Matchers.<HandshakerReq>any()))
.thenReturn(MockAltsHandshakerResp.getOkResponse(0));
ByteBuffer outFrame = handshaker.startClientHandshake();
assertEquals(ByteString.copyFrom(outFrame), MockAltsHandshakerResp.getOutFrame());
HandshakerReq req =
HandshakerReq.newBuilder()
.setClientStart(
StartClientHandshakeReq.newBuilder()
.setHandshakeSecurityProtocol(HandshakeProtocol.ALTS)
.addApplicationProtocols(AltsHandshakerClient.getApplicationProtocol())
.addRecordProtocols(AltsHandshakerClient.getRecordProtocol())
.setTargetName(TEST_TARGET_NAME)
.addTargetIdentities(
Identity.newBuilder().setServiceAccount(TEST_TARGET_SERVICE_ACCOUNT))
.build())
.build();
verify(mockStub).send(req);
}
@Test(expected = TechnicalServiceNotAliveException.class)
public void modifySubscriptionPaymentData_SuspendedTechnicalServiceNotAliveException()
throws Exception {
Mockito.doThrow(new TechnicalServiceNotAliveException())
.when(applicationServiceMock)
.activateInstance(Matchers.eq(subscription));
try {
setPaymentTypesForProduct(subscription.getProduct(),
paymentInfoCreditCard.getPaymentType());
subscriptionServiceBean.modifySubscriptionPaymentData(sub, bc,
piCreditCard);
} finally {
Mockito.verify(applicationServiceMock, Mockito.times(1))
.activateInstance(Matchers.eq(subscription));
Assert.assertEquals(SubscriptionStatus.SUSPENDED,
subscription.getStatus());
Mockito.verify(sessionContextMock, Mockito.times(1))
.setRollbackOnly();
}
}
@Test
public void delete_SubscriptionsChargeableActive_TechnicalServiceOperationException()
throws Exception {
Set<Subscription> subs = createSubs(SubscriptionStatus.ACTIVE);
Subscription sub = subs.iterator().next();
sub.getPriceModel().setType(PriceModelType.PRO_RATA);
// ensure that exception is not thrown
Mockito.doThrow(new TechnicalServiceOperationException())
.when(applicationServiceMock)
.deactivateInstance(Matchers.eq(sub));
billingContact.setSubscriptions(subs);
accountServiceBean.deleteBillingContact(bc);
// verify that setRollbackOnly has been called never
Mockito.verify(sessionContextMock, Mockito.never()).setRollbackOnly();
Assert.assertNull(sub.getBillingContact());
Assert.assertEquals(SubscriptionStatus.SUSPENDED, sub.getStatus());
Mockito.verify(applicationServiceMock, Mockito.times(1))
.deactivateInstance(Matchers.eq(sub));
}
/**
*
* This test will check if the ACL is null when removing it from a document
*
*/
@Test
public void removeACLFromDocument() throws Exception {
user = new User(workspace, new Account(DocumentUtil.USER_1_LOGIN, DocumentUtil.USER_1_NAME, DocumentUtil.USER1_MAIL, DocumentUtil.LANGUAGE, new Date(), null));
DocumentMaster documentMaster = new DocumentMaster(workspace, DocumentUtil.DOCUMENT_ID, user);
documentRevision = new DocumentRevision(documentMaster, "A", user);
documentIteration = new DocumentIteration(documentRevision, user);
documentRevision.setCheckOutUser(user);
documentRevision.setCheckOutDate(new Date());
acl = new ACL();
acl.addEntry(user, ACLPermission.READ_ONLY);
documentRevision.setACL(acl);
DocumentRevisionKey documentRevisionKey = new DocumentRevisionKey(workspace.getId(), documentMaster.getId(), documentRevision.getVersion());
Mockito.when(userManager.checkWorkspaceReadAccess(workspace.getId())).thenReturn(user);
Mockito.when(aclTypedQuery.setParameter(Matchers.anyString(), Matchers.any())).thenReturn(aclTypedQuery);
Mockito.when(documentRevisionDAO.getDocRRef(documentRevisionKey)).thenReturn(documentRevision);
documentManagerBean.removeACLFromDocumentRevision(documentRevision.getKey());
Assert.assertNull(documentRevision.getACL());
}
@Test
public void testRestartJob() throws Exception {
int containerId = 1;
List<String> expectedCommand = asList("aurora job restart %s/%s %s %s %d",
JOB_SPEC, containerId, VERBOSE_CONFIG, BATCH_CONFIG, Integer.MAX_VALUE);
// Failed
Mockito.doReturn(false).when(controller).runProcess(Matchers.anyListOf(String.class));
Assert.assertFalse(controller.restart(containerId));
Mockito.verify(controller).runProcess(Mockito.eq(expectedCommand));
// Happy path
Mockito.doReturn(true).when(controller).runProcess(Matchers.anyListOf(String.class));
Assert.assertTrue(controller.restart(containerId));
Mockito.verify(controller, Mockito.times(2)).runProcess(expectedCommand);
}
@SuppressWarnings("unchecked")
@Test
public void getAttributeValuesTest() throws IOException {
AttributeValuesRequest attributeValuesRequest = getAttributeValuesRequest();
when(config.getElasticSearch()).thenReturn(getElasticSearchProperty());
HttpEntity jsonEntity = new StringEntity("{}", ContentType.APPLICATION_JSON);
when(response.getEntity()).thenReturn(jsonEntity);
when(restClient.performRequest(anyString(), anyString(), any(Map.class), any(HttpEntity.class),
Matchers.<Header>anyVararg())).thenReturn(response);
ReflectionTestUtils.setField(targetTypesServiceImpl, "restClient", restClient);
when(sl.getStatusCode()).thenReturn(200);
when(response.getStatusLine()).thenReturn(sl);
Map<String, Object> ruleParamDetails = Maps.newHashMap();
when(mapper.readValue(anyString(), any(TypeReference.class))).thenReturn(ruleParamDetails);
assertThat(targetTypesService.getAttributeValues(attributeValuesRequest), is(notNullValue()));
}
@Test
public void loadBalancerThrowsInHandleResolvedAddresses() {
RuntimeException ex = new RuntimeException("simulated");
// Delay the success of name resolution until allResolved() is called
FakeNameResolverFactory nameResolverFactory =
new FakeNameResolverFactory.Builder(expectedUri)
.setResolvedAtStart(false)
.setServers(Collections.singletonList(new EquivalentAddressGroup(socketAddress)))
.build();
channelBuilder.nameResolverFactory(nameResolverFactory);
createChannel();
verify(mockLoadBalancerFactory).newLoadBalancer(any(Helper.class));
doThrow(ex).when(mockLoadBalancer).handleResolvedAddressGroups(
Matchers.<List<EquivalentAddressGroup>>anyObject(), any(Attributes.class));
// NameResolver returns addresses.
nameResolverFactory.allResolved();
// Exception thrown from balancer is caught by ChannelExecutor, making channel enter panic mode.
verifyPanicMode(ex);
}
@Test
public void statusPropagatedFromStreamToCallListener() {
DelayedExecutor executor = new DelayedExecutor();
ClientCallImpl<Void, Void> call = new ClientCallImpl<Void, Void>(
method,
executor,
baseCallOptions,
provider,
deadlineCancellationExecutor,
channelCallTracer,
false /* retryEnabled */);
call.start(callListener, new Metadata());
verify(stream).start(listenerArgumentCaptor.capture());
final ClientStreamListener streamListener = listenerArgumentCaptor.getValue();
streamListener.headersRead(new Metadata());
Status status = Status.RESOURCE_EXHAUSTED.withDescription("simulated");
streamListener.closed(status , new Metadata());
executor.release();
verify(callListener).onClose(same(status), Matchers.isA(Metadata.class));
}
@Test
public void testCreateWebServerPopulatesTemplatesFromGroup() throws IOException {
final JsonCreateWebServer jsonCreateWebServer = mock(JsonCreateWebServer.class);
when(Config.mockWebServerService.createWebServer(any(CreateWebServerRequest.class), any(User.class))).thenReturn(webServer);
List<String> templateNames = new ArrayList<>();
templateNames.add("httpd.conf");
when(Config.mockGroupService.getGroupWebServersResourceTemplateNames(anyString())).thenReturn(templateNames);
when(Config.mockGroupService.getGroupWebServerResourceTemplate(anyString(), anyString(), eq(false), any(ResourceGroup.class))).thenReturn("httpd.conf template");
when(Config.mockGroupService.getGroupWebServerResourceTemplateMetaData(anyString(), anyString())).thenReturn("{}");
ResourceTemplateMetaData mockMetaData = mock(ResourceTemplateMetaData.class);
when(mockMetaData.getDeployFileName()).thenReturn("httpd.conf");
when(Config.mockResourceService.getTokenizedMetaData(anyString(), Matchers.anyObject(), anyString())).thenReturn(mockMetaData);
final Response response = webServerServiceRest.createWebServer(jsonCreateWebServer, Config.mockAuthenticatedUser);
assertEquals(Response.Status.CREATED.getStatusCode(), response.getStatus());
}
@Test
public void testNoControlFileZipFileProcessor() throws Exception {
Exchange preObject = new DefaultExchange(new DefaultCamelContext());
String batchJobId = NewBatchJob.createId("NoControlFile.zip");
Mockito.when(workNote.getBatchJobId()).thenReturn(batchJobId);
preObject.getIn().setBody(workNote);
Mockito.when(mockedBatchJobDAO.findBatchJobById(Matchers.eq(batchJobId))).thenReturn(mockedJob);
File zipFile = IngestionTest.getFile("zip/NoControlFile.zip");
ResourceEntry entry = new ResourceEntry();
entry.setResourceName(zipFile.getAbsolutePath());
Mockito.when(mockedJob.getZipResourceEntry()).thenReturn(entry);
createResourceEntryAndAddToJob(zipFile, mockedJob);
mockedJob.setSourceId("zip");
Mockito.when(mockedBatchJobDAO.findBatchJobById(Matchers.eq(batchJobId))).thenReturn(mockedJob);
preObject.getIn().setHeader("BatchJobId", batchJobId);
zipProc.process(preObject);
Assert.assertNotNull(preObject.getIn().getBody());
Assert.assertTrue(preObject.getIn().getBody(WorkNote.class).hasErrors());
Assert.assertEquals(preObject.getIn().getHeader("IngestionMessageType") , MessageType.BATCH_REQUEST.name());
}
@Test
public void testCreateManyFiles() throws Exception{
watchService.start(basePath);
File file = null;
int fileNumbers = 1000;
for (int i = 1; i <= fileNumbers; i++){
String randomFileName = WatchServiceTestHelpers.getRandomString(9, "abcdefg123456789");
file = Paths.get(basePath.toString(), randomFileName + ".txt").toFile();
FileWriter out = new FileWriter(file);
WatchServiceTestHelpers.writeRandomData(out, NUM_CHARS_SMALL_FILE);
out.close();
// System.out.println("File added: Itemnr.: " + i);
}
sleep();
Mockito.verify(fileManager, Mockito.times(fileNumbers)).add(Matchers.anyObject());
}
@Test
public void shouldCreateAlertTrigger() throws Exception {
when(alertTriggerService.save(Matchers.any(Tenant.class), Matchers.any(Application.class), Matchers.any(AlertTrigger.class)))
.thenReturn(ServiceResponseBuilder.<AlertTrigger> ok()
.withResult(silenceAlertTrigger).build());
getMockMvc()
.perform(MockMvcRequestBuilders
.post(MessageFormat.format("/{0}/{1}", application.getName(), BASEPATH))
.contentType("application/json")
.content(getJson(new AlertTriggerInputVO().apply(silenceAlertTrigger)))
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().is2xxSuccessful())
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$.code", is(HttpStatus.CREATED.value())))
.andExpect(jsonPath("$.status", is("success")))
.andExpect(jsonPath("$.timestamp",greaterThan(1400000000)))
.andExpect(jsonPath("$.result.name", is(silenceAlertTrigger.getName())))
.andExpect(jsonPath("$.result.description", is(silenceAlertTrigger.getDescription())))
.andExpect(jsonPath("$.result.deviceModelName", is(deviceModel.getName())))
.andExpect(jsonPath("$.result.locationName", is(location.getName())))
.andExpect(jsonPath("$.result.type", is("SILENCE")))
.andExpect(jsonPath("$.result.minutes", is(200)))
;
}
@Test
public void testAuthenticateAndLoadVsoContexts_specifiedAccountUrl() {
final ServerContextLookupOperation.ContextScope scope = ServerContextLookupOperation.ContextScope.REPOSITORY;
final String serverUrl = "http://test.visualstudio.com";
final AuthenticationInfo authInfo = new AuthenticationInfo("user1", "pass1", serverUrl, "userOne");
final LoginPageModel loginPageModel = Mockito.mock(LoginPageModel.class);
when(loginPageModel.getServerName()).thenReturn(serverUrl);
final ServerContextLookupPageModel lookupPageModel = Mockito.mock(ServerContextLookupPageModel.class);
final AuthenticationProvider authenticationProvider = Mockito.mock(AuthenticationProvider.class);
when(authenticationProvider.isAuthenticated(serverUrl)).thenReturn(true);
when(authenticationProvider.getAuthenticationInfo(serverUrl)).thenReturn(authInfo);
final ServerContextLookupListener lookupListener = Mockito.mock(ServerContextLookupListener.class);
LookupHelper.authenticateAndLoadVsoContexts(loginPageModel, lookupPageModel,
authenticationProvider, lookupListener, scope);
verify(loginPageModel).setConnected(true);
verify(lookupPageModel).setLoading(true);
verify(lookupListener).loadContexts(anyList(), Matchers.eq(scope));
}
@Test
public void testCreateFailure() throws ResourceAllocationException, ResourceUnavailableException, ConcurrentOperationException, InsufficientCapacityException {
NetworkService networkService = Mockito.mock(NetworkService.class);
AddIpToVmNicCmd ipTonicCmd = Mockito.mock(AddIpToVmNicCmd.class);
Mockito.when(
networkService.allocateSecondaryGuestIP(Matchers.anyLong(), Matchers.any()))
.thenReturn(null);
ipTonicCmd._networkService = networkService;
try {
ipTonicCmd.execute();
} catch (InsufficientAddressCapacityException e) {
throw new InvalidParameterValueException("Allocating guest ip for nic failed");
}
}
@Test
public void testPollSkipsEmptyChannels() {
EventReaderDAO readerDao = mock(EventReaderDAO.class);
EventStore eventStore = new DefaultEventStore(readerDao, mock(EventWriterDAO.class), new AstyanaxEventIdSerializer(), new MockClaimStore());
DedupQueue q = new DedupQueue("test-queue", "read", "write",
mock(QueueDAO.class), eventStore, Suppliers.ofInstance(true), mock(ScheduledExecutorService.class), getPersistentSortedQueueFactory(),
mock(MetricRegistry.class));
q.startAndWait();
// The first poll checks the read channel, find it empty, checks the write channel.
q.poll(Duration.ofSeconds(30), new SimpleEventSink(10));
verify(readerDao).readNewer(eq("read"), Matchers.<EventSink>any());
verify(readerDao).readNewer(eq("write"), Matchers.<EventSink>any());
verifyNoMoreInteractions(readerDao);
reset(readerDao);
// Subsequent polls w/in a short window skips the poll operations.
q.poll(Duration.ofSeconds(30), new SimpleEventSink(10));
verifyNoMoreInteractions(readerDao);
}
@Test
public void testOnRestart() throws Exception {
KubernetesController controller = Mockito.mock(KubernetesController.class);
Mockito.doReturn(controller).when(scheduler).getController();
scheduler.initialize(config, mockRuntime);
// Construct RestartTopologyRequest
Scheduler.RestartTopologyRequest restartTopologyRequest =
Scheduler.RestartTopologyRequest.newBuilder()
.setTopologyName(TOPOLOGY_NAME)
.setContainerIndex(CONTAINER_INDEX)
.build();
// Fail to restart
Mockito.doReturn(false).when(controller).restart(Mockito.anyInt());
Assert.assertFalse(scheduler.onRestart(restartTopologyRequest));
Mockito.verify(controller).restart(Matchers.anyInt());
// Succeed to restart
Mockito.doReturn(true).when(controller).restart(Mockito.anyInt());
Assert.assertTrue(scheduler.onRestart(restartTopologyRequest));
Mockito.verify(controller, Mockito.times(2)).restart(Matchers.anyInt());
}
@Test
public void testWhenSubmittingAValidTemplateWithoutVariablesThenTheDefaultJobVariableIsUsed() throws Exception {
when(scheduler.submit(Matchers.<Job> any())).thenReturn(new JobIdImpl(88L, "job"));
ArgumentCaptor<Job> argumentCaptor = ArgumentCaptor.forClass(Job.class);
String workflowUrl = getBaseUriTestWorkflowsServer() + "/workflow";
JobIdData response = schedulerRest.submitFromUrl(sessionId, workflowUrl, getEmptyPathSegment(), null);
verify(scheduler).submit(argumentCaptor.capture());
Job interceptedJob = argumentCaptor.getValue();
Assert.assertEquals(1, interceptedJob.getVariables().size());
Assert.assertEquals("defaultvalue", interceptedJob.getVariables().get("var1").getValue());
Assert.assertEquals(88L, response.getId());
Assert.assertEquals("job", response.getReadableName());
}
@Test
@SuppressWarnings("unchecked")
public void testTaskEvent() throws Exception {
final AbstractReader reader = new MockReader(createInputGate(1));
final EventListener<TaskEvent> listener1 = mock(EventListener.class);
final EventListener<TaskEvent> listener2 = mock(EventListener.class);
final EventListener<TaskEvent> listener3 = mock(EventListener.class);
reader.registerTaskEventListener(listener1, TestTaskEvent1.class);
reader.registerTaskEventListener(listener2, TestTaskEvent2.class);
reader.registerTaskEventListener(listener3, TaskEvent.class);
reader.handleEvent(new TestTaskEvent1()); // for listener1 only
reader.handleEvent(new TestTaskEvent2()); // for listener2 only
verify(listener1, times(1)).onEvent(Matchers.any(TaskEvent.class));
verify(listener2, times(1)).onEvent(Matchers.any(TaskEvent.class));
verify(listener3, times(0)).onEvent(Matchers.any(TaskEvent.class));
}
@Test
public void finishExecutionWhenSuccessful() {
// given
when(executionContext.wasSuccessful()).thenReturn(true);
// when
lfr.finishExecution(0, executionContext);
// then
verify(executionContext, times(1)).wasSuccessful();
verifyNoMoreInteractions(executionContext);
verify(scheduleCtx, times(1)).clearFromRunning(Matchers.<SlotKey>any());
verify(scheduleCtx).getCurrentTimeMillis();
verifyNoMoreInteractions(scheduleCtx);
}
@SuppressWarnings({ "unchecked", "static-access" })
@Test
public void configureIndexAndTypesTest() throws Exception{
PowerMockito.mockStatic(ConfigManager.class);
List<String> types = new ArrayList<>();
types.add("ds");
when(ConfigManager.getTypes(anyString())).thenReturn(new HashSet<>(types));
HttpEntity jsonEntity = new StringEntity("{}", ContentType.APPLICATION_JSON);
when(response.getEntity()).thenReturn(jsonEntity);
when(restClient.performRequest(anyString(), anyString(), anyMap(), any(HttpEntity.class),
Matchers.<Header>anyVararg())).thenReturn(response);
ReflectionTestUtils.setField(esManager, "restClient", restClient);
when(sl.getStatusCode()).thenReturn(100);
when(response.getStatusLine()).thenReturn(sl);
esManager.configureIndexAndTypes("index",new ArrayList<>());
}
private WebTarget mockedWebTarget() {
final WebTarget webTarget = Mockito.mock(WebTarget.class);
final Invocation.Builder invBuilder = Mockito.mock(Invocation.Builder.class);
final Response response = Mockito.mock(Response.class);
Mockito.when(webTarget.path(Matchers.anyString())).thenReturn(webTarget);
Mockito.when(
webTarget.queryParam(Matchers.eq("quietOnNotFound"), Matchers.anyBoolean())).thenReturn(
webTarget);
Mockito.when(webTarget.request()).thenReturn(invBuilder);
Mockito.when(invBuilder.get()).thenReturn(response);
Mockito.when(invBuilder.delete()).thenReturn(response);
Mockito.when(invBuilder.post(Matchers.any(Entity.class))).thenReturn(response);
return webTarget;
}
/**
* Test extractHeaderNamesAndValues method for invalid inputs.
*
* @throws Exception
*/
@Test
public void testExtractHeaderNamesAndValueForInvalidValues() throws Exception {
exception.expect(Exception.class);
inputBuilder.extractHeaderNamesAndValues(HEADERS_WITH_MISSING_COLUMNDELIMITER,
DEFAULT_ROW_DELIMITER, DEFAULT_COLUMN_DELIMITER);
verify(inputBuilderSpy).validateRow(Matchers.<String>any(), Matchers.<String>any(), Matchers.anyInt());
}
/**
* BASIC認証AuthorizationHeaderとcookie認証情報が同時に指定された場合のAccessContext生成の正常系テスト.
*/
@Test
public void BASIC認証AuthorizationHeaderとcookie認証情報が同時に指定された場合のAccessContext生成の正常系テスト() {
Cell cell = (Cell) mock(Cell.class);
when(cell.authenticateAccount((OEntityWrapper) Matchers.any(), Matchers.anyString())).thenReturn(true);
when(cell.getOwner()).thenReturn("cellOwner");
UriInfo uriInfo = new TestUriInfo();
// uluut発行処理
UnitLocalUnitUserToken uluut = new UnitLocalUnitUserToken(
System.currentTimeMillis(), UnitLocalUnitUserToken.ACCESS_TOKEN_EXPIRES_HOUR * MILLISECS_IN_AN_HOUR,
cell.getOwner(), uriInfo.getBaseUri().getHost() + ":" + uriInfo.getBaseUri().getPort());
String tokenString = uluut.toTokenString();
// dc_cookie_peerとして、ランダムなUUIDを設定する
String dcCookiePeer = UUID.randomUUID().toString();
String cookieValue = dcCookiePeer + "\t" + tokenString;
// ヘッダに返却するdc-cookie値は、暗号化する
String encodedCookieValue = LocalToken.encode(cookieValue,
UnitLocalUnitUserToken.getIvBytes(AccessContext.getCookieCryptKey(uriInfo.getBaseUri())));
String basicAuth = "Basic "
+ DcCoreUtils.encodeBase64Url("user:pass".getBytes());
// 第1引数は AuthHeader, 第2引数は UriInfo, 第3引数は cookie_peer, 第4引数は cookie内の暗号化されたトークン情報
AccessContext accessContext = AccessContext.create(basicAuth, uriInfo, dcCookiePeer, encodedCookieValue,
cell, BASE_URL, UrlUtils.getHost(), OWNER);
assertEquals(AccessContext.TYPE_INVALID, accessContext.getType());
}
public void testWaveletNotification() {
submitDeltaToNewWavelet(WAVELET_NAME, USER1, addParticipantToWavelet(USER2));
verify(notifiee).waveletUpdate(Matchers.<ReadableWaveletData>any(),
Matchers.<ImmutableList<WaveletDeltaRecord>>any(), eq(ImmutableSet.of(DOMAIN)));
verify(notifiee).waveletCommitted(eq(WAVELET_NAME), Matchers.<HashedVersion>any(),
eq(ImmutableSet.of(DOMAIN)));
}
@Test
public void testMergeConsecutiveWindows() {
MergingWindowAssigner.MergeCallback callback = mock(MergingWindowAssigner.MergeCallback.class);
SessionWindowTimeGapExtractor extractor = mock(SessionWindowTimeGapExtractor.class);
when(extractor.extract(any())).thenReturn(5000L);
DynamicEventTimeSessionWindows assigner = DynamicEventTimeSessionWindows.withDynamicGap(extractor);
assigner.mergeWindows(
Lists.newArrayList(
new TimeWindow(0, 1),
new TimeWindow(1, 2),
new TimeWindow(2, 3),
new TimeWindow(4, 5),
new TimeWindow(5, 6)),
callback);
verify(callback, times(1)).merge(
(Collection<TimeWindow>) argThat(containsInAnyOrder(new TimeWindow(0, 1), new TimeWindow(1, 2), new TimeWindow(2, 3))),
eq(new TimeWindow(0, 3)));
verify(callback, times(1)).merge(
(Collection<TimeWindow>) argThat(containsInAnyOrder(new TimeWindow(4, 5), new TimeWindow(5, 6))),
eq(new TimeWindow(4, 6)));
verify(callback, times(2)).merge(anyCollection(), Matchers.anyObject());
}