method2testcases
stringlengths
118
3.08k
### Question: RemoteJwkSetCache extends AbstractIdentifiableInitializableComponent { public void setStorage(@Nonnull final StorageService storageService) { ComponentSupport.ifInitializedThrowUnmodifiabledComponentException(this); storage = Constraint.isNotNull(storageService, "StorageService cannot be null"); final StorageCapabilities caps = storage.getCapabilities(); if (caps instanceof StorageCapabilitiesEx) { Constraint.isTrue(((StorageCapabilitiesEx) caps).isServerSide(), "StorageService cannot be client-side"); } } @NonnullAfterInit StorageService getStorage(); void setStorage(@Nonnull final StorageService storageService); void setHttpClient(@Nonnull final HttpClient client); void setHttpClientSecurityParameters(@Nullable final HttpClientSecurityParameters params); @Override void doInitialize(); JWKSet fetch(@Nonnull final URI uri, final long expires); JWKSet fetch(@Nonnull @NotEmpty final String context, @Nonnull final URI uri, final long expires); static final String CONTEXT_NAME; }### Answer: @Test(expectedExceptions = ComponentInitializationException.class) public void testNoHttpClient() throws ComponentInitializationException { jwkSetCache.setStorage(storageService); jwkSetCache.initialize(); }
### Question: RemoteJwkSetCache extends AbstractIdentifiableInitializableComponent { public void setHttpClient(@Nonnull final HttpClient client) { ComponentSupport.ifInitializedThrowUnmodifiabledComponentException(this); ComponentSupport.ifDestroyedThrowDestroyedComponentException(this); httpClient = Constraint.isNotNull(client, "HttpClient cannot be null"); } @NonnullAfterInit StorageService getStorage(); void setStorage(@Nonnull final StorageService storageService); void setHttpClient(@Nonnull final HttpClient client); void setHttpClientSecurityParameters(@Nullable final HttpClientSecurityParameters params); @Override void doInitialize(); JWKSet fetch(@Nonnull final URI uri, final long expires); JWKSet fetch(@Nonnull @NotEmpty final String context, @Nonnull final URI uri, final long expires); static final String CONTEXT_NAME; }### Answer: @Test(expectedExceptions = ComponentInitializationException.class) public void testNoStorageService() throws ComponentInitializationException { jwkSetCache.setHttpClient(HttpClientBuilder.create().build()); jwkSetCache.initialize(); }
### Question: AbstractAuthenticationRequestLookupFunction implements ContextDataLookupFunction<ProfileRequestContext, T> { @Override @Nullable public T apply(@Nullable final ProfileRequestContext input) { if (input == null || input.getInboundMessageContext() == null || input.getOutboundMessageContext() == null) { return null; } Object message = input.getInboundMessageContext().getMessage(); if (message == null || !(message instanceof AuthenticationRequest)) { return null; } OIDCAuthenticationResponseContext ctx = input.getOutboundMessageContext().getSubcontext(OIDCAuthenticationResponseContext.class, false); if (ctx == null) { return null; } requestObject = ctx.getRequestObject(); return doLookup((AuthenticationRequest) message); } @Override @Nullable T apply(@Nullable final ProfileRequestContext input); }### Answer: @Test public void testOK() { Assert.assertEquals("OK", mock.apply(prc)); } @Test public void testNoInboundCtxts() { Assert.assertNull(mock.apply(null)); prc.setInboundMessageContext(null); Assert.assertNull(mock.apply(prc)); prc.setInboundMessageContext(msgCtx); msgCtx.setMessage(null); Assert.assertNull(mock.apply(prc)); } @Test public void testNoOutboundCtxts() { prc.setOutboundMessageContext(null); Assert.assertNull(mock.apply(prc)); prc.setOutboundMessageContext(new MessageContext()); Assert.assertNull(mock.apply(prc)); }
### Question: AbstractTokenRequestLookupFunction implements ContextDataLookupFunction<ProfileRequestContext, T> { @Override @Nullable public T apply(@Nullable final ProfileRequestContext input) { if (input == null || input.getInboundMessageContext() == null) { return null; } Object message = input.getInboundMessageContext().getMessage(); if (!(message instanceof TokenRequest)) { return null; } return doLookup((TokenRequest) message); } @Override @Nullable T apply(@Nullable final ProfileRequestContext input); }### Answer: @Test public void testOK() { Assert.assertEquals("OK", mock.apply(prc)); } @Test public void testNoInboundCtxts() { Assert.assertNull(mock.apply(null)); prc.setInboundMessageContext(null); Assert.assertNull(mock.apply(prc)); prc.setInboundMessageContext(msgCtx); msgCtx.setMessage(null); Assert.assertNull(mock.apply(prc)); }
### Question: OIDCRegistrationResponseContextLookupFunction implements ContextDataLookupFunction<ProfileRequestContext, OIDCClientRegistrationResponseContext> { @Override @Nullable public OIDCClientRegistrationResponseContext apply(@Nullable final ProfileRequestContext input) { if (input == null || input.getOutboundMessageContext() == null) { return null; } return input.getOutboundMessageContext().getSubcontext(OIDCClientRegistrationResponseContext.class, false); } @Override @Nullable OIDCClientRegistrationResponseContext apply(@Nullable final ProfileRequestContext input); }### Answer: @Test public void testSuccess() { Assert.assertNotNull(lookup.apply(prc)); } @SuppressWarnings("unchecked") @Test public void testNoInput() { Assert.assertNull(lookup.apply(null)); prc.getOutboundMessageContext().removeSubcontext(OIDCClientRegistrationResponseContext.class); Assert.assertNull(lookup.apply(prc)); prc.setOutboundMessageContext(null); Assert.assertNull(lookup.apply(prc)); }
### Question: DefaultUserInfoSigningAlgLookupFunction implements ContextDataLookupFunction<ProfileRequestContext, JWSAlgorithm> { @Override @Nullable public JWSAlgorithm apply(@Nullable final ProfileRequestContext input) { if (input == null || input.getInboundMessageContext() == null) { return null; } OIDCMetadataContext ctx = input.getInboundMessageContext().getSubcontext(OIDCMetadataContext.class, false); if (ctx == null || ctx.getClientInformation() == null || ctx.getClientInformation().getOIDCMetadata() == null) { return null; } return ctx.getClientInformation().getOIDCMetadata().getUserInfoJWSAlg(); } @Override @Nullable JWSAlgorithm apply(@Nullable final ProfileRequestContext input); }### Answer: @Test public void testSuccess() { Assert.assertEquals(JWSAlgorithm.ES256, lookup.apply(prc)); } @SuppressWarnings("unchecked") @Test public void testNoInput() { Assert.assertNull(lookup.apply(null)); ctx.setClientInformation(null); Assert.assertNull(lookup.apply(prc)); prc.getInboundMessageContext().removeSubcontext(OIDCMetadataContext.class); Assert.assertNull(lookup.apply(prc)); prc.setInboundMessageContext(null); Assert.assertNull(lookup.apply(prc)); }
### Question: UserInfoResponseClaimsSetLookupFunction implements ContextDataLookupFunction<ProfileRequestContext, ClaimsSet> { @Override @Nullable public ClaimsSet apply(@Nullable final ProfileRequestContext input) { if (input == null || input.getOutboundMessageContext() == null) { return null; } OIDCAuthenticationResponseContext ctx = input.getOutboundMessageContext().getSubcontext(OIDCAuthenticationResponseContext.class, false); if (ctx == null) { return null; } return ctx.getUserInfo(); } @Override @Nullable ClaimsSet apply(@Nullable final ProfileRequestContext input); }### Answer: @Test public void testSuccess() { Assert.assertEquals("sub", (String) lookup.apply(prc).getClaim("sub")); } @SuppressWarnings("unchecked") @Test public void testNoInput() { Assert.assertNull(lookup.apply(null)); oidcCtx.setUserInfo(null); Assert.assertNull(lookup.apply(prc)); prc.getOutboundMessageContext().removeSubcontext(OIDCAuthenticationResponseContext.class); Assert.assertNull(lookup.apply(prc)); prc.setOutboundMessageContext(null); Assert.assertNull(lookup.apply(prc)); }
### Question: DefaultClientIDLookupFunction implements ContextDataLookupFunction<MessageContext, ClientID> { @Override public ClientID apply(@Nullable MessageContext input) { if (input == null) { return null; } Object message = input.getMessage(); if (!(message instanceof AuthenticationRequest)) { return null; } return ((AuthenticationRequest) message).getClientID(); } @Override ClientID apply(@Nullable MessageContext input); }### Answer: @SuppressWarnings("unchecked") @Test public void testNullInput() { Assert.assertNull(lookup.apply(null)); ctx.setMessage(null); Assert.assertNull(lookup.apply(null)); } @Test public void testSuccess() { Assert.assertEquals(new ClientID("000123"), lookup.apply(ctx)); }
### Question: UserInfoRequestClientIDLookupFunction implements ContextDataLookupFunction<MessageContext, ClientID> { @Override public ClientID apply(@Nullable MessageContext input) { if (input == null) { return null; } if (!(input.getParent() instanceof ProfileRequestContext)) { return null; } MessageContext msgCtx = ((ProfileRequestContext) input.getParent()).getOutboundMessageContext(); if (msgCtx == null) { return null; } OIDCAuthenticationResponseContext ctx = msgCtx.getSubcontext(OIDCAuthenticationResponseContext.class, false); if (ctx == null || ctx.getTokenClaimsSet() == null) { return null; } return ctx.getTokenClaimsSet().getClientID(); } @Override ClientID apply(@Nullable MessageContext input); }### Answer: @SuppressWarnings({"unchecked", "rawtypes"}) @Test public void testNullInput() { lookup = new UserInfoRequestClientIDLookupFunction(); Assert.assertNull(lookup.apply(null)); oidcCtx.setTokenClaimsSet(null); Assert.assertNull(lookup.apply(prc.getInboundMessageContext())); prc.getOutboundMessageContext().removeSubcontext(OIDCAuthenticationResponseContext.class); oidcCtx.setTokenClaimsSet(null); Assert.assertNull(lookup.apply(prc.getInboundMessageContext())); prc.setInboundMessageContext(new MessageContext()); prc.setOutboundMessageContext(null); Assert.assertNull(lookup.apply(prc.getInboundMessageContext())); } @Test public void testSuccess() { lookup = new UserInfoRequestClientIDLookupFunction(); Assert.assertEquals(cliendID, lookup.apply(prc.getOutboundMessageContext())); }
### Question: DefaultValidRedirectUrisLookupFunction implements ContextDataLookupFunction<ProfileRequestContext, Set<URI>> { @Override @Nullable public Set<URI> apply(@Nullable final ProfileRequestContext input) { if (input == null || input.getInboundMessageContext() == null) { return null; } OIDCMetadataContext ctx = input.getInboundMessageContext().getSubcontext(OIDCMetadataContext.class, false); if (ctx == null || ctx.getClientInformation() == null || ctx.getClientInformation().getMetadata() == null) { return null; } return ctx.getClientInformation().getMetadata().getRedirectionURIs(); } @Override @Nullable Set<URI> apply(@Nullable final ProfileRequestContext input); }### Answer: @Test public void testSuccess() { Assert.assertNotNull(lookup.apply(prc)); } @SuppressWarnings("unchecked") @Test public void testNoInput() { Assert.assertNull(lookup.apply(null)); ctx.setClientInformation(null); Assert.assertNull(lookup.apply(prc)); prc.getInboundMessageContext().removeSubcontext(OIDCMetadataContext.class); Assert.assertNull(lookup.apply(prc)); prc.setInboundMessageContext(null); Assert.assertNull(lookup.apply(prc)); }
### Question: OIDCAuthenticationResponseContextLookupFunction implements ContextDataLookupFunction<ProfileRequestContext, OIDCAuthenticationResponseContext> { @Override @Nullable public OIDCAuthenticationResponseContext apply(@Nullable final ProfileRequestContext input) { if (input == null || input.getOutboundMessageContext() == null) { return null; } return input.getOutboundMessageContext().getSubcontext(OIDCAuthenticationResponseContext.class, false); } @Override @Nullable OIDCAuthenticationResponseContext apply(@Nullable final ProfileRequestContext input); }### Answer: @Test public void testSuccess() { Assert.assertNotNull(lookup.apply(prc)); } @SuppressWarnings("unchecked") @Test public void testNoInput() { Assert.assertNull(lookup.apply(null)); prc.getOutboundMessageContext().removeSubcontext(OIDCAuthenticationResponseContext.class); Assert.assertNull(lookup.apply(prc)); prc.setOutboundMessageContext(null); Assert.assertNull(lookup.apply(prc)); }
### Question: FilesystemMetadataValueResolver extends AbstractFileOIDCEntityResolver<Identifier, Object> implements RefreshableMetadataValueResolver { @Override public Object resolveSingle(ProfileRequestContext profileRequestContext) throws ResolverException { return resolve(profileRequestContext).iterator().next(); } FilesystemMetadataValueResolver(@Nonnull final Resource metadata); FilesystemMetadataValueResolver(@Nullable final Timer backgroundTaskTimer, @Nonnull final Resource metadata); @Override Iterable<Object> resolve(ProfileRequestContext profileRequestContext); @Override Object resolveSingle(ProfileRequestContext profileRequestContext); }### Answer: @Test public void testString() throws Exception { final FilesystemMetadataValueResolver resolver = initTests("/org/geant/idpextension/oidc/metadata/impl/dyn-value1.json"); final Object value = resolver.resolveSingle(null); Assert.assertNotNull(value); Assert.assertTrue(value instanceof String); Assert.assertEquals(value, "mockValue"); } @Test public void testJson() throws Exception { final FilesystemMetadataValueResolver resolver = initTests("/org/geant/idpextension/oidc/metadata/impl/dyn-value2.json"); final Object value = resolver.resolveSingle(null); Assert.assertNotNull(value); Assert.assertTrue(value instanceof JSONObject); final JSONObject jsonValue = (JSONObject) value; Assert.assertEquals(jsonValue.size(), 1); Assert.assertEquals(jsonValue.get("mockKey"), "mockValue"); }
### Question: DefaultResponseClaimsSetLookupFunction implements ContextDataLookupFunction<ProfileRequestContext, ClaimsSet> { @Override @Nullable public ClaimsSet apply(@Nullable final ProfileRequestContext input) { if (input == null || input.getOutboundMessageContext() == null) { return null; } OIDCAuthenticationResponseContext ctx = input.getOutboundMessageContext().getSubcontext(OIDCAuthenticationResponseContext.class, false); if (ctx == null) { return null; } return ctx.getIDToken(); } @Override @Nullable ClaimsSet apply(@Nullable final ProfileRequestContext input); }### Answer: @Test public void testSuccess() { Assert.assertEquals("sub", (String) lookup.apply(prc).getClaim("sub")); } @SuppressWarnings("unchecked") @Test public void testNoInput() { Assert.assertNull(lookup.apply(null)); oidcCtx.setIDToken(null); Assert.assertNull(lookup.apply(prc)); prc.getOutboundMessageContext().removeSubcontext(OIDCAuthenticationResponseContext.class); Assert.assertNull(lookup.apply(prc)); prc.setOutboundMessageContext(null); Assert.assertNull(lookup.apply(prc)); }
### Question: TokenRequestClientIDLookupFunction implements ContextDataLookupFunction<MessageContext, ClientID> { @Override public ClientID apply(@Nullable MessageContext input) { if (input == null) { return null; } Object message = input.getMessage(); if (!(message instanceof AbstractOptionallyAuthenticatedRequest)) { return null; } AbstractOptionallyAuthenticatedRequest req = (AbstractOptionallyAuthenticatedRequest) message; if (req.getClientAuthentication() != null && req.getClientAuthentication().getClientID() != null) { return req.getClientAuthentication().getClientID(); } if (!(message instanceof AbstractOptionallyIdentifiedRequest)) { return null; } return ((AbstractOptionallyIdentifiedRequest) req).getClientID(); } @Override ClientID apply(@Nullable MessageContext input); }### Answer: @SuppressWarnings("unchecked") @Test public void testNullInput() { Assert.assertNull(lookup.apply(null)); ctx.setMessage(new String("totallynotmessage")); Assert.assertNull(lookup.apply(null)); ctx.setMessage(null); Assert.assertNull(lookup.apply(null)); } @Test public void testSuccess() { Assert.assertEquals(new ClientID("clientId"), lookup.apply(ctx)); }
### Question: ValidatedRedirectURILookupFunction implements ContextDataLookupFunction<ProfileRequestContext, URI> { @Override @Nullable public URI apply(@Nullable final ProfileRequestContext input) { if (input == null || input.getOutboundMessageContext() == null) { return null; } OIDCAuthenticationResponseContext ctx = input.getOutboundMessageContext().getSubcontext(OIDCAuthenticationResponseContext.class, false); if (ctx == null) { return null; } return ctx.getRedirectURI(); } @Override @Nullable URI apply(@Nullable final ProfileRequestContext input); }### Answer: @SuppressWarnings("unchecked") @Test public void testNoInput() { Assert.assertNull(lookup.apply(null)); oidcCtx.setRedirectURI(null); Assert.assertNull(lookup.apply(prc)); prc.getOutboundMessageContext().removeSubcontext(OIDCAuthenticationResponseContext.class); Assert.assertNull(lookup.apply(prc)); prc.setOutboundMessageContext(null); Assert.assertNull(lookup.apply(prc)); } @Test public void testSuccess() throws URISyntaxException { Assert.assertEquals(new URI("http: }
### Question: DefaultAuthTimeLookupFunction implements ContextDataLookupFunction<ProfileRequestContext, Long> { @Override @Nullable public Long apply(@Nullable final ProfileRequestContext input) { if (input == null) { return null; } AuthenticationContext authCtx = input.getSubcontext(AuthenticationContext.class, false); if (authCtx == null) { return null; } AuthenticationResult authResult = authCtx.getAuthenticationResult(); if (authResult == null) { return null; } return authResult.getAuthenticationInstant(); } @Override @Nullable Long apply(@Nullable final ProfileRequestContext input); }### Answer: @Test public void testSuccess() { Assert.assertEquals(instant.getTime(), (long) lookup.apply(prc)); } @Test public void testNoCtxts() { Assert.assertNull(lookup.apply(null)); authCtx.setAuthenticationResult(null); Assert.assertNull(lookup.apply(prc)); prc.removeSubcontext(AuthenticationContext.class); Assert.assertNull(lookup.apply(prc)); }
### Question: ProfileResponderIdLookupFunction extends AbstractIdentifiableInitializableComponent implements ContextDataLookupFunction<ProfileRequestContext, String> { @Override @Nullable public String apply(@Nullable final ProfileRequestContext input) { if (profileResponders.containsKey(input.getProfileId())) { return profileResponders.get(input.getProfileId()); } return defaultResponder; } void setDefaultResponder(@Nonnull String resp); void setProfileResponders(@Nullable Map<ProfileConfiguration, String> resp); @Override @Nullable String apply(@Nullable final ProfileRequestContext input); }### Answer: @Test public void testSuccess() throws ComponentInitializationException { prc.setProfileId("unknown"); Assert.assertEquals(lookup.apply(prc), "defaultvalue"); prc.setProfileId("id1"); Assert.assertEquals(lookup.apply(prc), "value1"); prc.setProfileId("id2"); Assert.assertEquals(lookup.apply(prc), "value2"); }
### Question: AbstractTokenClaimsLookupFunction implements ContextDataLookupFunction<ProfileRequestContext, T> { @Override @Nullable public T apply(@Nullable final ProfileRequestContext input) { if (input == null || input.getOutboundMessageContext() == null) { return null; } OIDCAuthenticationResponseContext oidcResponseContext = input.getOutboundMessageContext().getSubcontext(OIDCAuthenticationResponseContext.class, false); if (oidcResponseContext == null) { return null; } TokenClaimsSet tokenClaims = oidcResponseContext.getTokenClaimsSet(); if (tokenClaims == null) { return null; } return doLookup(tokenClaims); } @Override @Nullable T apply(@Nullable final ProfileRequestContext input); }### Answer: @Test public void testSubjectSuccess() { Assert.assertEquals("subject", mock.apply(prc)); } @Test public void testNoCtxts() { Assert.assertNull(mock.apply(null)); prc.setOutboundMessageContext(null); Assert.assertNull(mock.apply(prc)); prc.setOutboundMessageContext(new MessageContext()); Assert.assertNull(mock.apply(prc)); prc.getOutboundMessageContext().addSubcontext(new OIDCAuthenticationResponseContext()); Assert.assertNull(mock.apply(prc)); }
### Question: DefaultOIDCMetadataContextLookupFunction implements ContextDataLookupFunction<ProfileRequestContext, OIDCMetadataContext> { @Override @Nullable public OIDCMetadataContext apply(@Nullable final ProfileRequestContext input) { if (input == null || input.getInboundMessageContext() == null) { return null; } return input.getInboundMessageContext().getSubcontext(OIDCMetadataContext.class, false); } @Override @Nullable OIDCMetadataContext apply(@Nullable final ProfileRequestContext input); }### Answer: @Test public void testSuccess() { OIDCMetadataContext ctx = lookup.apply(prc); Assert.assertNotNull(ctx); } @Test public void testNoMetadataCtx() { prc.getInboundMessageContext().removeSubcontext(OIDCMetadataContext.class); Assert.assertNull(lookup.apply(prc)); } @SuppressWarnings("unchecked") @Test public void testNoMessageCtx() { prc.setInboundMessageContext(null); Assert.assertNull(lookup.apply(prc)); } @Test public void testNoPrc() { Assert.assertNull(lookup.apply(null)); }
### Question: RevocationCache extends AbstractIdentifiableInitializableComponent { public void setStorage(@Nonnull final StorageService storageService) { ComponentSupport.ifInitializedThrowUnmodifiabledComponentException(this); storage = Constraint.isNotNull(storageService, "StorageService cannot be null"); final StorageCapabilities caps = storage.getCapabilities(); if (caps instanceof StorageCapabilitiesEx) { Constraint.isTrue(((StorageCapabilitiesEx) caps).isServerSide(), "StorageService cannot be client-side"); } } RevocationCache(); @Duration void setEntryExpiration(@Positive @Duration final long entryExpiration); @NonnullAfterInit StorageService getStorage(); void setStorage(@Nonnull final StorageService storageService); boolean isStrict(); void setStrict(final boolean flag); @Override void doInitialize(); @SuppressWarnings("rawtypes") synchronized boolean revoke(@Nonnull @NotEmpty final String context, @Nonnull @NotEmpty final String s); @SuppressWarnings("rawtypes") synchronized boolean isRevoked(@Nonnull @NotEmpty final String context, @Nonnull @NotEmpty final String s); }### Answer: @Test public void testInit() { revocationCache = new RevocationCache(); try { revocationCache.setStorage(null); Assert.fail("Null StorageService should have caused constraint violation"); } catch (Exception e) { } try { revocationCache.setStorage(new ClientStorageService()); Assert.fail("ClientStorageService should have caused constraint violation"); } catch (Exception e) { } }
### Question: RevocationCache extends AbstractIdentifiableInitializableComponent { @Duration public void setEntryExpiration(@Positive @Duration final long entryExpiration) { expires = Constraint.isGreaterThan(0, entryExpiration, "revocation cache entry expiration must be greater than 0"); } RevocationCache(); @Duration void setEntryExpiration(@Positive @Duration final long entryExpiration); @NonnullAfterInit StorageService getStorage(); void setStorage(@Nonnull final StorageService storageService); boolean isStrict(); void setStrict(final boolean flag); @Override void doInitialize(); @SuppressWarnings("rawtypes") synchronized boolean revoke(@Nonnull @NotEmpty final String context, @Nonnull @NotEmpty final String s); @SuppressWarnings("rawtypes") synchronized boolean isRevoked(@Nonnull @NotEmpty final String context, @Nonnull @NotEmpty final String s); }### Answer: @Test (expectedExceptions = ConstraintViolationException.class) public void testExpirationSetter() throws ComponentInitializationException { revocationCache.setEntryExpiration(0); }
### Question: RevocationCache extends AbstractIdentifiableInitializableComponent { @NonnullAfterInit public StorageService getStorage() { return storage; } RevocationCache(); @Duration void setEntryExpiration(@Positive @Duration final long entryExpiration); @NonnullAfterInit StorageService getStorage(); void setStorage(@Nonnull final StorageService storageService); boolean isStrict(); void setStrict(final boolean flag); @Override void doInitialize(); @SuppressWarnings("rawtypes") synchronized boolean revoke(@Nonnull @NotEmpty final String context, @Nonnull @NotEmpty final String s); @SuppressWarnings("rawtypes") synchronized boolean isRevoked(@Nonnull @NotEmpty final String context, @Nonnull @NotEmpty final String s); }### Answer: @Test public void testStorageGetter() throws ComponentInitializationException { Assert.assertEquals(storageService, revocationCache.getStorage()); }
### Question: JSONSuccessResponse implements SuccessResponse { @Override public HTTPResponse toHTTPResponse() { HTTPResponse httpResponse = new HTTPResponse(HTTPResponse.SC_OK); httpResponse.setContentType(CommonContentTypes.APPLICATION_JSON); if (cacheControl != null) { httpResponse.setCacheControl(cacheControl); } if (pragma != null) { httpResponse.setPragma(pragma); } httpResponse.setContent(content.toJSONString()); return httpResponse; } JSONSuccessResponse(@Nonnull JSONObject contentObject); JSONSuccessResponse(@Nonnull JSONObject contentObject, String cacheControlValue, String pragmaValue); @Override boolean indicatesSuccess(); @Override HTTPResponse toHTTPResponse(); }### Answer: @Test public void testSuccess() throws ParseException { response = new JSONSuccessResponse(content, "no-store", "no-cache"); HTTPResponse httpResponse = response.toHTTPResponse(); Assert.assertEquals(HTTPResponse.SC_OK, httpResponse.getStatusCode()); Assert.assertEquals("application/json; charset=UTF-8", httpResponse.getContentType().toString()); Assert.assertEquals("no-store", httpResponse.getCacheControl()); Assert.assertEquals("no-cache", httpResponse.getPragma()); JSONObject parsedContent = (JSONObject) new JSONParser(JSONParser.MODE_PERMISSIVE).parse(httpResponse.getContent()); Assert.assertEquals(content.get("field1"), parsedContent.get("field1")); Assert.assertEquals(content.get("field2"), parsedContent.get("field2")); } @Test public void testSuccess2() throws ParseException { response = new JSONSuccessResponse(content); HTTPResponse httpResponse = response.toHTTPResponse(); Assert.assertEquals(HTTPResponse.SC_OK, httpResponse.getStatusCode()); Assert.assertEquals("application/json; charset=UTF-8", httpResponse.getContentType().toString()); Assert.assertNull(httpResponse.getCacheControl()); Assert.assertNull(httpResponse.getPragma()); JSONObject parsedContent = (JSONObject) new JSONParser(JSONParser.MODE_PERMISSIVE).parse(httpResponse.getContent()); Assert.assertEquals(content.get("field1"), parsedContent.get("field1")); Assert.assertEquals(content.get("field2"), parsedContent.get("field2")); }
### Question: StorageServiceClientInformationManager extends BaseStorageServiceClientInformationComponent implements ClientInformationManager { @Override public void storeClientInformation(final OIDCClientInformation clientInformation, final Long expiration) throws ClientInformationManagerException { log.debug("Attempting to store client information"); final String clientId = clientInformation.getID().getValue(); final String serialized = clientInformation.toJSONObject().toJSONString(); try { getStorageService().create(CONTEXT_NAME, clientId, serialized, expiration); } catch (IOException e) { log.error("Could not store the client information", e); throw new ClientInformationManagerException("Could not store the client information", e); } log.info("Successfully stored the client information for id {}", clientId); } StorageServiceClientInformationManager(); @Override void storeClientInformation(final OIDCClientInformation clientInformation, final Long expiration); @Override void destroyClientInformation(ClientID clientId); }### Answer: @Test public void testStore() throws Exception { final OIDCClientInformation clientInformation = initializeInformation(); manager.storeClientInformation(clientInformation, null); final CriteriaSet criteria = initializeCriteria(); final OIDCClientInformation result = resolver.resolveSingle(criteria); Assert.assertNotNull(result); Assert.assertEquals(result.getID().getValue(), clientIdValue); } @Test public void testExpiration() throws Exception { final OIDCClientInformation clientInformation = initializeInformation(); manager.storeClientInformation(clientInformation, System.currentTimeMillis() + new Long(2000)); final CriteriaSet criteria = initializeCriteria(); final OIDCClientInformation result = resolver.resolveSingle(criteria); Assert.assertNotNull(result); Assert.assertEquals(result.getID().getValue(), clientIdValue); Thread.sleep(2100); final OIDCClientInformation delayedResult = resolver.resolveSingle(criteria); Assert.assertNull(delayedResult); }
### Question: AuthenticationContextClassReferencePrincipal implements CloneablePrincipal { @Override public AuthenticationContextClassReferencePrincipal clone() throws CloneNotSupportedException { final AuthenticationContextClassReferencePrincipal copy = (AuthenticationContextClassReferencePrincipal) super.clone(); copy.authnContextClassReference = authnContextClassReference; return copy; } AuthenticationContextClassReferencePrincipal( @Nonnull @NotEmpty @ParameterName(name = "classRef") final String classRef); @Override @Nonnull @NotEmpty String getName(); @Override int hashCode(); @Override boolean equals(final Object other); @Override String toString(); @Override AuthenticationContextClassReferencePrincipal clone(); static final String UNSPECIFIED; }### Answer: @Test public void testClone() throws CloneNotSupportedException { Assert.assertEquals(principal, principal.clone()); }
### Question: SubjectActivationCondition implements Predicate<ProfileRequestContext> { @Override public boolean apply(ProfileRequestContext input) { final MessageContext outboundMessageCtx = input.getOutboundMessageContext(); if (outboundMessageCtx == null) { return true; } OIDCAuthenticationResponseContext oidcResponseContext = outboundMessageCtx.getSubcontext(OIDCAuthenticationResponseContext.class, false); if (oidcResponseContext == null) { return true; } return oidcResponseContext.getSubject() == null; } @Override boolean apply(ProfileRequestContext input); }### Answer: @Test public void testSubjectExists() { Assert.assertFalse(lookup.apply(prc)); } @Test public void testNoSubject() { respCtx.setSubject(null); Assert.assertTrue(lookup.apply(prc)); } @Test public void testNoOIDCResponseCtx() { prc.getOutboundMessageContext().removeSubcontext(OIDCAuthenticationResponseContext.class); Assert.assertTrue(lookup.apply(prc)); } @SuppressWarnings("unchecked") @Test public void testNoOutboundCtx() { prc.setOutboundMessageContext(null); Assert.assertTrue(lookup.apply(prc)); }
### Question: AuthenticationContextClassReferencePrincipal implements CloneablePrincipal { @Override public String toString() { return MoreObjects.toStringHelper(this).add("authnContextClassReference", authnContextClassReference) .toString(); } AuthenticationContextClassReferencePrincipal( @Nonnull @NotEmpty @ParameterName(name = "classRef") final String classRef); @Override @Nonnull @NotEmpty String getName(); @Override int hashCode(); @Override boolean equals(final Object other); @Override String toString(); @Override AuthenticationContextClassReferencePrincipal clone(); static final String UNSPECIFIED; }### Answer: @Test public void testToString() { Assert.assertEquals(principal.toString(), "AuthenticationContextClassReferencePrincipal{authnContextClassReference=" + principal.getName() + "}"); }
### Question: AttributeResolutionSubjectLookupFunction extends AbstractIdentifiableInitializableComponent implements ContextDataLookupFunction<ProfileRequestContext, String> { public void setAttributeContextLookupStrategy( @Nonnull final Function<ProfileRequestContext, AttributeContext> strategy) { ComponentSupport.ifInitializedThrowUnmodifiabledComponentException(this); attributeContextLookupStrategy = Constraint.isNotNull(strategy, "AttributeContext lookup strategy cannot be null"); } AttributeResolutionSubjectLookupFunction(); void setAttributeContextLookupStrategy( @Nonnull final Function<ProfileRequestContext, AttributeContext> strategy); @Override @Nullable String apply(@Nullable final ProfileRequestContext input); }### Answer: @Test(expectedExceptions = ConstraintViolationException.class) public void testFailNullStrategy() throws ComponentInitializationException { lookup = new AttributeResolutionSubjectLookupFunction(); lookup.setAttributeContextLookupStrategy(null); }
### Question: EncodeMessage extends AbstractProfileAction { public void setMessageEncoderFactory(@Nonnull final MessageEncoderFactory factory) { encoderFactory = Constraint.isNotNull(factory, "MessageEncoderFactory cannot be null"); } void setMessageEncoderFactory(@Nonnull final MessageEncoderFactory factory); void setMessageEncoder(@Nonnull final MessageEncoder enc); void setMessageHandler(@Nullable final MessageHandler handler); }### Answer: @SuppressWarnings("unchecked") @Test public void testDecodeMessage() throws Exception { EncodeMessage action = new EncodeMessage(); action.setMessageEncoderFactory(new MockEncoderFactory()); action.initialize(); action.execute(profileCtx); ActionTestingSupport.assertProceedEvent(profileCtx); Assert.assertEquals(encoder.getEncodedMessage(), expectedMessage); } @SuppressWarnings("unchecked") @Test public void testThrowException() throws Exception { encoder.setThrowException(true); EncodeMessage action = new EncodeMessage(); action.setMessageEncoderFactory(new MockEncoderFactory()); action.initialize(); action.execute(profileCtx); ActionTestingSupport.assertEvent(profileCtx, EventIds.UNABLE_TO_ENCODE); }
### Question: SetSectorIdentifierForAttributeResolution extends AbstractOIDCAuthenticationRequestAction { public void setSectorIdentifierLookupStrategy(@Nonnull final Function<ProfileRequestContext, String> strategy) { ComponentSupport.ifInitializedThrowUnmodifiabledComponentException(this); sectorIdentifierLookupStrategy = Constraint.isNotNull(strategy, "SectorIdentifierLookupStrategy lookup strategy cannot be null"); } SetSectorIdentifierForAttributeResolution(); void setSectorIdentifierLookupStrategy(@Nonnull final Function<ProfileRequestContext, String> strategy); void setSubjectTypeLookupStrategy(@Nonnull final Function<ProfileRequestContext, SubjectType> strategy); }### Answer: @Test(expectedExceptions = ConstraintViolationException.class) public void testNullStrategySectorIdentifier() { action = new SetSectorIdentifierForAttributeResolution(); action.setSectorIdentifierLookupStrategy(null); }
### Question: SetSectorIdentifierForAttributeResolution extends AbstractOIDCAuthenticationRequestAction { public void setSubjectTypeLookupStrategy(@Nonnull final Function<ProfileRequestContext, SubjectType> strategy) { ComponentSupport.ifInitializedThrowUnmodifiabledComponentException(this); subjectTypeLookupStrategy = Constraint.isNotNull(strategy, "SubjectTypeLookupStrategy lookup strategy cannot be null"); } SetSectorIdentifierForAttributeResolution(); void setSectorIdentifierLookupStrategy(@Nonnull final Function<ProfileRequestContext, String> strategy); void setSubjectTypeLookupStrategy(@Nonnull final Function<ProfileRequestContext, SubjectType> strategy); }### Answer: @Test(expectedExceptions = ConstraintViolationException.class) public void testNullStrategySubjectType() { action = new SetSectorIdentifierForAttributeResolution(); action.setSubjectTypeLookupStrategy(null); }
### Question: RevokeConsent extends AbstractOIDCResponseAction { public void setPromptLookupStrategy(@Nonnull final Function<ProfileRequestContext, Prompt> strategy) { ComponentSupport.ifInitializedThrowUnmodifiabledComponentException(this); promptLookupStrategy = Constraint.isNotNull(strategy, "PromptLookupStrategy lookup strategy cannot be null"); } RevokeConsent(); void setPromptLookupStrategy(@Nonnull final Function<ProfileRequestContext, Prompt> strategy); }### Answer: @Test(expectedExceptions = ConstraintViolationException.class) public void testNullStrategy() throws NoSuchAlgorithmException, ComponentInitializationException { action = new RevokeConsent(); action.setPromptLookupStrategy(null); }
### Question: OIDCClientInformationEncryptionParametersResolver extends BasicEncryptionParametersResolver { @Override @Nullable public EncryptionParameters resolveSingle(@Nonnull final CriteriaSet criteria) throws ResolverException { Constraint.isNotNull(criteria, "CriteriaSet was null"); Constraint.isNotNull(criteria.get(EncryptionConfigurationCriterion.class), "Resolver requires an instance of EncryptionConfigurationCriterion"); final Predicate<String> whitelistBlacklistPredicate = getWhitelistBlacklistPredicate(criteria); final EncryptionParameters params = (target == ParameterType.REQUEST_OBJECT_DECRYPTION) ? new OIDCDecryptionParameters() : new EncryptionParameters(); resolveAndPopulateCredentialsAndAlgorithms(params, criteria, whitelistBlacklistPredicate); boolean encryptionOptional = false; final EncryptionOptionalCriterion encryptionOptionalCrit = criteria.get(EncryptionOptionalCriterion.class); if (encryptionOptionalCrit != null) { encryptionOptional = encryptionOptionalCrit.isEncryptionOptional(); } if (validate(params, encryptionOptional)) { logResult(params); return params; } else { return null; } } void setParameterType(ParameterType value); @Override @Nullable EncryptionParameters resolveSingle(@Nonnull final CriteriaSet criteria); }### Answer: @Test public void testIdTokenParameters() throws ResolverException { EncryptionParameters params = resolver.resolveSingle(criteria); Assert.assertEquals("RSA-OAEP-256", params.getKeyTransportEncryptionAlgorithm()); Assert.assertEquals("A192CBC-HS384", params.getDataEncryptionAlgorithm()); Assert.assertNotNull(params.getKeyTransportEncryptionCredential().getPublicKey()); } @Test public void testIdTokenParametersDefaultEnc() throws ResolverException { metaData.setIDTokenJWEEnc(null); EncryptionParameters params = resolver.resolveSingle(criteria); Assert.assertEquals("RSA-OAEP-256", params.getKeyTransportEncryptionAlgorithm()); Assert.assertEquals("A128CBC-HS256", params.getDataEncryptionAlgorithm()); Assert.assertNotNull(params.getKeyTransportEncryptionCredential().getPublicKey()); }
### Question: InitializeAuthenticationContext extends AbstractOIDCAuthenticationRequestAction { public void setLoginHintLookupStrategy(@Nonnull final Function<ProfileRequestContext, String> strategy) { ComponentSupport.ifInitializedThrowUnmodifiabledComponentException(this); loginHintLookupStrategy = Constraint.isNotNull(strategy, "LoginHintLookupStrategy lookup strategy cannot be null"); } InitializeAuthenticationContext(); void setPromptLookupStrategy(@Nonnull final Function<ProfileRequestContext, Prompt> strategy); void setLoginHintLookupStrategy(@Nonnull final Function<ProfileRequestContext, String> strategy); void setMaxAgeLookupStrategy(@Nonnull final Function<ProfileRequestContext, Long> strategy); }### Answer: @Test(expectedExceptions = ConstraintViolationException.class) public void testSetNullLoginHintLookupStrategy() throws Exception { action = new InitializeAuthenticationContext(); action.setLoginHintLookupStrategy(null); }
### Question: InitializeAuthenticationContext extends AbstractOIDCAuthenticationRequestAction { public void setPromptLookupStrategy(@Nonnull final Function<ProfileRequestContext, Prompt> strategy) { ComponentSupport.ifInitializedThrowUnmodifiabledComponentException(this); promptLookupStrategy = Constraint.isNotNull(strategy, "PromptLookupStrategy lookup strategy cannot be null"); } InitializeAuthenticationContext(); void setPromptLookupStrategy(@Nonnull final Function<ProfileRequestContext, Prompt> strategy); void setLoginHintLookupStrategy(@Nonnull final Function<ProfileRequestContext, String> strategy); void setMaxAgeLookupStrategy(@Nonnull final Function<ProfileRequestContext, Long> strategy); }### Answer: @Test(expectedExceptions = ConstraintViolationException.class) public void testSetNullPromptLookupStrategy() throws Exception { action = new InitializeAuthenticationContext(); action.setPromptLookupStrategy(null); }
### Question: InitializeAuthenticationContext extends AbstractOIDCAuthenticationRequestAction { public void setMaxAgeLookupStrategy(@Nonnull final Function<ProfileRequestContext, Long> strategy) { ComponentSupport.ifInitializedThrowUnmodifiabledComponentException(this); maxAgeLookupStrategy = Constraint.isNotNull(strategy, "MaxAgeLookupStrategy lookup strategy cannot be null"); } InitializeAuthenticationContext(); void setPromptLookupStrategy(@Nonnull final Function<ProfileRequestContext, Prompt> strategy); void setLoginHintLookupStrategy(@Nonnull final Function<ProfileRequestContext, String> strategy); void setMaxAgeLookupStrategy(@Nonnull final Function<ProfileRequestContext, Long> strategy); }### Answer: @Test(expectedExceptions = ConstraintViolationException.class) public void testSetNullMaxAgeLookupStrategy() throws Exception { action = new InitializeAuthenticationContext(); action.setMaxAgeLookupStrategy(null); }
### Question: EncryptProcessedToken extends AbstractOIDCResponseAction { public void setEncryptionContextLookupStrategy( @Nonnull final Function<ProfileRequestContext, EncryptionContext> strategy) { ComponentSupport.ifInitializedThrowUnmodifiabledComponentException(this); encryptionContextLookupStrategy = Constraint.isNotNull(strategy, "EncryptionContext lookup strategy cannot be null"); } EncryptProcessedToken(); void setEncryptionContextLookupStrategy( @Nonnull final Function<ProfileRequestContext, EncryptionContext> strategy); }### Answer: @SuppressWarnings("rawtypes") @Test(expectedExceptions = UnmodifiableComponentException.class) public void testInitializationFail() { action.setEncryptionContextLookupStrategy( Functions.compose(new ChildContextLookup<>(EncryptionContext.class, false), new ChildContextLookup<ProfileRequestContext, RelyingPartyContext>(RelyingPartyContext.class))); } @Test(expectedExceptions = ConstraintViolationException.class) public void testInitializationFail2() { action = new EncryptProcessedToken(); action.setEncryptionContextLookupStrategy(null); }
### Question: SetTokenDeliveryAttributesFromTokenToResponseContext extends AbstractOIDCResponseAction { public void setDeliveryClaimsLookupStrategy(@Nonnull final Function<ProfileRequestContext, ClaimsSet> strategy) { ComponentSupport.ifInitializedThrowUnmodifiabledComponentException(this); deliveryClaimsLookupStrategy = Constraint.isNotNull(strategy, "DeliveryClaimsLookupStrategy lookup strategy cannot be null"); } SetTokenDeliveryAttributesFromTokenToResponseContext(); void setDeliveryClaimsLookupStrategy(@Nonnull final Function<ProfileRequestContext, ClaimsSet> strategy); void setIDTokenDeliveryClaimsLookupStrategy( @Nullable final Function<ProfileRequestContext, ClaimsSet> strategy); void setUserinfoDeliveryClaimsLookupStrategy( @Nullable final Function<ProfileRequestContext, ClaimsSet> strategy); }### Answer: @Test(expectedExceptions = ConstraintViolationException.class) public void testNullStrategyDClaims() { action = new SetTokenDeliveryAttributesFromTokenToResponseContext(); action.setDeliveryClaimsLookupStrategy(null); }
### Question: SetTokenDeliveryAttributesFromTokenToResponseContext extends AbstractOIDCResponseAction { public void setIDTokenDeliveryClaimsLookupStrategy( @Nullable final Function<ProfileRequestContext, ClaimsSet> strategy) { ComponentSupport.ifInitializedThrowUnmodifiabledComponentException(this); idTokenDeliveryClaimsLookupStrategy = strategy; } SetTokenDeliveryAttributesFromTokenToResponseContext(); void setDeliveryClaimsLookupStrategy(@Nonnull final Function<ProfileRequestContext, ClaimsSet> strategy); void setIDTokenDeliveryClaimsLookupStrategy( @Nullable final Function<ProfileRequestContext, ClaimsSet> strategy); void setUserinfoDeliveryClaimsLookupStrategy( @Nullable final Function<ProfileRequestContext, ClaimsSet> strategy); }### Answer: @Test public void testNullStrategyIDTokenDClaims() throws ComponentInitializationException, URISyntaxException { init(); action = new SetTokenDeliveryAttributesFromTokenToResponseContext(); action.setIDTokenDeliveryClaimsLookupStrategy(null); action.initialize(); final Event event = action.execute(requestCtx); ActionTestingSupport.assertProceedEvent(event); OIDCAuthenticationResponseTokenClaimsContext respTokenClaims = respCtx.getSubcontext(OIDCAuthenticationResponseTokenClaimsContext.class); Assert.assertNotNull(respTokenClaims); Assert.assertEquals(respTokenClaims.getUserinfoClaims().getClaim("deliveryClaimUI"), "deliveryClaimUIValue"); Assert.assertNull(respTokenClaims.getIdtokenClaims().getClaim("deliveryClaimID")); Assert.assertEquals(respTokenClaims.getClaims().getClaim("deliveryClaim"), "deliveryClaimValue"); }
### Question: SetTokenDeliveryAttributesFromTokenToResponseContext extends AbstractOIDCResponseAction { public void setUserinfoDeliveryClaimsLookupStrategy( @Nullable final Function<ProfileRequestContext, ClaimsSet> strategy) { ComponentSupport.ifInitializedThrowUnmodifiabledComponentException(this); userinfoDeliveryClaimsLookupStrategy = strategy; } SetTokenDeliveryAttributesFromTokenToResponseContext(); void setDeliveryClaimsLookupStrategy(@Nonnull final Function<ProfileRequestContext, ClaimsSet> strategy); void setIDTokenDeliveryClaimsLookupStrategy( @Nullable final Function<ProfileRequestContext, ClaimsSet> strategy); void setUserinfoDeliveryClaimsLookupStrategy( @Nullable final Function<ProfileRequestContext, ClaimsSet> strategy); }### Answer: @Test public void testNullStrategyUIDClaims() throws ComponentInitializationException, URISyntaxException { init(); action = new SetTokenDeliveryAttributesFromTokenToResponseContext(); action.setUserinfoDeliveryClaimsLookupStrategy(null); action.initialize(); final Event event = action.execute(requestCtx); ActionTestingSupport.assertProceedEvent(event); OIDCAuthenticationResponseTokenClaimsContext respTokenClaims = respCtx.getSubcontext(OIDCAuthenticationResponseTokenClaimsContext.class); Assert.assertNotNull(respTokenClaims); Assert.assertNull(respTokenClaims.getUserinfoClaims().getClaim("deliveryClaimUI")); Assert.assertEquals(respTokenClaims.getIdtokenClaims().getClaim("deliveryClaimID"), "deliveryClaimIDValue"); Assert.assertEquals(respTokenClaims.getClaims().getClaim("deliveryClaim"), "deliveryClaimValue"); }
### Question: InitializeUnverifiedRelyingPartyContext extends AbstractProfileAction { public void setRelyingPartyContextCreationStrategy( @Nonnull final Function<ProfileRequestContext, RelyingPartyContext> strategy) { ComponentSupport.ifInitializedThrowUnmodifiabledComponentException(this); relyingPartyContextCreationStrategy = Constraint.isNotNull(strategy, "RelyingPartyContext creation strategy cannot be null"); } InitializeUnverifiedRelyingPartyContext(); void setRelyingPartyContextCreationStrategy( @Nonnull final Function<ProfileRequestContext, RelyingPartyContext> strategy); }### Answer: @Test(expectedExceptions = ConstraintViolationException.class) public void testFailsNullRelyingPartyContextCreationStrategy() { action = new InitializeUnverifiedRelyingPartyContext(); action.setRelyingPartyContextCreationStrategy(null); }
### Question: PopulateOIDCEncryptionParameters extends AbstractProfileAction { public void setConfigurationLookupStrategy( @Nonnull final Function<ProfileRequestContext, List<EncryptionConfiguration>> strategy) { ComponentSupport.ifInitializedThrowUnmodifiabledComponentException(this); configurationLookupStrategy = Constraint.isNotNull(strategy, "EncryptionConfiguration lookup strategy cannot be null"); } PopulateOIDCEncryptionParameters(); void setForDecryption(boolean value); void setEncryptionContextLookupStrategy( @Nonnull final Function<ProfileRequestContext, EncryptionContext> strategy); void setOIDCMetadataContextContextLookupStrategy( @Nonnull final Function<ProfileRequestContext, OIDCMetadataContext> strategy); void setConfigurationLookupStrategy( @Nonnull final Function<ProfileRequestContext, List<EncryptionConfiguration>> strategy); void setEncryptionParametersResolver(@Nonnull final EncryptionParametersResolver newResolver); }### Answer: @Test(expectedExceptions = ConstraintViolationException.class) public void testFailureNullStrategyConf() { action = new PopulateOIDCEncryptionParameters(); action.setConfigurationLookupStrategy(null); }
### Question: PopulateOIDCEncryptionParameters extends AbstractProfileAction { public void setEncryptionContextLookupStrategy( @Nonnull final Function<ProfileRequestContext, EncryptionContext> strategy) { ComponentSupport.ifInitializedThrowUnmodifiabledComponentException(this); encryptionContextLookupStrategy = Constraint.isNotNull(strategy, "EncryptionContext lookup strategy cannot be null"); } PopulateOIDCEncryptionParameters(); void setForDecryption(boolean value); void setEncryptionContextLookupStrategy( @Nonnull final Function<ProfileRequestContext, EncryptionContext> strategy); void setOIDCMetadataContextContextLookupStrategy( @Nonnull final Function<ProfileRequestContext, OIDCMetadataContext> strategy); void setConfigurationLookupStrategy( @Nonnull final Function<ProfileRequestContext, List<EncryptionConfiguration>> strategy); void setEncryptionParametersResolver(@Nonnull final EncryptionParametersResolver newResolver); }### Answer: @Test(expectedExceptions = ConstraintViolationException.class) public void testFailureNullStrategyEncrContext() { action = new PopulateOIDCEncryptionParameters(); action.setEncryptionContextLookupStrategy(null); }
### Question: PopulateOIDCEncryptionParameters extends AbstractProfileAction { public void setOIDCMetadataContextContextLookupStrategy( @Nonnull final Function<ProfileRequestContext, OIDCMetadataContext> strategy) { ComponentSupport.ifInitializedThrowUnmodifiabledComponentException(this); oidcMetadataContextLookupStrategy = Constraint.isNotNull(strategy, " OIDCMetadataContext lookup strategy cannot be null"); } PopulateOIDCEncryptionParameters(); void setForDecryption(boolean value); void setEncryptionContextLookupStrategy( @Nonnull final Function<ProfileRequestContext, EncryptionContext> strategy); void setOIDCMetadataContextContextLookupStrategy( @Nonnull final Function<ProfileRequestContext, OIDCMetadataContext> strategy); void setConfigurationLookupStrategy( @Nonnull final Function<ProfileRequestContext, List<EncryptionConfiguration>> strategy); void setEncryptionParametersResolver(@Nonnull final EncryptionParametersResolver newResolver); }### Answer: @Test(expectedExceptions = ConstraintViolationException.class) public void testFailureNullStrategyMetadataContext() { action = new PopulateOIDCEncryptionParameters(); action.setOIDCMetadataContextContextLookupStrategy(null); }
### Question: PopulateOIDCEncryptionParameters extends AbstractProfileAction { public void setEncryptionParametersResolver(@Nonnull final EncryptionParametersResolver newResolver) { ComponentSupport.ifInitializedThrowUnmodifiabledComponentException(this); encParamsresolver = Constraint.isNotNull(newResolver, "EncryptionParametersResolver cannot be null"); } PopulateOIDCEncryptionParameters(); void setForDecryption(boolean value); void setEncryptionContextLookupStrategy( @Nonnull final Function<ProfileRequestContext, EncryptionContext> strategy); void setOIDCMetadataContextContextLookupStrategy( @Nonnull final Function<ProfileRequestContext, OIDCMetadataContext> strategy); void setConfigurationLookupStrategy( @Nonnull final Function<ProfileRequestContext, List<EncryptionConfiguration>> strategy); void setEncryptionParametersResolver(@Nonnull final EncryptionParametersResolver newResolver); }### Answer: @Test(expectedExceptions = ConstraintViolationException.class) public void testFailureNullStrategyEncrParamas() { action = new PopulateOIDCEncryptionParameters(); action.setEncryptionParametersResolver(null); }
### Question: InitializeRelyingPartyContext extends AbstractProfileAction { public void setOidcMetadataContextLookupStrategy( @Nonnull final Function<ProfileRequestContext, OIDCMetadataContext> strategy) { ComponentSupport.ifInitializedThrowUnmodifiabledComponentException(this); oidcMetadataContextLookupStrategy = Constraint.isNotNull(strategy, "OIDCMetadataContext lookup strategy cannot be null"); } InitializeRelyingPartyContext(); void setClientIDLookupStrategy(@Nonnull final Function<MessageContext, ClientID> strategy); void setRelyingPartyContextCreationStrategy( @Nonnull final Function<ProfileRequestContext, RelyingPartyContext> strategy); void setOidcMetadataContextLookupStrategy( @Nonnull final Function<ProfileRequestContext, OIDCMetadataContext> strategy); }### Answer: @Test(expectedExceptions = ConstraintViolationException.class) public void testFailsNullOidcMetadataContextLookupStrategy() { action = new InitializeRelyingPartyContext(); action.setOidcMetadataContextLookupStrategy(null); }
### Question: InitializeRelyingPartyContext extends AbstractProfileAction { public void setClientIDLookupStrategy(@Nonnull final Function<MessageContext, ClientID> strategy) { ComponentSupport.ifInitializedThrowUnmodifiabledComponentException(this); clientIDLookupStrategy = Constraint.isNotNull(strategy, "ClientIDLookupStrategy lookup strategy cannot be null"); } InitializeRelyingPartyContext(); void setClientIDLookupStrategy(@Nonnull final Function<MessageContext, ClientID> strategy); void setRelyingPartyContextCreationStrategy( @Nonnull final Function<ProfileRequestContext, RelyingPartyContext> strategy); void setOidcMetadataContextLookupStrategy( @Nonnull final Function<ProfileRequestContext, OIDCMetadataContext> strategy); }### Answer: @Test(expectedExceptions = ConstraintViolationException.class) public void testFailsNullClientIDLookupStrategy() { action = new InitializeRelyingPartyContext(); action.setClientIDLookupStrategy(null); }
### Question: InitializeRelyingPartyContext extends AbstractProfileAction { public void setRelyingPartyContextCreationStrategy( @Nonnull final Function<ProfileRequestContext, RelyingPartyContext> strategy) { ComponentSupport.ifInitializedThrowUnmodifiabledComponentException(this); relyingPartyContextCreationStrategy = Constraint.isNotNull(strategy, "RelyingPartyContext creation strategy cannot be null"); } InitializeRelyingPartyContext(); void setClientIDLookupStrategy(@Nonnull final Function<MessageContext, ClientID> strategy); void setRelyingPartyContextCreationStrategy( @Nonnull final Function<ProfileRequestContext, RelyingPartyContext> strategy); void setOidcMetadataContextLookupStrategy( @Nonnull final Function<ProfileRequestContext, OIDCMetadataContext> strategy); }### Answer: @Test(expectedExceptions = ConstraintViolationException.class) public void testFailsNullRelyingPartyContextCreationStrategy() { action = new InitializeRelyingPartyContext(); action.setRelyingPartyContextCreationStrategy(null); }
### Question: FormOutboundDiscoveryResponse extends AbstractProfileAction { public void setMetadataResolver(final ProviderMetadataResolver resolver) { metadataResolver = Constraint.isNotNull(resolver, "The metadata resolver cannot be null!"); } FormOutboundDiscoveryResponse(); void setMetadataResolver(final ProviderMetadataResolver resolver); }### Answer: @Test public void testStatic() throws Exception { action.setMetadataResolver(initMetadataResolver()); action.initialize(); ActionTestingSupport.assertProceedEvent(action.execute(requestCtx)); Assert.assertTrue(profileRequestCtx.getOutboundMessageContext().getMessage() instanceof JSONSuccessResponse); final JSONSuccessResponse resp = (JSONSuccessResponse) profileRequestCtx.getOutboundMessageContext().getMessage(); Assert.assertTrue(resp.indicatesSuccess()); final JSONObject jsonObject = resp.toHTTPResponse().getContentAsJSONObject(); Assert.assertEquals(jsonObject.size(), 17); Assert.assertNull(jsonObject.get(dynamicClaim)); } @Test public void testDynamic() throws Exception { final Map<String, MetadataValueResolver> map = new HashMap<>(); map.put(dynamicClaim, initMockResolver(dynamicClaimValue)); action.setMetadataResolver(initMetadataResolver(map)); action.initialize(); ActionTestingSupport.assertProceedEvent(action.execute(requestCtx)); final JSONSuccessResponse resp = (JSONSuccessResponse) profileRequestCtx.getOutboundMessageContext().getMessage(); Assert.assertTrue(resp.indicatesSuccess()); final JSONObject jsonObject = resp.toHTTPResponse().getContentAsJSONObject(); Assert.assertEquals(jsonObject.size(), 18); Assert.assertNotNull(jsonObject.get(dynamicClaim)); Assert.assertEquals(jsonObject.get(dynamicClaim), dynamicClaimValue); }
### Question: CheckRedirectURIs extends AbstractProfileAction { protected boolean checkForbiddenHostname(final Set<URI> redirectURIs, final String hostname) { for (final URI redirectUri : redirectURIs) { if (hostname.equalsIgnoreCase(redirectUri.getHost())) { log.trace("{} Found forbidden {} as the hostname in the redirect URIs", getLogPrefix(), hostname); return true; } } return false; } CheckRedirectURIs(); void setHttpClient(@Nonnull final HttpClient client); void setHttpClientSecurityParameters(@Nullable final HttpClientSecurityParameters params); void doInitialize(); }### Answer: @SuppressWarnings({"rawtypes", "unchecked"}) @Test public void testCheckForbiddenHostname() throws Exception { Assert.assertFalse(action.checkForbiddenHostname(new HashSet(Arrays.asList(new URI("custom.test:/testing"))), "testing")); Assert.assertTrue(action.checkForbiddenHostname(new HashSet(Arrays.asList(new URI("custom.test: "testing")); Assert.assertTrue(action.checkForbiddenHostname(new HashSet(Arrays.asList(new URI("http: "localhost")); }
### Question: ValidateAccessToken extends AbstractOIDCUserInfoValidationResponseAction { public void setRevocationCache(@Nonnull final RevocationCache cache) { ComponentSupport.ifInitializedThrowUnmodifiabledComponentException(this); revocationCache = Constraint.isNotNull(cache, "ReplayCache cannot be null"); } ValidateAccessToken(@Nonnull @ParameterName(name = "sealer") final DataSealer sealer); void setRevocationCache(@Nonnull final RevocationCache cache); }### Answer: @Test public void testFailsRevoked() throws NoSuchAlgorithmException, ComponentInitializationException, URISyntaxException, DataSealerException { action = new ValidateAccessToken(getDataSealer()); action.setRevocationCache(new MockRevocationCache(true, true)); action.initialize(); TokenClaimsSet claims = new AccessTokenClaimsSet.Builder(idGenerator, new ClientID(), "issuer", "userPrin", "subject", new Date(), new Date(System.currentTimeMillis() + 1000), new Date(), new URI("http: BearerAccessToken token = new BearerAccessToken(claims.serialize(getDataSealer())); UserInfoRequest req = new UserInfoRequest(new URI("http: setUserInfoRequest(req); final Event event = action.execute(requestCtx); ActionTestingSupport.assertEvent(event, OidcEventIds.INVALID_GRANT); }
### Question: OIDCClientInformationSignatureSigningParametersResolver extends BasicSignatureSigningParametersResolver { @Nullable public SignatureSigningParameters resolveSingle(@Nonnull final CriteriaSet criteria) throws ResolverException { Constraint.isNotNull(criteria, "CriteriaSet was null"); Constraint.isNotNull(criteria.get(SignatureSigningConfigurationCriterion.class), "Resolver requires an instance of SignatureSigningConfigurationCriterion"); final Predicate<String> whitelistBlacklistPredicate = getWhitelistBlacklistPredicate(criteria); final SignatureSigningParameters params = new SignatureSigningParameters(); resolveAndPopulateCredentialAndSignatureAlgorithm(params, criteria, whitelistBlacklistPredicate); if (validate(params)) { logResult(params); return params; } else { return null; } } void setParameterType(ParameterType value); @Nullable SignatureSigningParameters resolveSingle(@Nonnull final CriteriaSet criteria); }### Answer: @Test public void testIdTokenParameters() throws ResolverException { SignatureSigningParameters params = resolver.resolveSingle(criteria); Assert.assertEquals(params.getSignatureAlgorithm(), "RS256"); Assert.assertTrue(params.getSigningCredential().getPrivateKey() instanceof RSAPrivateKey); } @Test public void testDefaultIdTokenParameters() throws ResolverException { metaData.setIDTokenJWSAlg(null); SignatureSigningParameters params = resolver.resolveSingle(criteria); Assert.assertEquals(params.getSignatureAlgorithm(), "RS256"); Assert.assertTrue(params.getSigningCredential().getPrivateKey() instanceof RSAPrivateKey); } @Test public void testIdTokenParametersHS() throws ResolverException { metaData.setIDTokenJWSAlg(JWSAlgorithm.HS256); SignatureSigningParameters params = resolver.resolveSingle(criteria); Assert.assertEquals(params.getSignatureAlgorithm(), "HS256"); Assert.assertNotNull(params.getSigningCredential().getSecretKey()); }
### Question: AddScopeToClientMetadata extends AbstractOIDCClientMetadataPopulationAction { public void setDefaultScope(final Scope scope) { defaultScope = Constraint.isNotNull(scope, "The default scope cannot be null"); } AddScopeToClientMetadata(); void setDefaultScope(final Scope scope); Scope getDefaultScope(); }### Answer: @Test(expectedExceptions = ConstraintViolationException.class) public void testNullDefault() { action = new AddScopeToClientMetadata(); action.setDefaultScope(null); } @Test public void testNullScopeCustomDefault() throws ComponentInitializationException { action = new AddScopeToClientMetadata(); Scope defaultScope = new Scope(OIDCScopeValue.OPENID, OIDCScopeValue.ADDRESS); action.setDefaultScope(defaultScope); action.initialize(); OIDCClientMetadata input = new OIDCClientMetadata(); OIDCClientMetadata output = new OIDCClientMetadata(); setUpContext(input, output); Assert.assertNull(action.execute(requestCtx)); Assert.assertEquals(output.getScope(), defaultScope); }
### Question: AddScopeToClientMetadata extends AbstractOIDCClientMetadataPopulationAction { public Scope getDefaultScope() { return defaultScope; } AddScopeToClientMetadata(); void setDefaultScope(final Scope scope); Scope getDefaultScope(); }### Answer: @Test public void testNullScope() throws ComponentInitializationException { OIDCClientMetadata input = new OIDCClientMetadata(); OIDCClientMetadata output = new OIDCClientMetadata(); setUpContext(input, output); Assert.assertNull(action.execute(requestCtx)); Assert.assertEquals(output.getScope(), action.getDefaultScope()); } @Test public void testEmptyScope() throws ComponentInitializationException { OIDCClientMetadata input = new OIDCClientMetadata(); input.setScope(new Scope()); OIDCClientMetadata output = new OIDCClientMetadata(); setUpContext(input, output); Assert.assertNull(action.execute(requestCtx)); Assert.assertEquals(output.getScope(), action.getDefaultScope()); }
### Question: AddUserInfoShell extends AbstractOIDCResponseAction { public void setIssuerLookupStrategy(@Nonnull final Function<ProfileRequestContext, String> strategy) { ComponentSupport.ifInitializedThrowUnmodifiabledComponentException(this); issuerLookupStrategy = Constraint.isNotNull(strategy, "IssuerLookupStrategy lookup strategy cannot be null"); } AddUserInfoShell(); void setUserInfoSigningAlgLookupStrategy(@Nonnull final Function<ProfileRequestContext, JWSAlgorithm> strategy); void setRelyingPartyContextLookupStrategy( @Nonnull final Function<ProfileRequestContext, RelyingPartyContext> strategy); void setIssuerLookupStrategy(@Nonnull final Function<ProfileRequestContext, String> strategy); }### Answer: @Test(expectedExceptions = ConstraintViolationException.class) public void testNullIssuerLookupStrategy() { action = new AddUserInfoShell(); action.setIssuerLookupStrategy(null); }
### Question: AddUserInfoShell extends AbstractOIDCResponseAction { public void setRelyingPartyContextLookupStrategy( @Nonnull final Function<ProfileRequestContext, RelyingPartyContext> strategy) { ComponentSupport.ifInitializedThrowUnmodifiabledComponentException(this); relyingPartyContextLookupStrategy = Constraint.isNotNull(strategy, "RelyingPartyContext lookup strategy cannot be null"); } AddUserInfoShell(); void setUserInfoSigningAlgLookupStrategy(@Nonnull final Function<ProfileRequestContext, JWSAlgorithm> strategy); void setRelyingPartyContextLookupStrategy( @Nonnull final Function<ProfileRequestContext, RelyingPartyContext> strategy); void setIssuerLookupStrategy(@Nonnull final Function<ProfileRequestContext, String> strategy); }### Answer: @Test(expectedExceptions = ConstraintViolationException.class) public void testNullRelyingPartyContextLookupStrategy() { action = new AddUserInfoShell(); action.setRelyingPartyContextLookupStrategy(null); }
### Question: AddUserInfoShell extends AbstractOIDCResponseAction { public void setUserInfoSigningAlgLookupStrategy(@Nonnull final Function<ProfileRequestContext, JWSAlgorithm> strategy) { ComponentSupport.ifInitializedThrowUnmodifiabledComponentException(this); userInfoSigAlgStrategy = Constraint.isNotNull(strategy, "User Info Signing Algorithm lookup strategy cannot be null"); } AddUserInfoShell(); void setUserInfoSigningAlgLookupStrategy(@Nonnull final Function<ProfileRequestContext, JWSAlgorithm> strategy); void setRelyingPartyContextLookupStrategy( @Nonnull final Function<ProfileRequestContext, RelyingPartyContext> strategy); void setIssuerLookupStrategy(@Nonnull final Function<ProfileRequestContext, String> strategy); }### Answer: @Test(expectedExceptions = ConstraintViolationException.class) public void testNulltUserInfoSigningAlgLookupStrategy() { action = new AddUserInfoShell(); action.setUserInfoSigningAlgLookupStrategy(null); }
### Question: ValidateGrant extends AbstractOIDCTokenResponseAction { public void setReplayCache(@Nonnull final ReplayCache cache) { ComponentSupport.ifInitializedThrowUnmodifiabledComponentException(this); replayCache = Constraint.isNotNull(cache, "ReplayCache cannot be null"); } ValidateGrant(@Nonnull @ParameterName(name = "sealer") final DataSealer sealer); void setRelyingPartyContextLookupStrategy( @Nonnull final Function<ProfileRequestContext, RelyingPartyContext> strategy); void setReplayCache(@Nonnull final ReplayCache cache); void setRevocationCache(@Nonnull final RevocationCache cache); }### Answer: @Test(expectedExceptions = ConstraintViolationException.class) public void testNoRevocationCache() throws NoSuchAlgorithmException, ComponentInitializationException { action = new ValidateGrant(getDataSealer()); ReplayCache replayCache = new ReplayCache(); MemoryStorageService storageService = new MemoryStorageService(); storageService.setId("mockId"); storageService.initialize(); replayCache.setStorage(storageService); action.setReplayCache(replayCache); action.initialize(); }
### Question: ValidateGrant extends AbstractOIDCTokenResponseAction { public void setRevocationCache(@Nonnull final RevocationCache cache) { ComponentSupport.ifInitializedThrowUnmodifiabledComponentException(this); revocationCache = Constraint.isNotNull(cache, "ReplayCache cannot be null"); } ValidateGrant(@Nonnull @ParameterName(name = "sealer") final DataSealer sealer); void setRelyingPartyContextLookupStrategy( @Nonnull final Function<ProfileRequestContext, RelyingPartyContext> strategy); void setReplayCache(@Nonnull final ReplayCache cache); void setRevocationCache(@Nonnull final RevocationCache cache); }### Answer: @Test(expectedExceptions = ConstraintViolationException.class) public void testNoReplayCache() throws NoSuchAlgorithmException, ComponentInitializationException { action = new ValidateGrant(getDataSealer()); action.setRevocationCache(new MockRevocationCache(false, true)); action.initialize(); }
### Question: SetSubjectToResponseContext extends AbstractOIDCResponseAction { public void setSubjectLookupStrategy(@Nonnull final Function<ProfileRequestContext, String> strategy) { ComponentSupport.ifInitializedThrowUnmodifiabledComponentException(this); subjectLookupStrategy = Constraint.isNotNull(strategy, "SubjectLookupStrategy lookup strategy cannot be null"); } SetSubjectToResponseContext(); void setSubjectTypeLookupStrategy(@Nonnull final Function<ProfileRequestContext, SubjectType> strategy); void setSubjectLookupStrategy(@Nonnull final Function<ProfileRequestContext, String> strategy); }### Answer: @Test(expectedExceptions = ConstraintViolationException.class) public void testNoStrategy() throws NoSuchAlgorithmException, ComponentInitializationException { action = new SetSubjectToResponseContext(); action.setSubjectLookupStrategy(null); } @Test(expectedExceptions = UnmodifiableComponentException.class) public void testInitialized() throws NoSuchAlgorithmException, ComponentInitializationException { init(); action.setSubjectLookupStrategy(new TokenRequestSubjectLookupFunction()); }
### Question: OIDCScopedStringAttributeEncoder extends AbstractOIDCAttributeEncoder { @SuppressWarnings("rawtypes") @Override public JSONObject encode(IdPAttribute idpAttribute) throws AttributeEncodingException { Constraint.isNotNull(idpAttribute, "Attribute to encode cannot be null"); Constraint.isNotNull(scopeDelimiter, "Scope delimiter cannot be null"); JSONObject obj = new JSONObject(); List<String> values = new ArrayList<String>(); for (IdPAttributeValue value : idpAttribute.getValues()) { if (value instanceof ScopedStringAttributeValue && value.getValue() != null) { values.add(value.getValue() + scopeDelimiter + ((ScopedStringAttributeValue) value).getScope()); } } obj.put(getName(), values.isEmpty() ? null : encodeValues(values)); return obj; } OIDCScopedStringAttributeEncoder(); void setScopeDelimiter(@Nullable final String newScopeDelimiter); @SuppressWarnings("rawtypes") @Override JSONObject encode(IdPAttribute idpAttribute); }### Answer: @Test public void testEncodingNull() throws ComponentInitializationException, AttributeEncodingException { init(); boolean exceptionOccurred = false; try { encoder.encode(null); } catch (ConstraintViolationException e) { exceptionOccurred = true; } Assert.assertTrue(exceptionOccurred); } @Test public void testEncodingWrongType() throws ComponentInitializationException, AttributeEncodingException { init(); IdPAttribute attribute = new IdPAttribute("test"); List<ByteAttributeValue> byteAttributeValues = new ArrayList<ByteAttributeValue>(); byte[] bytes = new byte[1]; bytes[0] = 0; byteAttributeValues.add(new ByteAttributeValue(bytes)); attribute.setValues(byteAttributeValues); JSONObject object = encoder.encode(attribute); Assert.assertNull(object.get("attributeName")); }
### Question: RefreshTokenClaimsSet extends TokenClaimsSet { public static RefreshTokenClaimsSet parse(String refreshTokenClaimsSet) throws ParseException { JWTClaimsSet atClaimsSet = JWTClaimsSet.parse(refreshTokenClaimsSet); verifyParsedClaims(VALUE_TYPE_RF, atClaimsSet); return new RefreshTokenClaimsSet(atClaimsSet); } RefreshTokenClaimsSet(@Nonnull TokenClaimsSet tokenClaimsSet, @Nonnull Date iat, @Nonnull Date exp); private RefreshTokenClaimsSet(JWTClaimsSet refreshTokenClaimsSet); static RefreshTokenClaimsSet parse(String refreshTokenClaimsSet); static RefreshTokenClaimsSet parse(@Nonnull String wrappedAccessToken, @Nonnull DataSealer dataSealer); }### Answer: @Test public void testSerialization() throws ParseException, DataSealerException { init(); RefreshTokenClaimsSet rfClaimsSet2 = RefreshTokenClaimsSet.parse(rfClaimsSet.serialize()); Assert.assertEquals(rfClaimsSet2.getACR(), acr.getValue()); RefreshTokenClaimsSet rfClaimsSet3 = RefreshTokenClaimsSet.parse(rfClaimsSet2.serialize(sealer), sealer); Assert.assertEquals(rfClaimsSet3.getACR(), acr.getValue()); } @Test(expectedExceptions = ParseException.class) public void testSerializationWrongType() throws ParseException { AuthorizeCodeClaimsSet accessnClaimsSet = new AuthorizeCodeClaimsSet.Builder(new SecureRandomIdentifierGenerationStrategy(), clientID, issuer, userPrincipal, subject, iat, exp, authTime, redirectURI, scope).build(); rfClaimsSet = RefreshTokenClaimsSet.parse(accessnClaimsSet.serialize()); }
### Question: ChaosMonkeyScheduler { public void reloadConfig() { String cronExpression = config.getRuntimeAssaultCronExpression(); boolean active = !"OFF".equals(cronExpression); if (currentTask != null) { Logger.info("Cancelling previous task"); currentTask.cancel(); currentTask = null; } if (active) { CronTask task = new CronTask(runtimeScope::callChaosMonkey, cronExpression); currentTask = scheduler.scheduleCronTask(task); } } ChaosMonkeyScheduler( ScheduledTaskRegistrar scheduler, AssaultProperties config, ChaosMonkeyRuntimeScope runtimeScope); void reloadConfig(); }### Answer: @Test void shouldScheduleANewTaskAfterAnUpdate() { String schedule = "*/1 * * * * ?"; ScheduledTask oldTask = mock(ScheduledTask.class); ScheduledTask newTask = mock(ScheduledTask.class); when(config.getRuntimeAssaultCronExpression()).thenReturn(schedule); when(registrar.scheduleCronTask(any())).thenReturn(oldTask, newTask); ChaosMonkeyScheduler cms = new ChaosMonkeyScheduler(registrar, config, scope); cms.reloadConfig(); verify(registrar, times(2)).scheduleCronTask(argThat(hasScheduleLike(schedule))); verify(oldTask).cancel(); }
### Question: LatencyAssault implements ChaosMonkeyRequestAssault { @Override public void attack() { Logger.debug("Chaos Monkey - timeout"); atomicTimeoutGauge.set(determineLatency()); if (metricEventPublisher != null) { metricEventPublisher.publishMetricEvent(MetricType.LATENCY_ASSAULT); metricEventPublisher.publishMetricEvent(MetricType.LATENCY_ASSAULT, atomicTimeoutGauge); } assaultExecutor.execute(atomicTimeoutGauge.get()); } LatencyAssault( ChaosMonkeySettings settings, MetricEventPublisher metricEventPublisher, ChaosMonkeyLatencyAssaultExecutor executor); LatencyAssault(ChaosMonkeySettings settings, MetricEventPublisher metricEventPublisher); @Override boolean isActive(); @Override void attack(); }### Answer: @Test void threadSleepHasBeenCalled() { int latencyRangeStart = 100; int latencyRangeEnd = 200; TestLatencyAssaultExecutor executor = new TestLatencyAssaultExecutor(); when(assaultProperties.getLatencyRangeStart()).thenReturn(latencyRangeStart); when(assaultProperties.getLatencyRangeEnd()).thenReturn(latencyRangeEnd); when(chaosMonkeySettings.getAssaultProperties()).thenReturn(assaultProperties); LatencyAssault latencyAssault = new LatencyAssault(chaosMonkeySettings, null, executor); latencyAssault.attack(); assertTrue(executor.executed); String assertionMessage = "Latency not in range 100-200, actual latency: " + executor.duration; assertTrue(executor.duration >= latencyRangeStart, assertionMessage); assertTrue(executor.duration <= latencyRangeEnd, assertionMessage); }
### Question: KillAppAssault implements ChaosMonkeyRuntimeAssault, ApplicationContextAware { @Override public void attack() { try { Logger.info("Chaos Monkey - I am killing your Application!"); if (metricEventPublisher != null) { metricEventPublisher.publishMetricEvent(MetricType.KILLAPP_ASSAULT); } int exit = SpringApplication.exit(context, (ExitCodeGenerator) () -> 0); Thread.sleep(5000); System.exit(exit); } catch (Exception e) { Logger.info("Chaos Monkey - Unable to kill the App, I am not the BOSS!"); } } KillAppAssault(ChaosMonkeySettings settings, MetricEventPublisher metricEventPublisher); @Override boolean isActive(); @Override void attack(); @Override void setApplicationContext(ApplicationContext applicationContext); }### Answer: @Test void killsSpringBootApplication() { KillAppAssault killAppAssault = new KillAppAssault(null, metricsMock); killAppAssault.attack(); verify(mockAppender, times(2)).doAppend(captorLoggingEvent.capture()); assertEquals(Level.INFO, captorLoggingEvent.getAllValues().get(0).getLevel()); assertEquals(Level.INFO, captorLoggingEvent.getAllValues().get(1).getLevel()); assertEquals( "Chaos Monkey - I am killing your Application!", captorLoggingEvent.getAllValues().get(0).getMessage()); assertEquals( "Chaos Monkey - Unable to kill the App, I am not the BOSS!", captorLoggingEvent.getAllValues().get(1).getMessage()); }
### Question: GreetingService { public String greet() { return "Greetings from the server side!"; } GreetingService( HelloRepo helloRepo, HelloRepoSearchAndSorting repoSearchAndSorting, HelloRepoJpa helloRepoJpa, HelloRepoAnnotation helloRepoAnnotation); String greet(); String greetFromRepo(); String greetFromRepoPagingSorting(); String greetFromRepoJpa(); String greetFromRepoAnnotation(); }### Answer: @Test public void greet() { assertThat(greetingService.greet(), is("Greetings from the server side!")); }
### Question: GreetingService { public String greetFromRepo() { Hello databaseSide = helloRepo.save(new Hello(0, "Greetings from the database side")); return databaseSide.getMessage(); } GreetingService( HelloRepo helloRepo, HelloRepoSearchAndSorting repoSearchAndSorting, HelloRepoJpa helloRepoJpa, HelloRepoAnnotation helloRepoAnnotation); String greet(); String greetFromRepo(); String greetFromRepoPagingSorting(); String greetFromRepoJpa(); String greetFromRepoAnnotation(); }### Answer: @Test public void greetFromRepo() { String message = "message"; Hello saveObject = new Hello(0, message); when(helloRepoMock.save(any(Hello.class))).thenReturn(saveObject); assertThat(greetingService.greetFromRepo(), is(message)); verify(helloRepoMock, times(1)).save(any(Hello.class)); verifyNoMoreInteractions( helloRepoMock, helloRepoSearchAndSortingMock, helloRepoJpaMock, helloRepoAnnotationMock); }
### Question: GreetingService { public String greetFromRepoPagingSorting() { Hello databaseSide = repoSearchAndSorting.save( new Hello(0, "Greetings from the paging and sorting database side")); Optional<Hello> byId = repoSearchAndSorting.findById(databaseSide.getId()); return byId.orElse(new Hello(-99, "not found")).getMessage(); } GreetingService( HelloRepo helloRepo, HelloRepoSearchAndSorting repoSearchAndSorting, HelloRepoJpa helloRepoJpa, HelloRepoAnnotation helloRepoAnnotation); String greet(); String greetFromRepo(); String greetFromRepoPagingSorting(); String greetFromRepoJpa(); String greetFromRepoAnnotation(); }### Answer: @Test public void testPagingAndSorting() { String message = "message"; Hello saveObject = new Hello(0, message); when(helloRepoSearchAndSortingMock.save(any(Hello.class))).thenReturn(saveObject); when(helloRepoSearchAndSortingMock.findById(saveObject.getId())) .thenReturn(Optional.of(saveObject)); assertThat(greetingService.greetFromRepoPagingSorting(), is(message)); verify(helloRepoSearchAndSortingMock, times(1)).save(any(Hello.class)); verify(helloRepoSearchAndSortingMock, times(1)).findById(saveObject.getId()); verifyNoMoreInteractions( helloRepoMock, helloRepoSearchAndSortingMock, helloRepoJpaMock, helloRepoAnnotationMock); }
### Question: GreetingService { public String greetFromRepoJpa() { Hello databaseSide = helloRepoJpa.save(new Hello(0, "Greetings from the paging and sorting database side")); Optional<Hello> byId = helloRepoJpa.findById(databaseSide.getId()); return byId.orElse(new Hello(-99, "not found")).getMessage(); } GreetingService( HelloRepo helloRepo, HelloRepoSearchAndSorting repoSearchAndSorting, HelloRepoJpa helloRepoJpa, HelloRepoAnnotation helloRepoAnnotation); String greet(); String greetFromRepo(); String greetFromRepoPagingSorting(); String greetFromRepoJpa(); String greetFromRepoAnnotation(); }### Answer: @Test public void testJpaRepo() { String message = "message"; Hello saveObject = new Hello(0, message); when(helloRepoJpaMock.save(any(Hello.class))).thenReturn(saveObject); when(helloRepoJpaMock.findById(saveObject.getId())).thenReturn(Optional.of(saveObject)); assertThat(greetingService.greetFromRepoJpa(), is(message)); verify(helloRepoJpaMock, times(1)).save(any(Hello.class)); verify(helloRepoJpaMock, times(1)).findById(saveObject.getId()); verifyNoMoreInteractions( helloRepoMock, helloRepoSearchAndSortingMock, helloRepoJpaMock, helloRepoAnnotationMock); }
### Question: GreetingService { public String greetFromRepoAnnotation() { Hello databaseSide = helloRepoAnnotation.save( new Hello(0, "Greetings from the paging and sorting database side")); Optional<Hello> byId = helloRepoAnnotation.findById(databaseSide.getId()); return byId.orElse(new Hello(-99, "not found")).getMessage(); } GreetingService( HelloRepo helloRepo, HelloRepoSearchAndSorting repoSearchAndSorting, HelloRepoJpa helloRepoJpa, HelloRepoAnnotation helloRepoAnnotation); String greet(); String greetFromRepo(); String greetFromRepoPagingSorting(); String greetFromRepoJpa(); String greetFromRepoAnnotation(); }### Answer: @Test public void testAnnotationRepo() { String message = "message"; Hello saveObject = new Hello(0, message); when(helloRepoAnnotationMock.save(any(Hello.class))).thenReturn(saveObject); when(helloRepoAnnotationMock.findById(saveObject.getId())).thenReturn(Optional.of(saveObject)); assertThat(greetingService.greetFromRepoAnnotation(), is(message)); verify(helloRepoAnnotationMock, times(1)).save(any(Hello.class)); verify(helloRepoAnnotationMock, times(1)).findById(saveObject.getId()); verifyNoMoreInteractions( helloRepoMock, helloRepoSearchAndSortingMock, helloRepoJpaMock, helloRepoAnnotationMock); }
### Question: ExponentialMovingAverage { public static long predictNext(TreeMap<Integer, Long> laps) { float smoothing = (((float) 2) / (laps.size() + 1)); long previousEMA = laps.get(laps.firstKey()); Set<Integer> keys = laps.keySet(); for (Iterator<Integer> i = keys.iterator(); i.hasNext();) { Integer key = i.next(); previousEMA = (long) ((laps.get(key) - previousEMA) * smoothing + previousEMA); } return (long) ((previousEMA - previousEMA) * smoothing + previousEMA); } static long getAverage(TreeMap<Integer, Long> laps); static long predictNext(TreeMap<Integer, Long> laps); }### Answer: @Test public void test() { TreeMap<Integer, Long> laps = new TreeMap<Integer, Long>(); laps.put(1, (long) 2227); laps.put(2, (long) 2219); laps.put(3, (long) 2208); laps.put(4, (long) 2217); laps.put(5, (long) 2213); laps.put(6, (long) 2223); laps.put(7, (long) 2243); laps.put(8, (long) 2224); laps.put(9, (long) 2229); System.out.println(ExponentialMovingAverage.predictNext(laps)); }
### Question: MyService { @GET @Path("/helloworld") public String helloWorld() { return "Hello World!"; } @GET @Path("/helloworld") String helloWorld(); @GET @Path("/friends/{name}") Response getFriends(@PathParam("name") String name, @Context GraphDatabaseService db); @POST @Path("/permissions") Response permissions(String body, @Context GraphDatabaseService db); }### Answer: @Test public void shouldRespondToHelloWorld() { assertEquals("Hello World!", service.helloWorld()); }
### Question: MyService { @GET @Path("/friends/{name}") public Response getFriends(@PathParam("name") String name, @Context GraphDatabaseService db) throws IOException { ExecutionEngine executionEngine = new ExecutionEngine(db); ExecutionResult result = executionEngine.execute("START person=node:Users(unique_id={n}) MATCH person-[:KNOWS]-other RETURN other.unique_id", Collections.<String, Object>singletonMap("n", name)); List<String> friends = new ArrayList<String>(); for (Map<String, Object> item : result) { friends.add((String) item.get("other.unique_id")); } return Response.ok().entity(objectMapper.writeValueAsString(friends)).build(); } @GET @Path("/helloworld") String helloWorld(); @GET @Path("/friends/{name}") Response getFriends(@PathParam("name") String name, @Context GraphDatabaseService db); @POST @Path("/permissions") Response permissions(String body, @Context GraphDatabaseService db); }### Answer: @Test public void shouldQueryDbForFriends() throws IOException { Response response = service.getFriends("B", db); List list = objectMapper.readValue((String) response.getEntity(), List.class); assertEquals(new HashSet<String>(Arrays.asList("A", "C")), new HashSet<String>(list)); }
### Question: InstructionLoader { void loadInstruction() { bannerComponentTree.loadInstruction(textView); } InstructionLoader(TextView textView, @NonNull BannerText bannerText); InstructionLoader(TextView textView, BannerComponentTree bannerComponentTree); }### Answer: @Test public void loadInstruction() { TextView textView = mock(TextView.class); BannerComponentTree bannerComponentTree = mock(BannerComponentTree.class); InstructionLoader instructionLoader = new InstructionLoader(textView, bannerComponentTree); instructionLoader.loadInstruction(); verify(bannerComponentTree).loadInstruction(textView); }
### Question: MapFpsDelegate implements OnTrackingModeChangedListener, OnTrackingModeTransitionListener { @Override public void onTransitionFinished(int trackingMode) { updateCameraTracking(trackingMode); } MapFpsDelegate(MapView mapView, MapBatteryMonitor batteryMonitor); @Override void onTrackingModeChanged(int trackingMode); @Override void onTransitionFinished(int trackingMode); @Override void onTransitionCancelled(int trackingMode); }### Answer: @Test public void onTransitionFinished_resetFpsWhenNotTracking() { MapView mapView = mock(MapView.class); MapFpsDelegate delegate = new MapFpsDelegate(mapView, mock(MapBatteryMonitor.class)); delegate.onTransitionFinished(NavigationCamera.NAVIGATION_TRACKING_MODE_NONE); verify(mapView).setMaximumFps(eq(Integer.MAX_VALUE)); }
### Question: MapFpsDelegate implements OnTrackingModeChangedListener, OnTrackingModeTransitionListener { @Override public void onTransitionCancelled(int trackingMode) { updateCameraTracking(trackingMode); } MapFpsDelegate(MapView mapView, MapBatteryMonitor batteryMonitor); @Override void onTrackingModeChanged(int trackingMode); @Override void onTransitionFinished(int trackingMode); @Override void onTransitionCancelled(int trackingMode); }### Answer: @Test public void onTransitionCancelled_resetFpsWhenNotTracking() { MapView mapView = mock(MapView.class); MapFpsDelegate delegate = new MapFpsDelegate(mapView, mock(MapBatteryMonitor.class)); delegate.onTransitionCancelled(NavigationCamera.NAVIGATION_TRACKING_MODE_NONE); verify(mapView).setMaximumFps(eq(Integer.MAX_VALUE)); }
### Question: MapFpsDelegate implements OnTrackingModeChangedListener, OnTrackingModeTransitionListener { void updateEnabled(boolean isEnabled) { this.isEnabled = isEnabled; resetMaxFps(!isEnabled); } MapFpsDelegate(MapView mapView, MapBatteryMonitor batteryMonitor); @Override void onTrackingModeChanged(int trackingMode); @Override void onTransitionFinished(int trackingMode); @Override void onTransitionCancelled(int trackingMode); }### Answer: @Test public void updateEnabledFalse_maxFpsReset() { MapView mapView = mock(MapView.class); MapFpsDelegate delegate = new MapFpsDelegate(mapView, mock(MapBatteryMonitor.class)); delegate.updateEnabled(false); mapView.setMaximumFps(eq(Integer.MAX_VALUE)); }
### Question: MapWayNameChangedListener implements OnWayNameChangedListener { @Override public void onWayNameChanged(@NonNull String wayName) { for (OnWayNameChangedListener listener : listeners) { listener.onWayNameChanged(wayName); } } MapWayNameChangedListener(List<OnWayNameChangedListener> listeners); @Override void onWayNameChanged(@NonNull String wayName); }### Answer: @Test public void onWayNameChanged_listenersAreUpdated() { List<OnWayNameChangedListener> listeners = new ArrayList<>(); OnWayNameChangedListener listener = mock(OnWayNameChangedListener.class); listeners.add(listener); MapWayNameChangedListener wayNameChangedListener = new MapWayNameChangedListener(listeners); String someWayName = "some way name"; wayNameChangedListener.onWayNameChanged(someWayName); verify(listener).onWayNameChanged(eq(someWayName)); }
### Question: MapPaddingAdjustor { void adjustLocationIconWith(@NonNull int[] customPadding) { this.customPadding = customPadding; updatePaddingWith(customPadding); } MapPaddingAdjustor(@NonNull MapView mapView, MapboxMap mapboxMap); MapPaddingAdjustor(MapboxMap mapboxMap, int[] defaultPadding); static final int BOTTOMSHEET_PADDING_MULTIPLIER_PORTRAIT; static final int BOTTOMSHEET_PADDING_MULTIPLIER_LANDSCAPE; static final int WAYNAME_PADDING_MULTIPLIER; }### Answer: @Test public void adjustLocationIconWith_customPaddingIsSet() { MapboxMap mapboxMap = mock(MapboxMap.class); int[] defaultPadding = {0, 250, 0, 0}; int[] customPadding = {0, 0, 0, 0}; MapPaddingAdjustor paddingAdjustor = new MapPaddingAdjustor(mapboxMap, defaultPadding); paddingAdjustor.adjustLocationIconWith(customPadding); verify(mapboxMap).setPadding(0, 0, 0, 0); }
### Question: MapPaddingAdjustor { boolean isUsingDefault() { return customPadding == null; } MapPaddingAdjustor(@NonNull MapView mapView, MapboxMap mapboxMap); MapPaddingAdjustor(MapboxMap mapboxMap, int[] defaultPadding); static final int BOTTOMSHEET_PADDING_MULTIPLIER_PORTRAIT; static final int BOTTOMSHEET_PADDING_MULTIPLIER_LANDSCAPE; static final int WAYNAME_PADDING_MULTIPLIER; }### Answer: @Test public void isUsingDefault_trueWithoutCustomPadding() { MapboxMap mapboxMap = mock(MapboxMap.class); int[] defaultPadding = {0, 250, 0, 0}; MapPaddingAdjustor paddingAdjustor = new MapPaddingAdjustor(mapboxMap, defaultPadding); assertTrue(paddingAdjustor.isUsingDefault()); }
### Question: MapPaddingAdjustor { void updatePaddingWith(int[] padding) { mapboxMap.setPadding(padding[0], padding[1], padding[2], padding[3]); } MapPaddingAdjustor(@NonNull MapView mapView, MapboxMap mapboxMap); MapPaddingAdjustor(MapboxMap mapboxMap, int[] defaultPadding); static final int BOTTOMSHEET_PADDING_MULTIPLIER_PORTRAIT; static final int BOTTOMSHEET_PADDING_MULTIPLIER_LANDSCAPE; static final int WAYNAME_PADDING_MULTIPLIER; }### Answer: @Test public void updatePaddingWithZero_updatesMapToZeroPadding() { MapboxMap mapboxMap = mock(MapboxMap.class); int[] defaultPadding = {0, 250, 0, 0}; MapPaddingAdjustor paddingAdjustor = new MapPaddingAdjustor(mapboxMap, defaultPadding); paddingAdjustor.updatePaddingWith(new int[]{0, 0, 0, 0}); verify(mapboxMap).setPadding(0, 0, 0, 0); }
### Question: MapPaddingAdjustor { @NonNull int[] retrieveCurrentPadding() { return mapboxMap.getPadding(); } MapPaddingAdjustor(@NonNull MapView mapView, MapboxMap mapboxMap); MapPaddingAdjustor(MapboxMap mapboxMap, int[] defaultPadding); static final int BOTTOMSHEET_PADDING_MULTIPLIER_PORTRAIT; static final int BOTTOMSHEET_PADDING_MULTIPLIER_LANDSCAPE; static final int WAYNAME_PADDING_MULTIPLIER; }### Answer: @Test public void retrieveCurrentPadding_returnsCurrentMapPadding() { MapboxMap mapboxMap = mock(MapboxMap.class); int[] defaultPadding = {0, 250, 0, 0}; MapPaddingAdjustor paddingAdjustor = new MapPaddingAdjustor(mapboxMap, defaultPadding); paddingAdjustor.retrieveCurrentPadding(); verify(mapboxMap).getPadding(); }
### Question: WaynameFeatureFinder { @NonNull List<Feature> queryRenderedFeatures(@NonNull PointF point, String[] layerIds) { return mapboxMap.queryRenderedFeatures(point, layerIds); } WaynameFeatureFinder(MapboxMap mapboxMap); }### Answer: @Test public void queryRenderedFeatures_mapboxMapIsCalled() { MapboxMap mapboxMap = mock(MapboxMap.class); WaynameFeatureFinder featureFinder = new WaynameFeatureFinder(mapboxMap); PointF point = mock(PointF.class); String[] layerIds = {"id", "id"}; featureFinder.queryRenderedFeatures(point, layerIds); verify(mapboxMap).queryRenderedFeatures(point, layerIds); }
### Question: NavigationSymbolManager { void addDestinationMarkerFor(@NonNull Point position) { if (destinationSymbol != null) { symbolManager.delete(destinationSymbol); markersSymbols.remove(destinationSymbol.getId()); } SymbolOptions options = createSymbolOptionsFor(position); destinationSymbol = createSymbolFrom(options); } NavigationSymbolManager(@NonNull SymbolManager symbolManager); }### Answer: @Test public void addDestinationMarkerFor_symbolManagerAddsOptions() { SymbolManager symbolManager = mock(SymbolManager.class); Symbol symbol = buildSymbolWith(DEFAULT_SYMBOL_ID, DEFAULT_SYMBOL_ICON_IMAGE); when(symbolManager.create(any(SymbolOptions.class))).thenReturn(symbol); NavigationSymbolManager navigationSymbolManager = new NavigationSymbolManager(symbolManager); Point position = Point.fromLngLat(1.2345, 1.3456); navigationSymbolManager.addDestinationMarkerFor(position); verify(symbolManager).create(any(SymbolOptions.class)); } @Test public void addDestinationMarkerFor_destinationSymbolRemovedIfPreviouslyAdded() { SymbolManager symbolManager = mock(SymbolManager.class); Symbol oldDestinationSymbol = mock(Symbol.class); Symbol currentDestinationSymbol = mock(Symbol.class); when(symbolManager.create(any(SymbolOptions.class))).thenReturn(oldDestinationSymbol, currentDestinationSymbol); NavigationSymbolManager navigationSymbolManager = new NavigationSymbolManager(symbolManager); Point position = Point.fromLngLat(1.2345, 1.3456); navigationSymbolManager.addDestinationMarkerFor(position); navigationSymbolManager.addDestinationMarkerFor(position); verify(symbolManager, times(2)).create(any(SymbolOptions.class)); verify(symbolManager, times(1)).delete(eq(oldDestinationSymbol)); }
### Question: NavigationSymbolManager { Symbol addCustomSymbolFor(@NonNull SymbolOptions options) { return createSymbolFrom(options); } NavigationSymbolManager(@NonNull SymbolManager symbolManager); }### Answer: @Test public void addCustomSymbolFor_symbolManagerCreatesSymbol() { Symbol symbol = buildSymbolWith(DEFAULT_SYMBOL_ID, DEFAULT_SYMBOL_ICON_IMAGE); SymbolOptions symbolOptions = mock(SymbolOptions.class); SymbolManager symbolManager = buildSymbolManager(symbolOptions, symbol); NavigationSymbolManager navigationSymbolManager = new NavigationSymbolManager(symbolManager); navigationSymbolManager.addCustomSymbolFor(symbolOptions); verify(symbolManager).create(symbolOptions); }
### Question: WaynameFeatureFilter { @Nullable Point findPointFromCurrentPoint(@Nullable Point currentPoint, @NonNull LineString lineString) { List<Point> lineStringCoordinates = lineString.coordinates(); int coordinateSize = lineStringCoordinates.size(); if (coordinateSize < TWO_POINTS) { return null; } Point lastLinePoint = lineStringCoordinates.get(coordinateSize - 1); if (currentPoint == null || currentPoint.equals(lastLinePoint)) { return null; } LineString sliceFromCurrentPoint = lineSlice(currentPoint, lastLinePoint, lineString); LineString meterSlice = lineSliceAlong(sliceFromCurrentPoint, ZERO_METERS, (double) 10, UNIT_METRES); List<Point> slicePoints = meterSlice.coordinates(); if (slicePoints.isEmpty()) { return null; } return slicePoints.get(FIRST); } WaynameFeatureFilter( @NonNull List<Feature> queriedFeatures, @NonNull Location currentLocation, @NonNull List<Point> currentStepPoints); }### Answer: @Test public void findPointFromCurrentPoint() { Feature featureOne = Feature.fromJson(loadJsonFixture("feature_one.json")); Point currentPoint = Point.fromLngLat(1.234, 4.567); WaynameFeatureFilter waynameFeatureFilter = buildFilter(); Point featureAheadOfUser = waynameFeatureFilter.findPointFromCurrentPoint(currentPoint, (LineString) featureOne.geometry()); }
### Question: LocationFpsDelegate implements MapboxMap.OnCameraIdleListener { void onStart() { mapboxMap.addOnCameraIdleListener(this); } LocationFpsDelegate(@NonNull MapboxMap mapboxMap, @NonNull LocationComponent locationComponent); @Override void onCameraIdle(); }### Answer: @Test public void onStart_idleListenerAdded() { MapboxMap mapboxMap = mock(MapboxMap.class); LocationComponent locationComponent = mock(LocationComponent.class); LocationFpsDelegate locationFpsDelegate = new LocationFpsDelegate(mapboxMap, locationComponent); locationFpsDelegate.onStart(); verify(mapboxMap, times(2)).addOnCameraIdleListener(eq(locationFpsDelegate)); }
### Question: LocationFpsDelegate implements MapboxMap.OnCameraIdleListener { void onStop() { mapboxMap.removeOnCameraIdleListener(this); } LocationFpsDelegate(@NonNull MapboxMap mapboxMap, @NonNull LocationComponent locationComponent); @Override void onCameraIdle(); }### Answer: @Test public void onStop_idleListenerRemoved() { MapboxMap mapboxMap = mock(MapboxMap.class); LocationComponent locationComponent = mock(LocationComponent.class); LocationFpsDelegate locationFpsDelegate = new LocationFpsDelegate(mapboxMap, locationComponent); locationFpsDelegate.onStop(); verify(mapboxMap).removeOnCameraIdleListener(eq(locationFpsDelegate)); }
### Question: LocationFpsDelegate implements MapboxMap.OnCameraIdleListener { void updateEnabled(boolean isEnabled) { this.isEnabled = isEnabled; resetMaxFps(); } LocationFpsDelegate(@NonNull MapboxMap mapboxMap, @NonNull LocationComponent locationComponent); @Override void onCameraIdle(); }### Answer: @Test public void updateEnabled_falseResetsToMax() { MapboxMap mapboxMap = mock(MapboxMap.class); LocationComponent locationComponent = mock(LocationComponent.class); LocationFpsDelegate locationFpsDelegate = new LocationFpsDelegate(mapboxMap, locationComponent); locationFpsDelegate.updateEnabled(false); verify(locationComponent).setMaxAnimationFps(eq(Integer.MAX_VALUE)); }
### Question: MapWayName { void updateWayNameWithPoint(PointF point) { if (!isAutoQueryEnabled) { return; } List<Feature> roadLabelFeatures = findRoadLabelFeatures(point); boolean invalidLabelFeatures = roadLabelFeatures.isEmpty(); if (invalidLabelFeatures) { return; } executeFeatureFilterTask(roadLabelFeatures); } MapWayName(WaynameFeatureFinder featureInteractor, @NonNull MapPaddingAdjustor paddingAdjustor); }### Answer: @Test public void onFeatureWithoutNamePropertyReturned_updateIsIgnored() { PointF point = mock(PointF.class); SymbolLayer waynameLayer = mock(SymbolLayer.class); List<Feature> roads = new ArrayList<>(); Feature road = mock(Feature.class); roads.add(road); MapWayName mapWayName = buildMapWayname(point, roads); mapWayName.updateWayNameWithPoint(point); verify(waynameLayer, times(0)).setProperties(any(PropertyValue.class)); }
### Question: NavigationViewSubscriber implements LifecycleObserver { @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY) void unsubscribe() { navigationViewModel.retrieveRoute().removeObservers(lifecycleOwner); navigationViewModel.retrieveDestination().removeObservers(lifecycleOwner); navigationViewModel.retrieveNavigationLocation().removeObservers(lifecycleOwner); navigationViewModel.retrieveShouldRecordScreenshot().removeObservers(lifecycleOwner); navigationViewModel.retrieveIsFeedbackSentSuccess().removeObservers(lifecycleOwner); } NavigationViewSubscriber(final LifecycleOwner owner, final NavigationViewModel navigationViewModel, final NavigationPresenter navigationPresenter); }### Answer: @Test public void checkObserversAreRemovedWhenUnsubscribe() { when(navigationViewModel.retrieveRoute()).thenReturn(mock(MutableLiveData.class)); when(navigationViewModel.retrieveNavigationLocation()).thenReturn(mock(MutableLiveData.class)); when(navigationViewModel.retrieveDestination()).thenReturn(mock(MutableLiveData.class)); when(navigationViewModel.retrieveShouldRecordScreenshot()).thenReturn(mock(MutableLiveData.class)); when(navigationViewModel.retrieveIsFeedbackSentSuccess()).thenReturn(mock(MutableLiveData.class)); theNavigationViewSubscriber.unsubscribe(); verify(navigationViewModel.retrieveRoute()).removeObservers(eq(lifecycleOwner)); verify(navigationViewModel.retrieveNavigationLocation()).removeObservers(eq(lifecycleOwner)); verify(navigationViewModel.retrieveDestination()).removeObservers(eq(lifecycleOwner)); verify(navigationViewModel.retrieveShouldRecordScreenshot()).removeObservers(eq(lifecycleOwner)); verify(navigationViewModel.retrieveIsFeedbackSentSuccess()).removeObservers(eq(lifecycleOwner)); }
### Question: NavigationOnCameraTrackingChangedListener implements OnCameraTrackingChangedListener { @Override public void onCameraTrackingDismissed() { if (summaryBehavior.getState() != BottomSheetBehavior.STATE_HIDDEN) { navigationPresenter.onCameraTrackingDismissed(); } } NavigationOnCameraTrackingChangedListener(NavigationPresenter navigationPresenter, BottomSheetBehavior summaryBehavior); @Override void onCameraTrackingDismissed(); @Override void onCameraTrackingChanged(int currentMode); }### Answer: @Test public void onCameraTrackingDismissed_presenterNotifiedWithVisibleBottomsheet() { NavigationPresenter presenter = mock(NavigationPresenter.class); BottomSheetBehavior behavior = mock(BottomSheetBehavior.class); when(behavior.getState()).thenReturn(BottomSheetBehavior.STATE_EXPANDED); NavigationOnCameraTrackingChangedListener listener = new NavigationOnCameraTrackingChangedListener( presenter, behavior ); listener.onCameraTrackingDismissed(); verify(presenter).onCameraTrackingDismissed(); } @Test public void onCameraTrackingDismissed_ignoredWithHiddenBottomsheet() { NavigationPresenter presenter = mock(NavigationPresenter.class); BottomSheetBehavior behavior = mock(BottomSheetBehavior.class); when(behavior.getState()).thenReturn(BottomSheetBehavior.STATE_HIDDEN); NavigationOnCameraTrackingChangedListener listener = new NavigationOnCameraTrackingChangedListener( presenter, behavior ); listener.onCameraTrackingDismissed(); verify(presenter, times(0)).onCameraTrackingDismissed(); }
### Question: AbbreviationCreator extends NodeCreator<AbbreviationCreator.AbbreviationNode, AbbreviationVerifier> { @Override void preProcess(@NonNull TextView textView, @NonNull List<BannerComponentNode> bannerComponentNodes) { String text = abbreviateBannerText(textView, bannerComponentNodes); textView.setText(text); } AbbreviationCreator(AbbreviationVerifier abbreviationVerifier, HashMap abbreviations, TextViewUtils textViewUtils); AbbreviationCreator(AbbreviationVerifier abbreviationVerifier); AbbreviationCreator(); }### Answer: @Test public void preProcess_abbreviate() { String abbreviation = "smtxt"; BannerComponents bannerComponents = BannerComponentsFaker.bannerComponentsBuilder() .abbreviation(abbreviation) .abbreviationPriority(0) .build(); TextView textView = mock(TextView.class); AbbreviationVerifier abbreviationVerifier = mock(AbbreviationVerifier.class); when(abbreviationVerifier.isNodeType(bannerComponents)).thenReturn(true); TextViewUtils textViewUtils = mock(TextViewUtils.class); when(textViewUtils.textFits(textView, abbreviation)).thenReturn(true); when(textViewUtils.textFits(textView, bannerComponents.text())).thenReturn(false); BannerComponentNode node = mock(AbbreviationCreator.AbbreviationNode.class); when(((AbbreviationCreator.AbbreviationNode) node).getAbbreviate()).thenReturn(true); when(node.toString()).thenReturn(abbreviation); AbbreviationCreator abbreviationCreator = new AbbreviationCreator(abbreviationVerifier); abbreviationCreator.preProcess(textView, Collections.singletonList(node)); verify(textView).setText(abbreviation); }
### Question: AbbreviationCreator extends NodeCreator<AbbreviationCreator.AbbreviationNode, AbbreviationVerifier> { @NonNull @Override AbbreviationNode setupNode(@NonNull BannerComponents components, int index, int startIndex, String modifier) { addPriorityInfo(components, index); return new AbbreviationNode(components, startIndex); } AbbreviationCreator(AbbreviationVerifier abbreviationVerifier, HashMap abbreviations, TextViewUtils textViewUtils); AbbreviationCreator(AbbreviationVerifier abbreviationVerifier); AbbreviationCreator(); }### Answer: @Test public void setupNode() { String abbreviation = "smtxt"; int abbreviationPriority = 0; BannerComponents bannerComponents = BannerComponentsFaker.bannerComponentsBuilder() .abbreviation(abbreviation) .abbreviationPriority(abbreviationPriority) .build(); AbbreviationVerifier abbreviationVerifier = mock(AbbreviationVerifier.class); when(abbreviationVerifier.isNodeType(bannerComponents)).thenReturn(true); HashMap<Integer, List<Integer>> abbreviations = new HashMap(); AbbreviationCreator abbreviationCreator = new AbbreviationCreator(abbreviationVerifier, abbreviations, mock(TextViewUtils.class)); List<BannerComponentNode> bannerComponentNodes = new ArrayList<>(); bannerComponentNodes.add(new AbbreviationCreator.AbbreviationNode(bannerComponents, 0)); abbreviationCreator.setupNode(bannerComponents, 0, 0, ""); assertEquals(abbreviations.size(), 1); assertEquals(abbreviations.get(abbreviationPriority).get(0), Integer.valueOf(0)); }
### Question: NavigationPresenter { void onRouteOverviewClick() { view.setWayNameActive(false); view.setWayNameVisibility(false); view.updateCameraRouteOverview(); view.showRecenterBtn(); } NavigationPresenter(NavigationContract.View view); }### Answer: @Test public void onRouteOverviewButtonClick_cameraIsAdjustedToRoute() { NavigationContract.View view = mock(NavigationContract.View.class); NavigationPresenter presenter = new NavigationPresenter(view); presenter.onRouteOverviewClick(); verify(view).updateCameraRouteOverview(); } @Test public void onRouteOverviewButtonClick_recenterBtnIsShown() { NavigationContract.View view = mock(NavigationContract.View.class); NavigationPresenter presenter = new NavigationPresenter(view); presenter.onRouteOverviewClick(); verify(view).showRecenterBtn(); } @Test public void onRouteOverviewButtonClick_mapWaynameIsHidden() { NavigationContract.View view = mock(NavigationContract.View.class); NavigationPresenter presenter = new NavigationPresenter(view); presenter.onRouteOverviewClick(); verify(view).setWayNameActive(false); verify(view).setWayNameVisibility(false); }
### Question: BannerComponentTree { void loadInstruction(TextView textView) { for (NodeCreator nodeCreator : nodeCreators) { nodeCreator.preProcess(textView, bannerComponentNodes); } for (NodeCreator nodeCreator : nodeCreators) { nodeCreator.postProcess(textView, bannerComponentNodes); } } BannerComponentTree(@NonNull BannerText bannerText, NodeCreator... nodeCreators); }### Answer: @Test public void loadInstruction() { BannerComponents bannerComponents = BannerComponentsFaker.bannerComponents(); List<BannerComponents> bannerComponentsList = Collections.singletonList(bannerComponents); TestNode testNode = mock(TestNode.class); TestCreator testCreator = mock(TestCreator.class); when(testCreator.isNodeType(bannerComponents)).thenReturn(true); when(testCreator.setupNode(bannerComponents, 0, 0, null)).thenReturn(testNode); TextView textView = mock(TextView.class); BannerText bannerText = mock(BannerText.class); when(bannerText.components()).thenReturn(bannerComponentsList); BannerComponentTree bannerComponentTree = new BannerComponentTree(bannerText, testCreator); bannerComponentTree.loadInstruction(textView); InOrder inOrder = inOrder(testCreator, testCreator); inOrder.verify(testCreator).preProcess(any(TextView.class), any(List.class)); inOrder.verify(testCreator).postProcess(any(TextView.class), any(List.class)); }
### Question: NavigationPresenter { void onRecenterClick() { view.setSummaryBehaviorHideable(false); view.setSummaryBehaviorState(BottomSheetBehavior.STATE_EXPANDED); view.setWayNameActive(true); if (!TextUtils.isEmpty(view.retrieveWayNameText())) { view.setWayNameVisibility(true); } view.resetCameraPosition(); view.hideRecenterBtn(); } NavigationPresenter(NavigationContract.View view); }### Answer: @Test public void onRecenterBtnClick_recenterBtnIsHidden() { NavigationContract.View view = mock(NavigationContract.View.class); NavigationPresenter presenter = new NavigationPresenter(view); presenter.onRecenterClick(); verify(view).hideRecenterBtn(); } @Test public void onRecenterBtnClick_cameraIsResetToTracking() { NavigationContract.View view = mock(NavigationContract.View.class); NavigationPresenter presenter = new NavigationPresenter(view); presenter.onRecenterClick(); verify(view).resetCameraPosition(); } @Test public void onRecenterBtnClick_mapWayNameIsShown() { NavigationContract.View view = mock(NavigationContract.View.class); when(view.retrieveWayNameText()).thenReturn("Some way name"); NavigationPresenter presenter = new NavigationPresenter(view); presenter.onRecenterClick(); verify(view).setWayNameActive(true); verify(view).setWayNameVisibility(true); }
### Question: NavigationPresenter { void onWayNameChanged(@NonNull String wayName) { if (TextUtils.isEmpty(wayName) || view.isSummaryBottomSheetHidden()) { view.setWayNameActive(false); view.setWayNameVisibility(false); return; } view.updateWayNameView(wayName); view.setWayNameActive(true); view.setWayNameVisibility(true); } NavigationPresenter(NavigationContract.View view); }### Answer: @Test public void onWayNameChanged_mapWayNameIsShown() { NavigationContract.View view = mock(NavigationContract.View.class); NavigationPresenter presenter = new NavigationPresenter(view); presenter.onWayNameChanged("Some way name"); verify(view).setWayNameActive(true); verify(view).setWayNameVisibility(true); } @Test public void onWayNameChanged_mapWayNameIsUpdated() { String someWayName = "Some way name"; NavigationContract.View view = mock(NavigationContract.View.class); NavigationPresenter presenter = new NavigationPresenter(view); presenter.onWayNameChanged(someWayName); verify(view).updateWayNameView(someWayName); } @Test public void onWayNameChanged_mapWayNameIsHidden() { NavigationContract.View view = mock(NavigationContract.View.class); NavigationPresenter presenter = new NavigationPresenter(view); presenter.onWayNameChanged(""); verify(view).setWayNameActive(false); verify(view).setWayNameVisibility(false); } @Test public void onWayNameChanged_mapWayNameIsHiddenWithCollapsedBottomsheet() { NavigationContract.View view = mock(NavigationContract.View.class); when(view.isSummaryBottomSheetHidden()).thenReturn(true); NavigationPresenter presenter = new NavigationPresenter(view); presenter.onWayNameChanged("some valid way name"); verify(view).setWayNameActive(false); verify(view).setWayNameVisibility(false); }
### Question: NavigationPresenter { void onNavigationStopped() { view.setWayNameActive(false); view.setWayNameVisibility(false); } NavigationPresenter(NavigationContract.View view); }### Answer: @Test public void onNavigationStopped_mapWayNameIsHidden() { NavigationContract.View view = mock(NavigationContract.View.class); NavigationPresenter presenter = new NavigationPresenter(view); presenter.onNavigationStopped(); verify(view).setWayNameActive(false); verify(view).setWayNameVisibility(false); }
### Question: NavigationPresenter { void onRouteUpdate(DirectionsRoute directionsRoute) { view.drawRoute(directionsRoute); if (resumeState && view.isRecenterButtonVisible()) { view.updateCameraRouteOverview(); } else { view.startCamera(directionsRoute); } } NavigationPresenter(NavigationContract.View view); }### Answer: @Test public void onRouteUpdate_routeIsDrawn() { DirectionsRoute directionsRoute = mock(DirectionsRoute.class); NavigationContract.View view = mock(NavigationContract.View.class); NavigationPresenter presenter = new NavigationPresenter(view); presenter.onRouteUpdate(directionsRoute); verify(view).drawRoute(directionsRoute); } @Test public void onRouteUpdate_cameraIsStartedOnFirstRoute() { DirectionsRoute directionsRoute = mock(DirectionsRoute.class); NavigationContract.View view = mock(NavigationContract.View.class); NavigationPresenter presenter = new NavigationPresenter(view); presenter.onRouteUpdate(directionsRoute); verify(view).startCamera(directionsRoute); }