private static void checkPopulatorFailure( IndexPopulator populator ) { verify( populator ).markAsFailed( contains( "something went wrong" ) ); verify( populator ).close( false ); }
@Test public void shouldHandleAlreadyClosedException() throws BucketNotFoundException { Mockito.when(manager.getRepository(any(), any(), any())) .thenThrow(AlreadyClosedException.class); AsyncEvent event = Mockito.mock(AsyncEvent.class); boolean result = listener.processEvents(Arrays.asList(event)); assertFalse(result); verify(listener, times(1)) .logDebugMessage(contains("the lucene index is already closed"), any(AlreadyClosedException.class)); }
@Test public void shouldHandleCacheClosedException() throws BucketNotFoundException { Mockito.when(manager.getRepository(any(), any(), any())) .thenThrow(CacheClosedException.class); AsyncEvent event = Mockito.mock(AsyncEvent.class); boolean result = listener.processEvents(Arrays.asList(event)); assertFalse(result); verify(listener, times(1)) .logDebugMessage(contains("cache has been closed"), any(CacheClosedException.class)); }
@Test public void beginEmailChange() throws Exception { setUpForBeginEmailChange(); Mockito.verify(messageService).sendMessage( eq("new@example.com"), eq(MessageType.CHANGE_EMAIL), eq(String.format("%s Email change verification", IDENTITY_ZONE_NAME)), contains("<a href=\"http://localhost/login/verify_email?code=the_secret_code\">Verify your email</a>") ); }
@Test public void testGetStories() { when(TestRestServiceFactory.algoliaRestService.searchByMinTimestamp(any())) .thenReturn(Observable.error(new IOException())); client.getStories(range, ItemManager.MODE_DEFAULT, mock(ResponseListener.class)); verify(TestRestServiceFactory.algoliaRestService) .searchByMinTimestamp(contains("created_at_i>")); }
@Test public void testLoadSessionEventPublisher() throws Exception { Mockito.when(context.getResource(ArgumentMatchers.contains("${APPLICATION_CONFIG_URL}"))).thenReturn( new ByteArrayResource("foo: bar\nspam:\n foo: baz".getBytes())); initializer.initialize(context); ArgumentCaptor<HttpSessionEventPublisher> httpSessionEventPublisherArgumentCaptor = ArgumentCaptor.forClass(HttpSessionEventPublisher.class); verify(servletContext, atLeastOnce()).addListener(httpSessionEventPublisherArgumentCaptor.capture()); assertNotNull(httpSessionEventPublisherArgumentCaptor.getValue()); }
@Test public void forgotPasswordFallsBackToUsernameIfNoPrimaryEmail() throws Exception { ScimUser user = new ScimUser("user-id-001", "user@example.com", "firstName", "lastName"); String zoneID = IdentityZoneHolder.get().getId(); when(scimUserProvisioning.query(contains("origin"), eq(zoneID))).thenReturn(Arrays.asList(user)); Timestamp expiresAt = new Timestamp(System.currentTimeMillis()); when(codeStore.generateCode(anyString(), any(Timestamp.class), anyString(), anyString())) .thenReturn(new ExpiringCode("code", expiresAt, "user-id-001", null)); ForgotPasswordInfo forgotPasswordInfo = uaaResetPasswordService.forgotPassword("exampleUser", "example", "redirect.example.com"); assertThat(forgotPasswordInfo.getEmail(), equalTo("user@example.com")); }
@Test public void forgotPassword_ThrowsConflictException() throws Exception { ScimUser user = new ScimUser("user-id-001","exampleUser","firstName","lastName"); user.setPrimaryEmail("user@example.com"); String zoneId = IdentityZoneHolder.get().getId(); when(scimUserProvisioning.query(contains("origin"), eq(zoneId))).thenReturn(Arrays.asList(new ScimUser[]{})); when(scimUserProvisioning.query(eq("userName eq \"exampleUser\""), eq(zoneId))).thenReturn(Arrays.asList(new ScimUser[]{user})); when(codeStore.generateCode(anyString(), any(Timestamp.class), eq(null), anyString())).thenReturn(new ExpiringCode("code", new Timestamp(System.currentTimeMillis()), "user-id-001", null)); when(codeStore.retrieveCode(anyString(), anyString())).thenReturn(new ExpiringCode("code", new Timestamp(System.currentTimeMillis()), "user-id-001", null)); try { uaaResetPasswordService.forgotPassword("exampleUser", "", ""); fail(); } catch (ConflictException e) { assertThat(e.getUserId(), equalTo("user-id-001")); } }
@Test public void shouldCloseAndFailOnFailure() throws Exception { createNode( map( name, "irrelephant" ), FIRST ); LogProvider logProvider = NullLogProvider.getInstance(); FlippableIndexProxy index = mock( FlippableIndexProxy.class ); IndexPopulator populator = spy( indexPopulator( false ) ); IndexPopulationJob job = newIndexPopulationJob( populator, index, indexStoreView, logProvider, EntityType.NODE, indexDescriptor( FIRST, name, false ) ); String failureMessage = "not successful"; IllegalStateException failure = new IllegalStateException( failureMessage ); doThrow( failure ).when( populator ).create(); // When job.run(); // Then verify( populator ).markAsFailed( contains( failureMessage ) ); }
@Test public void forgotPassword_PublishesResetPasswordRequestEvent() throws Exception { ApplicationEventPublisher publisher = mock(ApplicationEventPublisher.class); Authentication authentication = mock(Authentication.class); uaaResetPasswordService.setApplicationEventPublisher(publisher); SecurityContextHolder.getContext().setAuthentication(authentication); ScimUser user = new ScimUser("user-id-001", "exampleUser", "firstName", "lastName"); user.setPrimaryEmail("user@example.com"); String zoneId = IdentityZoneHolder.get().getId(); when(scimUserProvisioning.query(contains("origin"), eq(zoneId))).thenReturn(Arrays.asList(user)); Timestamp expiresAt = new Timestamp(System.currentTimeMillis()); when(codeStore.generateCode(anyString(), any(Timestamp.class), anyString(), anyString())).thenReturn(new ExpiringCode("code", expiresAt, "user-id-001", null)); uaaResetPasswordService.forgotPassword("exampleUser", "", ""); ArgumentCaptor<ResetPasswordRequestEvent> captor = ArgumentCaptor.forClass(ResetPasswordRequestEvent.class); verify(publisher).publishEvent(captor.capture()); ResetPasswordRequestEvent event = captor.getValue(); assertThat(event.getSource(), equalTo("exampleUser")); assertThat(event.getCode(), equalTo("code")); assertThat(event.getEmail(), equalTo("user@example.com")); assertThat(event.getAuthentication(), sameInstance(authentication)); }
@Test public void testLoadDefaultResource() throws Exception { Mockito.when(context.getResource(ArgumentMatchers.contains("${APPLICATION_CONFIG_URL}"))).thenReturn( new ByteArrayResource("foo: bar\nspam:\n foo: baz".getBytes())); initializer.initialize(context); assertEquals("bar", environment.getProperty("foo")); assertEquals("baz", environment.getProperty("spam.foo")); }
@Test public void forgotPassword_ResetCodeIsReturnedSuccessfully() throws Exception { ScimUser user = new ScimUser("user-id-001","exampleUser","firstName","lastName"); user.setPasswordLastModified(new Date(1234)); user.setPrimaryEmail("user@example.com"); String zoneID = IdentityZoneHolder.get().getId(); when(scimUserProvisioning.query(contains("origin"), eq(zoneID))).thenReturn(Arrays.asList(user)); Timestamp expiresAt = new Timestamp(System.currentTimeMillis()); ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class); when(codeStore.generateCode(eq("{\"user_id\":\"user-id-001\",\"username\":\"exampleUser\",\"passwordModifiedTime\":1234,\"client_id\":\"example\",\"redirect_uri\":\"redirect.example.com\"}"), any(Timestamp.class), anyString(), anyString())).thenReturn(new ExpiringCode("code", expiresAt, "user-id-001", null)); ForgotPasswordInfo forgotPasswordInfo = uaaResetPasswordService.forgotPassword("exampleUser", "example", "redirect.example.com"); verify(codeStore).expireByIntent(captor.capture(), anyString()); assertEquals(UaaResetPasswordService.FORGOT_PASSWORD_INTENT_PREFIX+user.getId(), captor.getValue()); assertThat(forgotPasswordInfo.getUserId(), equalTo("user-id-001")); assertThat(forgotPasswordInfo.getEmail(), equalTo("user@example.com")); ExpiringCode resetPasswordCode = forgotPasswordInfo.getResetPasswordCode(); assertThat(resetPasswordCode.getCode(), equalTo("code")); assertThat(resetPasswordCode.getExpiresAt(), equalTo(expiresAt)); assertThat(resetPasswordCode.getData(), equalTo("user-id-001")); }
@Test public void testDeprecatedOption() throws Exception { class Provider extends ConfigurationOptionProvider { private ConfigurationOption<String> deprecatedOption = ConfigurationOption.stringOption() .key("foo") .tags("deprecated") .buildRequired(); } final ConfigurationRegistry configurationRegistry = ConfigurationRegistry.builder() .addOptionProvider(new Provider()) .addConfigSource(new SimpleSource().add("foo", "bar")) .build(); configurationLogger.logConfiguration(configurationRegistry); verify(logger).warn(contains("Detected usage of deprecated configuration option '{}'"), eq("foo")); }
/** * ExecutorManager should try to dispatch to all executors & when both fail it should remove the * execution from queue and finalize it. */ @Ignore @Test public void testDispatchFailed() throws Exception { testSetUpForRunningFlows(); this.manager.start(); final ExecutableFlow flow1 = TestUtils.createTestExecutableFlow("exectest1", "exec1"); flow1.getExecutionOptions().setFailureEmails(Arrays.asList("test@example.com")); when(this.loader.fetchExecutableFlow(-1)).thenReturn(flow1); when(this.apiGateway.callWithExecutable(any(), any(), eq(ConnectorParams.EXECUTE_ACTION))) .thenThrow(new ExecutorManagerException("Mocked dispatch exception")); this.manager.submitExecutableFlow(flow1, this.user.getUserId()); waitFlowFinished(flow1); verify(this.apiGateway) .callWithExecutable(flow1, this.manager.fetchExecutor(1), ConnectorParams.EXECUTE_ACTION); verify(this.apiGateway) .callWithExecutable(flow1, this.manager.fetchExecutor(2), ConnectorParams.EXECUTE_ACTION); verify(this.loader, Mockito.times(2)).unassignExecutor(-1); verify(this.mailAlerter).alertOnError(eq(flow1), eq("Failed to dispatch queued execution derived-member-data because reached " + "azkaban.maxDispatchingErrors (tried 2 executors)"), contains("Mocked dispatch exception")); }
@Test public void shouldProfilePurge() { profiler.start("foo"); clock.sleep(10); profiler.stop(); profiler.start("bar"); clock.sleep(5); profiler.stop(); profiler.start("foo"); clock.sleep(8); profiler.stop(); profiler.dump(50, logger); verify(logger).info(contains("foo: 18ms")); verify(logger).info(contains("bar: 5ms")); }
@Test public void shouldResetPurgeProfiling() { profiler.start("foo"); clock.sleep(10); profiler.stop(); profiler.reset(); profiler.start("bar"); clock.sleep(5); profiler.stop(); profiler.start("foo"); clock.sleep(8); profiler.stop(); profiler.dump(50, logger); verify(logger).info(contains("foo: 8ms")); verify(logger).info(contains("bar: 5ms")); }
@Test public void closeImporterWithoutDiagnosticState() throws IOException { ExecutionMonitor monitor = mock( ExecutionMonitor.class ); try ( BatchingNeoStores stores = batchingNeoStoresWithExternalPageCache( storage.fileSystem(), storage.pageCache(), NULL, storage.directory().directory(), defaultFormat(), DEFAULT, getInstance(), EMPTY, defaults() ) ) { //noinspection EmptyTryBlock try ( ImportLogic logic = new ImportLogic( storage.directory().directory(), storage.fileSystem(), stores, DEFAULT, getInstance(), monitor, defaultFormat(), NO_MONITOR ) ) { // nothing to run in this import logic.success(); } } verify( monitor ).done( eq( true ), anyLong(), contains( "Data statistics is not available." ) ); }
eq(MessageType.PASSWORD_RESET), eq(companyName + " account password reset request"), contains("<a href=\"" + url + "\">Reset your password</a>") ); } finally {
@Test public void shouldUseDataStatisticsCountsForPrintingFinalStats() throws IOException { // given ExecutionMonitor monitor = mock( ExecutionMonitor.class ); try ( BatchingNeoStores stores = batchingNeoStoresWithExternalPageCache( storage.fileSystem(), storage.pageCache(), NULL, storage.directory().directory(), defaultFormat(), DEFAULT, getInstance(), EMPTY, defaults() ) ) { // when RelationshipTypeCount[] relationshipTypeCounts = new RelationshipTypeCount[] { new RelationshipTypeCount( 0, 33 ), new RelationshipTypeCount( 1, 66 ) }; DataStatistics dataStatistics = new DataStatistics( 100123, 100456, relationshipTypeCounts ); try ( ImportLogic logic = new ImportLogic( storage.directory().directory(), storage.fileSystem(), stores, DEFAULT, getInstance(), monitor, defaultFormat(), NO_MONITOR ) ) { logic.putState( dataStatistics ); logic.success(); } // then verify( monitor ).done( eq( true ), anyLong(), contains( dataStatistics.toString() ) ); } } }
checkTableIsLegal(htd); verify(masterLogger).warn(contains("MEMSTORE_FLUSHSIZE for table " + "descriptor or \"hbase.hregion.memstore.flush.size\" (0) is too small, which might " + "cause very frequent flushing."));