method2testcases
stringlengths
118
3.08k
### Question: ResourceSetResource implements CollectionResourceProvider { @Override public Promise<ResourceResponse, ResourceException> createInstance(Context context, CreateRequest request) { return new NotSupportedException().asPromise(); } @Inject ResourceSetResource(ResourceSetService resourceSetService, ContextHelper contextHelper, UmaLabelsStore umaLabelsStore, ResourceSetDescriptionValidator validator, ExtensionFilterManager extensionFilterManager); @Override Promise<ResourceResponse, ResourceException> createInstance(Context context, CreateRequest request); @Override Promise<ResourceResponse, ResourceException> readInstance(Context context, String resourceId, ReadRequest request); @Override Promise<ActionResponse, ResourceException> actionCollection(Context context, ActionRequest request); @Override Promise<QueryResponse, ResourceException> queryCollection(final Context context, final QueryRequest request, final QueryResourceHandler handler); @Override Promise<ResourceResponse, ResourceException> updateInstance(Context context, String resourceId, UpdateRequest request); @Override Promise<ResourceResponse, ResourceException> deleteInstance(Context context, String resourceId, DeleteRequest request); @Override Promise<ResourceResponse, ResourceException> patchInstance(Context context, String resourceId, PatchRequest request); @Override Promise<ActionResponse, ResourceException> actionInstance(Context context, String resourceId, ActionRequest request); }### Answer: @Test public void createShouldNotBeSupported() { Context context = mock(Context.class); CreateRequest request = mock(CreateRequest.class); Promise<ResourceResponse, ResourceException> instancePromise = resource.createInstance(context, request); AssertJPromiseAssert.assertThat(instancePromise).failedWithException().isInstanceOf(NotSupportedException.class); } @Test public void createShouldNotBeSupported() { Context context = mock(Context.class); CreateRequest request = mock(CreateRequest.class); Promise<ResourceResponse, ResourceException> instancePromise = resource.createInstance(context, request); assertThat(instancePromise).failedWithException().isInstanceOf(NotSupportedException.class); }
### Question: ResourceSetResource implements CollectionResourceProvider { @Override public Promise<ResourceResponse, ResourceException> deleteInstance(Context context, String resourceId, DeleteRequest request) { return new NotSupportedException().asPromise(); } @Inject ResourceSetResource(ResourceSetService resourceSetService, ContextHelper contextHelper, UmaLabelsStore umaLabelsStore, ResourceSetDescriptionValidator validator, ExtensionFilterManager extensionFilterManager); @Override Promise<ResourceResponse, ResourceException> createInstance(Context context, CreateRequest request); @Override Promise<ResourceResponse, ResourceException> readInstance(Context context, String resourceId, ReadRequest request); @Override Promise<ActionResponse, ResourceException> actionCollection(Context context, ActionRequest request); @Override Promise<QueryResponse, ResourceException> queryCollection(final Context context, final QueryRequest request, final QueryResourceHandler handler); @Override Promise<ResourceResponse, ResourceException> updateInstance(Context context, String resourceId, UpdateRequest request); @Override Promise<ResourceResponse, ResourceException> deleteInstance(Context context, String resourceId, DeleteRequest request); @Override Promise<ResourceResponse, ResourceException> patchInstance(Context context, String resourceId, PatchRequest request); @Override Promise<ActionResponse, ResourceException> actionInstance(Context context, String resourceId, ActionRequest request); }### Answer: @Test public void deleteShouldNotBeSupported() { Context context = mock(Context.class); DeleteRequest request = mock(DeleteRequest.class); Promise<ResourceResponse, ResourceException> promise = resource.deleteInstance(context, "RESOURCE_SET_UID", request); AssertJPromiseAssert.assertThat(promise).failedWithException().isInstanceOf(NotSupportedException.class); } @Test public void deleteShouldNotBeSupported() { Context context = mock(Context.class); DeleteRequest request = mock(DeleteRequest.class); Promise<ResourceResponse, ResourceException> promise = resource.deleteInstance(context, "RESOURCE_SET_UID", request); assertThat(promise).failedWithException().isInstanceOf(NotSupportedException.class); }
### Question: ResourceSetResource implements CollectionResourceProvider { @Override public Promise<ResourceResponse, ResourceException> patchInstance(Context context, String resourceId, PatchRequest request) { return new NotSupportedException().asPromise(); } @Inject ResourceSetResource(ResourceSetService resourceSetService, ContextHelper contextHelper, UmaLabelsStore umaLabelsStore, ResourceSetDescriptionValidator validator, ExtensionFilterManager extensionFilterManager); @Override Promise<ResourceResponse, ResourceException> createInstance(Context context, CreateRequest request); @Override Promise<ResourceResponse, ResourceException> readInstance(Context context, String resourceId, ReadRequest request); @Override Promise<ActionResponse, ResourceException> actionCollection(Context context, ActionRequest request); @Override Promise<QueryResponse, ResourceException> queryCollection(final Context context, final QueryRequest request, final QueryResourceHandler handler); @Override Promise<ResourceResponse, ResourceException> updateInstance(Context context, String resourceId, UpdateRequest request); @Override Promise<ResourceResponse, ResourceException> deleteInstance(Context context, String resourceId, DeleteRequest request); @Override Promise<ResourceResponse, ResourceException> patchInstance(Context context, String resourceId, PatchRequest request); @Override Promise<ActionResponse, ResourceException> actionInstance(Context context, String resourceId, ActionRequest request); }### Answer: @Test public void patchShouldNotBeSupported() { Context context = mock(Context.class); PatchRequest request = mock(PatchRequest.class); Promise<ResourceResponse, ResourceException> promise = resource.patchInstance(context, "RESOURCE_SET_UID", request); AssertJPromiseAssert.assertThat(promise).failedWithException().isInstanceOf(NotSupportedException.class); } @Test public void patchShouldNotBeSupported() { Context context = mock(Context.class); PatchRequest request = mock(PatchRequest.class); Promise<ResourceResponse, ResourceException> promise = resource.patchInstance(context, "RESOURCE_SET_UID", request); assertThat(promise).failedWithException().isInstanceOf(NotSupportedException.class); }
### Question: ResourceSetResource implements CollectionResourceProvider { @Override public Promise<ActionResponse, ResourceException> actionInstance(Context context, String resourceId, ActionRequest request) { return new NotSupportedException().asPromise(); } @Inject ResourceSetResource(ResourceSetService resourceSetService, ContextHelper contextHelper, UmaLabelsStore umaLabelsStore, ResourceSetDescriptionValidator validator, ExtensionFilterManager extensionFilterManager); @Override Promise<ResourceResponse, ResourceException> createInstance(Context context, CreateRequest request); @Override Promise<ResourceResponse, ResourceException> readInstance(Context context, String resourceId, ReadRequest request); @Override Promise<ActionResponse, ResourceException> actionCollection(Context context, ActionRequest request); @Override Promise<QueryResponse, ResourceException> queryCollection(final Context context, final QueryRequest request, final QueryResourceHandler handler); @Override Promise<ResourceResponse, ResourceException> updateInstance(Context context, String resourceId, UpdateRequest request); @Override Promise<ResourceResponse, ResourceException> deleteInstance(Context context, String resourceId, DeleteRequest request); @Override Promise<ResourceResponse, ResourceException> patchInstance(Context context, String resourceId, PatchRequest request); @Override Promise<ActionResponse, ResourceException> actionInstance(Context context, String resourceId, ActionRequest request); }### Answer: @Test public void actionInstanceShouldNotBeSupported() { Context context = mock(Context.class); ActionRequest request = mock(ActionRequest.class); Promise<ActionResponse, ResourceException> promise = resource.actionInstance(context, "RESOURCE_SET_UID", request); AssertJPromiseAssert.assertThat(promise).failedWithException().isInstanceOf(NotSupportedException.class); } @Test public void actionInstanceShouldNotBeSupported() { Context context = mock(Context.class); ActionRequest request = mock(ActionRequest.class); Promise<ActionResponse, ResourceException> promise = resource.actionInstance(context, "RESOURCE_SET_UID", request); assertThat(promise).failedWithException().isInstanceOf(NotSupportedException.class); }
### Question: AlphaNumericValidator implements ServiceAttributeValidator { @Override public boolean validate(Set<String> values) { for (String toTest : values) { if (StringUtils.isEmpty(toTest) || NOT_ALPHA_NUM.matcher(toTest).find()) { return false; } } return true; } @Override boolean validate(Set<String> values); }### Answer: @Test(dataProvider = "data") public void checkCorrectness(String name, boolean expected) { boolean result = validator.validate(Collections.singleton(name)); assertThat(result).isEqualTo(expected); }
### Question: CodeLengthValidator implements ServiceAttributeValidator { @Override public boolean validate(Set<String> values) { try { for (String toTest : values) { if (Integer.valueOf(toTest) < MIN_CODE_LENGTH) { return false; } } } catch (NumberFormatException nfe) { return false; } return true; } @Override boolean validate(Set<String> values); static final int MIN_CODE_LENGTH; }### Answer: @Test(dataProvider = "data") public void checkCorrectness(String name, boolean expected) { boolean result = validator.validate(Collections.singleton(name)); assertThat(result).isEqualTo(expected); }
### Question: OathMaker { OathDeviceSettings createDeviceProfile(int minSharedSecretLength) { Reject.ifFalse(minSharedSecretLength >= 0, "minSharedSecretLength must not be negative"); int sharedSecretByteLength = Math.max(MIN_SHARED_SECRET_BYTE_LENGTH, (int)Math.ceil(minSharedSecretLength / 2d)); byte[] secretBytes = new byte[sharedSecretByteLength]; secureRandom.nextBytes(secretBytes); String sharedSecret = DatatypeConverter.printHexBinary(secretBytes); return new OathDeviceSettings(sharedSecret, DEVICE_NAME, INITIAL_LAST_LOGIN_TIME, INITIAL_COUNTER_VALUE); } @Inject OathMaker(final @Nonnull OathDevicesDao devicesDao, final @Nonnull @Named("amAuthOATH") Debug debug, final @Nonnull SecureRandom secureRandom, final @Nonnull DeviceJsonUtils<OathDeviceSettings> jsonUtils); }### Answer: @Test public void shouldGenerateCorrectLengthSecret() throws Exception { OathDeviceSettings deviceSettings = testFactory.createDeviceProfile(SECRET_HEX_LENGTH); assertThat(deviceSettings.getSharedSecret()).hasSize(SECRET_HEX_LENGTH); } @Test public void shouldNotGenerateLessThan8BytesOfSecret() throws Exception { OathDeviceSettings deviceSettings = testFactory.createDeviceProfile(0); assertThat(deviceSettings.getSharedSecret()).hasSize(16); } @Test public void shouldDefaultCounterToZero() throws Exception { OathDeviceSettings deviceSettings = testFactory.createDeviceProfile(SECRET_HEX_LENGTH); assertThat(deviceSettings.getCounter()).isEqualTo(0); } @Test public void shouldDefaultLastLoginTimeToZero() throws Exception { OathDeviceSettings deviceSettings = testFactory.createDeviceProfile(SECRET_HEX_LENGTH); assertThat(deviceSettings.getLastLogin()).isEqualTo(0); } @Test public void shouldDefaultDeviceName() throws Exception { OathDeviceSettings deviceSettings = testFactory.createDeviceProfile(SECRET_HEX_LENGTH); assertThat(deviceSettings.getDeviceName()).isNotEmpty(); }
### Question: OathMaker { void saveDeviceProfile(@Nonnull String user, @Nonnull String realm, @Nonnull OathDeviceSettings deviceSettings) throws AuthLoginException { Reject.ifNull(user, realm, deviceSettings); try { devicesDao.saveDeviceProfiles(user, realm, jsonUtils.toJsonValues(Collections.singletonList(deviceSettings))); } catch (IOException e) { debug.error("OathMaker.createDeviceProfile(): Unable to save device profile for user {} in realm {}", user, realm, e); throw new AuthLoginException(e); } } @Inject OathMaker(final @Nonnull OathDevicesDao devicesDao, final @Nonnull @Named("amAuthOATH") Debug debug, final @Nonnull SecureRandom secureRandom, final @Nonnull DeviceJsonUtils<OathDeviceSettings> jsonUtils); }### Answer: @Test @SuppressWarnings({"unchecked", "rawtypes"}) public void shouldSaveGeneratedDevice() throws Exception { OathDeviceSettings deviceSettings = new OathDeviceSettings(); deviceSettings.setCounter(42); deviceSettings.setSharedSecret("sekret"); deviceSettings.setChecksumDigit(true); deviceSettings.setLastLogin(99, TimeUnit.MILLISECONDS); deviceSettings.setDeviceName("test device"); deviceSettings.setTruncationOffset(32); JsonValue expectedJson = new DeviceJsonUtils<>(OathDeviceSettings.class).toJsonValue(deviceSettings); testFactory.saveDeviceProfile(USER, REALM, deviceSettings); ArgumentCaptor<List> savedProfileList = ArgumentCaptor.forClass(List.class); verify(mockDao).saveDeviceProfiles(eq(USER), eq(REALM), savedProfileList.capture()); assertThat(savedProfileList.getValue()).hasSize(1); assertThat(savedProfileList.getValue().get(0).toString()).isEqualTo(expectedJson.toString()); }
### Question: EmbeddedOpenDJBackupManager { void createOpenDJBackup() throws ConfiguratorException { createBackupDirectories(); File backupFile = getBackupFileLocation(); File opendjDirectory = new File(baseDirectory, OPENDJ_DIR); try { zipUtils.zipDirectory(opendjDirectory, backupFile); } catch (IOException e) { throw new ConfiguratorException("Failed to create OpenDJ backup: " + e.getMessage()); } } EmbeddedOpenDJBackupManager(Debug logger, ZipUtils zipUtils, String baseDirectory); void createBackupDirectories(); }### Answer: @Test public void whenInUpgradeRequiredStateItShouldBackupOpenDjDirectory() throws Exception { EmbeddedOpenDJBackupManager openDJBackupManager = setupInstallOpenDJRequiringUpgrade(); openDJBackupManager.createOpenDJBackup(); verifyBackupZipFileCreated(); verifyContentsOfBackupZip(); } @Test public void whenInUpgradeRequiredStateItShouldCreateUpgradeDirectory() throws Exception { EmbeddedOpenDJBackupManager openDJBackupManager = setupInstallOpenDJRequiringUpgrade(); openDJBackupManager.createOpenDJBackup(); assertThat(new File(baseDirectory, "upgrade").exists()).isTrue(); }
### Question: MonitoredCTSConnectionFactory implements ConnectionFactory<C> { public C create() throws DataLayerException { boolean success = false; try { C response = connectionFactory.create(); success = true; return response; } finally { monitorStore.addConnection(success); } } MonitoredCTSConnectionFactory(ConnectionFactory<C> connectionFactory, CTSConnectionMonitoringStore monitorStore); C create(); @Override Promise<C, DataLayerException> createAsync(); @Override void close(); @Override boolean isValid(C connection); }### Answer: @Test public void shouldAddToFailedConnectionOnError() throws Exception { doThrow(DataLayerException.class).when(connectionFactory).create(); try { monitoredConnectionFactory.create(); fail("Should throw exception"); } catch (DataLayerException e) { } verify(monitoringStore).addConnection(false); } @Test public void shouldAddToFailedConnectionOnError() throws Exception { doThrow(Exception.class).when(connectionFactory).create(); try { monitoredConnectionFactory.create(); fail("Should throw exception"); } catch (Exception e) { } verify(monitoringStore).addConnection(false); } @Test public void shouldAddToSuccessfulConnection() throws Exception { boolean success = true; monitoredConnectionFactory.create(); verify(monitoringStore).addConnection(success); }
### Question: Token { public <T> void setAttribute(CoreTokenField field, T value) { if (isFieldReadOnly(field)) { throw new IllegalArgumentException(MessageFormat.format( "Token Field {0} is read only and cannot be set.", field.toString())); } try { CoreTokenFieldTypes.validateType(field, value); } catch (CoreTokenException e) { throw new IllegalArgumentException(e.getMessage(), e); } put(field, value); } private Token(); Token(String tokenId, TokenType type); Token(Token copy); String getTokenId(); TokenType getType(); String getUserId(); void setUserId(String userId); Calendar getExpiryTimestamp(); void setExpiryTimestamp(Calendar expiryDate); byte[] getBlob(); void setBlob(byte[] data); Collection<CoreTokenField> getAttributeNames(); T getValue(CoreTokenField field); void setAttribute(CoreTokenField field, T value); void clearAttribute(CoreTokenField field); static boolean isFieldReadOnly(CoreTokenField field); @Override String toString(); }### Answer: @Test public void shouldCopyToken() { Token token = new Token("badger", TokenType.SAML2); token.setAttribute(CoreTokenField.INTEGER_ONE, 1234); token.setAttribute(CoreTokenField.STRING_ONE, "Weasel"); token.setAttribute(DATE_ONE, getCalendarInstance()); Token result = new Token(token); TokenTestUtils.assertTokenEquals(result, token); } @Test public void shouldCopyToken() { Token token = new Token("badger", TokenType.SAML2); token.setAttribute(CoreTokenField.INTEGER_ONE, 1234); token.setAttribute(CoreTokenField.STRING_ONE, "Weasel"); token.setAttribute(CoreTokenField.DATE_ONE, Calendar.getInstance()); Token result = new Token(token); TokenTestUtils.assertTokenEquals(result, token); }
### Question: TokenBlobStrategy { public byte[] reverse(byte[] data) throws TokenStrategyFailedException { return apply(reverseStrategies, false, data); } @Inject TokenBlobStrategy(TokenStrategyFactory factory, CoreTokenConfig config); byte[] perform(byte[] data); byte[] reverse(byte[] data); }### Answer: @Test public void shouldReverseAllStrategy() throws TokenStrategyFailedException { BlobStrategy first = mock(BlobStrategy.class); BlobStrategy second = mock(BlobStrategy.class); BlobStrategy third = mock(BlobStrategy.class); given(factory.getStrategies(any(CoreTokenConfig.class))) .willReturn(Arrays.asList(first, second, third)); byte[] data = new byte[0]; TokenBlobStrategy strategy = new TokenBlobStrategy(factory, config); strategy.reverse(data); verify(first).reverse(nullable(byte[].class)); verify(second).reverse(nullable(byte[].class)); verify(third).reverse(nullable(byte[].class)); } @Test public void shouldReverseAllStrategy() throws TokenStrategyFailedException { BlobStrategy first = mock(BlobStrategy.class); BlobStrategy second = mock(BlobStrategy.class); BlobStrategy third = mock(BlobStrategy.class); given(factory.getStrategies(any(CoreTokenConfig.class))) .willReturn(Arrays.asList(first, second, third)); byte[] data = new byte[0]; TokenBlobStrategy strategy = new TokenBlobStrategy(factory, config); strategy.reverse(data); verify(first).reverse(any(byte[].class)); verify(second).reverse(any(byte[].class)); verify(third).reverse(any(byte[].class)); }
### Question: CoreTokenAdapter { public ResultHandler<Token, CoreTokenException> create(Token token) throws CoreTokenException { applyBlobStrategy(token); debug("Create: queued {0} Token {1}\n{2}", token.getType(), token.getTokenId(), token); final ResultHandler<Token, CoreTokenException> createHandler = handlerFactory.getCreateHandler(); dispatcher.create(token, createHandler); return createHandler; } @Inject CoreTokenAdapter(TokenBlobStrategy strategy, TaskDispatcher dispatcher, ResultHandlerFactory handlerFactory, CTSReaperInit reaperInit, @Named(CoreTokenConstants.CTS_DEBUG) Debug debug); ResultHandler<Token, CoreTokenException> create(Token token); Token read(String tokenId); ResultHandler<Token, CoreTokenException> updateOrCreate(Token token); ResultHandler<String, CoreTokenException> delete(String tokenId); Collection<Token> query(final TokenFilter tokenFilter); Collection<PartialToken> attributeQuery(final TokenFilter filter); void deleteOnQuery(final TokenFilter filter); }### Answer: @Test public void shouldCreateToken() throws LdapException, CoreTokenException { Token token = new Token("badger", TokenType.SESSION); adapter.create(token); verify(mockTaskDispatcher).create(eq(token), nullable(ResultHandler.class)); } @Test public void shouldCreateToken() throws LdapException, CoreTokenException { Token token = new Token("badger", TokenType.SESSION); adapter.create(token); verify(mockTaskDispatcher).create(eq(token), any(ResultHandler.class)); }
### Question: CoreTokenAdapter { public ResultHandler<Token, CoreTokenException> updateOrCreate(Token token) throws CoreTokenException { applyBlobStrategy(token); debug("UpdateOrCreate: queued {0} Token {1}\n{2}", token.getType(), token.getTokenId(), token); final ResultHandler<Token, CoreTokenException> updateHandler = handlerFactory.getUpdateHandler(); dispatcher.update(token, updateHandler); return updateHandler; } @Inject CoreTokenAdapter(TokenBlobStrategy strategy, TaskDispatcher dispatcher, ResultHandlerFactory handlerFactory, CTSReaperInit reaperInit, @Named(CoreTokenConstants.CTS_DEBUG) Debug debug); ResultHandler<Token, CoreTokenException> create(Token token); Token read(String tokenId); ResultHandler<Token, CoreTokenException> updateOrCreate(Token token); ResultHandler<String, CoreTokenException> delete(String tokenId); Collection<Token> query(final TokenFilter tokenFilter); Collection<PartialToken> attributeQuery(final TokenFilter filter); void deleteOnQuery(final TokenFilter filter); }### Answer: @Test public void shouldUseTaskQueueForUpdate() throws CoreTokenException { Token token = new Token("badger", TokenType.SESSION); adapter.updateOrCreate(token); verify(mockTaskDispatcher).update(eq(token), nullable(ResultHandler.class)); } @Test public void shouldUseTaskQueueForUpdate() throws CoreTokenException { Token token = new Token("badger", TokenType.SESSION); adapter.updateOrCreate(token); verify(mockTaskDispatcher).update(eq(token), any(ResultHandler.class)); }
### Question: CoreTokenAdapter { public ResultHandler<String, CoreTokenException> delete(String tokenId) throws CoreTokenException { debug("Delete: queued delete {0}", tokenId); final ResultHandler<String, CoreTokenException> deleteHandler = handlerFactory.getDeleteHandler(); dispatcher.delete(tokenId, deleteHandler); return deleteHandler; } @Inject CoreTokenAdapter(TokenBlobStrategy strategy, TaskDispatcher dispatcher, ResultHandlerFactory handlerFactory, CTSReaperInit reaperInit, @Named(CoreTokenConstants.CTS_DEBUG) Debug debug); ResultHandler<Token, CoreTokenException> create(Token token); Token read(String tokenId); ResultHandler<Token, CoreTokenException> updateOrCreate(Token token); ResultHandler<String, CoreTokenException> delete(String tokenId); Collection<Token> query(final TokenFilter tokenFilter); Collection<PartialToken> attributeQuery(final TokenFilter filter); void deleteOnQuery(final TokenFilter filter); }### Answer: @Test public void shouldPerformDelete() throws CoreTokenException { String tokenId = "badger"; adapter.delete(tokenId); verify(mockTaskDispatcher).delete(eq(tokenId), nullable(ResultHandler.class)); } @Test public void shouldPerformDelete() throws CoreTokenException { String tokenId = "badger"; adapter.delete(tokenId); verify(mockTaskDispatcher).delete(eq(tokenId), any(ResultHandler.class)); }
### Question: CoreTokenAdapter { public void deleteOnQuery(final TokenFilter filter) throws CoreTokenException, IllegalArgumentException { filter.addReturnAttribute(CoreTokenField.TOKEN_ID); ResultHandler<Collection<PartialToken>, CoreTokenException> handler = handlerFactory.getDeleteOnQueryHandler(); try { attributeQueryWithHandler(filter, handler); } catch (CoreTokenException e) { throw new QueryFailedException(filter, e); } } @Inject CoreTokenAdapter(TokenBlobStrategy strategy, TaskDispatcher dispatcher, ResultHandlerFactory handlerFactory, CTSReaperInit reaperInit, @Named(CoreTokenConstants.CTS_DEBUG) Debug debug); ResultHandler<Token, CoreTokenException> create(Token token); Token read(String tokenId); ResultHandler<Token, CoreTokenException> updateOrCreate(Token token); ResultHandler<String, CoreTokenException> delete(String tokenId); Collection<Token> query(final TokenFilter tokenFilter); Collection<PartialToken> attributeQuery(final TokenFilter filter); void deleteOnQuery(final TokenFilter filter); }### Answer: @Test public void shouldAddTokenIDAsReturnFieldForDeleteOnQuery() throws CoreTokenException { TokenFilter filter = new TokenFilterBuilder().build(); adapter.deleteOnQuery(filter); ArgumentCaptor<TokenFilter> captor = ArgumentCaptor.forClass(TokenFilter.class); verify(mockTaskDispatcher).partialQuery(captor.capture(), nullable(ResultHandler.class)); TokenFilter capturedFilter = captor.getValue(); assertThat(capturedFilter).isSameAs(filter); assertThat(capturedFilter.getReturnFields()).containsOnly(CoreTokenField.TOKEN_ID); } @Test public void shouldAddTokenIDAsReturnFieldForDeleteOnQuery() throws CoreTokenException { TokenFilter filter = new TokenFilterBuilder().build(); adapter.deleteOnQuery(filter); ArgumentCaptor<TokenFilter> captor = ArgumentCaptor.forClass(TokenFilter.class); verify(mockTaskDispatcher).partialQuery(captor.capture(), any(ResultHandler.class)); TokenFilter capturedFilter = captor.getValue(); assertThat(capturedFilter).isSameAs(filter); assertThat(capturedFilter.getReturnFields()).containsOnly(CoreTokenField.TOKEN_ID); }
### Question: ReaperConnection implements ReaperQuery { @Override public Collection<String> nextPage() throws CoreTokenException { if (Thread.currentThread().isInterrupted()) { close(); return null; } if (failed) { throw new IllegalStateException(); } try { initConnection(); Collection<String> results = impl.nextPage(); endProcessing(results); return results; } catch (CoreTokenException e) { failed = true; close(); throw e; } } @Inject ReaperConnection(@DataLayer(ConnectionType.CTS_REAPER) ConnectionFactory factory, ReaperImpl impl); @Override Collection<String> nextPage(); void close(); }### Answer: @Test public void shouldRespondToInterrupt() throws CoreTokenException { Thread.currentThread().interrupt(); connection.nextPage(); verify(mockImpl, times(0)).nextPage(); } @Test public void shouldOpenConnectionOnFirstCall() throws Exception { given(mockFactory.create()).willReturn(mockConnection); connection.nextPage(); verify(mockImpl).setConnection(eq(mockConnection)); } @Test (expectedExceptions = IllegalStateException.class) public void shouldNotReturnFurtherPagesOnceFailed() throws Exception { given(mockFactory.create()).willReturn(mockConnection); given(mockImpl.nextPage()).willThrow(new CoreTokenException("")); try { connection.nextPage(); } catch (CoreTokenException e) {} connection.nextPage(); }
### Question: ReaperImpl implements ReaperQuery { public void setConnection(C connection) { Reject.ifNull(connection); this.connection = connection; } @Inject ReaperImpl(@DataLayer(ConnectionType.CTS_REAPER) QueryFactory queryFactory, CoreTokenConfig config); void setConnection(C connection); @Override Collection<String> nextPage(); @Override void close(); }### Answer: @Test (expectedExceptions = NullPointerException.class) public void shouldPreventNullConnection() { impl.setConnection(null); }
### Question: ReaperImpl implements ReaperQuery { @Override public Collection<String> nextPage() throws CoreTokenException { Reject.ifTrue(connection == null, "Connection must be assigned before use"); if (results == null) { results = query.executeRawResults(connection, String.class); } if (isQueryComplete()) { return null; } return results.next(); } @Inject ReaperImpl(@DataLayer(ConnectionType.CTS_REAPER) QueryFactory queryFactory, CoreTokenConfig config); void setConnection(C connection); @Override Collection<String> nextPage(); @Override void close(); }### Answer: @Test (expectedExceptions = IllegalArgumentException.class) public void shouldNotStartUnlessConnectionIsProvided() throws CoreTokenException { impl.nextPage(); }
### Question: LdapAdapter implements TokenStorageAdapter<Connection> { public void create(Connection connection, Token token) throws LdapOperationFailedException { Entry entry = conversion.getEntry(token); try { processResult(connection.add(LDAPRequests.newAddRequest(entry))); } catch (LdapException e) { throw new LdapOperationFailedException(e.getResult()); } } @Inject LdapAdapter(LdapTokenAttributeConversion conversion, LdapQueryFilterVisitor queryConverter, LdapQueryFactory queryFactory); void create(Connection connection, Token token); Token read(Connection connection, String tokenId); boolean update(Connection connection, Token previous, Token updated); void delete(Connection connection, String tokenId); @Override Collection<Token> query(Connection connection, TokenFilter query); @Override Collection<PartialToken> partialQuery(Connection connection, TokenFilter query); }### Answer: @Test public void shouldUseConnectionForCreate() throws Exception { Token token = new Token("badger", TokenType.SESSION); Result successResult = mockSuccessfulResult(); given(mockConnection.add(nullable(Entry.class))).willReturn(successResult); given(mockConversion.getEntry(nullable(Token.class))).willReturn(mock(Entry.class)); adapter.create(mockConnection, token); verify(mockConnection).add(any(Entry.class)); } @Test public void shouldUseConnectionForCreate() throws Exception { Token token = new Token("badger", TokenType.SESSION); Result successResult = mockSuccessfulResult(); given(mockConnection.add(any(Entry.class))).willReturn(successResult); given(mockConversion.getEntry(any(Token.class))).willReturn(mock(Entry.class)); adapter.create(mockConnection, token); verify(mockConnection).add(any(Entry.class)); }
### Question: PollingWaitAssistant { public PollingWaitState getPollingWaitState() { if (!started) { return PollingWaitState.NOT_STARTED; } if ( Time.currentTimeMillis() - startTime > timeoutInMilliSeconds) { return PollingWaitState.TIMEOUT; } if (!spamChecker.isWaitLongEnough()) { spamChecker.incrementSpamCheck(); if (spamChecker.isSpammed()) { return PollingWaitState.SPAMMED; } return PollingWaitState.TOO_EARLY; } if (finishFutureEvent.isDone()) { return PollingWaitState.COMPLETE; } return PollingWaitState.WAITING; } PollingWaitAssistant(final long timeoutInMilliSeconds, final long shortTimeout, final long medTimeout, final long longTimeout); PollingWaitAssistant(final long timeoutInMilliSeconds); void start(Future<?> finishFutureEvent); PollingWaitState getPollingWaitState(); long getWaitPeriod(); void resetWait(); }### Answer: @Test public void checkThatNotStartedStateIsReturnedWhenAppropriate() { PollingWaitAssistant assistant = new PollingWaitAssistant(TIMEOUT, SHORT_POLL, MEDIUM_POLL, LONG_POLL); assertThat(assistant.getPollingWaitState()).isEqualTo(PollingWaitAssistant.PollingWaitState.NOT_STARTED); }
### Question: StatelessSSOToken implements SSOToken { @Override public void addSSOTokenListener(SSOTokenListener listener) throws SSOException { throw new SSOTokenListenersUnsupportedException(StatelessSession.SSOTOKEN_LISTENERS_UNSUPPORTED); } StatelessSSOToken(StatelessSession session); boolean isValid(boolean reset); @Override Principal getPrincipal(); @Override String getAuthType(); @Override int getAuthLevel(); @Override InetAddress getIPAddress(); @Override String getHostName(); @Override long getTimeLeft(); @Override long getMaxSessionTime(); @Override long getIdleTime(); @Override long getMaxIdleTime(); @Override SSOTokenID getTokenID(); @Override void setProperty(String name, String value); @Override String getProperty(String name); @Override String getProperty(String name, boolean ignoreState); @Override void addSSOTokenListener(SSOTokenListener listener); @Override String encodeURL(String url); @Override boolean isTokenRestricted(); @Override String dereferenceRestrictedTokenID(SSOToken requester, String restrictedId); @Override String toString(); }### Answer: @Test(expectedExceptions = SSOTokenListenersUnsupportedException.class) public void shouldNotSupportListeners() throws Exception { SSOTokenListener listener = mock(SSOTokenListener.class); statelessSSOToken.addSSOTokenListener(listener); }
### Question: ApplicationQueryFilterVisitor extends ServiceConfigQueryFilterVisitor { @Override protected Map<String, Set<String>> getConfigData(ServiceConfig serviceConfig) { @SuppressWarnings("unchecked") Map<String, Set<String>> appData = serviceConfig.getAttributes(); appData.put("name", singleton(applicationName)); Set<String> metaData = appData.get("meta"); for (String entry : metaData) { Set<String> attributeValue = emptySet(); if (isNotEmpty(entry)) { String[] tokens = entry.split("="); if (tokens.length == 2) { attributeValue = singleton(tokens[1]); } } if (entry.startsWith(CREATED_BY_ATTRIBUTE)) { appData.put("createdBy", attributeValue); } else if (entry.startsWith(CREATION_DATE_ATTRIBUTE)) { appData.put("creationDate", attributeValue); } else if (entry.startsWith(LAST_MODIFIED_BY_ATTRIBUTE)) { appData.put("lastModifiedBy", attributeValue); } else if (entry.startsWith(LAST_MODIFIED_DATE_ATTRIBUTE)) { appData.put("lastModifiedDate", attributeValue); } } return appData; } ApplicationQueryFilterVisitor(String applicationName); }### Answer: @Test public void shouldModifyConfigData() { Map<String, Set<String>> configData = applicationQueryFilterVisitor.getConfigData(serviceConfig); assertThat(configData.get("name")).contains(APPLICATION_NAME); assertThat(configData.get("createdBy")).contains(CREATED_BY); assertThat(configData.get("creationDate")).contains(CREATION_DATE); assertThat(configData.get("lastModifiedBy")).contains(LAST_MODIFIED_BY); assertThat(configData.get("lastModifiedDate")).contains(LAST_MODIFIED_DATE); }
### Question: RecoveryCodeGenerator { public String generateCode(CodeGeneratorSource alphabet, int length) { Reject.ifTrue(length < 1); Reject.ifNull(alphabet); StringBuilder codeBuilder = new StringBuilder(length); String chars = alphabet.getChars(); for (int k = 0; k < length; k++) { codeBuilder.append(chars.charAt(secureRandom.nextInt(chars.length()))); } return codeBuilder.toString(); } RecoveryCodeGenerator(SecureRandom secureRandom, int retryMaximum); @Inject RecoveryCodeGenerator(SecureRandom secureRandom); String generateCode(CodeGeneratorSource alphabet, int length); String generateDelimitedCode(CodeGeneratorSource alphabet, char delimiter, int... groups); String generateDelimitedCodeWithSpecifics(CodeGeneratorSource alphabet, char delimiter, Map<Integer, Character> specifics, int... groups); String[] generateCodes(int numCodes, CodeGeneratorSource alphabet, boolean allowDuplicates); String[] generateCodes(int numCodes, CodeGeneratorSource alphabet, int length, boolean allowDuplicates); String[] generateDelimitedCodes(int numCodes, CodeGeneratorSource alphabet, char delimiter, boolean allowDuplicates, int... groups); String[] generateDelimitedCodesWithSpecifics(int numCodes, CodeGeneratorSource alphabet, char delimiter, Map<Integer, Character> specifics, boolean allowDuplicates, int... groups); final static int DEFAULT_LENGTH; final static int DEFAULT_RETRIES; }### Answer: @Test (expectedExceptions = IllegalArgumentException.class) public void shouldErrorRequestedLengthTooSmall2() throws CodeException { recoveryCodeGenerator.generateCode(new TestAlphabet(), 0); } @Test (expectedExceptions = NullPointerException.class) public void shouldErrorNullAlphabet4() throws CodeException { recoveryCodeGenerator.generateCode(null, 10); }
### Question: RecoveryCodeGenerator { public String generateDelimitedCodeWithSpecifics(CodeGeneratorSource alphabet, char delimiter, Map<Integer, Character> specifics, int... groups) { StringBuilder codeBuilder = new StringBuilder(generateDelimitedCode(alphabet, delimiter, groups)); int maxLength = codeBuilder.length(); for(Map.Entry<Integer, Character> specific : specifics.entrySet()) { Reject.ifTrue(specific.getKey() < 0 || specific.getKey() > maxLength); Reject.ifNull(specific.getValue()); codeBuilder.replace(specific.getKey(), specific.getKey() + 1, String.valueOf(specific.getValue())); } return codeBuilder.toString(); } RecoveryCodeGenerator(SecureRandom secureRandom, int retryMaximum); @Inject RecoveryCodeGenerator(SecureRandom secureRandom); String generateCode(CodeGeneratorSource alphabet, int length); String generateDelimitedCode(CodeGeneratorSource alphabet, char delimiter, int... groups); String generateDelimitedCodeWithSpecifics(CodeGeneratorSource alphabet, char delimiter, Map<Integer, Character> specifics, int... groups); String[] generateCodes(int numCodes, CodeGeneratorSource alphabet, boolean allowDuplicates); String[] generateCodes(int numCodes, CodeGeneratorSource alphabet, int length, boolean allowDuplicates); String[] generateDelimitedCodes(int numCodes, CodeGeneratorSource alphabet, char delimiter, boolean allowDuplicates, int... groups); String[] generateDelimitedCodesWithSpecifics(int numCodes, CodeGeneratorSource alphabet, char delimiter, Map<Integer, Character> specifics, boolean allowDuplicates, int... groups); final static int DEFAULT_LENGTH; final static int DEFAULT_RETRIES; }### Answer: @Test (expectedExceptions = NullPointerException.class) public void shouldErrorNullAlphabet6() throws CodeException { Map<Integer, Character> map = new HashMap<>(); map.put(0, 'L'); recoveryCodeGenerator.generateDelimitedCodeWithSpecifics(null, '-', map, 1); }
### Question: EmbeddedOpenDJManager { public State getState() { return state; } EmbeddedOpenDJManager(Debug logger, String baseDirectory, OpenDJUpgrader upgrader); State getState(); State upgrade(); static final String OPENDJ_DIR; }### Answer: @Test public void whenBaseDirectoryDoesNotExistItIsInNoEmbeddedInstanceState() { String baseDirectory = "/tmp/non-existent-base-directory"; EmbeddedOpenDJManager embeddedOpenDJManager = new EmbeddedOpenDJManager(logger, baseDirectory, upgrader); assertThat(embeddedOpenDJManager.getState()).isEqualTo(NO_EMBEDDED_INSTANCE); } @Test public void whenOpenDJDirectoryDoesNotExistItIsInNoEmbeddedInstanceState() throws Exception { createBaseDirectory("empty-base-directory"); EmbeddedOpenDJManager embeddedOpenDJManager = new EmbeddedOpenDJManager(logger, baseDirectory, upgrader); assertThat(embeddedOpenDJManager.getState()).isEqualTo(NO_EMBEDDED_INSTANCE); } @Test public void whenOpenDJDirectoryExistsAndDoesNotRequireUpgradeItIsInConfiguredState() throws Exception { EmbeddedOpenDJManager embeddedOpenDJManager = setupInstallOpenDJNotRequiringUpgrade(); assertThat(embeddedOpenDJManager.getState()).isEqualTo(CONFIGURED); } @Test public void whenOpenDJDirectoryExistsAndRequireUpgradeItIsInUpgradeRequiredState() throws Exception { EmbeddedOpenDJManager embeddedOpenDJManager = setupInstallOpenDJRequiringUpgrade(); assertThat(embeddedOpenDJManager.getState()).isEqualTo(UPGRADE_REQUIRED); }
### Question: BloomFilterBlacklist implements Blacklist<T> { @Override public void subscribe(Listener listener) { delegate.subscribe(listener); } @VisibleForTesting BloomFilterBlacklist(Blacklist<T> delegate, long purgeDelayMs, final BloomFilter<BlacklistEntry> bloomFilter); BloomFilterBlacklist(Blacklist<T> delegate, long purgeDelayMs); @Override void blacklist(T entry); @Override boolean isBlacklisted(T entry); @Override void subscribe(Listener listener); }### Answer: @Test public void shouldSubscribeForUpdatesFromOtherServers() { verify(mockDelegate).subscribe(any(Blacklist.Listener.class)); } @Test public void shouldAddNotifiedBlacklistedSessionsToTheBloomFilter() { ArgumentCaptor<Blacklist.Listener> listenerArgumentCaptor = ArgumentCaptor.forClass(Blacklist.Listener.class); willDoNothing().given(mockDelegate).subscribe(listenerArgumentCaptor.capture()); testBlacklist = new BloomFilterBlacklist<>(mockDelegate, PURGE_DELAY, mockBloomFilter); Blacklist.Listener listener = listenerArgumentCaptor.getValue(); String id = "testSession"; long expiryTime = 1234l; listener.onBlacklisted(id, expiryTime); verify(mockBloomFilter).add(new BloomFilterBlacklist.BlacklistEntry(id, expiryTime)); } @Test public void shouldDelegateSubscriptions() { Blacklist.Listener listener = mock(Blacklist.Listener.class); testBlacklist.subscribe(listener); mockDelegate.subscribe(listener); }
### Question: BloomFilterBlacklist implements Blacklist<T> { @Override public void blacklist(T entry) throws BlacklistException { delegate.blacklist(entry); } @VisibleForTesting BloomFilterBlacklist(Blacklist<T> delegate, long purgeDelayMs, final BloomFilter<BlacklistEntry> bloomFilter); BloomFilterBlacklist(Blacklist<T> delegate, long purgeDelayMs); @Override void blacklist(T entry); @Override boolean isBlacklisted(T entry); @Override void subscribe(Listener listener); }### Answer: @Test public void shouldDelegateBlacklistToDelegate() throws Exception { testBlacklist.blacklist(mockSession); verify(mockDelegate).blacklist(mockSession); }
### Question: BloomFilterBlacklist implements Blacklist<T> { @Override public boolean isBlacklisted(T entry) throws BlacklistException { DEBUG.message("BloomFilterBlacklist: checking blacklist"); boolean blacklisted = false; if (bloomFilter.mightContain(BlacklistEntry.from(entry, purgeDelayMs))) { blacklisted = delegate.isBlacklisted(entry); } return blacklisted; } @VisibleForTesting BloomFilterBlacklist(Blacklist<T> delegate, long purgeDelayMs, final BloomFilter<BlacklistEntry> bloomFilter); BloomFilterBlacklist(Blacklist<T> delegate, long purgeDelayMs); @Override void blacklist(T entry); @Override boolean isBlacklisted(T entry); @Override void subscribe(Listener listener); }### Answer: @Test public void shouldNotCheckDelegateIfSessionNotInBloomFilter() throws Exception { String id = "testSession"; long expiryTime = 1234l; given(mockSession.getStableStorageID()).willReturn(id); given(mockSession.getBlacklistExpiryTime()).willReturn(expiryTime); given(mockBloomFilter.mightContain(new BloomFilterBlacklist.BlacklistEntry(id, expiryTime))) .willReturn(false); boolean result = testBlacklist.isBlacklisted(mockSession); assertThat(result).isFalse(); verify(mockDelegate, never()).isBlacklisted(any(Session.class)); } @Test public void shouldCheckDelegateIfSessionIsInBloomFilter() throws Exception { String id = "testSession"; long expiryTime = 1234L; given(mockSession.getStableStorageID()).willReturn(id); given(mockSession.getBlacklistExpiryTime()).willReturn(expiryTime); given(mockBloomFilter.mightContain(new BloomFilterBlacklist.BlacklistEntry(id, expiryTime + PURGE_DELAY))) .willReturn(true); given(mockDelegate.isBlacklisted(mockSession)).willReturn(true); boolean result = testBlacklist.isBlacklisted(mockSession); assertThat(result).isTrue(); verify(mockDelegate).isBlacklisted(mockSession); }
### Question: CachingBlacklist implements Blacklist<T> { @Override public boolean isBlacklisted(T entry) throws BlacklistException { final String key = entry.getStableStorageID(); if (cache.containsKey(key)) { return true; } boolean isBlacklisted = delegate.isBlacklisted(entry); if (isBlacklisted) { cache.put(key, entry.getBlacklistExpiryTime() + purgeDelayMs); } return isBlacklisted; } @VisibleForTesting CachingBlacklist(Blacklist<T> delegate, int maxSize, long purgeDelayMs, final TimeService clock); CachingBlacklist(Blacklist<T> delegate, int maxSize, long purgeDelayMs); @Override void blacklist(T entry); @Override boolean isBlacklisted(T entry); @Override void subscribe(Listener listener); }### Answer: @Test public void shouldHitDelegateIfResultNotCached() throws Exception { given(mockDelegate.isBlacklisted(mockSession)).willReturn(true); boolean result = testBlacklist.isBlacklisted(mockSession); assertThat(result).isTrue(); } @Test public void shouldCachePositiveResults() throws Exception { given(mockSession.getTimeLeft()).willReturn(1L); given(mockClock.now()).willReturn(0L); given(mockDelegate.isBlacklisted(mockSession)).willReturn(true); testBlacklist.isBlacklisted(mockSession); verify(mockDelegate).isBlacklisted(mockSession); boolean result = testBlacklist.isBlacklisted(mockSession); verifyNoMoreInteractions(mockDelegate); assertThat(result).isTrue(); } @Test public void shouldNotCacheNegativeResults() throws Exception { given(mockSession.getTimeLeft()).willReturn(1L); given(mockClock.now()).willReturn(0L); given(mockDelegate.isBlacklisted(mockSession)).willReturn(false); testBlacklist.isBlacklisted(mockSession); boolean result = testBlacklist.isBlacklisted(mockSession); verify(mockDelegate, times(2)).isBlacklisted(mockSession); assertThat(result).isFalse(); }
### Question: CTSBlacklist implements Blacklist<T> { @Override public boolean isBlacklisted(T entry) throws BlacklistException { try { return cts.read(entry.getStableStorageID()) != null; } catch (CoreTokenException ex) { DEBUG.error("CTSBlacklist: error checking blacklist", ex); throw new BlacklistException(ex); } } @Inject CTSBlacklist(CTSPersistentStore cts, TokenType tokenType, @Named(CoreTokenConstants.CTS_SCHEDULED_SERVICE) ScheduledExecutorService scheduler, ThreadMonitor threadMonitor, WebtopNamingQuery serverConfig, long purgeDelayMs, long pollIntervalMs); @Override void blacklist(T entry); @Override boolean isBlacklisted(T entry); @Override void subscribe(final Listener listener); }### Answer: @Test public void shouldReturnTrueForBlacklistedSessions() throws Exception { given(mockCts.read(SID)).willReturn(new Token(SID, TokenType.SESSION_BLACKLIST)); final boolean result = testBlacklist.isBlacklisted(mockSession); assertThat(result).isTrue(); } @Test public void shouldReturnFalseForNonBlacklistedSessions() throws Exception { given(mockCts.read(SID)).willReturn(null); final boolean result = testBlacklist.isBlacklisted(mockSession); assertThat(result).isFalse(); } @Test public void shouldConvertCtsReadExceptions() throws Exception { given(mockCts.read(SID)).willThrow(new CoreTokenException("test")); assertThatThrownBy( new ThrowableAssert.ThrowingCallable() { @Override public void call() throws Throwable { testBlacklist.isBlacklisted(mockSession); } }) .isInstanceOf(BlacklistException.class); }
### Question: ExternalLdapConfig implements ConnectionConfig { public void update(LdapDataLayerConfiguration config) { config.updateExternalLdapConfiguration(hosts, username, password, maxConnections, sslMode, heartbeat); } @Inject ExternalLdapConfig(@Named(SessionConstants.SESSION_DEBUG) Debug debug); Set<LDAPURL> getLDAPURLs(); String getBindDN(); char[] getBindPassword(); int getMaxConnections(); int getLdapHeartbeat(); boolean isSSLMode(); boolean hasChanged(); void update(LdapDataLayerConfiguration config); @Override String toString(); static final int INVALID; }### Answer: @Test public void shouldUseSystemPropertiesWrapperForNotifyChanges() throws Exception { PowerMockito.mockStatic(SystemProperties.class); ExternalLdapConfig config = new ExternalLdapConfig(debug); config.update(dataLayerConfiguration); PowerMockito.verifyStatic(SystemProperties.class,times(3)); SystemProperties.get(anyString()); PowerMockito.verifyStatic(SystemProperties.class); SystemProperties.getAsBoolean(anyString(), anyBoolean()); PowerMockito.verifyStatic(SystemProperties.class); SystemProperties.getAsInt(anyString(), eq(-1)); } @Test public void shouldUseSystemPropertiesWrapperForNotifyChanges() throws Exception { PowerMockito.mockStatic(SystemProperties.class); ExternalLdapConfig config = new ExternalLdapConfig(debug); config.update(dataLayerConfiguration); PowerMockito.verifyStatic(times(3)); SystemProperties.get(anyString()); PowerMockito.verifyStatic(); SystemProperties.getAsBoolean(anyString(), anyBoolean()); PowerMockito.verifyStatic(); SystemProperties.getAsInt(anyString(), eq(-1)); }
### Question: ServerGroupConfiguration implements ConnectionConfig { public char[] getBindPassword() { String password = instance.getPasswd(); if (password == null) { return null; } return password.toCharArray(); } ServerGroupConfiguration(ServerGroup group, ServerInstance instance); String getBindDN(); char[] getBindPassword(); int getMaxConnections(); int getLdapHeartbeat(); Set<LDAPURL> getLDAPURLs(); }### Answer: @Test public void shouldReturnPasswordFromInstance() { ServerInstance mockInstance = mock(ServerInstance.class); ServerGroup mockGroup = mock(ServerGroup.class); ServerGroupConfiguration config = new ServerGroupConfiguration(mockGroup, mockInstance); given(mockInstance.getPasswd()).willReturn(""); config.getBindPassword(); verify(mockInstance).getPasswd(); }
### Question: IdCacheBlock extends CacheBlockBase { public boolean isEntryExpirationEnabled() { return ENTRY_EXPIRATION_ENABLED_FLAG; } IdCacheBlock(String entryDN, boolean validEntry); IdCacheBlock(String entryDN, String orgDN, boolean validEntry); Set getFullyQualifiedNames(); void setFullyQualifiedNames(Set fqn); boolean isEntryExpirationEnabled(); long getUserEntryExpirationTime(); long getDefaultEntryExpirationTime(); Debug getDebug(); }### Answer: @Test public void clearCacheTest() throws Exception { IdCacheBlock cb = new IdCacheBlock(ENTRY_DN, true); Assert.assertFalse(cb.isEntryExpirationEnabled()); cb.putAttributes(PRINCIPAL_DN, attributes, null, true, false); Assert.assertTrue(cb.hasCache(PRINCIPAL_DN)); Assert.assertTrue(cb.hasCompleteSet(PRINCIPAL_DN)); cb.clear(); Assert.assertFalse(cb.hasCache(PRINCIPAL_DN)); Assert.assertFalse(cb.hasCompleteSet(PRINCIPAL_DN)); Map cachedAttributes = cb.getAttributes(PRINCIPAL_DN, false); Assert.assertTrue(cachedAttributes.isEmpty()); }
### Question: AuthenticationProcessEventAuditor extends AbstractAuthenticationEventAuditor { public void auditLoginSuccess(LoginState loginState) { String realm = getRealmFromState(loginState); if (eventPublisher.isAuditing(realm, AUTHENTICATION_TOPIC, AM_LOGIN_COMPLETED)) { String moduleName = null; String userDN = null; if (loginState != null) { moduleName = loginState.getAuthModuleNames(); userDN = loginState.getUserDN(); } AMAuthenticationAuditEventBuilder builder = eventFactory.authenticationEvent(realm) .timestamp(System.currentTimeMillis(), eventPublisher.isLtzEnabled()) .transactionId(getTransactionIdValue()) .component(AUTHENTICATION) .eventName(AM_LOGIN_COMPLETED) .result(SUCCESSFUL) .entry(getAuditEntryDetail(moduleName, loginState)) .trackingIds(getTrackingIds(loginState)) .userId(userDN == null ? "" : userDN) .principal(DNUtils.DNtoName(userDN)); eventPublisher.tryPublish(AUTHENTICATION_TOPIC, builder.toEvent()); } } @Inject AuthenticationProcessEventAuditor(AuditEventPublisher eventPublisher, AuditEventFactory eventFactory); void auditLoginSuccess(LoginState loginState); void auditLoginFailure(LoginState loginState); void auditLoginFailure(LoginState loginState, AuthenticationFailureReason failureReason); void auditLogout(SSOToken token); }### Answer: @Test public void shouldNotFailAuditLoginSuccess() { auditor.auditLoginSuccess(null); auditor.auditLoginSuccess(emptyState); verify(eventPublisher, times(2)).tryPublish(anyString(), any(AuditEvent.class)); }
### Question: AuthenticationProcessEventAuditor extends AbstractAuthenticationEventAuditor { public void auditLogout(SSOToken token) { String realm = getRealmFromToken(token); if (eventPublisher.isAuditing(realm, AUTHENTICATION_TOPIC, AM_LOGOUT)) { String principalName; try { Principal principal = token == null ? null : token.getPrincipal(); principalName = principal == null ? null : DNUtils.DNtoName(principal.getName()); } catch (SSOException e) { principalName = null; } AuthenticationAuditEntry entryDetail = new AuthenticationAuditEntry(); entryDetail.setModuleId(getSSOTokenProperty(token, AUTH_TYPE)); String host = getSSOTokenProperty(token, HOST); if (isNotEmpty(host)) { entryDetail.addInfo(IP_ADDRESS, host); } String trackingId = getTrackingIdFromSSOToken(token); String userId = AMAuditEventBuilderUtils.getUserId(token); AMAuthenticationAuditEventBuilder builder = eventFactory.authenticationEvent(realm) .timestamp(System.currentTimeMillis(), eventPublisher.isLtzEnabled()) .transactionId(getTransactionIdValue()) .component(AUTHENTICATION) .eventName(AM_LOGOUT) .result(SUCCESSFUL) .entry(entryDetail) .trackingId(trackingId == null ? "" : trackingId) .userId(userId == null ? "" : userId) .principal(principalName); eventPublisher.tryPublish(AUTHENTICATION_TOPIC, builder.toEvent()); } } @Inject AuthenticationProcessEventAuditor(AuditEventPublisher eventPublisher, AuditEventFactory eventFactory); void auditLoginSuccess(LoginState loginState); void auditLoginFailure(LoginState loginState); void auditLoginFailure(LoginState loginState, AuthenticationFailureReason failureReason); void auditLogout(SSOToken token); }### Answer: @Test public void shouldNotFailAuditLogout() { auditor.auditLogout(null); auditor.auditLogout(emptyToken); verify(eventPublisher, times(2)).tryPublish(anyString(), any(AuditEvent.class)); }
### Question: GlobalMapValueValidator implements ServiceAttributeValidator { public boolean validate(Set<String> values) { boolean valid = true; boolean globalFound = false; if (!CollectionUtils.isEmpty(values)) { for (String val : values) { if (!valid) { break; } String trimmed = val.trim(); Matcher matcher = pattern.matcher(trimmed); valid = matcher.matches(); Matcher globalMatcher = globalPattern.matcher(trimmed); boolean globalMatch = globalMatcher.matches(); if (globalFound && globalMatch && valid) { valid = false; } else if (globalMatch && valid) { globalFound = true; } } } else { valid = false; } if (valid) { valid = MapDuplicateKeyChecker.checkForNoDuplicateKeyInValue(values); } return valid; } boolean validate(Set<String> values); }### Answer: @Test(dataProvider = "data") public void checkCorrectness(String name, boolean expected) { boolean result = validator.validate(Collections.singleton(name)); assertThat(result).isEqualTo(expected); } @Test public void checkSetOnlyContainsOneConfigPerApp() { Set<String> set = new HashSet<>(); set.add("[asdf]=ALL"); set.add("[asdf]=NONE"); boolean result = validator.validate(set); assertThat(result).isEqualTo(false); } @Test public void checkSetOnlyContainsOneGlobalConfig() { Set<String> set = new HashSet<>(); set.add("=ALL"); set.add("=NONE"); boolean result = validator.validate(set); assertThat(result).isEqualTo(false); } @Test public void checkEmptySetFails() { Set<String> set = new HashSet<>(); boolean result = validator.validate(set); assertThat(result).isEqualTo(false); }
### Question: FilterModeValueValidator implements ServiceAttributeValidator { public boolean validate(Set<String> values) { boolean valid = true; boolean globalFound = false; if (CollectionUtils.isNotEmpty(values)) { for (String val : values) { if (!valid) { break; } String trimmed = val.trim(); Matcher matcher = pattern.matcher(trimmed); valid = matcher.matches(); Matcher globalMatcher = globalPattern.matcher(trimmed); boolean globalMatch = globalMatcher.matches(); if (globalFound && globalMatch && valid) { valid = false; } else if (globalMatch && valid) { globalFound = true; } } } else { valid = false; } if (valid) valid = MapDuplicateKeyChecker.checkForNoDuplicateKeyInValue(values); return valid; } boolean validate(Set<String> values); }### Answer: @Test(dataProvider = "data") public void checkCorrectness(String name, boolean expected) { boolean result = validator.validate(Collections.singleton(name)); assertThat(result).isEqualTo(expected); } @Test public void checkSetOnlyContainsOneConfigPerApp() { Set<String> set = new HashSet<>(); set.add("[asdf]=ALL"); set.add("[asdf]=NONE"); boolean result = validator.validate(set); assertThat(result).isEqualTo(false); } @Test public void checkSetOnlyContainsOneGlobalConfig() { Set<String> set = new HashSet<>(); set.add("=ALL"); set.add("=NONE"); boolean result = validator.validate(set); assertThat(result).isEqualTo(false); } @Test public void checkEmptySetFails() { Set<String> set = new HashSet<>(); boolean result = validator.validate(set); assertThat(result).isEqualTo(false); }
### Question: MapValueValidator implements ServiceAttributeValidator { public boolean validate(Set<String> values) { boolean valid = true; if (!CollectionUtils.isEmpty(values)) { for (String value : values) { if (!valid) { break; } if (value.length() > 0) { Matcher m = pattern.matcher(value); valid = m.matches(); } } } if (valid) { valid = MapDuplicateKeyChecker.checkForNoDuplicateKeyInValue(values); } return valid; } boolean validate(Set<String> values); }### Answer: @Test(dataProvider = "data") public void checkCorrectness(String name, boolean expected) { boolean result = validator.validate(Collections.singleton(name)); assertThat(result).isEqualTo(expected); } @Test public void checkSetOnlyContainsOneConfigPerApp() { Set<String> set = new HashSet<>(); set.add("[asdf]=ALL"); set.add("[asdf]=NONE"); boolean result = validator.validate(set); assertThat(result).isEqualTo(false); } @Test public void checkEmptySetPasses() { Set<String> set = new HashSet<>(); boolean result = validator.validate(set); assertThat(result).isEqualTo(true); }
### Question: ListValueValidator implements ServiceAttributeValidator { public boolean validate(Set<String> values) { boolean valid = true; if (!CollectionUtils.isEmpty(values)) { for (String value : values) { if (!valid) { break; } if (value.length() > 0) { Matcher m = pattern.matcher(value); valid = m.matches(); } } } if (valid) { valid = checkForValidIntegerKeyInValue(values); } return valid; } boolean validate(Set<String> values); }### Answer: @Test(dataProvider = "data") public void checkCorrectness(String name, boolean expected) { boolean result = validator.validate(Collections.singleton(name)); assertThat(result).isEqualTo(expected); } @Test public void checkSequentialSetOnlyContainsOneConfigPerApp() { Set<String> set = new HashSet<>(); set.add("[0]=ALL"); set.add("[1]=NONE"); boolean result = validator.validate(set); assertThat(result).isEqualTo(true); } @Test public void checkMissingNumberInSequentialSetAlsoSucceeds() { Set<String> set = new HashSet<>(); set.add("[5]="); set.add("[3]=ALL"); set.add("[1]=NONE"); boolean result = validator.validate(set); assertThat(result).isEqualTo(true); } @Test public void checkSetOnlyContainsOneConfigPerApp() { Set<String> set = new HashSet<>(); set.add("[0]=ALL"); set.add("[0]=NONE"); boolean result = validator.validate(set); assertThat(result).isEqualTo(false); } @Test public void checkEmptySetPasses() { Set<String> set = new HashSet<>(); boolean result = validator.validate(set); assertThat(result).isEqualTo(true); }
### Question: AMSetupFilter implements Filter { @Override public void init(FilterConfig config) throws ServletException { System.out.println("Starting up OpenAM at " + DateFormat.getDateTimeInstance().format(Time.getCalendarInstance().getTime())); ServletContext servletContext = config.getServletContext(); SystemStartupInjectorHolder startupInjectorHolder = SystemStartupInjectorHolder.getInstance(); setupManager = startupInjectorHolder.getInstance(AMSetupManager.class); if (!setupManager.isConfigured()) { servletContext.setAttribute(AM_ENCRYPTION_PASSWORD_PROPERTY_KEY, AMSetupUtils.getRandomString()); } } @Override void init(FilterConfig config); @Override void doFilter(ServletRequest req, ServletResponse resp, FilterChain filterChain); @Override void destroy(); }### Answer: @Test public void initShouldSetEncryptionPasswordIfNotConfigured() throws Exception { FilterConfig config = mock(FilterConfig.class); ServletContext context = mock(ServletContext.class); given(config.getServletContext()).willReturn(context); systemIsNotConfigured(); setupFilter.init(config); verify(context).setAttribute(eq("am.enc.pwd"), anyString()); } @Test public void initShouldNotSetEncryptionPasswordIfConfigured() throws Exception { FilterConfig config = mock(FilterConfig.class); ServletContext context = mock(ServletContext.class); given(config.getServletContext()).willReturn(context); systemIsConfigured(); setupFilter.init(config); verifyZeroInteractions(context); }
### Question: ResourceManager implements IOFogModule { public void start() { new Thread(getUsageData, Constants.RESOURCE_MANAGER_GET_USAGE_DATA).start(); LoggingService.logDebug("ResourceManager", "started"); } @Override int getModuleIndex(); @Override String getModuleName(); void start(); static final String HW_INFO_URL; static final String USB_INFO_URL; static final String COMMAND_HW_INFO; static final String COMMAND_USB_INFO; }### Answer: @Test ( timeout = 100000L ) public void testStart() { resourceManager.start(); verify(resourceManager, Mockito.times(1)).start(); assertEquals(Constants.RESOURCE_MANAGER, resourceManager.getModuleIndex()); assertEquals("ResourceManager", resourceManager.getModuleName()); PowerMockito.verifyStatic(LoggingService.class, atLeastOnce()); LoggingService.logDebug("ResourceManager", "started"); }
### Question: VersionHandler { static boolean isReadyToRollback() { LoggingService.logDebug(MODULE_NAME, "Checking is ready to rollback"); String[] backupsFiles = new File(BACKUPS_DIR).list(); boolean isReadyToRollback = !(backupsFiles == null || backupsFiles.length == 0); LoggingService.logDebug(MODULE_NAME, "Is ready to rollback : " + isReadyToRollback); return isReadyToRollback; } }### Answer: @Test public void isReadyToRollbackFalse() { when(file.list()).thenReturn(null); assertFalse(VersionHandler.isReadyToRollback()); Mockito.verify(file).list(); verifyStatic(LoggingService.class, atLeastOnce()); LoggingService.logDebug(MODULE_NAME, "Is ready to rollback : false"); } @Test public void isReadyToRollbackTrue() { assertTrue(VersionHandler.isReadyToRollback()); Mockito.verify(file).list(); verifyStatic(LoggingService.class, atLeastOnce()); LoggingService.logDebug(MODULE_NAME, "Is ready to rollback : true"); }
### Question: Tracker implements IOFogModule { public static Tracker getInstance() { if (instance == null) { synchronized (Tracker.class) { if (instance == null) instance = new Tracker(); } } return instance; } static Tracker getInstance(); @Override void start(); @Override int getModuleIndex(); @Override String getModuleName(); void handleEvent(TrackingEventType type, String value); void handleEvent(TrackingEventType type, JsonStructure value); }### Answer: @Test public void testGetInstanceIsSameAsMock() { assertSame(tracker, Tracker.getInstance()); }
### Question: Tracker implements IOFogModule { @Override public int getModuleIndex() { return Constants.TRACKER; } static Tracker getInstance(); @Override void start(); @Override int getModuleIndex(); @Override String getModuleName(); void handleEvent(TrackingEventType type, String value); void handleEvent(TrackingEventType type, JsonStructure value); }### Answer: @Test public void getModuleIndex() { assertEquals(Constants.TRACKER, tracker.getModuleIndex()); }
### Question: Tracker implements IOFogModule { @Override public String getModuleName() { return MODULE_NAME; } static Tracker getInstance(); @Override void start(); @Override int getModuleIndex(); @Override String getModuleName(); void handleEvent(TrackingEventType type, String value); void handleEvent(TrackingEventType type, JsonStructure value); }### Answer: @Test public void getModuleName() { assertEquals(MODULE_NAME, tracker.getModuleName()); }
### Question: DockerUtil { public String getContainerName(Container container) { return container.getNames()[0].substring(1); } private DockerUtil(); static DockerUtil getInstance(); void reInitDockerClient(); String getDockerBridgeName(); void startContainer(Microservice microservice); void stopContainer(String id); void removeContainer(String id, Boolean withRemoveVolumes); @SuppressWarnings("deprecation") String getContainerIpAddress(String id); String getContainerName(Container container); String getContainerMicroserviceUuid(Container container); static String getIoFogContainerName(String microserviceUuid); Optional<Container> getContainer(String microserviceUuid); MicroserviceStatus getMicroserviceStatus(String containerId); List<Container> getRunningContainers(); List<Container> getRunningIofogContainers(); Optional<Statistics> getContainerStats(String containerId); long getContainerStartedAt(String id); boolean areMicroserviceAndContainerEqual(String containerId, Microservice microservice); Optional<String> getContainerStatus(String containerId); boolean isContainerRunning(String containerId); List<Container> getContainers(); void removeImageById(String imageId); @SuppressWarnings("resource") void pullImage(String imageName, String microserviceUuid, Registry registry); boolean findLocalImage(String imageName); String createContainer(Microservice microservice, String host); PruneResponse dockerPrune(); void update(PullResponseItem item, Map<String, ItemStatus> statuses); }### Answer: @Test public void testGetContainerName() { assertEquals("iofog_containerName1", dockerUtil.getContainerName(container)); } @Test public void testGetContainerNameWhenThereIsNoContainer() { String[] containers = {" "}; PowerMockito.when(container.getNames()).thenReturn(containers); assertEquals("", dockerUtil.getContainerName(container)); }
### Question: TrackingEvent { public JsonObject toJsonObject() { return Json.createObjectBuilder() .add("uuid", uuid) .add("timestamp", timestamp) .add("sourceType", sourceType) .add("type", type.getName()) .add("data", data) .build(); } TrackingEvent(String uuid, Long timestamp, TrackingEventType type, JsonStructure data); String getUuid(); void setUuid(String uuid); Long getTimestamp(); void setTimestamp(Long timestamp); TrackingEventType getType(); void setType(TrackingEventType type); JsonStructure getData(); void setData(JsonStructure data); @Override String toString(); JsonObject toJsonObject(); }### Answer: @Test public void toJsonObject() { try { trackingEvent = new TrackingEvent(uuid, timestamp, type, data); assertTrue(trackingEvent.toJsonObject().containsKey("uuid")); assertTrue(trackingEvent.toJsonObject().containsKey("timestamp")); assertTrue(trackingEvent.toJsonObject().containsKey("sourceType")); assertTrue(trackingEvent.toJsonObject().containsKey("type")); assertTrue(trackingEvent.toJsonObject().containsKey("data")); assertFalse(trackingEvent.toJsonObject().containsKey("randomKeyWhichIsNotPresent")); } catch (AgentSystemException e) { fail("This will never happen"); } }
### Question: StatusReporter { public static void start() { LoggingService.logInfo(MODULE_NAME, "Starting Status Reporter"); ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); scheduler.scheduleAtFixedRate(setStatusReporterSystemTime, Configuration.getSetSystemTimeFreqSeconds(), Configuration.getSetSystemTimeFreqSeconds(), TimeUnit.SECONDS); LoggingService.logInfo(MODULE_NAME, "Started Status Reporter"); } private StatusReporter(); static String getStatusReport(); static SupervisorStatus setSupervisorStatus(); static ResourceConsumptionManagerStatus setResourceConsumptionManagerStatus(); static ResourceManagerStatus setResourceManagerStatus(); static MessageBusStatus setMessageBusStatus(); static FieldAgentStatus setFieldAgentStatus(); static StatusReporterStatus setStatusReporterStatus(); static ProcessManagerStatus setProcessManagerStatus(); static SshProxyManagerStatus setSshProxyManagerStatus(); static ProcessManagerStatus getProcessManagerStatus(); static LocalApiStatus setLocalApiStatus(); static SupervisorStatus getSupervisorStatus(); static MessageBusStatus getMessageBusStatus(); static ResourceConsumptionManagerStatus getResourceConsumptionManagerStatus(); static ResourceManagerStatus getResourceManagerStatus(); static FieldAgentStatus getFieldAgentStatus(); static StatusReporterStatus getStatusReporterStatus(); static LocalApiStatus getLocalApiStatus(); static SshProxyManagerStatus getSshManagerStatus(); static void start(); }### Answer: @SuppressWarnings("static-access") @Test ( timeout = 5000L ) public void testStart() throws InterruptedException { statusReporter.start(); verify( statusReporter ).setStatusReporterStatus().setSystemTime(anyLong());; }
### Question: MessageCallback { public void sendRealtimeMessage(Message message) { MessageWebsocketHandler handler = new MessageWebsocketHandler(); handler.sendRealTimeMessage(name, message); } MessageCallback(String name); void sendRealtimeMessage(Message message); }### Answer: @Test public void testSendRealtimeMessage() { messageCallback.sendRealtimeMessage(message); Mockito.verify(messageWebsocketHandler).sendRealTimeMessage(Mockito.eq(name), Mockito.eq(message)); }
### Question: LocalApiServerPipelineFactory extends ChannelInitializer<SocketChannel> { public void initChannel(SocketChannel ch) throws Exception { LoggingService.logDebug(MODULE_NAME, "Start Initialize channel for communication and assign handler"); ChannelPipeline pipeline = ch.pipeline(); if (sslCtx != null) { pipeline.addLast(sslCtx.newHandler(ch.alloc())); } pipeline.addLast(new HttpServerCodec()); pipeline.addLast(new HttpObjectAggregator(Integer.MAX_VALUE)); pipeline.addLast(new LocalApiServerHandler(executor)); LoggingService.logDebug(MODULE_NAME, "Finished Initialize channel for communication and assign handler"); } LocalApiServerPipelineFactory(SslContext sslCtx); void initChannel(SocketChannel ch); }### Answer: @Test public void testInitChannel() { try { localApiServerPipelineFactory.initChannel(channel); Mockito.verify(pipeline).addLast(Mockito.eq(httpObjectAggregator)); Mockito.verify(pipeline).addLast(Mockito.eq(serverHandler)); Mockito.verify(pipeline).addLast(Mockito.eq(httpServerCodec)); } catch (Exception e) { fail("This should not happen"); } }
### Question: DockerUtil { public static String getIoFogContainerName(String microserviceUuid) { return Constants.IOFOG_DOCKER_CONTAINER_NAME_PREFIX + microserviceUuid; } private DockerUtil(); static DockerUtil getInstance(); void reInitDockerClient(); String getDockerBridgeName(); void startContainer(Microservice microservice); void stopContainer(String id); void removeContainer(String id, Boolean withRemoveVolumes); @SuppressWarnings("deprecation") String getContainerIpAddress(String id); String getContainerName(Container container); String getContainerMicroserviceUuid(Container container); static String getIoFogContainerName(String microserviceUuid); Optional<Container> getContainer(String microserviceUuid); MicroserviceStatus getMicroserviceStatus(String containerId); List<Container> getRunningContainers(); List<Container> getRunningIofogContainers(); Optional<Statistics> getContainerStats(String containerId); long getContainerStartedAt(String id); boolean areMicroserviceAndContainerEqual(String containerId, Microservice microservice); Optional<String> getContainerStatus(String containerId); boolean isContainerRunning(String containerId); List<Container> getContainers(); void removeImageById(String imageId); @SuppressWarnings("resource") void pullImage(String imageName, String microserviceUuid, Registry registry); boolean findLocalImage(String imageName); String createContainer(Microservice microservice, String host); PruneResponse dockerPrune(); void update(PullResponseItem item, Map<String, ItemStatus> statuses); }### Answer: @Test public void getIoFogContainerName() { assertEquals(Constants.IOFOG_DOCKER_CONTAINER_NAME_PREFIX + microserviceUuid, dockerUtil.getIoFogContainerName(microserviceUuid)); }
### Question: ControlSignalSentInfo { public long getTimeMillis() { return timeMillis; } ControlSignalSentInfo(int count, long timeMillis); long getTimeMillis(); void setTimeMillis(long timeMillis); int getSendTryCount(); void setSendTryCount(int sendTryCount); }### Answer: @Test public void testGetTimeMillis() { assertEquals(timeMillis, controlSignalSentInfo.getTimeMillis()); }
### Question: ControlSignalSentInfo { public void setTimeMillis(long timeMillis) { this.timeMillis = timeMillis; } ControlSignalSentInfo(int count, long timeMillis); long getTimeMillis(); void setTimeMillis(long timeMillis); int getSendTryCount(); void setSendTryCount(int sendTryCount); }### Answer: @Test public void testSetTimeMillis() { timeMillis = timeMillis + 100; controlSignalSentInfo.setTimeMillis(timeMillis); assertEquals(timeMillis, controlSignalSentInfo.getTimeMillis()); }
### Question: ControlSignalSentInfo { public int getSendTryCount() { return sendTryCount; } ControlSignalSentInfo(int count, long timeMillis); long getTimeMillis(); void setTimeMillis(long timeMillis); int getSendTryCount(); void setSendTryCount(int sendTryCount); }### Answer: @Test public void testGetSendTryCount() { assertEquals(sendTryCount, controlSignalSentInfo.getSendTryCount()); }
### Question: ControlSignalSentInfo { public void setSendTryCount(int sendTryCount) { this.sendTryCount = sendTryCount; } ControlSignalSentInfo(int count, long timeMillis); long getTimeMillis(); void setTimeMillis(long timeMillis); int getSendTryCount(); void setSendTryCount(int sendTryCount); }### Answer: @Test public void testSetSendTryCount() { sendTryCount = sendTryCount + 15; controlSignalSentInfo.setSendTryCount(sendTryCount); assertEquals(sendTryCount, controlSignalSentInfo.getSendTryCount()); }
### Question: LocalApiServerHandler extends SimpleChannelInboundHandler<Object> { @Override public void channelReadComplete(ChannelHandlerContext ctx) { ctx.flush(); } LocalApiServerHandler(EventExecutorGroup executor); @Override void channelRead0(ChannelHandlerContext ctx, Object msg); @Override void channelReadComplete(ChannelHandlerContext ctx); @Override void exceptionCaught(ChannelHandlerContext ctx, Throwable cause); }### Answer: @Test public void channelReadComplete() { }
### Question: LocalApiServerHandler extends SimpleChannelInboundHandler<Object> { @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { LoggingService.logError(MODULE_NAME, "Uncaught exception", cause); FullHttpResponse response = ApiHandlerHelpers.internalServerErrorResponse(ctx.alloc().buffer(), cause.getMessage()); sendHttpResponse(ctx, request, response); } LocalApiServerHandler(EventExecutorGroup executor); @Override void channelRead0(ChannelHandlerContext ctx, Object msg); @Override void channelReadComplete(ChannelHandlerContext ctx); @Override void exceptionCaught(ChannelHandlerContext ctx, Throwable cause); }### Answer: @Test public void exceptionCaught() { }
### Question: RestartStuckChecker { public static boolean isStuck(String containerId) { List<LocalDateTime> datesOfRestart = restarts.computeIfAbsent(containerId, k -> new ArrayList<>()); LocalDateTime now = LocalDateTime.now(); datesOfRestart.removeIf(dateOfRestart -> dateOfRestart.isBefore(now.minusMinutes(INTERVAL_IN_MINUTES))); datesOfRestart.add(now); return datesOfRestart.size() >= ABNORMAL_NUMBER_OF_RESTARTS; } static boolean isStuck(String containerId); }### Answer: @Test public void testIsStuckFirstTime() { assertFalse(RestartStuckChecker.isStuck("containerId")); } @Test public void testIsStuckSixthTime() { for (int i =1 ; i<=5 ; i++){ RestartStuckChecker.isStuck("uuid"); } assertTrue(RestartStuckChecker.isStuck("uuid")); }
### Question: LocalApiServer { public void start() throws Exception { final SslContext sslCtx; if (SSL) { SelfSignedCertificate ssc = new SelfSignedCertificate(); sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build(); } else { sslCtx = null; } try{ ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .childHandler(new LocalApiServerPipelineFactory(sslCtx)); Channel ch = b.bind(PORT).sync().channel(); LoggingService.logDebug(MODULE_NAME, "Local api server started at port: " + PORT + "\n"); ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); scheduler.scheduleAtFixedRate(new ControlWebsocketWorker(), 10, 10, TimeUnit.SECONDS); scheduler.scheduleAtFixedRate(new MessageWebsocketWorker(), 10, 10, TimeUnit.SECONDS); ch.closeFuture().sync(); }finally{ bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } } void start(); }### Answer: @Test public void testStart() { try { localApiServer.start(); Mockito.verify(serverBootstrap).childHandler(Mockito.eq(localApiServerPipelineFactory)); Mockito.verify(serverBootstrap).channel(Mockito.eq(NioServerSocketChannel.class)); Mockito.verify(serverBootstrap).bind(Mockito.eq(54321)); Mockito.verify(channel).closeFuture(); Mockito.verify(channelFuture).channel(); Mockito.verify(channelFuture, Mockito.atLeastOnce()).sync(); } catch (Exception e) { fail("This should not happen"); } }
### Question: LocalApiServer { void stop() { LoggingService.logDebug(MODULE_NAME, "Stopping Local api server\n"); bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } void start(); }### Answer: @Test public void testStop() { try { localApiServer.stop(); PowerMockito.mockStatic(LoggingService.class); LoggingService.logInfo(MODULE_NAME, "Start stopping Local api server\n"); PowerMockito.mockStatic(LoggingService.class); LoggingService.logInfo(MODULE_NAME, "Local api server stopped\n"); } catch (Exception e) { fail("This should not happen"); } }
### Question: ApiHandlerHelpers { public static boolean validateMethod(HttpRequest request, HttpMethod expectedMethod) { return request.method() == expectedMethod; } static boolean validateMethod(HttpRequest request, HttpMethod expectedMethod); static String validateContentType(HttpRequest request, String expectedContentType); static boolean validateAccessToken(HttpRequest request); static FullHttpResponse successResponse(ByteBuf outputBuffer, String content); static FullHttpResponse methodNotAllowedResponse(); static FullHttpResponse badRequestResponse(ByteBuf outputBuffer, String content); static FullHttpResponse unauthorizedResponse(ByteBuf outputBuffer, String content); static FullHttpResponse notFoundResponse(ByteBuf outputBuffer, String content); static FullHttpResponse internalServerErrorResponse(ByteBuf outputBuffer, String content); }### Answer: @Test public void testValidateMethodWhenEqual() { try { PowerMockito.when(request.method()).thenReturn(HttpMethod.POST); assertTrue(ApiHandlerHelpers.validateMethod(request, expectedMethod)); } catch (Exception e){ fail("This should not happen"); } } @Test public void testValidateMethodWhenUnEqual() { try { PowerMockito.when(request.method()).thenReturn(HttpMethod.GET); assertFalse(ApiHandlerHelpers.validateMethod(request, expectedMethod)); } catch (Exception e){ fail("This should not happen"); } }
### Question: ApiHandlerHelpers { public static FullHttpResponse successResponse(ByteBuf outputBuffer, String content) { return createResponse(outputBuffer, content, OK); } static boolean validateMethod(HttpRequest request, HttpMethod expectedMethod); static String validateContentType(HttpRequest request, String expectedContentType); static boolean validateAccessToken(HttpRequest request); static FullHttpResponse successResponse(ByteBuf outputBuffer, String content); static FullHttpResponse methodNotAllowedResponse(); static FullHttpResponse badRequestResponse(ByteBuf outputBuffer, String content); static FullHttpResponse unauthorizedResponse(ByteBuf outputBuffer, String content); static FullHttpResponse notFoundResponse(ByteBuf outputBuffer, String content); static FullHttpResponse internalServerErrorResponse(ByteBuf outputBuffer, String content); }### Answer: @Test public void testSuccessResponseWhenByteBuffAndContentAreNull() { assertEquals(new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.OK), ApiHandlerHelpers.successResponse(null, null)); } @Test public void testSuccessResponseWhenContentIsNull() { assertEquals(defaultResponse, ApiHandlerHelpers.successResponse(byteBuf, null)); } @Test public void testSuccessResponseWhenContentNotNull() { FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.OK, byteBuf); HttpUtil.setContentLength(res, byteBuf.readableBytes()); assertEquals(res, ApiHandlerHelpers.successResponse(byteBuf, content)); }
### Question: ApiHandlerHelpers { public static FullHttpResponse methodNotAllowedResponse() { return createResponse(null, null, METHOD_NOT_ALLOWED); } static boolean validateMethod(HttpRequest request, HttpMethod expectedMethod); static String validateContentType(HttpRequest request, String expectedContentType); static boolean validateAccessToken(HttpRequest request); static FullHttpResponse successResponse(ByteBuf outputBuffer, String content); static FullHttpResponse methodNotAllowedResponse(); static FullHttpResponse badRequestResponse(ByteBuf outputBuffer, String content); static FullHttpResponse unauthorizedResponse(ByteBuf outputBuffer, String content); static FullHttpResponse notFoundResponse(ByteBuf outputBuffer, String content); static FullHttpResponse internalServerErrorResponse(ByteBuf outputBuffer, String content); }### Answer: @Test public void testMethodNotAllowedResponse() { defaultResponse = new DefaultFullHttpResponse(HTTP_1_1, METHOD_NOT_ALLOWED); assertEquals(defaultResponse, ApiHandlerHelpers.methodNotAllowedResponse()); }
### Question: ApiHandlerHelpers { public static FullHttpResponse badRequestResponse(ByteBuf outputBuffer, String content) { return createResponse(outputBuffer, content, BAD_REQUEST); } static boolean validateMethod(HttpRequest request, HttpMethod expectedMethod); static String validateContentType(HttpRequest request, String expectedContentType); static boolean validateAccessToken(HttpRequest request); static FullHttpResponse successResponse(ByteBuf outputBuffer, String content); static FullHttpResponse methodNotAllowedResponse(); static FullHttpResponse badRequestResponse(ByteBuf outputBuffer, String content); static FullHttpResponse unauthorizedResponse(ByteBuf outputBuffer, String content); static FullHttpResponse notFoundResponse(ByteBuf outputBuffer, String content); static FullHttpResponse internalServerErrorResponse(ByteBuf outputBuffer, String content); }### Answer: @Test public void testBadRequestResponseByteBufAndContentIsNull() { defaultResponse = new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST); assertEquals(defaultResponse, ApiHandlerHelpers.badRequestResponse(null, null)); } @Test public void testBadRequestResponseContentIsNull() { defaultResponse = new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST); assertEquals(defaultResponse, ApiHandlerHelpers.badRequestResponse(byteBuf, null)); } @Test public void testBadRequestResponseNotNull() { FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST, byteBuf); HttpUtil.setContentLength(res, byteBuf.readableBytes()); assertEquals(res, ApiHandlerHelpers.badRequestResponse(byteBuf, content)); }
### Question: ApiHandlerHelpers { public static FullHttpResponse unauthorizedResponse(ByteBuf outputBuffer, String content) { return createResponse(outputBuffer, content, UNAUTHORIZED); } static boolean validateMethod(HttpRequest request, HttpMethod expectedMethod); static String validateContentType(HttpRequest request, String expectedContentType); static boolean validateAccessToken(HttpRequest request); static FullHttpResponse successResponse(ByteBuf outputBuffer, String content); static FullHttpResponse methodNotAllowedResponse(); static FullHttpResponse badRequestResponse(ByteBuf outputBuffer, String content); static FullHttpResponse unauthorizedResponse(ByteBuf outputBuffer, String content); static FullHttpResponse notFoundResponse(ByteBuf outputBuffer, String content); static FullHttpResponse internalServerErrorResponse(ByteBuf outputBuffer, String content); }### Answer: @Test public void testUnauthorizedResponseByteBufAndContentIsNull() { defaultResponse = new DefaultFullHttpResponse(HTTP_1_1, UNAUTHORIZED); assertEquals(defaultResponse, ApiHandlerHelpers.unauthorizedResponse(null, null)); } @Test public void testUnauthorizedResponse() { FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, UNAUTHORIZED, byteBuf); HttpUtil.setContentLength(res, byteBuf.readableBytes()); assertEquals(res, ApiHandlerHelpers.unauthorizedResponse(byteBuf, content)); }
### Question: ApiHandlerHelpers { public static FullHttpResponse notFoundResponse(ByteBuf outputBuffer, String content) { return createResponse(outputBuffer, content, NOT_FOUND); } static boolean validateMethod(HttpRequest request, HttpMethod expectedMethod); static String validateContentType(HttpRequest request, String expectedContentType); static boolean validateAccessToken(HttpRequest request); static FullHttpResponse successResponse(ByteBuf outputBuffer, String content); static FullHttpResponse methodNotAllowedResponse(); static FullHttpResponse badRequestResponse(ByteBuf outputBuffer, String content); static FullHttpResponse unauthorizedResponse(ByteBuf outputBuffer, String content); static FullHttpResponse notFoundResponse(ByteBuf outputBuffer, String content); static FullHttpResponse internalServerErrorResponse(ByteBuf outputBuffer, String content); }### Answer: @Test public void testNotFoundResponseByteBufAndContentIsNull() { defaultResponse = new DefaultFullHttpResponse(HTTP_1_1, NOT_FOUND); assertEquals(defaultResponse, ApiHandlerHelpers.notFoundResponse(null, null)); } @Test public void testNotFoundResponse() { FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, NOT_FOUND, byteBuf); HttpUtil.setContentLength(res, byteBuf.readableBytes()); assertEquals(res, ApiHandlerHelpers.notFoundResponse(byteBuf, content)); }
### Question: ApiHandlerHelpers { public static FullHttpResponse internalServerErrorResponse(ByteBuf outputBuffer, String content) { return createResponse(outputBuffer, content, INTERNAL_SERVER_ERROR); } static boolean validateMethod(HttpRequest request, HttpMethod expectedMethod); static String validateContentType(HttpRequest request, String expectedContentType); static boolean validateAccessToken(HttpRequest request); static FullHttpResponse successResponse(ByteBuf outputBuffer, String content); static FullHttpResponse methodNotAllowedResponse(); static FullHttpResponse badRequestResponse(ByteBuf outputBuffer, String content); static FullHttpResponse unauthorizedResponse(ByteBuf outputBuffer, String content); static FullHttpResponse notFoundResponse(ByteBuf outputBuffer, String content); static FullHttpResponse internalServerErrorResponse(ByteBuf outputBuffer, String content); }### Answer: @Test public void testInternalServerErrorResponseByteBufAndContentIsNull() { defaultResponse = new DefaultFullHttpResponse(HTTP_1_1, INTERNAL_SERVER_ERROR); assertEquals(defaultResponse, ApiHandlerHelpers.internalServerErrorResponse(null, null)); } @Test public void testInternalServerErrorResponse() { FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, INTERNAL_SERVER_ERROR, byteBuf); HttpUtil.setContentLength(res, byteBuf.readableBytes()); assertEquals(res, ApiHandlerHelpers.internalServerErrorResponse(byteBuf, content)); }
### Question: ResourceConsumptionManager implements IOFogModule { @Override public int getModuleIndex() { return RESOURCE_CONSUMPTION_MANAGER; } private ResourceConsumptionManager(); @Override int getModuleIndex(); @Override String getModuleName(); static ResourceConsumptionManager getInstance(); void instanceConfigUpdated(); void start(); }### Answer: @Test public void testGetModuleIndex() { assertEquals(Constants.RESOURCE_CONSUMPTION_MANAGER, resourceConsumptionManager.getModuleIndex()); }
### Question: ResourceConsumptionManager implements IOFogModule { @Override public String getModuleName() { return MODULE_NAME; } private ResourceConsumptionManager(); @Override int getModuleIndex(); @Override String getModuleName(); static ResourceConsumptionManager getInstance(); void instanceConfigUpdated(); void start(); }### Answer: @Test public void testGetModuleName() { assertEquals("Resource Consumption Manager", resourceConsumptionManager.getModuleName()); }
### Question: ResourceConsumptionManager implements IOFogModule { public static ResourceConsumptionManager getInstance() { if (instance == null) { synchronized (ResourceConsumptionManager.class) { if (instance == null) instance = new ResourceConsumptionManager(); } } return instance; } private ResourceConsumptionManager(); @Override int getModuleIndex(); @Override String getModuleName(); static ResourceConsumptionManager getInstance(); void instanceConfigUpdated(); void start(); }### Answer: @Test public void testGetInstanceIsSameAsMock() { assertSame(resourceConsumptionManager, ResourceConsumptionManager.getInstance()); }
### Question: ResourceConsumptionManager implements IOFogModule { public void instanceConfigUpdated() { logInfo("Start Configuration instance updated"); diskLimit = Configuration.getDiskLimit() * 1_000_000_000; cpuLimit = Configuration.getCpuLimit(); memoryLimit = Configuration.getMemoryLimit() * 1_000_000; logInfo("Finished Config updated"); } private ResourceConsumptionManager(); @Override int getModuleIndex(); @Override String getModuleName(); static ResourceConsumptionManager getInstance(); void instanceConfigUpdated(); void start(); }### Answer: @Test public void testInstanceConfigUpdated() throws Exception{ Field privateDiskLimitField = ResourceConsumptionManager.class. getDeclaredField("diskLimit"); Field privateCpuLimitField = ResourceConsumptionManager.class. getDeclaredField("cpuLimit"); Field privateMemoryLimitField = ResourceConsumptionManager.class. getDeclaredField("memoryLimit"); privateDiskLimitField.setAccessible(true); privateCpuLimitField.setAccessible(true); privateMemoryLimitField.setAccessible(true); resourceConsumptionManager.instanceConfigUpdated(); PowerMockito.verifyStatic(LoggingService.class, Mockito.atLeastOnce()); LoggingService.logInfo(MODULE_NAME, "Start Configuration instance updated"); LoggingService.logInfo(MODULE_NAME, "Finished Config updated"); assertEquals(1.0E9f, privateDiskLimitField.get(resourceConsumptionManager)); assertEquals(1.0f, privateCpuLimitField.get(resourceConsumptionManager)); assertEquals(1000000.0f, privateMemoryLimitField.get(resourceConsumptionManager)); privateDiskLimitField.setAccessible(false); privateCpuLimitField.setAccessible(false); privateMemoryLimitField.setAccessible(false); }
### Question: ResourceConsumptionManager implements IOFogModule { public void start() { logDebug("Starting"); instanceConfigUpdated(); new Thread(getUsageData, Constants.RESOURCE_CONSUMPTION_MANAGER_GET_USAGE_DATA).start(); logDebug("started"); } private ResourceConsumptionManager(); @Override int getModuleIndex(); @Override String getModuleName(); static ResourceConsumptionManager getInstance(); void instanceConfigUpdated(); void start(); }### Answer: @Test public void testStartThread() { resourceConsumptionManager.start(); PowerMockito.verifyStatic(LoggingService.class, Mockito.atLeastOnce()); LoggingService.logDebug(MODULE_NAME, "Starting"); PowerMockito.verifyStatic(LoggingService.class, Mockito.atLeastOnce()); LoggingService.logDebug(MODULE_NAME, "started"); }
### Question: ResourceConsumptionManager implements IOFogModule { private void removeArchives(float amount) { logDebug("Start remove archives : " + amount); String archivesDirectory = Configuration.getDiskDirectory() + "messages/archive/"; final File workingDirectory = new File(archivesDirectory); File[] filesList = workingDirectory.listFiles((dir, fileName) -> fileName.substring(fileName.indexOf(".")).equals(".idx")); if (filesList != null) { Arrays.sort(filesList, (o1, o2) -> { String t1 = o1.getName().substring(o1.getName().indexOf('_') + 1, o1.getName().indexOf(".")); String t2 = o2.getName().substring(o2.getName().indexOf('_') + 1, o2.getName().indexOf(".")); return t1.compareTo(t2); }); for (File indexFile : filesList) { File dataFile = new File(archivesDirectory + indexFile.getName().substring(0, indexFile.getName().indexOf('.')) + ".iomsg"); amount -= indexFile.length(); indexFile.delete(); amount -= dataFile.length(); dataFile.delete(); if (amount < 0) break; } } logDebug("Finished remove archives : "); } private ResourceConsumptionManager(); @Override int getModuleIndex(); @Override String getModuleName(); static ResourceConsumptionManager getInstance(); void instanceConfigUpdated(); void start(); }### Answer: @Test public void testRemoveArchives() throws Exception{ float amount = 0f; method = ResourceConsumptionManager.class.getDeclaredMethod("removeArchives", float.class); method.setAccessible(true); method.invoke(resourceConsumptionManager, amount); PowerMockito.verifyStatic(LoggingService.class, Mockito.atLeastOnce()); LoggingService.logDebug(MODULE_NAME, "Start remove archives : " + amount); PowerMockito.verifyStatic(LoggingService.class, Mockito.atLeastOnce()); LoggingService.logDebug(MODULE_NAME, "Finished remove archives : "); PowerMockito.verifyStatic(Configuration.class, Mockito.atLeastOnce()); Configuration.getDiskDirectory(); }
### Question: ResourceConsumptionManager implements IOFogModule { private float getMemoryUsage() { logDebug("Start get memory usage"); Runtime runtime = Runtime.getRuntime(); long allocatedMemory = runtime.totalMemory(); long freeMemory = runtime.freeMemory(); logDebug("Finished get memory usage : "+ (float)(allocatedMemory - freeMemory)); return (allocatedMemory - freeMemory); } private ResourceConsumptionManager(); @Override int getModuleIndex(); @Override String getModuleName(); static ResourceConsumptionManager getInstance(); void instanceConfigUpdated(); void start(); }### Answer: @Test public void testGetMemoryUsage() throws Exception{ method = ResourceConsumptionManager.class.getDeclaredMethod("getMemoryUsage"); method.setAccessible(true); float memoryUsage = (float) method.invoke(resourceConsumptionManager); PowerMockito.verifyStatic(LoggingService.class, Mockito.atLeastOnce()); LoggingService.logDebug(MODULE_NAME, "Start get memory usage"); PowerMockito.verifyStatic(LoggingService.class, Mockito.atLeastOnce()); LoggingService.logDebug(MODULE_NAME, "Finished get memory usage : " + memoryUsage); }
### Question: ResourceConsumptionManager implements IOFogModule { private float getCpuUsage() { logDebug("Start get cpu usage"); String processName = ManagementFactory.getRuntimeMXBean().getName(); String processId = processName.split("@")[0]; if (SystemUtils.IS_OS_LINUX) { Pair<Long, Long> before = parseStat(processId); waitForSecond(); Pair<Long, Long> after = parseStat(processId); logDebug("Finished get cpu usage : " + 100f * (after._1() - before._1()) / (after._2() - before._2())); return 100f * (after._1() - before._1()) / (after._2() - before._2()); } else if (SystemUtils.IS_OS_WINDOWS) { String response = getWinCPUUsage(processId); logInfo("Finished get cpu usage : " + response); return Float.parseFloat(response); } else { logDebug("Finished get cpu usage : " + 0f); return 0f; } } private ResourceConsumptionManager(); @Override int getModuleIndex(); @Override String getModuleName(); static ResourceConsumptionManager getInstance(); void instanceConfigUpdated(); void start(); }### Answer: @Test public void testGetCpuUsage() throws Exception{ method = ResourceConsumptionManager.class.getDeclaredMethod("getCpuUsage"); method.setAccessible(true); float response = (float) method.invoke(resourceConsumptionManager); PowerMockito.verifyStatic(LoggingService.class, Mockito.atLeastOnce()); LoggingService.logDebug(MODULE_NAME, "Start get cpu usage"); PowerMockito.verifyStatic(LoggingService.class, Mockito.atLeastOnce()); LoggingService.logDebug(MODULE_NAME, "Finished get cpu usage : " + response); }
### Question: ResourceConsumptionManager implements IOFogModule { private long getAvailableDisk() { logDebug("Start get available disk"); File[] roots = File.listRoots(); long freeSpace = 0; for (File f : roots) { freeSpace += f.getUsableSpace(); } logDebug("Finished get available disk : " + freeSpace); return freeSpace; } private ResourceConsumptionManager(); @Override int getModuleIndex(); @Override String getModuleName(); static ResourceConsumptionManager getInstance(); void instanceConfigUpdated(); void start(); }### Answer: @Test public void testGetAvailableDisk() throws Exception{ method = ResourceConsumptionManager.class.getDeclaredMethod("getAvailableDisk"); method.setAccessible(true); long output = (long) method.invoke(resourceConsumptionManager); PowerMockito.verifyStatic(LoggingService.class, Mockito.atLeastOnce()); LoggingService.logDebug(MODULE_NAME, "Start get available disk"); PowerMockito.verifyStatic(LoggingService.class, Mockito.atLeastOnce()); LoggingService.logDebug(MODULE_NAME, "Finished get available disk : " + output); }
### Question: SupervisorStatus { public SupervisorStatus setDaemonStatus(ModulesStatus daemonStatus) { this.daemonStatus = daemonStatus; return this; } SupervisorStatus(); SupervisorStatus setModuleStatus(int module, ModulesStatus status); ModulesStatus getModuleStatus(int module); ModulesStatus getDaemonStatus(); SupervisorStatus setDaemonStatus(ModulesStatus daemonStatus); long getDaemonLastStart(); SupervisorStatus setDaemonLastStart(long daemonLastStart); long getOperationDuration(); SupervisorStatus setOperationDuration(long operationDuration); }### Answer: @Test public void testSetDaemonStatus(){ supervisorStatus.setDaemonStatus(Constants.ModulesStatus.STARTING); assertEquals(Constants.ModulesStatus.STARTING, supervisorStatus.getDaemonStatus()); }
### Question: Supervisor implements IOFogModule { public Supervisor() {} Supervisor(); void start(); @Override int getModuleIndex(); @Override String getModuleName(); }### Answer: @Test public void supervisor() { try { supervisor = spy(new Supervisor()); suppress(method(Supervisor.class, "startModule")); suppress(method(Supervisor.class, "operationDuration")); supervisor.start(); verify(supervisor, Mockito.atLeastOnce()).start(); verify(supervisor, Mockito.never()).getModuleIndex(); verify(supervisor, Mockito.atLeastOnce()).getModuleName(); verify(supervisor, Mockito.atLeastOnce()).logDebug("Starting Supervisor"); verify(supervisor, Mockito.atLeastOnce()).logDebug("Started Supervisor"); } catch (Exception e) { e.printStackTrace(); } }
### Question: Supervisor implements IOFogModule { private void startModule(IOFogModule ioFogModule) throws Exception { logInfo(" Starting " + ioFogModule.getModuleName()); StatusReporter.setSupervisorStatus().setModuleStatus(ioFogModule.getModuleIndex(), STARTING); ioFogModule.start(); StatusReporter.setSupervisorStatus().setModuleStatus(ioFogModule.getModuleIndex(), RUNNING); logInfo(" Started " + ioFogModule.getModuleName()); } Supervisor(); void start(); @Override int getModuleIndex(); @Override String getModuleName(); }### Answer: @Test public void testStartModule() throws Exception{ resourceManager = mock(ResourceManager.class); PowerMockito.when(resourceManager.getModuleIndex()).thenReturn(6); PowerMockito.when(resourceManager.getModuleName()).thenReturn("ResourceManager"); PowerMockito.when(StatusReporter.setSupervisorStatus().setModuleStatus(6, STARTING)).thenReturn(mock(SupervisorStatus.class)); PowerMockito.when(StatusReporter.setSupervisorStatus().setModuleStatus(6, RUNNING)).thenReturn(null); method = Supervisor.class.getDeclaredMethod("startModule", IOFogModule.class); method.setAccessible(true); PowerMockito.doNothing().when(resourceManager).start(); method.invoke(supervisor, resourceManager); verify(supervisor, Mockito.atLeastOnce()).logInfo(" Starting ResourceManager"); verify(supervisor, Mockito.atLeastOnce()).logInfo(" Started ResourceManager"); }
### Question: Orchestrator { public void sendFileToController(String command, File file) throws Exception { logDebug(MODULE_NAME, "Start send file to Controller"); InputStream inputStream = new FileInputStream(file); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); builder.addBinaryBody("upstream", inputStream, ContentType.create("application/zip"), file.getName()); HttpEntity entity = builder.build(); getJsonObject(null, RequestType.PUT, entity, createUri(command)); logDebug(MODULE_NAME, "Finished send file to Controller"); } Orchestrator(); boolean ping(); JsonObject provision(String key); JsonObject request(String command, RequestType requestType, Map<String, Object> queryParams, JsonObject json); void sendFileToController(String command, File file); void update(); }### Answer: @Test public void testSendFileToController() { try { orchestrator.sendFileToController("strace", file); PowerMockito.verifyPrivate(orchestrator).invoke("getJsonObject", Mockito.eq(null), Mockito.eq(RequestType.PUT), Mockito.eq(httpEntity), Mockito.any()); } catch (Exception e) { fail("This should not happen"); } } @Test (expected = Exception.class) public void throwsExceptionSendFileToController() throws Exception{ PowerMockito.doThrow(mock(Exception.class)).when(httpClients).execute(Mockito.any()); orchestrator.sendFileToController("strace", file); PowerMockito.verifyPrivate(orchestrator).invoke("getJsonObject", Mockito.eq(null), Mockito.eq(RequestType.PUT), Mockito.eq(httpEntity), Mockito.any()); }
### Question: X509TrustManagerImpl implements X509TrustManager { @Override public void checkServerTrusted(X509Certificate[] certs, String arg1) throws CertificateException { boolean verified = false; if (certs !=null){ for (X509Certificate cert : certs) { if (cert.equals(controllerCert)) { verified = true; break; } } } if (!verified) throw new CertificateException(); } X509TrustManagerImpl(Certificate controllerCert); @Override void checkServerTrusted(X509Certificate[] certs, String arg1); @Override void checkClientTrusted(X509Certificate[] certs, String arg1); @Override X509Certificate[] getAcceptedIssuers(); }### Answer: @Test (expected = CertificateException.class) public void throwsExceptionWhenCertificateIsNullInCheckServerTrusted() throws CertificateException { x509TrustManager.checkServerTrusted(null, null); } @Test (expected = CertificateException.class) public void throwsExceptionWhenCertificateIsNotEqualInCheckServerTrusted() throws CertificateException { x509TrustManager.checkServerTrusted(certificates, "args"); } @Test public void testCheckServerTrusted() { try { certificate = x509Certificate; x509TrustManager = spy(new X509TrustManagerImpl(certificate)); x509TrustManager.checkServerTrusted(certificates, "args"); } catch (CertificateException e) { fail("This should not happen"); } }
### Question: X509TrustManagerImpl implements X509TrustManager { @Override public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } X509TrustManagerImpl(Certificate controllerCert); @Override void checkServerTrusted(X509Certificate[] certs, String arg1); @Override void checkClientTrusted(X509Certificate[] certs, String arg1); @Override X509Certificate[] getAcceptedIssuers(); }### Answer: @Test public void getAcceptedIssuers() { assertNotNull(x509TrustManager.getAcceptedIssuers()); }
### Question: LogFormatter extends Formatter { public String format(LogRecord record) { IOFogNetworkInterfaceManager fogNetworkInterfaceManager = IOFogNetworkInterfaceManager.getInstance(); final DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); JsonBuilderFactory factory = Json.createBuilderFactory(null); JsonObjectBuilder jsonObjectBuilder = factory.createObjectBuilder(); jsonObjectBuilder.add("timestamp", df.format(System.currentTimeMillis())); jsonObjectBuilder.add("level", record.getLevel().toString()); jsonObjectBuilder.add("agent_id", Configuration.getIofogUuid()); jsonObjectBuilder.add("pid", fogNetworkInterfaceManager.getPid() != 0 ? fogNetworkInterfaceManager.getPid() : fogNetworkInterfaceManager.getFogPid()); jsonObjectBuilder.add("hostname", fogNetworkInterfaceManager.getHostName() != null ? fogNetworkInterfaceManager.getHostName(): IOFogNetworkInterface.getHostName()); jsonObjectBuilder.add("thread", record.getSourceClassName()); jsonObjectBuilder.add("module", record.getSourceMethodName()); jsonObjectBuilder.add("message", record.getMessage()); if (record.getThrown() != null) { jsonObjectBuilder.add("exception_message", record.getThrown().getLocalizedMessage()); jsonObjectBuilder.add("stacktrace", ExceptionUtils.getFullStackTrace(record.getThrown())); } return jsonObjectBuilder.build().toString().concat("\n"); } String format(LogRecord record); }### Answer: @Test public void testFormat() { assertTrue(logFormatter.format(logRecord).contains("SEVERE")); }
### Question: LoggingService { public static void logInfo(String moduleName, String msg) { if (Configuration.debugging || logger == null) System.out.println(String.format("%s %s : %s (%s)", Thread.currentThread().getName(), moduleName, msg, new Date(System.currentTimeMillis()))); else { logger.logp(Level.INFO, Thread.currentThread().getName(), moduleName, msg); } } private LoggingService(); static void logInfo(String moduleName, String msg); static void logWarning(String moduleName, String msg); static void logDebug(String moduleName, String msg); static void logError(String moduleName, String msg, Throwable e); static void setupLogger(); static void setupMicroserviceLogger(String microserviceUuid, long logSize); static boolean microserviceLogInfo(String microserviceUuid, String msg); static boolean microserviceLogWarning(String microserviceUuid, String msg); static void instanceConfigUpdated(); }### Answer: @Test public void testLogInfo() { try { LoggingService.setupLogger(); LoggingService.logInfo(MODULE_NAME, message); Mockito.verify(logger).logp(Level.INFO, Thread.currentThread().getName(), MODULE_NAME, message); } catch (Exception e) { fail("This should not happen"); } }
### Question: LoggingService { public static void logWarning(String moduleName, String msg) { if (Configuration.debugging || logger == null) { System.out.println(String.format("%s %s : %s (%s)", Thread.currentThread().getName(), moduleName, msg, new Date(System.currentTimeMillis()))); } else { logger.logp(Level.WARNING, Thread.currentThread().getName(), moduleName, msg); } } private LoggingService(); static void logInfo(String moduleName, String msg); static void logWarning(String moduleName, String msg); static void logDebug(String moduleName, String msg); static void logError(String moduleName, String msg, Throwable e); static void setupLogger(); static void setupMicroserviceLogger(String microserviceUuid, long logSize); static boolean microserviceLogInfo(String microserviceUuid, String msg); static boolean microserviceLogWarning(String microserviceUuid, String msg); static void instanceConfigUpdated(); }### Answer: @Test public void testLogWarning() { try { LoggingService.setupLogger(); LoggingService.logWarning(MODULE_NAME, message); Mockito.verify(logger).logp(Level.WARNING, Thread.currentThread().getName(), MODULE_NAME, message); } catch (Exception e) { fail("This should not happen"); } }
### Question: LoggingService { public static void logDebug(String moduleName, String msg) { if (Configuration.debugging || logger == null) System.out.println(String.format("%s %s : %s (%s)", Thread.currentThread().getName(), moduleName, msg, new Date(System.currentTimeMillis()))); else { logger.logp(Level.FINE, Thread.currentThread().getName(), moduleName, msg); } } private LoggingService(); static void logInfo(String moduleName, String msg); static void logWarning(String moduleName, String msg); static void logDebug(String moduleName, String msg); static void logError(String moduleName, String msg, Throwable e); static void setupLogger(); static void setupMicroserviceLogger(String microserviceUuid, long logSize); static boolean microserviceLogInfo(String microserviceUuid, String msg); static boolean microserviceLogWarning(String microserviceUuid, String msg); static void instanceConfigUpdated(); }### Answer: @Test public void testLogDebug() { try { LoggingService.setupLogger(); LoggingService.logDebug(MODULE_NAME, message); Mockito.verify(logger).logp(Level.FINE, Thread.currentThread().getName(), MODULE_NAME, message); } catch (Exception e) { fail("This should not happen"); } }
### Question: LoggingService { public static void logError(String moduleName, String msg, Throwable e) { if (newSentryException(e)) { Sentry.getContext().addExtra("version", getVersion()); Sentry.getStoredClient().getContext().setUser(new User(System.getProperty("user.name"), System.getProperty("user.name"), "", "")); Sentry.capture(e); } if (Configuration.debugging || logger == null) { System.out.println(String.format("%s %s : %s (%s) - Exception: %s - Stack trace: %s", Thread.currentThread().getName(), moduleName, msg, new Date(System.currentTimeMillis()), e.getMessage(), ExceptionUtils.getStackTrace(e))); } else { logger.logp(Level.SEVERE, Thread.currentThread().getName(), moduleName, msg, e); } } private LoggingService(); static void logInfo(String moduleName, String msg); static void logWarning(String moduleName, String msg); static void logDebug(String moduleName, String msg); static void logError(String moduleName, String msg, Throwable e); static void setupLogger(); static void setupMicroserviceLogger(String microserviceUuid, long logSize); static boolean microserviceLogInfo(String microserviceUuid, String msg); static boolean microserviceLogWarning(String microserviceUuid, String msg); static void instanceConfigUpdated(); }### Answer: @Test public void testLogError() { try { LoggingService.setupLogger(); Exception e = new Exception("This is exception"); LoggingService.logError(MODULE_NAME, message, e); Mockito.verify(logger).logp(Level.SEVERE, Thread.currentThread().getName(), MODULE_NAME, message, e); } catch (Exception e) { fail("This should not happen"); } }
### Question: LoggingService { public static void instanceConfigUpdated() { try { setupLogger(); } catch (Exception exp) { logError(MODULE_NAME, exp.getMessage(), exp); } } private LoggingService(); static void logInfo(String moduleName, String msg); static void logWarning(String moduleName, String msg); static void logDebug(String moduleName, String msg); static void logError(String moduleName, String msg, Throwable e); static void setupLogger(); static void setupMicroserviceLogger(String microserviceUuid, long logSize); static boolean microserviceLogInfo(String microserviceUuid, String msg); static boolean microserviceLogWarning(String microserviceUuid, String msg); static void instanceConfigUpdated(); }### Answer: @Test public void testInstanceConfigUpdated() { try { LoggingService.instanceConfigUpdated(); PowerMockito.verifyStatic(LoggingService.class); LoggingService.setupLogger(); } catch (Exception e) { fail("This should not happen"); } } @Test public void TestInstanceConfigUpdated() throws IOException { Exception e = new SecurityException("This is exception"); PowerMockito.doThrow(e).when(logger).setLevel(Mockito.any()); LoggingService.instanceConfigUpdated(); PowerMockito.verifyStatic(LoggingService.class); LoggingService.setupLogger(); PowerMockito.verifyStatic(LoggingService.class); LoggingService.logError(MODULE_NAME, e.getMessage(), e); Mockito.verify(logger).logp(Level.SEVERE, Thread.currentThread().getName(), MODULE_NAME, e.getMessage(), e); }
### Question: CmdProperties { public static String getVersionMessage() { return cmdProperties.getProperty("version_msg"); } static String getVersionMessage(); static String getVersion(); static String getDeprovisionMessage(); static String getProvisionMessage(); static String getProvisionCommonErrorMessage(); static String getProvisionStatusErrorMessage(); static String getProvisionStatusSuccessMessage(); static String getConfigParamMessage(CommandLineConfigParam configParam); static String getIofogUuidMessage(); static String getIpAddressMessage(); }### Answer: @Test public void getVersionMessage() { assertEquals("ioFog %s \nCopyright (C) 2020 Edgeworx, Inc. \nEclipse ioFog is provided under the Eclipse Public License 2.0 (EPL-2.0) \nhttps: CmdProperties.getVersionMessage()); }
### Question: CmdProperties { public static String getVersion() { return versionProperties.getProperty("version"); } static String getVersionMessage(); static String getVersion(); static String getDeprovisionMessage(); static String getProvisionMessage(); static String getProvisionCommonErrorMessage(); static String getProvisionStatusErrorMessage(); static String getProvisionStatusSuccessMessage(); static String getConfigParamMessage(CommandLineConfigParam configParam); static String getIofogUuidMessage(); static String getIpAddressMessage(); }### Answer: @Test public void getVersion() { assertNotNull(CmdProperties.getVersion()); }
### Question: CmdProperties { public static String getDeprovisionMessage() { return cmdProperties.getProperty("deprovision_msg"); } static String getVersionMessage(); static String getVersion(); static String getDeprovisionMessage(); static String getProvisionMessage(); static String getProvisionCommonErrorMessage(); static String getProvisionStatusErrorMessage(); static String getProvisionStatusSuccessMessage(); static String getConfigParamMessage(CommandLineConfigParam configParam); static String getIofogUuidMessage(); static String getIpAddressMessage(); }### Answer: @Test public void testGetDeprovisionMessage() { assertEquals("Deprovisioning from controller ... %s", CmdProperties.getDeprovisionMessage()); }
### Question: CmdProperties { public static String getProvisionMessage() { return cmdProperties.getProperty("provision_msg"); } static String getVersionMessage(); static String getVersion(); static String getDeprovisionMessage(); static String getProvisionMessage(); static String getProvisionCommonErrorMessage(); static String getProvisionStatusErrorMessage(); static String getProvisionStatusSuccessMessage(); static String getConfigParamMessage(CommandLineConfigParam configParam); static String getIofogUuidMessage(); static String getIpAddressMessage(); }### Answer: @Test public void testGetProvisionMessage() { assertEquals("Provisioning with key \"%s\" ... Result: %s", CmdProperties.getProvisionMessage()); }
### Question: CmdProperties { public static String getProvisionCommonErrorMessage() { return cmdProperties.getProperty("provision_common_error"); } static String getVersionMessage(); static String getVersion(); static String getDeprovisionMessage(); static String getProvisionMessage(); static String getProvisionCommonErrorMessage(); static String getProvisionStatusErrorMessage(); static String getProvisionStatusSuccessMessage(); static String getConfigParamMessage(CommandLineConfigParam configParam); static String getIofogUuidMessage(); static String getIpAddressMessage(); }### Answer: @Test public void testGetProvisionCommonErrorMessage() { assertEquals("\nProvisioning failed", CmdProperties.getProvisionCommonErrorMessage()); }
### Question: CmdProperties { public static String getProvisionStatusErrorMessage() { return cmdProperties.getProperty("provision_status_error"); } static String getVersionMessage(); static String getVersion(); static String getDeprovisionMessage(); static String getProvisionMessage(); static String getProvisionCommonErrorMessage(); static String getProvisionStatusErrorMessage(); static String getProvisionStatusSuccessMessage(); static String getConfigParamMessage(CommandLineConfigParam configParam); static String getIofogUuidMessage(); static String getIpAddressMessage(); }### Answer: @Test public void testGetProvisionStatusErrorMessage() { assertEquals("\nProvision failed with error message: \"%s\"", CmdProperties.getProvisionStatusErrorMessage()); }
### Question: CmdProperties { public static String getProvisionStatusSuccessMessage() { return cmdProperties.getProperty("provision_status_success"); } static String getVersionMessage(); static String getVersion(); static String getDeprovisionMessage(); static String getProvisionMessage(); static String getProvisionCommonErrorMessage(); static String getProvisionStatusErrorMessage(); static String getProvisionStatusSuccessMessage(); static String getConfigParamMessage(CommandLineConfigParam configParam); static String getIofogUuidMessage(); static String getIpAddressMessage(); }### Answer: @Test public void testGetProvisionStatusSuccessMessage() { assertEquals("\nProvision success - Iofog UUID is %s", CmdProperties.getProvisionStatusSuccessMessage()); }
### Question: CmdProperties { public static String getIpAddressMessage() { return cmdProperties.getProperty("ip_address"); } static String getVersionMessage(); static String getVersion(); static String getDeprovisionMessage(); static String getProvisionMessage(); static String getProvisionCommonErrorMessage(); static String getProvisionStatusErrorMessage(); static String getProvisionStatusSuccessMessage(); static String getConfigParamMessage(CommandLineConfigParam configParam); static String getIofogUuidMessage(); static String getIpAddressMessage(); }### Answer: @Test public void testGetIpAddressMessage() { assertEquals("IP Address", CmdProperties.getIpAddressMessage()); }
### Question: CmdProperties { public static String getIofogUuidMessage() { return cmdProperties.getProperty("iofog_uuid"); } static String getVersionMessage(); static String getVersion(); static String getDeprovisionMessage(); static String getProvisionMessage(); static String getProvisionCommonErrorMessage(); static String getProvisionStatusErrorMessage(); static String getProvisionStatusSuccessMessage(); static String getConfigParamMessage(CommandLineConfigParam configParam); static String getIofogUuidMessage(); static String getIpAddressMessage(); }### Answer: @Test public void testGetIofogUuidMessage() { assertEquals("Iofog UUID", CmdProperties.getIofogUuidMessage()); }
### Question: MessageIdGenerator { public synchronized String generate(long time) { if (lastTime == time) { sequence--; } else { lastTime = time; sequence = MAX_SEQUENCE; } return toBase58(time) + toBase58(sequence); } MessageIdGenerator(); synchronized String generate(long time); String getNextId(); }### Answer: @Test public void testGenerate() { try { assertNotNull("Message Id not null", messageIdGenerator.generate(currentTimeMillis())); PowerMockito.verifyPrivate(messageIdGenerator, times(2)) .invoke("toBase58", anyLong()); } catch (Exception e) { fail("This should not happen"); } }
### Question: MessageIdGenerator { public String getNextId() { while (generatedIds.size() == 0); synchronized (generatedIds) { return generatedIds.poll(); } } MessageIdGenerator(); synchronized String generate(long time); String getNextId(); }### Answer: @Test public void testGetNextId() { assertNotNull("Next Id", messageIdGenerator.getNextId()); assertFalse(messageIdGenerator.getNextId().contains("?")); }