method2testcases
stringlengths
118
6.63k
### Question: SyncUpdate implements Origin { @Override public String getName() { return "sync update"; } SyncUpdate(final DateTimeProvider dateTimeProvider, final String remoteAddress); @Override boolean isDefaultOverride(); @Override boolean allowAdminOperations(); @Override String getId(); @Override String getFrom(); @Override String getResponseHeader(); @Override String getNotificationHeader(); @Override String getName(); @Override String toString(); }### Answer: @Test public void getName() { assertThat(subject.getName(), is("sync update")); }
### Question: SyncUpdate implements Origin { @Override public String getResponseHeader() { return getHeader(); } SyncUpdate(final DateTimeProvider dateTimeProvider, final String remoteAddress); @Override boolean isDefaultOverride(); @Override boolean allowAdminOperations(); @Override String getId(); @Override String getFrom(); @Override String getResponseHeader(); @Override String getNotificationHeader(); @Override String getName(); @Override String toString(); }### Answer: @Test public void response_header_for_any_request() { assertThat(subject.getResponseHeader(), containsString("" + " - From-Host: 127.0.0.1\n" + " - Date/Time: Thu Jan 1 00:00:00 1970\n")); }
### Question: SyncUpdate implements Origin { @Override public String getNotificationHeader() { return getHeader(); } SyncUpdate(final DateTimeProvider dateTimeProvider, final String remoteAddress); @Override boolean isDefaultOverride(); @Override boolean allowAdminOperations(); @Override String getId(); @Override String getFrom(); @Override String getResponseHeader(); @Override String getNotificationHeader(); @Override String getName(); @Override String toString(); }### Answer: @Test public void notification_header_for_any_request() { assertThat(subject.getNotificationHeader(), containsString("" + " - From-Host: 127.0.0.1\n" + " - Date/Time: Thu Jan 1 00:00:00 1970\n")); }
### Question: DelegatedStatsService implements EmbeddedValueResolverAware { public URI getUriForRedirect(final String requestPath, final Query query) { final Optional<ObjectType> objectType = query.getObjectTypes().stream() .filter(ALLOWED_OBJECTTYPES::contains) .findFirst(); if (objectType.isPresent()) { for (Map.Entry<CIString, String> entry : sourceToPathMap.entrySet()) { final CIString sourceName = entry.getKey(); final AuthoritativeResource authoritativeResource = resourceData.getAuthoritativeResource(sourceName); if (authoritativeResource.isMaintainedInRirSpace(objectType.get(), CIString.ciString(query.getSearchValue()))) { final String basePath = entry.getValue(); LOGGER.debug("Redirecting {} to {}", requestPath, sourceName); return URI.create(String.format("%s%s", basePath, requestPath.replaceFirst("/rdap", ""))); } } } LOGGER.debug("Resource {} not found", query.getSearchValue()); throw new WebApplicationException(Response.Status.NOT_FOUND); } @Autowired DelegatedStatsService(@Value("${rdap.sources:}") String rdapSourceNames, final AuthoritativeResourceData resourceData); @Override void setEmbeddedValueResolver(StringValueResolver valueResolver); URI getUriForRedirect(final String requestPath, final Query query); boolean isMaintainedInRirSpace(final CIString source, final ObjectType objectType, final CIString pkey); }### Answer: @Test public void getUri_value_not_found() { try { subject.getUriForRedirect("/rdap/autnum/3546", Query.parse("-T aut-num AS3546")); fail(); } catch (WebApplicationException expected) { assertThat(expected.getResponse().getStatus(), is(Response.Status.NOT_FOUND.getStatusCode())); } }
### Question: DummifierCurrent implements Dummifier { @Override public boolean isAllowed(final int version, final RpslObject object) { return version >= 3; } @Override RpslObject dummify(final int version, final RpslObject rpslObject); @Override boolean isAllowed(final int version, final RpslObject object); }### Answer: @Test public void allowed() { assertThat(subject.isAllowed(3, object), is(true)); assertThat(subject.isAllowed(2, object), is(false)); assertThat(subject.isAllowed(1, object), is(false)); }
### Question: RdapObjectMapper { public Object mapSearch(final String requestUrl, final List<RpslObject> objects, final Iterable<LocalDateTime> localDateTimes, final int maxResultSize) { final SearchResult searchResult = new SearchResult(); final Iterator<LocalDateTime> iterator = localDateTimes.iterator(); for (final RpslObject object : objects) { if (object.getType() == DOMAIN) { searchResult.addDomainSearchResult((Domain) getRdapObject(requestUrl, object, iterator.next(), Optional.empty())); } else { searchResult.addEntitySearchResult((Entity) getRdapObject(requestUrl, object, iterator.next(), Optional.empty())); } } if(objects.size() == maxResultSize) { final Notice notice = new Notice(); notice.setTitle(String.format("limited search results to %s maximum" , maxResultSize)); searchResult.getNotices().add(notice); } return mapCommons(searchResult, requestUrl); } @Autowired RdapObjectMapper( final NoticeFactory noticeFactory, @Qualifier("jdbcRpslObjectSlaveDao") final RpslObjectDao rpslObjectDao, final Ipv4Tree ipv4Tree, final Ipv6Tree ipv6Tree, @Value("${rdap.port43:}") final String port43); Object map(final String requestUrl, final RpslObject rpslObject, final LocalDateTime lastChangedTimestamp, final Optional<AbuseContact> abuseContact); Object mapSearch(final String requestUrl, final List<RpslObject> objects, final Iterable<LocalDateTime> localDateTimes, final int maxResultSize); RdapObject mapError(final int errorCode, final String errorTitle, final List<String> errorDescriptions); RdapObject mapHelp(final String requestUrl); }### Answer: @Test public void mapSearch_twoObjects() { final List<RpslObject> objects = Lists.newArrayList( RpslObject.parse("organisation: ORG-TOL-TEST\norg-name: Test Organisation\nstatus: OTHER\ndescr: comment 1\nsource: TEST"), RpslObject.parse("organisation: ORG-TST-TEST\norg-name: Test Company\nstatus: OTHER\ndescr: comment 2\nsource: TEST") ); final SearchResult response = (SearchResult)mapSearch(objects, Lists.newArrayList(LocalDateTime.parse("1970-04-14T09:22:14.857"), LocalDateTime.parse("1996-02-05T03:52:05.938"))); assertThat(response.getEntitySearchResults(), hasSize(2)); final Entity first = response.getEntitySearchResults().get(0); assertThat(first.getHandle(), is("ORG-TOL-TEST")); assertThat(first.getEvents(), hasSize(1)); assertThat(first.getEvents().get(0).getEventAction(), is(Action.LAST_CHANGED)); assertThat(first.getRemarks(), hasSize(1)); assertThat(first.getRemarks().get(0).getDescription().get(0), is("comment 1")); final Entity last = response.getEntitySearchResults().get(1); assertThat(last.getHandle(), is("ORG-TST-TEST")); assertThat(last.getEvents(), hasSize(1)); assertThat(last.getEvents().get(0).getEventAction(), is(Action.LAST_CHANGED)); assertThat(last.getRemarks(), hasSize(1)); assertThat(last.getRemarks().get(0).getDescription().get(0), is("comment 2")); }
### Question: RdapObjectMapper { public RdapObject mapHelp(final String requestUrl) { return mapCommons(new RdapObject(), requestUrl); } @Autowired RdapObjectMapper( final NoticeFactory noticeFactory, @Qualifier("jdbcRpslObjectSlaveDao") final RpslObjectDao rpslObjectDao, final Ipv4Tree ipv4Tree, final Ipv6Tree ipv6Tree, @Value("${rdap.port43:}") final String port43); Object map(final String requestUrl, final RpslObject rpslObject, final LocalDateTime lastChangedTimestamp, final Optional<AbuseContact> abuseContact); Object mapSearch(final String requestUrl, final List<RpslObject> objects, final Iterable<LocalDateTime> localDateTimes, final int maxResultSize); RdapObject mapError(final int errorCode, final String errorTitle, final List<String> errorDescriptions); RdapObject mapHelp(final String requestUrl); }### Answer: @Test public void help() { final RdapObject result = mapper.mapHelp("http: assertThat(result.getLinks(), hasSize(2)); assertThat(result.getLinks().get(0).getRel(), is("self")); assertThat(result.getLinks().get(1).getRel(), is("copyright")); assertThat(result.getEvents(), is(emptyIterable())); assertThat(result.getStatus(), is(emptyIterable())); assertThat(result.getPort43(), is("whois.ripe.net")); }
### Question: RdapRequestValidator { public void validateEntity(final String key) { if (key.toUpperCase().startsWith("ORG-")) { if (!AttributeType.ORGANISATION.isValidValue(ORGANISATION, key)) { throw new NotFoundException("Invalid syntax."); } } else { if (!AttributeType.MNTNER.isValidValue(MNTNER, key)) { throw new NotFoundException("Invalid syntax."); } } } @Autowired RdapRequestValidator(final ReservedAutnum reservedAutnum); void validateDomain(final String key); void validateIp(final String rawUri, final String key); void validateAutnum(final String key); void validateEntity(final String key); boolean isReservedAsNumber(String key); }### Answer: @Test public void shouldThrowExceptionForInvalidOrganisation() { expectedEx.expect(NotFoundException.class); expectedEx.expectMessage("Invalid syntax"); validator.validateEntity("ORG-Test"); } @Test public void shouldNotThrowAnyExceptionForValidEntity() { validator.validateEntity("ORG-BAD1-TEST"); }
### Question: RdapRequestValidator { public void validateAutnum(final String key) { try { AutNum.parse(key); } catch (AttributeParseException e) { throw new BadRequestException("Invalid syntax."); } } @Autowired RdapRequestValidator(final ReservedAutnum reservedAutnum); void validateDomain(final String key); void validateIp(final String rawUri, final String key); void validateAutnum(final String key); void validateEntity(final String key); boolean isReservedAsNumber(String key); }### Answer: @Test(expected = BadRequestException.class) public void shouldThrowExceptionForInvalidAutnum() { validator.validateAutnum("TEST"); } @Test public void shouldNotThrowAExceptionForValidAutnum() { validator.validateAutnum("AS102"); }
### Question: RdapRequestValidator { public void validateIp(final String rawUri, final String key) { try { IpInterval.parse(key); } catch (IllegalArgumentException e) { throw new BadRequestException("Invalid syntax."); } if (rawUri.contains(" throw new BadRequestException("Invalid syntax."); } } @Autowired RdapRequestValidator(final ReservedAutnum reservedAutnum); void validateDomain(final String key); void validateIp(final String rawUri, final String key); void validateAutnum(final String key); void validateEntity(final String key); boolean isReservedAsNumber(String key); }### Answer: @Test(expected = BadRequestException.class) public void shouldThrowExceptionForInvalidIP() { validator.validateIp("", "invalid"); } @Test public void shouldNotThrowExceptionForValidIP() { validator.validateIp("", "192.0.0.0"); }
### Question: ExtensionOverridesAcceptHeaderFilter implements Filter { @Override public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { if (request instanceof HttpServletRequest) { chain.doFilter(OverrideAcceptHeaderWrapper.wrapRequest((HttpServletRequest) request), response); } else { LOGGER.warn("Unexpected request: {}", request); chain.doFilter(request, response); } } @Override void init(final FilterConfig filterConfig); @Override void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain); @Override void destroy(); }### Answer: @Test public void xml_extension() throws Exception { final HttpServletRequest request = doFilter("http", "localhost", "/whois/test/inet6num/No%20clue%20what%20the%20range%20is.xml"); assertThat(request.getRequestURI(), is("/whois/test/inet6num/No%20clue%20what%20the%20range%20is")); assertThat(request.getRequestURL().toString(), is("http: assertThat(request.getHeader("Accept"), is("application/xml")); assertThat(toList(request.getHeaders("Accept")), contains("application/xml")); } @Test public void json_extension() throws Exception { final HttpServletRequest request = doFilter("http", "localhost", "/whois/test/inet6num/No%20clue%20what%20the%20range%20is.json"); assertThat(request.getRequestURI(), is("/whois/test/inet6num/No%20clue%20what%20the%20range%20is")); assertThat(request.getRequestURL().toString(), is("http: assertThat(request.getHeader("Accept"), is("application/json")); assertThat(toList(request.getHeaders("Accept")), contains("application/json")); } @Test public void unknown_extension() throws Exception { final HttpServletRequest request = doFilter("http", "localhost", "/whois/test/inet6num/No%20clue%20what%20the%20range%20is.unknown"); assertThat(request.getRequestURI(), is("/whois/test/inet6num/No%20clue%20what%20the%20range%20is.unknown")); assertThat(request.getRequestURL().toString(), is("http: assertThat(request.getHeader("Accept"), is(nullValue())); assertThat(request.getHeaders("Accept"), is(nullValue())); } @Test public void no_extension() throws Exception { final HttpServletRequest request = doFilter("http", "localhost", "/whois/test/inet6num/No%20clue%20what%20the%20range%20is"); assertThat(request.getRequestURI(), is("/whois/test/inet6num/No%20clue%20what%20the%20range%20is")); assertThat(request.getRequestURL().toString(), is("http: assertThat(request.getHeader("Accept"), is(nullValue())); assertThat(request.getHeaders("Accept"), is(nullValue())); } @Test public void root_slash() throws Exception { final HttpServletRequest request = doFilter("http", "localhost", "/"); assertThat(request.getRequestURI(), is("/")); assertThat(request.getRequestURL().toString(), is("http: assertThat(request.getHeader("Accept"), is(nullValue())); assertThat(request.getHeaders("Accept"), is(nullValue())); } @Test public void root_no_slash() throws Exception { final HttpServletRequest request = doFilter("http", "localhost", ""); assertThat(request.getRequestURI(), is("")); assertThat(request.getRequestURL().toString(), is("http: assertThat(request.getHeader("Accept"), is(nullValue())); assertThat(request.getHeaders("Accept"), is(nullValue())); }
### Question: RemoteAddressFilter implements Filter { @Override public void init(final FilterConfig filterConfig) throws ServletException { } @Override void init(final FilterConfig filterConfig); @Override void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain); @Override void destroy(); }### Answer: @Test public void init() throws Exception { subject.init(null); }
### Question: RemoteAddressFilter implements Filter { @Override public void destroy() { } @Override void init(final FilterConfig filterConfig); @Override void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain); @Override void destroy(); }### Answer: @Test public void destroy() { subject.destroy(); }
### Question: RemoteAddressFilter implements Filter { @Override public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { if (request instanceof HttpServletRequest) { chain.doFilter(new RemoteAddressRequestWrapper((HttpServletRequest) request), response); } else { chain.doFilter(request, response); } } @Override void init(final FilterConfig filterConfig); @Override void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain); @Override void destroy(); }### Answer: @Test public void no_servletRequest() throws Exception { final ServletRequest servletRequest = mock(ServletRequest.class); final ServletResponse servletResponse = mock(ServletResponse.class); subject.doFilter(servletRequest, servletResponse, filterChain); verify(filterChain).doFilter(servletRequest, servletResponse); } @Test public void no_forward_header() throws Exception { when(request.getRemoteAddr()).thenReturn("10.0.0.0"); subject.doFilter(request, response, filterChain); verify(filterChain).doFilter(argThat(new CheckRemoteAddress("10.0.0.0")), any(ServletResponse.class)); } @Test public void forward_header() throws Exception { when(request.getHeaders(HttpHeaders.X_FORWARDED_FOR)).thenReturn(Collections.enumeration(Lists.newArrayList("193.0.20.1"))); when(request.getRemoteAddr()).thenReturn("10.0.0.0"); subject.doFilter(request, response, filterChain); verify(filterChain).doFilter(argThat(new CheckRemoteAddress("193.0.20.1")), any(ServletResponse.class)); } @Test public void forward_headers_ripe_range() throws Exception { when(request.getHeaders(HttpHeaders.X_FORWARDED_FOR)).thenReturn(Collections.enumeration(Lists.newArrayList("74.125.136.99", "193.0.20.1"))); when(request.getRemoteAddr()).thenReturn("10.0.0.0"); subject.doFilter(request, response, filterChain); verify(filterChain).doFilter(argThat(new CheckRemoteAddress("74.125.136.99")), any(ServletResponse.class)); } @Test public void forward_header_comma_separated_values() throws Exception { when(request.getHeaders(HttpHeaders.X_FORWARDED_FOR)).thenReturn(Collections.enumeration(Lists.newArrayList("74.125.136.99, 193.0.20.1"))); when(request.getRemoteAddr()).thenReturn("10.0.0.0"); subject.doFilter(request, response, filterChain); verify(filterChain).doFilter(argThat(new CheckRemoteAddress("193.0.20.1")), any(ServletResponse.class)); }
### Question: MailMessage implements Origin { public String getUpdateMessage() { StringBuilder builder = new StringBuilder(); Iterator<ContentWithCredentials> iterator = contentWithCredentials.iterator(); while (iterator.hasNext()) { builder.append(iterator.next().getContent()); if (iterator.hasNext()) { builder.append("\n\n"); } } return builder.toString(); } MailMessage(final String id, final String from, final String subject, final String date, final String replyTo, String replyToEmail, final Keyword keyword, List<ContentWithCredentials> contentWithCredentials); @Override boolean isDefaultOverride(); @Override boolean allowAdminOperations(); String getId(); String getSubject(); String getDate(); String getReplyTo(); String getReplyToEmail(); String getUpdateMessage(); List<ContentWithCredentials> getContentWithCredentials(); @Override String getFrom(); Keyword getKeyword(); @Override String getResponseHeader(); @Override String getNotificationHeader(); @Override String getName(); @Override String toString(); }### Answer: @Test public void getUpdateMessage() { List<ContentWithCredentials> contentWithCredentialsList = Lists.newArrayList(); contentWithCredentialsList.add(new ContentWithCredentials("password: some password\nmntner: TST-MNT")); contentWithCredentialsList.add(new ContentWithCredentials("password: another password\nmntner: TST2-MNT")); final MailMessage subject = new MailMessage("id", "from", "subject", "date", "replyTo", "replyToEmail", Keyword.NONE, contentWithCredentialsList); assertThat(subject.getUpdateMessage(), is("" + "password: some password\n" + "mntner: TST-MNT\n" + "\n" + "password: another password\n" + "mntner: TST2-MNT")); }
### Question: MessageFilter { public boolean shouldProcess(final MailMessage message) { String replyToEmail = message.getReplyToEmail(); if (replyToEmail == null) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, missing reply address")); return false; } try { new InternetAddress(replyToEmail, true); } catch (final AddressException e) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply address invalid: %s", replyToEmail)); return false; } if (!EmailValidator.getInstance().isValid(replyToEmail)) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply address invalid: %s", replyToEmail)); return false; } replyToEmail = replyToEmail.toLowerCase(); if (replyToEmail.endsWith("localhost") || replyToEmail.endsWith("127.0.0.1")) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply to localhost: %s", replyToEmail)); return false; } return true; } @Autowired MessageFilter(final LoggerContext loggerContext); boolean shouldProcess(final MailMessage message); }### Answer: @Test public void shouldProcess() throws Exception { when(message.getReplyTo()).thenReturn("[email protected]"); when(message.getReplyToEmail()).thenReturn("[email protected]"); assertThat(subject.shouldProcess(message), is(true)); } @Test public void shouldProcessFull() throws Exception { when(message.getReplyTo()).thenReturn("Maximus Maxus <[email protected]>"); when(message.getReplyToEmail()).thenReturn("[email protected]"); assertThat(subject.shouldProcess(message), is(true)); } @Test public void shouldProcess_localhost() throws Exception { when(message.getReplyTo()).thenReturn("something@localhost"); when(message.getReplyToEmail()).thenReturn("something@localhost"); assertThat(subject.shouldProcess(message), is(false)); } @Test public void shouldProcess_127_0_0_1() throws Exception { when(message.getReplyTo()).thenReturn("[email protected]"); when(message.getReplyToEmail()).thenReturn("[email protected]"); assertThat(subject.shouldProcess(message), is(false)); } @Test public void noReplytoFails() throws Exception { when(message.getReplyTo()).thenReturn(null); when(message.getReplyToEmail()).thenReturn(null); assertThat(subject.shouldProcess(message), is(false)); } @Test public void noReplytoFailsFull() throws Exception { when(message.getReplyTo()).thenReturn("Maximus Maxus"); when(message.getReplyToEmail()).thenReturn(null); assertThat(subject.shouldProcess(message), is(false)); } @Test public void invalidReplytoFails() throws Exception { when(message.getReplyTo()).thenReturn("email_with_no_domain_or_at_sign"); when(message.getReplyToEmail()).thenReturn("email_with_no_domain_or_at_sign"); assertThat(subject.shouldProcess(message), is(false)); } @Test public void invalidReplytoFailsFull() throws Exception { when(message.getReplyTo()).thenReturn("Minima Mina <email_with_no_domain_or_at_sign>"); when(message.getReplyToEmail()).thenReturn("email_with_no_domain_or_at_sign"); assertThat(subject.shouldProcess(message), is(false)); }
### Question: MessageDequeue implements ApplicationService { @Override public void stop(final boolean force) { LOGGER.info("Message dequeue stopping"); if (stopExecutor(pollerExecutor)) { pollerExecutor = null; } if (stopExecutor(handlerExecutor)) { handlerExecutor = null; } LOGGER.info("Message dequeue stopped"); } @Autowired MessageDequeue(final MaintenanceMode maintenanceMode, final MailGateway mailGateway, final MailMessageDao mailMessageDao, final MessageFilter messageFilter, final MessageParser messageParser, final UpdatesParser updatesParser, final UpdateRequestHandler messageHandler, final LoggerContext loggerContext, final DateTimeProvider dateTimeProvider); @Override void start(); @Override void stop(final boolean force); }### Answer: @Test public void stop_not_running() throws InterruptedException { subject.stop(true); }
### Question: MessageDequeue implements ApplicationService { private void handleMessage(final String messageId) { final MimeMessage message = mailMessageDao.getMessage(messageId); try { loggerContext.init(getMessageIdLocalPart(message)); try { handleMessageInContext(messageId, message); } finally { loggerContext.remove(); } } catch (MessagingException e) { LOGGER.error("Handle message", e); } catch (IOException e) { LOGGER.error("Handle message", e); } } @Autowired MessageDequeue(final MaintenanceMode maintenanceMode, final MailGateway mailGateway, final MailMessageDao mailMessageDao, final MessageFilter messageFilter, final MessageParser messageParser, final UpdatesParser updatesParser, final UpdateRequestHandler messageHandler, final LoggerContext loggerContext, final DateTimeProvider dateTimeProvider); @Override void start(); @Override void stop(final boolean force); }### Answer: @Test public void handleMessage() throws Exception { final MimeMessage message = MimeMessageProvider.getMessageSimpleTextUnsigned(); when(messageFilter.shouldProcess(any(MailMessage.class))).thenReturn(true); when(messageParser.parse(eq(message), any(UpdateContext.class))).thenReturn( new MailMessage("", "", "", "", "", "", Keyword.NONE, Lists.<ContentWithCredentials>newArrayList())); when(updatesParser.parse(any(UpdateContext.class), anyListOf(ContentWithCredentials.class))).thenReturn(Lists.<Update>newArrayList()); when(messageHandler.handle(any(UpdateRequest.class), any(UpdateContext.class))).thenReturn(new UpdateResponse(UpdateStatus.SUCCESS, "")); when(mailMessageDao.getMessage("1")).thenReturn(message); when(mailMessageDao.claimMessage()).thenReturn("1").thenReturn(null); subject.start(); verify(mailMessageDao, timeout(TIMEOUT)).deleteMessage("1"); verify(loggerContext, timeout(TIMEOUT)).init("20120527220444.GA6565"); verify(loggerContext, timeout(TIMEOUT)).log(eq("msg-in.txt"), any(MailMessageLogCallback.class)); verify(mailMessageDao, timeout(TIMEOUT)).setStatus("1", DequeueStatus.LOGGED); verify(mailMessageDao, timeout(TIMEOUT)).setStatus("1", DequeueStatus.PARSED); verify(messageHandler, timeout(TIMEOUT)).handle(any(UpdateRequest.class), any(UpdateContext.class)); verify(mailGateway, timeout(TIMEOUT)).sendEmail(anyString(), anyString(), anyString(), any()); }
### Question: MessageDequeue implements ApplicationService { String getMessageIdLocalPart(final Message message) throws MessagingException { final String[] headers = message.getHeader("Message-Id"); if (headers != null && headers.length > 0) { Matcher matcher = MESSAGE_ID_PATTERN.matcher(headers[0]); if (matcher.matches()) { return matcher.group(1); } LOGGER.debug("Unable to parse Message-Id: {}", headers[0]); } return "No-Message-Id." + dateTimeProvider.getElapsedTime(); } @Autowired MessageDequeue(final MaintenanceMode maintenanceMode, final MailGateway mailGateway, final MailMessageDao mailMessageDao, final MessageFilter messageFilter, final MessageParser messageParser, final UpdatesParser updatesParser, final UpdateRequestHandler messageHandler, final LoggerContext loggerContext, final DateTimeProvider dateTimeProvider); @Override void start(); @Override void stop(final boolean force); }### Answer: @Test public void getMessageIdLocalPart_local_and_domain_parts() throws Exception { Message message = mock(Message.class); when(message.getHeader("Message-Id")).thenReturn(new String[]{"<[email protected]>"}); final String messageIdLocalPart = subject.getMessageIdLocalPart(message); assertThat(messageIdLocalPart, is("20120527220444.GA6565")); } @Test public void getMessageIdLocalPart_local_part_only() throws Exception { Message message = mock(Message.class); when(message.getHeader("Message-Id")).thenReturn(new String[]{"<20120527220444.GA6565>"}); final String messageIdLocalPart = subject.getMessageIdLocalPart(message); assertThat(messageIdLocalPart, is("20120527220444.GA6565")); } @Test public void getMessageIdLocalPart_emptyMessageId() throws Exception { Message message = mock(Message.class); final String messageIdLocalPart = subject.getMessageIdLocalPart(message); assertThat(messageIdLocalPart, containsString("No-Message-Id.")); } @Test public void getMessageIdLocalPart_messageId_doesnt_match() throws Exception { Message message = mock(Message.class); when(message.getHeader("Message-Id")).thenReturn(new String[]{"<W[20"}); final String messageIdLocalPart = subject.getMessageIdLocalPart(message); assertThat(messageIdLocalPart, containsString("No-Message-Id.")); }
### Question: MessageParser { Charset getCharset(final ContentType contentType) { final String charset = contentType.getParameter("charset"); if (charset != null) { try { return Charset.forName(MimeUtility.javaCharset(charset)); } catch (UnsupportedCharsetException e) { loggerContext.log(new Message(Messages.Type.WARNING, "Unsupported charset: %s in contentType: %s", charset, contentType)); } catch (IllegalCharsetNameException e) { loggerContext.log(new Message(Messages.Type.WARNING, "Illegal charset: %s in contentType: %s", charset, contentType)); } } return StandardCharsets.ISO_8859_1; } @Autowired MessageParser(final LoggerContext loggerContext); MailMessage parse(final MimeMessage message, final UpdateContext updateContext); }### Answer: @Test public void illegal_charset() throws Exception { assertThat(subject.getCharset(new ContentType("text/plain;\n\tcharset=\"_iso-2022-jp$ESC\"")), is(StandardCharsets.ISO_8859_1)); }
### Question: DnsCheckRequest { @Override public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; final DnsCheckRequest that = (DnsCheckRequest) o; return Objects.equals(domain, that.domain) && Objects.equals(glue, that.glue); } DnsCheckRequest(final Update update, final String domain, final String glue); Update getUpdate(); String getDomain(); String getGlue(); @Override boolean equals(final Object o); @Override int hashCode(); @Override String toString(); }### Answer: @Test public void equals_null() { assertThat(new DnsCheckRequest(update, "domain", "glue").equals(null), is(false)); } @Test public void equals_other_class() { assertThat(new DnsCheckRequest(update, "domain", "glue").equals(""), is(false)); } @Test public void equals_same_instance() { final DnsCheckRequest dnsCheckRequest = new DnsCheckRequest(update, "domain", "glue"); assertThat(dnsCheckRequest.equals(dnsCheckRequest), is(true)); } @Test public void equals_not_equal_domain() { final DnsCheckRequest dnsCheckRequest1 = new DnsCheckRequest(update, "domain", "glue"); final DnsCheckRequest dnsCheckRequest2 = new DnsCheckRequest(update, "DOMAIN", "glue"); assertThat(dnsCheckRequest1.equals(dnsCheckRequest2), is(false)); } @Test public void equals_not_equal_glue() { final DnsCheckRequest dnsCheckRequest1 = new DnsCheckRequest(update, "domain", "glue"); final DnsCheckRequest dnsCheckRequest2 = new DnsCheckRequest(update, "domain", "GLUE"); assertThat(dnsCheckRequest1.equals(dnsCheckRequest2), is(false)); }
### Question: AutnumAuthentication extends AuthenticationStrategyBase { @Override public boolean supports(final PreparedUpdate update) { return update.getType().equals(ObjectType.AUT_NUM) && update.getAction().equals(Action.CREATE); } @Autowired AutnumAuthentication(final RpslObjectDao objectDao, final AuthenticationModule authenticationModule); @Override boolean supports(final PreparedUpdate update); @Override List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext); }### Answer: @Test public void supports_autnum_create() { when(update.getAction()).thenReturn(Action.CREATE); when(update.getType()).thenReturn(ObjectType.AUT_NUM); final boolean supported = subject.supports(update); assertThat(supported, is(true)); } @Test public void supports_other_than_autnum_create() { for (final ObjectType objectType : ObjectType.values()) { if (ObjectType.AUT_NUM.equals(objectType)) { continue; } when(update.getAction()).thenReturn(Action.CREATE); when(update.getType()).thenReturn(ObjectType.AS_BLOCK); final boolean supported = subject.supports(update); assertThat(supported, is(false)); reset(update); } } @Test public void supports_autnum_modify() { when(update.getAction()).thenReturn(Action.MODIFY); when(update.getType()).thenReturn(ObjectType.AUT_NUM); final boolean supported = subject.supports(update); assertThat(supported, is(false)); } @Test public void supports_autnum_delete() { when(update.getAction()).thenReturn(Action.DELETE); when(update.getType()).thenReturn(ObjectType.AUT_NUM); final boolean supported = subject.supports(update); assertThat(supported, is(false)); }
### Question: MntIrtAuthentication extends AuthenticationStrategyBase { @Override public boolean supports(final PreparedUpdate update) { return !update.getNewValues(AttributeType.MNT_IRT).isEmpty(); } @Autowired MntIrtAuthentication(final AuthenticationModule credentialValidators, final RpslObjectDao rpslObjectDao); @Override boolean supports(final PreparedUpdate update); @Override List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext); }### Answer: @Test public void operates_on_updates_with_new_mntirts() { when(update.getNewValues(AttributeType.MNT_IRT)).thenReturn(ciSet("IRT-MNT")); assertThat(subject.supports(update), is(true)); } @Test public void does_not_support_updates_with_same_mntirts() { when(update.getNewValues(AttributeType.MNT_IRT)).thenReturn(Sets.<CIString>newHashSet()); assertThat(subject.supports(update), is(false)); }
### Question: MntIrtAuthentication extends AuthenticationStrategyBase { @Override public List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext) { final Collection<CIString> keys = update.getNewValues(AttributeType.MNT_IRT); final List<RpslObject> candidates = rpslObjectDao.getByKeys(ObjectType.IRT, keys); if (isSelfReference(update, keys)) { candidates.add(update.getUpdatedObject()); } final List<RpslObject> authenticatedBy = credentialValidators.authenticate(update, updateContext, candidates); if (authenticatedBy.isEmpty()) { throw new AuthenticationFailedException(UpdateMessages.authenticationFailed(update.getReferenceObject(), AttributeType.MNT_IRT, candidates), candidates); } return authenticatedBy; } @Autowired MntIrtAuthentication(final AuthenticationModule credentialValidators, final RpslObjectDao rpslObjectDao); @Override boolean supports(final PreparedUpdate update); @Override List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext); }### Answer: @Test public void authentication_succeeds() { when(update.getType()).thenReturn(ObjectType.INETNUM); when(update.getNewValues(AttributeType.MNT_IRT)).thenReturn(ciSet("IRT-MNT")); when(update.getReferenceObject()).thenReturn(RpslObject.parse("inetnum: 192.0/24")); when(update.getUpdatedObject()).thenReturn(RpslObject.parse("inetnum: 192.0/24\nmnt-irt: IRT-MNT")); final RpslObject irt = RpslObject.parse("irt: IRT-MNT"); final ArrayList<RpslObject> irts = Lists.newArrayList(irt); when(rpslObjectDao.getByKeys(ObjectType.IRT, ciSet("IRT-MNT"))).thenReturn(irts); when(credentialValidators.authenticate(eq(update), eq(updateContext), anyCollection())).thenReturn(irts); final List<RpslObject> result = subject.authenticate(update, updateContext); assertThat(result.size(), is(1)); assertThat(result.get(0), is(irt)); verifyZeroInteractions(updateContext); } @Test(expected = AuthenticationFailedException.class) public void authentication_fails() { when(update.getType()).thenReturn(ObjectType.INETNUM); when(update.getReferenceObject()).thenReturn(RpslObject.parse("inetnum: 192.0/24\nmnt-irt: IRT-MNT")); final RpslObject irt = RpslObject.parse("irt: IRT-MNT"); final ArrayList<RpslObject> irts = Lists.newArrayList(irt); when(rpslObjectDao.getByKeys(ObjectType.IRT, ciSet("IRT-MNT"))).thenReturn(irts); when(credentialValidators.authenticate(eq(update), eq(updateContext), anyCollection())).thenReturn(Lists.<RpslObject>newArrayList()); subject.authenticate(update, updateContext); }
### Question: MntByAuthentication extends AuthenticationStrategyBase { @Override public boolean supports(final PreparedUpdate update) { return ObjectTemplate.getTemplate(update.getType()).hasAttribute(AttributeType.MNT_BY); } @Autowired MntByAuthentication(final Maintainers maintainers, final AuthenticationModule authenticationModule, final RpslObjectDao rpslObjectDao, final SsoTranslator ssoTranslator, final Ipv4Tree ipv4Tree, final Ipv6Tree ipv6Tree); @Override boolean supports(final PreparedUpdate update); @Override List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext); }### Answer: @Test public void supports_every_object_with_a_mntby_attribute() { when(update.getType()).thenReturn(ObjectType.POEM); assertThat(subject.supports(update), is(true)); when(update.getType()).thenReturn(ObjectType.INETNUM); assertThat(subject.supports(update), is(true)); verifyZeroInteractions(maintainers); }
### Question: DomainAuthentication extends AuthenticationStrategyBase { @Override public boolean supports(final PreparedUpdate update) { return update.getAction().equals(Action.CREATE) && (update.getType().equals(ObjectType.DOMAIN)); } @Autowired DomainAuthentication(final Ipv4Tree ipv4Tree, final Ipv6Tree ipv6Tree, final RpslObjectDao objectDao, final AuthenticationModule authenticationModule); @Override boolean supports(final PreparedUpdate update); @Override List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext); }### Answer: @Test public void supports_create_domain() { when(update.getAction()).thenReturn(Action.CREATE); when(update.getType()).thenReturn(ObjectType.DOMAIN); assertThat(subject.supports(update), is(true)); } @Test public void supports_modify_domain() { when(update.getAction()).thenReturn(Action.MODIFY); when(update.getType()).thenReturn(ObjectType.DOMAIN); assertThat(subject.supports(update), is(false)); } @Test public void supports_create_inetnum() { when(update.getAction()).thenReturn(Action.CREATE); when(update.getType()).thenReturn(ObjectType.INETNUM); assertThat(subject.supports(update), is(false)); }
### Question: OrgRefAuthentication extends AuthenticationStrategyBase { @Override public boolean supports(final PreparedUpdate update) { return !update.getNewValues(AttributeType.ORG).isEmpty(); } @Autowired OrgRefAuthentication(final AuthenticationModule credentialValidators, final RpslObjectDao rpslObjectDao); @Override boolean supports(final PreparedUpdate update); @Override List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext); }### Answer: @Test public void supports_update_with_new_org_references() { when(update.getNewValues(AttributeType.ORG)).thenReturn(ciSet("ORG2")); when(update.getUpdatedObject()).thenReturn(RpslObject.parse("organisation: ORG1\norg: ORG1")); assertThat(subject.supports(update), is(true)); } @Test public void no_difference_in_org_refs_is_not_supported() { when(update.getUpdatedObject()).thenReturn(RpslObject.parse("organisation: ORG1\norg: ORG1")); when(update.getReferenceObject()).thenReturn(RpslObject.parse("organisation: ORG1\norg: ORG1")); assertThat(subject.supports(update), is(false)); }
### Question: InetnumAuthentication extends AuthenticationStrategyBase { @Override public boolean supports(final PreparedUpdate update) { return update.getAction().equals(Action.CREATE) && (update.getType().equals(ObjectType.INETNUM) || update.getType().equals(ObjectType.INET6NUM)); } @Autowired InetnumAuthentication(final AuthenticationModule authenticationModule, final Ipv4Tree ipv4Tree, final Ipv6Tree ipv6Tree, final RpslObjectDao rpslObjectDao); @Override boolean supports(final PreparedUpdate update); @Override List<RpslObject> authenticate(final PreparedUpdate update, final UpdateContext updateContext); }### Answer: @Test public void supports_creating_inetnum() { when(update.getAction()).thenReturn(Action.CREATE); when(update.getType()).thenReturn(ObjectType.INETNUM); assertThat(subject.supports(update), is(true)); } @Test public void supports_creating_inet6num() { when(update.getAction()).thenReturn(Action.CREATE); when(update.getType()).thenReturn(ObjectType.INET6NUM); assertThat(subject.supports(update), is(true)); } @Test public void does_not_support_modifying() { when(update.getAction()).thenReturn(Action.MODIFY); when(update.getType()).thenReturn(ObjectType.INETNUM); assertThat(subject.supports(update), is(false)); }
### Question: X509CredentialValidator implements CredentialValidator<X509Credential, X509Credential> { @Override public boolean hasValidCredential(final PreparedUpdate update, final UpdateContext updateContext, final Collection<X509Credential> offeredCredentials, final X509Credential knownCredential) { for (final X509Credential offeredCredential : offeredCredentials) { if (verifySignedMessage(update, updateContext, offeredCredential, knownCredential)) { log(update, String.format("Successfully validated with keycert: %s", knownCredential.getKeyId())); return true; } } return false; } @Autowired X509CredentialValidator(final RpslObjectDao rpslObjectDao, final DateTimeProvider dateTimeProvider, final LoggerContext loggerContext); @Override Class<X509Credential> getSupportedCredentials(); @Override Class<X509Credential> getSupportedOfferedCredentialType(); @Override boolean hasValidCredential(final PreparedUpdate update, final UpdateContext updateContext, final Collection<X509Credential> offeredCredentials, final X509Credential knownCredential); }### Answer: @Test public void authentication_success() { boolean result = subject.hasValidCredential(update, updateContext, Sets.newHashSet(offeredCredential), knownCredential); assertThat(result, is(true)); } @Test public void authentication_keycert_not_found() throws Exception { when(rpslObjectDao.getByKey(ObjectType.KEY_CERT, "X509-1")).thenThrow(new EmptyResultDataAccessException(1)); boolean result = subject.hasValidCredential(update, updateContext, Sets.newHashSet(offeredCredential), knownCredential); assertThat(result, is(false)); } @Test public void authentication_keycert_is_invalid() throws Exception { when(rpslObjectDao.getByKey(ObjectType.KEY_CERT, "X509-1")).thenAnswer(new Answer<RpslObject>() { @Override public RpslObject answer(InvocationOnMock invocation) throws Throwable { return RpslObject.parse( "key-cert: AUTO-1\n" + "method: X509\n" + "mnt-by: OWNER-MNT\n" + "source: TEST\n"); } }); boolean result = subject.hasValidCredential(update, updateContext, Sets.newHashSet(offeredCredential), knownCredential); assertThat(result, is(false)); }
### Question: SsoCredentialValidator implements CredentialValidator<SsoCredential, SsoCredential> { @Override public Class<SsoCredential> getSupportedCredentials() { return SsoCredential.class; } @Autowired SsoCredentialValidator(final LoggerContext loggerContext); @Override Class<SsoCredential> getSupportedCredentials(); @Override Class<SsoCredential> getSupportedOfferedCredentialType(); @Override boolean hasValidCredential(final PreparedUpdate update, final UpdateContext updateContext, final Collection<SsoCredential> offeredCredentials, final SsoCredential knownCredential); }### Answer: @Test public void supportedCredentials() { assertThat(subject.getSupportedCredentials(), Is.<Class<SsoCredential>>is(SsoCredential.class)); }
### Question: PasswordCredentialValidator implements CredentialValidator<PasswordCredential, PasswordCredential> { @Override public Class<PasswordCredential> getSupportedCredentials() { return PasswordCredential.class; } @Autowired PasswordCredentialValidator(LoggerContext loggerContext); @Override Class<PasswordCredential> getSupportedCredentials(); @Override Class<PasswordCredential> getSupportedOfferedCredentialType(); @Override boolean hasValidCredential(final PreparedUpdate update, final UpdateContext updateContext, final Collection<PasswordCredential> offeredCredentials, final PasswordCredential knownCredential); }### Answer: @Test public void supports() { assertEquals(PasswordCredential.class, subject.getSupportedCredentials()); }
### Question: AutnumAttributeGenerator extends AttributeGenerator { @Override public RpslObject generateAttributes(final RpslObject originalObject, final RpslObject updatedObject, final Update update, final UpdateContext updateContext) { switch (updatedObject.getType()) { case AUT_NUM: return generateStatus(originalObject, updatedObject, update, updateContext); default: return updatedObject; } } @Autowired AutnumAttributeGenerator(final AuthoritativeResourceData authoritativeResourceData, final SourceContext sourceContext, final LegacyAutnum legacyAutnum); @Override RpslObject generateAttributes(final RpslObject originalObject, final RpslObject updatedObject, final Update update, final UpdateContext updateContext); }### Answer: @Test public void generate_other_status_on_create() { final RpslObject autnum = RpslObject.parse("aut-num: AS3333\nmnt-by: TEST-MNT\nsource: RIPE"); final RpslObject result = autnumStatusAttributeGenerator.generateAttributes(null, autnum, update, updateContext); assertThat(result.getValueForAttribute(AttributeType.STATUS), is(CIString.ciString("OTHER"))); } @Test public void generate_other_status_on_update() { final RpslObject originalObject = RpslObject.parse("aut-num: AS3333\nmnt-by: RIPE-NCC-HM-MNT\nsource: RIPE"); final RpslObject updatedObject = RpslObject.parse("aut-num: AS3333\nremarks: updated\nmnt-by: RIPE-NCC-HM-MNT\nsource: RIPE"); final RpslObject result = autnumStatusAttributeGenerator.generateAttributes(originalObject, updatedObject, update, updateContext); assertThat(result.getValueForAttribute(AttributeType.STATUS), is(CIString.ciString("OTHER"))); }
### Question: SsoTranslator { public RpslObject translateFromCacheAuthToUsername(final UpdateContext updateContext, final RpslObject rpslObject) { return translateAuthFromCache(updateContext, rpslObject); } @Autowired SsoTranslator(final CrowdClient crowdClient); void populateCacheAuthToUsername(final UpdateContext updateContext, final RpslObject rpslObject); void populateCacheAuthToUuid(final UpdateContext updateContext, final Update update); RpslObject translateFromCacheAuthToUuid(final UpdateContext updateContext, final RpslObject rpslObject); RpslObject translateFromCacheAuthToUsername(final UpdateContext updateContext, final RpslObject rpslObject); }### Answer: @Test public void translate_to_uuid_username_stored_in_context_already() { final RpslObject object = RpslObject.parse("mntner: TEST-MNT\nauth: SSO [email protected]"); when(updateContext.getSsoTranslationResult("[email protected]")).thenReturn("BBBB-1234-CCCC-DDDD"); final RpslObject result = subject.translateFromCacheAuthToUsername(updateContext, object); assertThat(result, is(RpslObject.parse("mntner: TEST-MNT\nauth: SSO BBBB-1234-CCCC-DDDD"))); }
### Question: RepoScanner { public RepoScanner() { githubUser = System.getProperty("githubUser"); githubToken = System.getProperty("githubToken"); if (githubUser == null || githubToken == null) { String msg = ("To scan GitHub for submissions please provide your username and a valid Personal Access Token.\n" + "Without this the submissions table will be out of date.\n" + "JVM parameters are githubUser and githubToken"); throw new IllegalStateException(msg); } } RepoScanner(); JSONObject getSubmissionsFromRepo(String repoName); }### Answer: @Test public void testRepoScanner() throws IOException { try { JSONObject submissions = new RepoScanner() .getSubmissionsFromRepo("bpmn-miwg/bpmn-miwg-test-suite"); System.out.println(submissions); FileUtils.writeStringToFile(new File("target/submissions.json"), submissions.toJSONString()); } catch (Throwable t) { assumeNoException("Assume no GitHub token provided, continuing", t); } }
### Question: ModelInterchangeMojo extends AbstractMojo { public void execute() throws MojoExecutionException { getLog().info("Running BPMN-MIWG test suite..."); if (!outputDirectory.exists()) { outputDirectory.mkdirs(); } try { Collection<String> inputFolders = new LinkedList<String>(); if (!resources.isEmpty()) { for (Resource resource : resources) { String folderName = resource.getDirectory(); inputFolders.add(folderName); } } Collection<AnalysisJob> jobs = BpmnFileScanner .buildListOfAnalysisJobs(new StandardScanParameters(application, null, inputFolders, outputDirectory.getCanonicalPath())); AnalysisFacade.executeAnalysisJobs(jobs, outputDirectory.getAbsolutePath()); } catch (Exception e) { e.printStackTrace(); } try (FileWriter out = new FileWriter(new File(outputDirectory, "submissions.json"))) { JSONObject submissions = new RepoScanner().getSubmissionsFromRepo("bpmn-miwg/bpmn-miwg-test-suite"); submissions.writeJSONString(out); } catch (Exception e) { e.printStackTrace(); } } void execute(); }### Answer: @Test public void testMojo() { try { Resource res = new Resource(); res.setDirectory(SRC_TEST_RESOURCES); mojo.resources.add(res); mojo.execute(); System.out .println("Checking expected output exists with base folder: " + TestUtil.REPORT_BASE_FOLDER_NAME); assertTrue(overview.exists()); Document document = docBuilder.parse(overview); XPathExpression xpath = createXpathExpression(" NodeList nodes = (NodeList) xpath.evaluate(document, XPathConstants.NODESET); assertEquals(7, nodes.getLength()); assertHtmlReportsExist(new File(TestUtil.REPORT_BASE_FOLDER_NAME, XmlCompareAnalysisTool.NAME)); assertHtmlReportsExist(new File(TestUtil.REPORT_BASE_FOLDER_NAME, SchemaAnalysisTool.NAME)); assertHtmlReportsExist(new File(TestUtil.REPORT_BASE_FOLDER_NAME, XpathAnalysisTool.NAME)); File xpathResult = new File(TestUtil.REPORT_BASE_FOLDER_NAME + File.separator + XpathAnalysisTool.NAME + File.separator + MavenTestConsts.W4_MODELER_ID + File.separator + MavenTestConsts.W4_MODELER_ID + "-A.1.0-roundtrip.html"); System.out.println("Checking file: " + xpathResult); assertTrue(xpathResult.exists()); document = docBuilder.parse(xpathResult); nodes = (NodeList) xPath.compile( " XPathConstants.NODESET); assertTrue("Did not find result element", nodes.getLength() == 1); nodes = (NodeList) xPath.compile( " .evaluate(document, XPathConstants.NODESET); assertTrue("Did not find tool element", nodes.getLength() == 1); nodes = (NodeList) xPath .compile( " .evaluate(document, XPathConstants.NODESET); assertTrue("Did not find test element", nodes.getLength() >= 1); } catch (Exception e) { e.printStackTrace(); fail(e.getClass() + ":" + e.getMessage()); } } @Test public void testMojoHandlingSchemaInvalidBpmn() throws XPathExpressionException, SAXException, IOException, MojoExecutionException { Resource res = new Resource(); res.setDirectory("src/test/invalid-resources"); mojo.resources.add(res); mojo.application = "Yaoqiang BPMN Editor 2.2.6"; mojo.execute(); assertTrue(overview.exists()); Document document = docBuilder.parse(overview); XPathExpression xpath = createXpathExpression(" NodeList nodes = (NodeList) xpath.evaluate(document, XPathConstants.NODESET); Node invalidNode = nodes.item(0); assertEquals("2", invalidNode.getAttributes().getNamedItem("data-xsd-finding") .getNodeValue()); }
### Question: DebugWebViewClient extends WebViewClient implements LogControl { @Override @Deprecated @SuppressWarnings("deprecation") public void onTooManyRedirects(WebView view, Message cancelMsg, Message continueMsg) { logger.onTooManyRedirects(view, cancelMsg, continueMsg); client.onTooManyRedirects(view, cancelMsg, continueMsg); } DebugWebViewClient(); DebugWebViewClient(@NonNull final WebViewClient client); @SuppressWarnings("WeakerAccess") DebugWebViewClient( @NonNull final WebViewClient client, @NonNull final DebugWebViewClientLogger logger); @RequiresApi(api = Build.VERSION_CODES.M) @Override void onReceivedError(final WebView view, final WebResourceRequest request, final WebResourceError error); @Override @Deprecated void onReceivedError(final WebView view, final int errorCode, final String description, final String failingUrl); @RequiresApi(api = Build.VERSION_CODES.M) @Override void onReceivedHttpError(final WebView view, final WebResourceRequest request, final WebResourceResponse errorResponse); @Override void onReceivedSslError(final WebView view, final SslErrorHandler handler, final SslError error); @RequiresApi(api = Build.VERSION_CODES.N) @Override boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request); @Override boolean shouldOverrideUrlLoading(WebView view, String url); @Override void onLoadResource(WebView view, String url); @TargetApi(Build.VERSION_CODES.M) @Override void onPageCommitVisible(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Deprecated WebResourceResponse shouldInterceptRequest(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request); @Override @Deprecated @SuppressWarnings("deprecation") //for use with older versions void onTooManyRedirects(WebView view, Message cancelMsg, Message continueMsg); @Override void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm); @Override void onPageStarted(WebView view, String url, Bitmap facIcon); @Override void onPageFinished(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override void onReceivedClientCertRequest(WebView view, ClientCertRequest request); @Override void onFormResubmission(final WebView view, final Message dontResend, final Message resend); @Override void doUpdateVisitedHistory(final WebView view, final String url, final boolean isReload); @Override boolean shouldOverrideKeyEvent(final WebView view, final KeyEvent event); @SuppressWarnings("unused") void onUnhandledInputEvent(final WebView view, final InputEvent event); @Override void onUnhandledKeyEvent(final WebView view, final KeyEvent event); @Override void onScaleChanged(final WebView view, final float oldScale, final float newScale); @Override void onReceivedLoginRequest(final WebView view, final String realm, final String account, final String args); @RequiresApi(api = Build.VERSION_CODES.O) @Override boolean onRenderProcessGone(final WebView view, final RenderProcessGoneDetail detail); @RequiresApi(api = Build.VERSION_CODES.O_MR1) @Override void onSafeBrowsingHit(final WebView view, final WebResourceRequest request, final int threatType, final SafeBrowsingResponse callback); @Override boolean isLoggingEnabled(); @Override void setLoggingEnabled(final boolean enabled); @Override boolean isLogKeyEventsEnabled(); @Override void setLogKeyEventsEnabled(final boolean enabled); }### Answer: @Test @SuppressWarnings("deprecation") public void onTooManyRedirects() { final Message cancelMsg = Mockito.mock(Message.class); final Message continueMsg = Mockito.mock(Message.class); debugClient.onTooManyRedirects(webView, cancelMsg, continueMsg); verifyLogger().onTooManyRedirects(webView, cancelMsg, continueMsg); verifyWrappedClient().onTooManyRedirects(webView, cancelMsg, continueMsg); }
### Question: DebugWebViewClient extends WebViewClient implements LogControl { @Override public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) { logger.onReceivedHttpAuthRequest(view, handler, host, realm); client.onReceivedHttpAuthRequest(view, handler, host, realm); } DebugWebViewClient(); DebugWebViewClient(@NonNull final WebViewClient client); @SuppressWarnings("WeakerAccess") DebugWebViewClient( @NonNull final WebViewClient client, @NonNull final DebugWebViewClientLogger logger); @RequiresApi(api = Build.VERSION_CODES.M) @Override void onReceivedError(final WebView view, final WebResourceRequest request, final WebResourceError error); @Override @Deprecated void onReceivedError(final WebView view, final int errorCode, final String description, final String failingUrl); @RequiresApi(api = Build.VERSION_CODES.M) @Override void onReceivedHttpError(final WebView view, final WebResourceRequest request, final WebResourceResponse errorResponse); @Override void onReceivedSslError(final WebView view, final SslErrorHandler handler, final SslError error); @RequiresApi(api = Build.VERSION_CODES.N) @Override boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request); @Override boolean shouldOverrideUrlLoading(WebView view, String url); @Override void onLoadResource(WebView view, String url); @TargetApi(Build.VERSION_CODES.M) @Override void onPageCommitVisible(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Deprecated WebResourceResponse shouldInterceptRequest(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request); @Override @Deprecated @SuppressWarnings("deprecation") //for use with older versions void onTooManyRedirects(WebView view, Message cancelMsg, Message continueMsg); @Override void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm); @Override void onPageStarted(WebView view, String url, Bitmap facIcon); @Override void onPageFinished(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override void onReceivedClientCertRequest(WebView view, ClientCertRequest request); @Override void onFormResubmission(final WebView view, final Message dontResend, final Message resend); @Override void doUpdateVisitedHistory(final WebView view, final String url, final boolean isReload); @Override boolean shouldOverrideKeyEvent(final WebView view, final KeyEvent event); @SuppressWarnings("unused") void onUnhandledInputEvent(final WebView view, final InputEvent event); @Override void onUnhandledKeyEvent(final WebView view, final KeyEvent event); @Override void onScaleChanged(final WebView view, final float oldScale, final float newScale); @Override void onReceivedLoginRequest(final WebView view, final String realm, final String account, final String args); @RequiresApi(api = Build.VERSION_CODES.O) @Override boolean onRenderProcessGone(final WebView view, final RenderProcessGoneDetail detail); @RequiresApi(api = Build.VERSION_CODES.O_MR1) @Override void onSafeBrowsingHit(final WebView view, final WebResourceRequest request, final int threatType, final SafeBrowsingResponse callback); @Override boolean isLoggingEnabled(); @Override void setLoggingEnabled(final boolean enabled); @Override boolean isLogKeyEventsEnabled(); @Override void setLogKeyEventsEnabled(final boolean enabled); }### Answer: @Test public void onReceivedHttpAuthRequest() { final HttpAuthHandler handler = Mockito.mock(HttpAuthHandler.class); final String host = "foo"; final String realm = "bar"; debugClient.onReceivedHttpAuthRequest(webView, handler, host, realm); verifyLogger().onReceivedHttpAuthRequest(webView, handler, host, realm); verifyWrappedClient().onReceivedHttpAuthRequest(webView, handler, host, realm); }
### Question: DebugWebViewClient extends WebViewClient implements LogControl { @Override public void onPageStarted(WebView view, String url, Bitmap facIcon) { logger.onPageStarted(view, url, facIcon); client.onPageStarted(view, url, facIcon); } DebugWebViewClient(); DebugWebViewClient(@NonNull final WebViewClient client); @SuppressWarnings("WeakerAccess") DebugWebViewClient( @NonNull final WebViewClient client, @NonNull final DebugWebViewClientLogger logger); @RequiresApi(api = Build.VERSION_CODES.M) @Override void onReceivedError(final WebView view, final WebResourceRequest request, final WebResourceError error); @Override @Deprecated void onReceivedError(final WebView view, final int errorCode, final String description, final String failingUrl); @RequiresApi(api = Build.VERSION_CODES.M) @Override void onReceivedHttpError(final WebView view, final WebResourceRequest request, final WebResourceResponse errorResponse); @Override void onReceivedSslError(final WebView view, final SslErrorHandler handler, final SslError error); @RequiresApi(api = Build.VERSION_CODES.N) @Override boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request); @Override boolean shouldOverrideUrlLoading(WebView view, String url); @Override void onLoadResource(WebView view, String url); @TargetApi(Build.VERSION_CODES.M) @Override void onPageCommitVisible(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Deprecated WebResourceResponse shouldInterceptRequest(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request); @Override @Deprecated @SuppressWarnings("deprecation") //for use with older versions void onTooManyRedirects(WebView view, Message cancelMsg, Message continueMsg); @Override void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm); @Override void onPageStarted(WebView view, String url, Bitmap facIcon); @Override void onPageFinished(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override void onReceivedClientCertRequest(WebView view, ClientCertRequest request); @Override void onFormResubmission(final WebView view, final Message dontResend, final Message resend); @Override void doUpdateVisitedHistory(final WebView view, final String url, final boolean isReload); @Override boolean shouldOverrideKeyEvent(final WebView view, final KeyEvent event); @SuppressWarnings("unused") void onUnhandledInputEvent(final WebView view, final InputEvent event); @Override void onUnhandledKeyEvent(final WebView view, final KeyEvent event); @Override void onScaleChanged(final WebView view, final float oldScale, final float newScale); @Override void onReceivedLoginRequest(final WebView view, final String realm, final String account, final String args); @RequiresApi(api = Build.VERSION_CODES.O) @Override boolean onRenderProcessGone(final WebView view, final RenderProcessGoneDetail detail); @RequiresApi(api = Build.VERSION_CODES.O_MR1) @Override void onSafeBrowsingHit(final WebView view, final WebResourceRequest request, final int threatType, final SafeBrowsingResponse callback); @Override boolean isLoggingEnabled(); @Override void setLoggingEnabled(final boolean enabled); @Override boolean isLogKeyEventsEnabled(); @Override void setLogKeyEventsEnabled(final boolean enabled); }### Answer: @Test public void onPageStarted() { final String url = "foo"; final Bitmap bitmap = Mockito.mock(Bitmap.class); debugClient.onPageStarted(webView, url, bitmap); verifyLogger().onPageStarted(webView, url, bitmap); verifyWrappedClient().onPageStarted(webView, url, bitmap); }
### Question: DebugWebViewClient extends WebViewClient implements LogControl { @Override public void onPageFinished(WebView view, String url) { logger.onPageFinished(view, url); client.onPageFinished(view, url); } DebugWebViewClient(); DebugWebViewClient(@NonNull final WebViewClient client); @SuppressWarnings("WeakerAccess") DebugWebViewClient( @NonNull final WebViewClient client, @NonNull final DebugWebViewClientLogger logger); @RequiresApi(api = Build.VERSION_CODES.M) @Override void onReceivedError(final WebView view, final WebResourceRequest request, final WebResourceError error); @Override @Deprecated void onReceivedError(final WebView view, final int errorCode, final String description, final String failingUrl); @RequiresApi(api = Build.VERSION_CODES.M) @Override void onReceivedHttpError(final WebView view, final WebResourceRequest request, final WebResourceResponse errorResponse); @Override void onReceivedSslError(final WebView view, final SslErrorHandler handler, final SslError error); @RequiresApi(api = Build.VERSION_CODES.N) @Override boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request); @Override boolean shouldOverrideUrlLoading(WebView view, String url); @Override void onLoadResource(WebView view, String url); @TargetApi(Build.VERSION_CODES.M) @Override void onPageCommitVisible(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Deprecated WebResourceResponse shouldInterceptRequest(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request); @Override @Deprecated @SuppressWarnings("deprecation") //for use with older versions void onTooManyRedirects(WebView view, Message cancelMsg, Message continueMsg); @Override void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm); @Override void onPageStarted(WebView view, String url, Bitmap facIcon); @Override void onPageFinished(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override void onReceivedClientCertRequest(WebView view, ClientCertRequest request); @Override void onFormResubmission(final WebView view, final Message dontResend, final Message resend); @Override void doUpdateVisitedHistory(final WebView view, final String url, final boolean isReload); @Override boolean shouldOverrideKeyEvent(final WebView view, final KeyEvent event); @SuppressWarnings("unused") void onUnhandledInputEvent(final WebView view, final InputEvent event); @Override void onUnhandledKeyEvent(final WebView view, final KeyEvent event); @Override void onScaleChanged(final WebView view, final float oldScale, final float newScale); @Override void onReceivedLoginRequest(final WebView view, final String realm, final String account, final String args); @RequiresApi(api = Build.VERSION_CODES.O) @Override boolean onRenderProcessGone(final WebView view, final RenderProcessGoneDetail detail); @RequiresApi(api = Build.VERSION_CODES.O_MR1) @Override void onSafeBrowsingHit(final WebView view, final WebResourceRequest request, final int threatType, final SafeBrowsingResponse callback); @Override boolean isLoggingEnabled(); @Override void setLoggingEnabled(final boolean enabled); @Override boolean isLogKeyEventsEnabled(); @Override void setLogKeyEventsEnabled(final boolean enabled); }### Answer: @Test public void onPageFinished() { final String url = "foo"; debugClient.onPageFinished(webView, url); verifyLogger().onPageFinished(webView, url); verifyWrappedClient().onPageFinished(webView, url); }
### Question: DebugWebViewClient extends WebViewClient implements LogControl { @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override public void onReceivedClientCertRequest(WebView view, ClientCertRequest request) { logger.onReceivedClientCertRequest(view, request); client.onReceivedClientCertRequest(view, request); } DebugWebViewClient(); DebugWebViewClient(@NonNull final WebViewClient client); @SuppressWarnings("WeakerAccess") DebugWebViewClient( @NonNull final WebViewClient client, @NonNull final DebugWebViewClientLogger logger); @RequiresApi(api = Build.VERSION_CODES.M) @Override void onReceivedError(final WebView view, final WebResourceRequest request, final WebResourceError error); @Override @Deprecated void onReceivedError(final WebView view, final int errorCode, final String description, final String failingUrl); @RequiresApi(api = Build.VERSION_CODES.M) @Override void onReceivedHttpError(final WebView view, final WebResourceRequest request, final WebResourceResponse errorResponse); @Override void onReceivedSslError(final WebView view, final SslErrorHandler handler, final SslError error); @RequiresApi(api = Build.VERSION_CODES.N) @Override boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request); @Override boolean shouldOverrideUrlLoading(WebView view, String url); @Override void onLoadResource(WebView view, String url); @TargetApi(Build.VERSION_CODES.M) @Override void onPageCommitVisible(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Deprecated WebResourceResponse shouldInterceptRequest(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request); @Override @Deprecated @SuppressWarnings("deprecation") //for use with older versions void onTooManyRedirects(WebView view, Message cancelMsg, Message continueMsg); @Override void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm); @Override void onPageStarted(WebView view, String url, Bitmap facIcon); @Override void onPageFinished(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override void onReceivedClientCertRequest(WebView view, ClientCertRequest request); @Override void onFormResubmission(final WebView view, final Message dontResend, final Message resend); @Override void doUpdateVisitedHistory(final WebView view, final String url, final boolean isReload); @Override boolean shouldOverrideKeyEvent(final WebView view, final KeyEvent event); @SuppressWarnings("unused") void onUnhandledInputEvent(final WebView view, final InputEvent event); @Override void onUnhandledKeyEvent(final WebView view, final KeyEvent event); @Override void onScaleChanged(final WebView view, final float oldScale, final float newScale); @Override void onReceivedLoginRequest(final WebView view, final String realm, final String account, final String args); @RequiresApi(api = Build.VERSION_CODES.O) @Override boolean onRenderProcessGone(final WebView view, final RenderProcessGoneDetail detail); @RequiresApi(api = Build.VERSION_CODES.O_MR1) @Override void onSafeBrowsingHit(final WebView view, final WebResourceRequest request, final int threatType, final SafeBrowsingResponse callback); @Override boolean isLoggingEnabled(); @Override void setLoggingEnabled(final boolean enabled); @Override boolean isLogKeyEventsEnabled(); @Override void setLogKeyEventsEnabled(final boolean enabled); }### Answer: @Test public void onReceivedClientCertRequest() { final ClientCertRequest request = Mockito.mock(ClientCertRequest.class); debugClient.onReceivedClientCertRequest(webView, request); verifyLogger().onReceivedClientCertRequest(webView, request); verifyWrappedClient().onReceivedClientCertRequest(webView, request); }
### Question: DebugWebViewClient extends WebViewClient implements LogControl { @Override public void onFormResubmission(final WebView view, final Message dontResend, final Message resend) { logger.onFormResubmission(view, dontResend, resend); client.onFormResubmission(view, dontResend, resend); } DebugWebViewClient(); DebugWebViewClient(@NonNull final WebViewClient client); @SuppressWarnings("WeakerAccess") DebugWebViewClient( @NonNull final WebViewClient client, @NonNull final DebugWebViewClientLogger logger); @RequiresApi(api = Build.VERSION_CODES.M) @Override void onReceivedError(final WebView view, final WebResourceRequest request, final WebResourceError error); @Override @Deprecated void onReceivedError(final WebView view, final int errorCode, final String description, final String failingUrl); @RequiresApi(api = Build.VERSION_CODES.M) @Override void onReceivedHttpError(final WebView view, final WebResourceRequest request, final WebResourceResponse errorResponse); @Override void onReceivedSslError(final WebView view, final SslErrorHandler handler, final SslError error); @RequiresApi(api = Build.VERSION_CODES.N) @Override boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request); @Override boolean shouldOverrideUrlLoading(WebView view, String url); @Override void onLoadResource(WebView view, String url); @TargetApi(Build.VERSION_CODES.M) @Override void onPageCommitVisible(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Deprecated WebResourceResponse shouldInterceptRequest(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request); @Override @Deprecated @SuppressWarnings("deprecation") //for use with older versions void onTooManyRedirects(WebView view, Message cancelMsg, Message continueMsg); @Override void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm); @Override void onPageStarted(WebView view, String url, Bitmap facIcon); @Override void onPageFinished(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override void onReceivedClientCertRequest(WebView view, ClientCertRequest request); @Override void onFormResubmission(final WebView view, final Message dontResend, final Message resend); @Override void doUpdateVisitedHistory(final WebView view, final String url, final boolean isReload); @Override boolean shouldOverrideKeyEvent(final WebView view, final KeyEvent event); @SuppressWarnings("unused") void onUnhandledInputEvent(final WebView view, final InputEvent event); @Override void onUnhandledKeyEvent(final WebView view, final KeyEvent event); @Override void onScaleChanged(final WebView view, final float oldScale, final float newScale); @Override void onReceivedLoginRequest(final WebView view, final String realm, final String account, final String args); @RequiresApi(api = Build.VERSION_CODES.O) @Override boolean onRenderProcessGone(final WebView view, final RenderProcessGoneDetail detail); @RequiresApi(api = Build.VERSION_CODES.O_MR1) @Override void onSafeBrowsingHit(final WebView view, final WebResourceRequest request, final int threatType, final SafeBrowsingResponse callback); @Override boolean isLoggingEnabled(); @Override void setLoggingEnabled(final boolean enabled); @Override boolean isLogKeyEventsEnabled(); @Override void setLogKeyEventsEnabled(final boolean enabled); }### Answer: @Test public void onFormResubmission() { final Message dontResend = Mockito.mock(Message.class); final Message resend = Mockito.mock(Message.class); debugClient.onFormResubmission(webView, dontResend, resend); verifyLogger().onFormResubmission(webView, dontResend, resend); verifyWrappedClient().onFormResubmission(webView, dontResend, resend); }
### Question: DebugWebViewClient extends WebViewClient implements LogControl { @Override public void doUpdateVisitedHistory(final WebView view, final String url, final boolean isReload) { logger.doUpdateVisitedHistory(view, url, isReload); client.doUpdateVisitedHistory(view, url, isReload); } DebugWebViewClient(); DebugWebViewClient(@NonNull final WebViewClient client); @SuppressWarnings("WeakerAccess") DebugWebViewClient( @NonNull final WebViewClient client, @NonNull final DebugWebViewClientLogger logger); @RequiresApi(api = Build.VERSION_CODES.M) @Override void onReceivedError(final WebView view, final WebResourceRequest request, final WebResourceError error); @Override @Deprecated void onReceivedError(final WebView view, final int errorCode, final String description, final String failingUrl); @RequiresApi(api = Build.VERSION_CODES.M) @Override void onReceivedHttpError(final WebView view, final WebResourceRequest request, final WebResourceResponse errorResponse); @Override void onReceivedSslError(final WebView view, final SslErrorHandler handler, final SslError error); @RequiresApi(api = Build.VERSION_CODES.N) @Override boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request); @Override boolean shouldOverrideUrlLoading(WebView view, String url); @Override void onLoadResource(WebView view, String url); @TargetApi(Build.VERSION_CODES.M) @Override void onPageCommitVisible(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Deprecated WebResourceResponse shouldInterceptRequest(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request); @Override @Deprecated @SuppressWarnings("deprecation") //for use with older versions void onTooManyRedirects(WebView view, Message cancelMsg, Message continueMsg); @Override void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm); @Override void onPageStarted(WebView view, String url, Bitmap facIcon); @Override void onPageFinished(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override void onReceivedClientCertRequest(WebView view, ClientCertRequest request); @Override void onFormResubmission(final WebView view, final Message dontResend, final Message resend); @Override void doUpdateVisitedHistory(final WebView view, final String url, final boolean isReload); @Override boolean shouldOverrideKeyEvent(final WebView view, final KeyEvent event); @SuppressWarnings("unused") void onUnhandledInputEvent(final WebView view, final InputEvent event); @Override void onUnhandledKeyEvent(final WebView view, final KeyEvent event); @Override void onScaleChanged(final WebView view, final float oldScale, final float newScale); @Override void onReceivedLoginRequest(final WebView view, final String realm, final String account, final String args); @RequiresApi(api = Build.VERSION_CODES.O) @Override boolean onRenderProcessGone(final WebView view, final RenderProcessGoneDetail detail); @RequiresApi(api = Build.VERSION_CODES.O_MR1) @Override void onSafeBrowsingHit(final WebView view, final WebResourceRequest request, final int threatType, final SafeBrowsingResponse callback); @Override boolean isLoggingEnabled(); @Override void setLoggingEnabled(final boolean enabled); @Override boolean isLogKeyEventsEnabled(); @Override void setLogKeyEventsEnabled(final boolean enabled); }### Answer: @Test public void doUpdateVisitedHistory() { final String url = "foo"; final boolean reload = true; debugClient.doUpdateVisitedHistory(webView, url, reload); verifyLogger().doUpdateVisitedHistory(webView, url, reload); verifyWrappedClient().doUpdateVisitedHistory(webView, url, reload); }
### Question: DebugWebViewClient extends WebViewClient implements LogControl { @Override public boolean shouldOverrideKeyEvent(final WebView view, final KeyEvent event) { final boolean retVal = client.shouldOverrideKeyEvent(view, event); logger.shouldOverrideKeyEvent(view, event, retVal); return retVal; } DebugWebViewClient(); DebugWebViewClient(@NonNull final WebViewClient client); @SuppressWarnings("WeakerAccess") DebugWebViewClient( @NonNull final WebViewClient client, @NonNull final DebugWebViewClientLogger logger); @RequiresApi(api = Build.VERSION_CODES.M) @Override void onReceivedError(final WebView view, final WebResourceRequest request, final WebResourceError error); @Override @Deprecated void onReceivedError(final WebView view, final int errorCode, final String description, final String failingUrl); @RequiresApi(api = Build.VERSION_CODES.M) @Override void onReceivedHttpError(final WebView view, final WebResourceRequest request, final WebResourceResponse errorResponse); @Override void onReceivedSslError(final WebView view, final SslErrorHandler handler, final SslError error); @RequiresApi(api = Build.VERSION_CODES.N) @Override boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request); @Override boolean shouldOverrideUrlLoading(WebView view, String url); @Override void onLoadResource(WebView view, String url); @TargetApi(Build.VERSION_CODES.M) @Override void onPageCommitVisible(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Deprecated WebResourceResponse shouldInterceptRequest(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request); @Override @Deprecated @SuppressWarnings("deprecation") //for use with older versions void onTooManyRedirects(WebView view, Message cancelMsg, Message continueMsg); @Override void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm); @Override void onPageStarted(WebView view, String url, Bitmap facIcon); @Override void onPageFinished(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override void onReceivedClientCertRequest(WebView view, ClientCertRequest request); @Override void onFormResubmission(final WebView view, final Message dontResend, final Message resend); @Override void doUpdateVisitedHistory(final WebView view, final String url, final boolean isReload); @Override boolean shouldOverrideKeyEvent(final WebView view, final KeyEvent event); @SuppressWarnings("unused") void onUnhandledInputEvent(final WebView view, final InputEvent event); @Override void onUnhandledKeyEvent(final WebView view, final KeyEvent event); @Override void onScaleChanged(final WebView view, final float oldScale, final float newScale); @Override void onReceivedLoginRequest(final WebView view, final String realm, final String account, final String args); @RequiresApi(api = Build.VERSION_CODES.O) @Override boolean onRenderProcessGone(final WebView view, final RenderProcessGoneDetail detail); @RequiresApi(api = Build.VERSION_CODES.O_MR1) @Override void onSafeBrowsingHit(final WebView view, final WebResourceRequest request, final int threatType, final SafeBrowsingResponse callback); @Override boolean isLoggingEnabled(); @Override void setLoggingEnabled(final boolean enabled); @Override boolean isLogKeyEventsEnabled(); @Override void setLogKeyEventsEnabled(final boolean enabled); }### Answer: @Test public void shouldOverrideKeyEvent() { final KeyEvent keyEvent = Mockito.mock(KeyEvent.class); final boolean retVal = debugClient.shouldOverrideKeyEvent(webView, keyEvent); verifyLogger().shouldOverrideKeyEvent(webView, keyEvent, retVal); verifyWrappedClient().shouldOverrideKeyEvent(webView, keyEvent); }
### Question: DebugWebViewClient extends WebViewClient implements LogControl { @Override public void onUnhandledKeyEvent(final WebView view, final KeyEvent event) { logger.onUnhandledKeyEvent(view, event); client.onUnhandledKeyEvent(view, event); } DebugWebViewClient(); DebugWebViewClient(@NonNull final WebViewClient client); @SuppressWarnings("WeakerAccess") DebugWebViewClient( @NonNull final WebViewClient client, @NonNull final DebugWebViewClientLogger logger); @RequiresApi(api = Build.VERSION_CODES.M) @Override void onReceivedError(final WebView view, final WebResourceRequest request, final WebResourceError error); @Override @Deprecated void onReceivedError(final WebView view, final int errorCode, final String description, final String failingUrl); @RequiresApi(api = Build.VERSION_CODES.M) @Override void onReceivedHttpError(final WebView view, final WebResourceRequest request, final WebResourceResponse errorResponse); @Override void onReceivedSslError(final WebView view, final SslErrorHandler handler, final SslError error); @RequiresApi(api = Build.VERSION_CODES.N) @Override boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request); @Override boolean shouldOverrideUrlLoading(WebView view, String url); @Override void onLoadResource(WebView view, String url); @TargetApi(Build.VERSION_CODES.M) @Override void onPageCommitVisible(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Deprecated WebResourceResponse shouldInterceptRequest(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request); @Override @Deprecated @SuppressWarnings("deprecation") //for use with older versions void onTooManyRedirects(WebView view, Message cancelMsg, Message continueMsg); @Override void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm); @Override void onPageStarted(WebView view, String url, Bitmap facIcon); @Override void onPageFinished(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override void onReceivedClientCertRequest(WebView view, ClientCertRequest request); @Override void onFormResubmission(final WebView view, final Message dontResend, final Message resend); @Override void doUpdateVisitedHistory(final WebView view, final String url, final boolean isReload); @Override boolean shouldOverrideKeyEvent(final WebView view, final KeyEvent event); @SuppressWarnings("unused") void onUnhandledInputEvent(final WebView view, final InputEvent event); @Override void onUnhandledKeyEvent(final WebView view, final KeyEvent event); @Override void onScaleChanged(final WebView view, final float oldScale, final float newScale); @Override void onReceivedLoginRequest(final WebView view, final String realm, final String account, final String args); @RequiresApi(api = Build.VERSION_CODES.O) @Override boolean onRenderProcessGone(final WebView view, final RenderProcessGoneDetail detail); @RequiresApi(api = Build.VERSION_CODES.O_MR1) @Override void onSafeBrowsingHit(final WebView view, final WebResourceRequest request, final int threatType, final SafeBrowsingResponse callback); @Override boolean isLoggingEnabled(); @Override void setLoggingEnabled(final boolean enabled); @Override boolean isLogKeyEventsEnabled(); @Override void setLogKeyEventsEnabled(final boolean enabled); }### Answer: @Test public void onUnhandledKeyEvent() { final KeyEvent keyEvent = Mockito.mock(KeyEvent.class); debugClient.onUnhandledKeyEvent(webView, keyEvent); verifyLogger().onUnhandledKeyEvent(webView, keyEvent); verifyWrappedClient().onUnhandledKeyEvent(webView, keyEvent); }
### Question: DebugWebViewClient extends WebViewClient implements LogControl { @Override public void onScaleChanged(final WebView view, final float oldScale, final float newScale) { logger.onScaleChanged(view, oldScale, newScale); client.onScaleChanged(view, oldScale, newScale); } DebugWebViewClient(); DebugWebViewClient(@NonNull final WebViewClient client); @SuppressWarnings("WeakerAccess") DebugWebViewClient( @NonNull final WebViewClient client, @NonNull final DebugWebViewClientLogger logger); @RequiresApi(api = Build.VERSION_CODES.M) @Override void onReceivedError(final WebView view, final WebResourceRequest request, final WebResourceError error); @Override @Deprecated void onReceivedError(final WebView view, final int errorCode, final String description, final String failingUrl); @RequiresApi(api = Build.VERSION_CODES.M) @Override void onReceivedHttpError(final WebView view, final WebResourceRequest request, final WebResourceResponse errorResponse); @Override void onReceivedSslError(final WebView view, final SslErrorHandler handler, final SslError error); @RequiresApi(api = Build.VERSION_CODES.N) @Override boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request); @Override boolean shouldOverrideUrlLoading(WebView view, String url); @Override void onLoadResource(WebView view, String url); @TargetApi(Build.VERSION_CODES.M) @Override void onPageCommitVisible(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Deprecated WebResourceResponse shouldInterceptRequest(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request); @Override @Deprecated @SuppressWarnings("deprecation") //for use with older versions void onTooManyRedirects(WebView view, Message cancelMsg, Message continueMsg); @Override void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm); @Override void onPageStarted(WebView view, String url, Bitmap facIcon); @Override void onPageFinished(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override void onReceivedClientCertRequest(WebView view, ClientCertRequest request); @Override void onFormResubmission(final WebView view, final Message dontResend, final Message resend); @Override void doUpdateVisitedHistory(final WebView view, final String url, final boolean isReload); @Override boolean shouldOverrideKeyEvent(final WebView view, final KeyEvent event); @SuppressWarnings("unused") void onUnhandledInputEvent(final WebView view, final InputEvent event); @Override void onUnhandledKeyEvent(final WebView view, final KeyEvent event); @Override void onScaleChanged(final WebView view, final float oldScale, final float newScale); @Override void onReceivedLoginRequest(final WebView view, final String realm, final String account, final String args); @RequiresApi(api = Build.VERSION_CODES.O) @Override boolean onRenderProcessGone(final WebView view, final RenderProcessGoneDetail detail); @RequiresApi(api = Build.VERSION_CODES.O_MR1) @Override void onSafeBrowsingHit(final WebView view, final WebResourceRequest request, final int threatType, final SafeBrowsingResponse callback); @Override boolean isLoggingEnabled(); @Override void setLoggingEnabled(final boolean enabled); @Override boolean isLogKeyEventsEnabled(); @Override void setLogKeyEventsEnabled(final boolean enabled); }### Answer: @Test public void onScaleChanged() { final float oldScale = 1.0f; final float newScale = 2.0f; debugClient.onScaleChanged(webView, oldScale, newScale); verifyLogger().onScaleChanged(webView, oldScale, newScale); verifyWrappedClient().onScaleChanged(webView, oldScale, newScale); }
### Question: DebugWebViewClient extends WebViewClient implements LogControl { @Override public void onReceivedLoginRequest(final WebView view, final String realm, final String account, final String args) { logger.onReceivedLoginRequest(view, realm, account, args); client.onReceivedLoginRequest(view, realm, account, args); } DebugWebViewClient(); DebugWebViewClient(@NonNull final WebViewClient client); @SuppressWarnings("WeakerAccess") DebugWebViewClient( @NonNull final WebViewClient client, @NonNull final DebugWebViewClientLogger logger); @RequiresApi(api = Build.VERSION_CODES.M) @Override void onReceivedError(final WebView view, final WebResourceRequest request, final WebResourceError error); @Override @Deprecated void onReceivedError(final WebView view, final int errorCode, final String description, final String failingUrl); @RequiresApi(api = Build.VERSION_CODES.M) @Override void onReceivedHttpError(final WebView view, final WebResourceRequest request, final WebResourceResponse errorResponse); @Override void onReceivedSslError(final WebView view, final SslErrorHandler handler, final SslError error); @RequiresApi(api = Build.VERSION_CODES.N) @Override boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request); @Override boolean shouldOverrideUrlLoading(WebView view, String url); @Override void onLoadResource(WebView view, String url); @TargetApi(Build.VERSION_CODES.M) @Override void onPageCommitVisible(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Deprecated WebResourceResponse shouldInterceptRequest(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request); @Override @Deprecated @SuppressWarnings("deprecation") //for use with older versions void onTooManyRedirects(WebView view, Message cancelMsg, Message continueMsg); @Override void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm); @Override void onPageStarted(WebView view, String url, Bitmap facIcon); @Override void onPageFinished(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override void onReceivedClientCertRequest(WebView view, ClientCertRequest request); @Override void onFormResubmission(final WebView view, final Message dontResend, final Message resend); @Override void doUpdateVisitedHistory(final WebView view, final String url, final boolean isReload); @Override boolean shouldOverrideKeyEvent(final WebView view, final KeyEvent event); @SuppressWarnings("unused") void onUnhandledInputEvent(final WebView view, final InputEvent event); @Override void onUnhandledKeyEvent(final WebView view, final KeyEvent event); @Override void onScaleChanged(final WebView view, final float oldScale, final float newScale); @Override void onReceivedLoginRequest(final WebView view, final String realm, final String account, final String args); @RequiresApi(api = Build.VERSION_CODES.O) @Override boolean onRenderProcessGone(final WebView view, final RenderProcessGoneDetail detail); @RequiresApi(api = Build.VERSION_CODES.O_MR1) @Override void onSafeBrowsingHit(final WebView view, final WebResourceRequest request, final int threatType, final SafeBrowsingResponse callback); @Override boolean isLoggingEnabled(); @Override void setLoggingEnabled(final boolean enabled); @Override boolean isLogKeyEventsEnabled(); @Override void setLogKeyEventsEnabled(final boolean enabled); }### Answer: @Test public void onReceivedLoginRequest() { final String realm = "realm"; final String account = "account"; final String args = "args"; debugClient.onReceivedLoginRequest(webView, realm, account, args); verifyLogger().onReceivedLoginRequest(webView, realm, account, args); verifyWrappedClient().onReceivedLoginRequest(webView, realm, account, args); }
### Question: DebugWebViewClient extends WebViewClient implements LogControl { @RequiresApi(api = Build.VERSION_CODES.O) @Override public boolean onRenderProcessGone(final WebView view, final RenderProcessGoneDetail detail) { final boolean retVal = client.onRenderProcessGone(view, detail); logger.onRenderProcessGone(view, detail, retVal); return retVal; } DebugWebViewClient(); DebugWebViewClient(@NonNull final WebViewClient client); @SuppressWarnings("WeakerAccess") DebugWebViewClient( @NonNull final WebViewClient client, @NonNull final DebugWebViewClientLogger logger); @RequiresApi(api = Build.VERSION_CODES.M) @Override void onReceivedError(final WebView view, final WebResourceRequest request, final WebResourceError error); @Override @Deprecated void onReceivedError(final WebView view, final int errorCode, final String description, final String failingUrl); @RequiresApi(api = Build.VERSION_CODES.M) @Override void onReceivedHttpError(final WebView view, final WebResourceRequest request, final WebResourceResponse errorResponse); @Override void onReceivedSslError(final WebView view, final SslErrorHandler handler, final SslError error); @RequiresApi(api = Build.VERSION_CODES.N) @Override boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request); @Override boolean shouldOverrideUrlLoading(WebView view, String url); @Override void onLoadResource(WebView view, String url); @TargetApi(Build.VERSION_CODES.M) @Override void onPageCommitVisible(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Deprecated WebResourceResponse shouldInterceptRequest(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request); @Override @Deprecated @SuppressWarnings("deprecation") //for use with older versions void onTooManyRedirects(WebView view, Message cancelMsg, Message continueMsg); @Override void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm); @Override void onPageStarted(WebView view, String url, Bitmap facIcon); @Override void onPageFinished(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override void onReceivedClientCertRequest(WebView view, ClientCertRequest request); @Override void onFormResubmission(final WebView view, final Message dontResend, final Message resend); @Override void doUpdateVisitedHistory(final WebView view, final String url, final boolean isReload); @Override boolean shouldOverrideKeyEvent(final WebView view, final KeyEvent event); @SuppressWarnings("unused") void onUnhandledInputEvent(final WebView view, final InputEvent event); @Override void onUnhandledKeyEvent(final WebView view, final KeyEvent event); @Override void onScaleChanged(final WebView view, final float oldScale, final float newScale); @Override void onReceivedLoginRequest(final WebView view, final String realm, final String account, final String args); @RequiresApi(api = Build.VERSION_CODES.O) @Override boolean onRenderProcessGone(final WebView view, final RenderProcessGoneDetail detail); @RequiresApi(api = Build.VERSION_CODES.O_MR1) @Override void onSafeBrowsingHit(final WebView view, final WebResourceRequest request, final int threatType, final SafeBrowsingResponse callback); @Override boolean isLoggingEnabled(); @Override void setLoggingEnabled(final boolean enabled); @Override boolean isLogKeyEventsEnabled(); @Override void setLogKeyEventsEnabled(final boolean enabled); }### Answer: @Test public void onRenderProcessGone() { final RenderProcessGoneDetail detail = Mockito.mock(RenderProcessGoneDetail.class); final boolean retVal = debugClient.onRenderProcessGone(webView, detail); verifyLogger().onRenderProcessGone(webView, detail, retVal); verifyWrappedClient().onRenderProcessGone(webView, detail); }
### Question: DebugWebViewClient extends WebViewClient implements LogControl { @RequiresApi(api = Build.VERSION_CODES.O_MR1) @Override public void onSafeBrowsingHit(final WebView view, final WebResourceRequest request, final int threatType, final SafeBrowsingResponse callback) { logger.onSafeBrowsingHit(view, request, threatType, callback); client.onSafeBrowsingHit(view, request, threatType, callback); } DebugWebViewClient(); DebugWebViewClient(@NonNull final WebViewClient client); @SuppressWarnings("WeakerAccess") DebugWebViewClient( @NonNull final WebViewClient client, @NonNull final DebugWebViewClientLogger logger); @RequiresApi(api = Build.VERSION_CODES.M) @Override void onReceivedError(final WebView view, final WebResourceRequest request, final WebResourceError error); @Override @Deprecated void onReceivedError(final WebView view, final int errorCode, final String description, final String failingUrl); @RequiresApi(api = Build.VERSION_CODES.M) @Override void onReceivedHttpError(final WebView view, final WebResourceRequest request, final WebResourceResponse errorResponse); @Override void onReceivedSslError(final WebView view, final SslErrorHandler handler, final SslError error); @RequiresApi(api = Build.VERSION_CODES.N) @Override boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request); @Override boolean shouldOverrideUrlLoading(WebView view, String url); @Override void onLoadResource(WebView view, String url); @TargetApi(Build.VERSION_CODES.M) @Override void onPageCommitVisible(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Deprecated WebResourceResponse shouldInterceptRequest(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request); @Override @Deprecated @SuppressWarnings("deprecation") //for use with older versions void onTooManyRedirects(WebView view, Message cancelMsg, Message continueMsg); @Override void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm); @Override void onPageStarted(WebView view, String url, Bitmap facIcon); @Override void onPageFinished(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override void onReceivedClientCertRequest(WebView view, ClientCertRequest request); @Override void onFormResubmission(final WebView view, final Message dontResend, final Message resend); @Override void doUpdateVisitedHistory(final WebView view, final String url, final boolean isReload); @Override boolean shouldOverrideKeyEvent(final WebView view, final KeyEvent event); @SuppressWarnings("unused") void onUnhandledInputEvent(final WebView view, final InputEvent event); @Override void onUnhandledKeyEvent(final WebView view, final KeyEvent event); @Override void onScaleChanged(final WebView view, final float oldScale, final float newScale); @Override void onReceivedLoginRequest(final WebView view, final String realm, final String account, final String args); @RequiresApi(api = Build.VERSION_CODES.O) @Override boolean onRenderProcessGone(final WebView view, final RenderProcessGoneDetail detail); @RequiresApi(api = Build.VERSION_CODES.O_MR1) @Override void onSafeBrowsingHit(final WebView view, final WebResourceRequest request, final int threatType, final SafeBrowsingResponse callback); @Override boolean isLoggingEnabled(); @Override void setLoggingEnabled(final boolean enabled); @Override boolean isLogKeyEventsEnabled(); @Override void setLogKeyEventsEnabled(final boolean enabled); }### Answer: @Test public void onSafeBrowsingHit() { final WebResourceRequest request = Mockito.mock(WebResourceRequest.class); final SafeBrowsingResponse callback = Mockito.mock(SafeBrowsingResponse.class); final int threatType = -1; debugClient.onSafeBrowsingHit(webView, request, threatType, callback); verifyLogger().onSafeBrowsingHit(webView, request, threatType, callback); verifyWrappedClient().onSafeBrowsingHit(webView, request, threatType, callback); }
### Question: DebugWebViewClientLogger implements LogControl { public void onReceivedSslError(final WebView view, final SslErrorHandler handler, final SslError error) { if (loggingEnabled) { logger.logError(String.format(LOCALE, "%s onReceivedSslError() ERR: %s", SPACE, error)); } } DebugWebViewClientLogger(); DebugWebViewClientLogger(@NonNull final String tag); @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE) protected DebugWebViewClientLogger(@NonNull final LogEngine logEngine); @RequiresApi(api = Build.VERSION_CODES.M) void onReceivedError(final WebView view, final WebResourceRequest request, final WebResourceError error); void onReceivedError(final WebView view, final int errorCode, final String description, final String failingUrl); @RequiresApi(api = Build.VERSION_CODES.M) void onReceivedHttpError(final WebView view, final WebResourceRequest request, final WebResourceResponse errorResponse); void onReceivedSslError(final WebView view, final SslErrorHandler handler, final SslError error); @RequiresApi(api = Build.VERSION_CODES.N) void shouldOverrideUrlLoading(WebView view, WebResourceRequest request, boolean retVal); void shouldOverrideUrlLoading(WebView view, String url, boolean retVal); void onLoadResource(WebView view, String url); @TargetApi(Build.VERSION_CODES.M) void onPageCommitVisible(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) void shouldInterceptRequest(WebView view, String url, WebResourceResponse retVal); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) void shouldInterceptRequest(WebView view, WebResourceRequest request, final WebResourceResponse retVal); void onTooManyRedirects(WebView view, Message cancelMsg, Message continueMsg); void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm); void onPageStarted(WebView view, String url, Bitmap facIcon); void onPageFinished(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) void onReceivedClientCertRequest(WebView view, ClientCertRequest request); void onFormResubmission(final WebView view, final Message dontResend, final Message resend); void doUpdateVisitedHistory(final WebView view, final String url, final boolean isReload); void shouldOverrideKeyEvent(final WebView view, final KeyEvent event, boolean retVal); void onUnhandledInputEvent(final WebView view, final InputEvent event); void onUnhandledKeyEvent(final WebView view, final KeyEvent event); void onScaleChanged(final WebView view, final float oldScale, final float newScale); void onReceivedLoginRequest(final WebView view, final String realm, final String account, final String args); @RequiresApi(api = Build.VERSION_CODES.O) void onRenderProcessGone(final WebView view, final RenderProcessGoneDetail detail, boolean retVal); @RequiresApi(api = Build.VERSION_CODES.O_MR1) void onSafeBrowsingHit(final WebView view, final WebResourceRequest request, final int threatType, final SafeBrowsingResponse callback); @Override boolean isLoggingEnabled(); @Override void setLoggingEnabled(final boolean enabled); @Override boolean isLogKeyEventsEnabled(); @Override void setLogKeyEventsEnabled(final boolean enabled); }### Answer: @Test public void onReceivedSslError() { final SslErrorHandler errorHandler = Mockito.mock(SslErrorHandler.class); final SslError sslError = Mockito.mock(SslError.class); logger.setLoggingEnabled(false); logger.onReceivedSslError(webView, errorHandler, sslError); verifyLogNotCalled(); logger.setLoggingEnabled(true); logger.onReceivedSslError(webView, errorHandler, sslError); verifyLogEngine().logError(Mockito.anyString()); }
### Question: DebugWebViewClientLogger implements LogControl { public void onLoadResource(WebView view, String url) { if (loggingEnabled) { logger.log(String.format(LOCALE, "%s onLoadResource() %s", SPACE, url)); } } DebugWebViewClientLogger(); DebugWebViewClientLogger(@NonNull final String tag); @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE) protected DebugWebViewClientLogger(@NonNull final LogEngine logEngine); @RequiresApi(api = Build.VERSION_CODES.M) void onReceivedError(final WebView view, final WebResourceRequest request, final WebResourceError error); void onReceivedError(final WebView view, final int errorCode, final String description, final String failingUrl); @RequiresApi(api = Build.VERSION_CODES.M) void onReceivedHttpError(final WebView view, final WebResourceRequest request, final WebResourceResponse errorResponse); void onReceivedSslError(final WebView view, final SslErrorHandler handler, final SslError error); @RequiresApi(api = Build.VERSION_CODES.N) void shouldOverrideUrlLoading(WebView view, WebResourceRequest request, boolean retVal); void shouldOverrideUrlLoading(WebView view, String url, boolean retVal); void onLoadResource(WebView view, String url); @TargetApi(Build.VERSION_CODES.M) void onPageCommitVisible(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) void shouldInterceptRequest(WebView view, String url, WebResourceResponse retVal); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) void shouldInterceptRequest(WebView view, WebResourceRequest request, final WebResourceResponse retVal); void onTooManyRedirects(WebView view, Message cancelMsg, Message continueMsg); void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm); void onPageStarted(WebView view, String url, Bitmap facIcon); void onPageFinished(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) void onReceivedClientCertRequest(WebView view, ClientCertRequest request); void onFormResubmission(final WebView view, final Message dontResend, final Message resend); void doUpdateVisitedHistory(final WebView view, final String url, final boolean isReload); void shouldOverrideKeyEvent(final WebView view, final KeyEvent event, boolean retVal); void onUnhandledInputEvent(final WebView view, final InputEvent event); void onUnhandledKeyEvent(final WebView view, final KeyEvent event); void onScaleChanged(final WebView view, final float oldScale, final float newScale); void onReceivedLoginRequest(final WebView view, final String realm, final String account, final String args); @RequiresApi(api = Build.VERSION_CODES.O) void onRenderProcessGone(final WebView view, final RenderProcessGoneDetail detail, boolean retVal); @RequiresApi(api = Build.VERSION_CODES.O_MR1) void onSafeBrowsingHit(final WebView view, final WebResourceRequest request, final int threatType, final SafeBrowsingResponse callback); @Override boolean isLoggingEnabled(); @Override void setLoggingEnabled(final boolean enabled); @Override boolean isLogKeyEventsEnabled(); @Override void setLogKeyEventsEnabled(final boolean enabled); }### Answer: @Test public void onLoadResource() { final String url = "foo"; logger.setLoggingEnabled(false); logger.onLoadResource(webView, url); verifyLogNotCalled(); logger.setLoggingEnabled(true); logger.onLoadResource(webView, url); verifyLogEngine().log(Mockito.anyString()); }
### Question: DebugWebViewClientLogger implements LogControl { @TargetApi(Build.VERSION_CODES.M) public void onPageCommitVisible(WebView view, String url) { if (loggingEnabled) { logger.log(String.format(LOCALE, "%s onPageCommitVisible() %s", SPACE, url)); } } DebugWebViewClientLogger(); DebugWebViewClientLogger(@NonNull final String tag); @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE) protected DebugWebViewClientLogger(@NonNull final LogEngine logEngine); @RequiresApi(api = Build.VERSION_CODES.M) void onReceivedError(final WebView view, final WebResourceRequest request, final WebResourceError error); void onReceivedError(final WebView view, final int errorCode, final String description, final String failingUrl); @RequiresApi(api = Build.VERSION_CODES.M) void onReceivedHttpError(final WebView view, final WebResourceRequest request, final WebResourceResponse errorResponse); void onReceivedSslError(final WebView view, final SslErrorHandler handler, final SslError error); @RequiresApi(api = Build.VERSION_CODES.N) void shouldOverrideUrlLoading(WebView view, WebResourceRequest request, boolean retVal); void shouldOverrideUrlLoading(WebView view, String url, boolean retVal); void onLoadResource(WebView view, String url); @TargetApi(Build.VERSION_CODES.M) void onPageCommitVisible(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) void shouldInterceptRequest(WebView view, String url, WebResourceResponse retVal); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) void shouldInterceptRequest(WebView view, WebResourceRequest request, final WebResourceResponse retVal); void onTooManyRedirects(WebView view, Message cancelMsg, Message continueMsg); void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm); void onPageStarted(WebView view, String url, Bitmap facIcon); void onPageFinished(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) void onReceivedClientCertRequest(WebView view, ClientCertRequest request); void onFormResubmission(final WebView view, final Message dontResend, final Message resend); void doUpdateVisitedHistory(final WebView view, final String url, final boolean isReload); void shouldOverrideKeyEvent(final WebView view, final KeyEvent event, boolean retVal); void onUnhandledInputEvent(final WebView view, final InputEvent event); void onUnhandledKeyEvent(final WebView view, final KeyEvent event); void onScaleChanged(final WebView view, final float oldScale, final float newScale); void onReceivedLoginRequest(final WebView view, final String realm, final String account, final String args); @RequiresApi(api = Build.VERSION_CODES.O) void onRenderProcessGone(final WebView view, final RenderProcessGoneDetail detail, boolean retVal); @RequiresApi(api = Build.VERSION_CODES.O_MR1) void onSafeBrowsingHit(final WebView view, final WebResourceRequest request, final int threatType, final SafeBrowsingResponse callback); @Override boolean isLoggingEnabled(); @Override void setLoggingEnabled(final boolean enabled); @Override boolean isLogKeyEventsEnabled(); @Override void setLogKeyEventsEnabled(final boolean enabled); }### Answer: @Test public void onPageCommitVisible() { final String url = "foo"; logger.setLoggingEnabled(false); logger.onPageCommitVisible(webView, url); verifyLogNotCalled(); logger.setLoggingEnabled(true); logger.onPageCommitVisible(webView, url); verifyLogEngine().log(Mockito.anyString()); }
### Question: DebugWebViewClientLogger implements LogControl { @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) public void shouldInterceptRequest(WebView view, String url, WebResourceResponse retVal) { if (loggingEnabled) { final String result = retVal == null ? "false" : StringUtils.toString(retVal); logger.log(String.format(LOCALE, "%s shouldInterceptRequest() 1/2 CALL : %s", SPACE, url)); logger.log(String.format(LOCALE, "%s shouldInterceptRequest() 2/2 OVERRIDE: %s", SPACE, url, result)); } } DebugWebViewClientLogger(); DebugWebViewClientLogger(@NonNull final String tag); @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE) protected DebugWebViewClientLogger(@NonNull final LogEngine logEngine); @RequiresApi(api = Build.VERSION_CODES.M) void onReceivedError(final WebView view, final WebResourceRequest request, final WebResourceError error); void onReceivedError(final WebView view, final int errorCode, final String description, final String failingUrl); @RequiresApi(api = Build.VERSION_CODES.M) void onReceivedHttpError(final WebView view, final WebResourceRequest request, final WebResourceResponse errorResponse); void onReceivedSslError(final WebView view, final SslErrorHandler handler, final SslError error); @RequiresApi(api = Build.VERSION_CODES.N) void shouldOverrideUrlLoading(WebView view, WebResourceRequest request, boolean retVal); void shouldOverrideUrlLoading(WebView view, String url, boolean retVal); void onLoadResource(WebView view, String url); @TargetApi(Build.VERSION_CODES.M) void onPageCommitVisible(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) void shouldInterceptRequest(WebView view, String url, WebResourceResponse retVal); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) void shouldInterceptRequest(WebView view, WebResourceRequest request, final WebResourceResponse retVal); void onTooManyRedirects(WebView view, Message cancelMsg, Message continueMsg); void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm); void onPageStarted(WebView view, String url, Bitmap facIcon); void onPageFinished(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) void onReceivedClientCertRequest(WebView view, ClientCertRequest request); void onFormResubmission(final WebView view, final Message dontResend, final Message resend); void doUpdateVisitedHistory(final WebView view, final String url, final boolean isReload); void shouldOverrideKeyEvent(final WebView view, final KeyEvent event, boolean retVal); void onUnhandledInputEvent(final WebView view, final InputEvent event); void onUnhandledKeyEvent(final WebView view, final KeyEvent event); void onScaleChanged(final WebView view, final float oldScale, final float newScale); void onReceivedLoginRequest(final WebView view, final String realm, final String account, final String args); @RequiresApi(api = Build.VERSION_CODES.O) void onRenderProcessGone(final WebView view, final RenderProcessGoneDetail detail, boolean retVal); @RequiresApi(api = Build.VERSION_CODES.O_MR1) void onSafeBrowsingHit(final WebView view, final WebResourceRequest request, final int threatType, final SafeBrowsingResponse callback); @Override boolean isLoggingEnabled(); @Override void setLoggingEnabled(final boolean enabled); @Override boolean isLogKeyEventsEnabled(); @Override void setLogKeyEventsEnabled(final boolean enabled); }### Answer: @Test public void shouldInterceptRequest() { final String url = "foo"; final WebResourceResponse response = Mockito.mock(WebResourceResponse.class); logger.setLoggingEnabled(false); logger.shouldInterceptRequest(webView, url, response); verifyLogNotCalled(); logger.setLoggingEnabled(true); logger.shouldInterceptRequest(webView, url, response); verifyLogEngine().log(Mockito.anyString()); }
### Question: DebugWebViewClient extends WebViewClient implements LogControl { @RequiresApi(api = Build.VERSION_CODES.M) @Override public void onReceivedHttpError(final WebView view, final WebResourceRequest request, final WebResourceResponse errorResponse) { logger.onReceivedHttpError(view, request, errorResponse); client.onReceivedHttpError(view, request, errorResponse); } DebugWebViewClient(); DebugWebViewClient(@NonNull final WebViewClient client); @SuppressWarnings("WeakerAccess") DebugWebViewClient( @NonNull final WebViewClient client, @NonNull final DebugWebViewClientLogger logger); @RequiresApi(api = Build.VERSION_CODES.M) @Override void onReceivedError(final WebView view, final WebResourceRequest request, final WebResourceError error); @Override @Deprecated void onReceivedError(final WebView view, final int errorCode, final String description, final String failingUrl); @RequiresApi(api = Build.VERSION_CODES.M) @Override void onReceivedHttpError(final WebView view, final WebResourceRequest request, final WebResourceResponse errorResponse); @Override void onReceivedSslError(final WebView view, final SslErrorHandler handler, final SslError error); @RequiresApi(api = Build.VERSION_CODES.N) @Override boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request); @Override boolean shouldOverrideUrlLoading(WebView view, String url); @Override void onLoadResource(WebView view, String url); @TargetApi(Build.VERSION_CODES.M) @Override void onPageCommitVisible(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Deprecated WebResourceResponse shouldInterceptRequest(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request); @Override @Deprecated @SuppressWarnings("deprecation") //for use with older versions void onTooManyRedirects(WebView view, Message cancelMsg, Message continueMsg); @Override void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm); @Override void onPageStarted(WebView view, String url, Bitmap facIcon); @Override void onPageFinished(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override void onReceivedClientCertRequest(WebView view, ClientCertRequest request); @Override void onFormResubmission(final WebView view, final Message dontResend, final Message resend); @Override void doUpdateVisitedHistory(final WebView view, final String url, final boolean isReload); @Override boolean shouldOverrideKeyEvent(final WebView view, final KeyEvent event); @SuppressWarnings("unused") void onUnhandledInputEvent(final WebView view, final InputEvent event); @Override void onUnhandledKeyEvent(final WebView view, final KeyEvent event); @Override void onScaleChanged(final WebView view, final float oldScale, final float newScale); @Override void onReceivedLoginRequest(final WebView view, final String realm, final String account, final String args); @RequiresApi(api = Build.VERSION_CODES.O) @Override boolean onRenderProcessGone(final WebView view, final RenderProcessGoneDetail detail); @RequiresApi(api = Build.VERSION_CODES.O_MR1) @Override void onSafeBrowsingHit(final WebView view, final WebResourceRequest request, final int threatType, final SafeBrowsingResponse callback); @Override boolean isLoggingEnabled(); @Override void setLoggingEnabled(final boolean enabled); @Override boolean isLogKeyEventsEnabled(); @Override void setLogKeyEventsEnabled(final boolean enabled); }### Answer: @Test public void onReceivedHttpError() { final WebResourceRequest request = Mockito.mock(WebResourceRequest.class); final WebResourceResponse response = Mockito.mock(WebResourceResponse.class); debugClient.onReceivedHttpError(webView, request, response); verifyLogger().onReceivedHttpError(webView, request, response); verifyWrappedClient().onReceivedHttpError(webView, request, response); }
### Question: DebugWebViewClientLogger implements LogControl { public void onTooManyRedirects(WebView view, Message cancelMsg, Message continueMsg) { if (loggingEnabled) { logger.logError(String.format(LOCALE, "%s onTooManyRedirects()", SPACE)); } } DebugWebViewClientLogger(); DebugWebViewClientLogger(@NonNull final String tag); @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE) protected DebugWebViewClientLogger(@NonNull final LogEngine logEngine); @RequiresApi(api = Build.VERSION_CODES.M) void onReceivedError(final WebView view, final WebResourceRequest request, final WebResourceError error); void onReceivedError(final WebView view, final int errorCode, final String description, final String failingUrl); @RequiresApi(api = Build.VERSION_CODES.M) void onReceivedHttpError(final WebView view, final WebResourceRequest request, final WebResourceResponse errorResponse); void onReceivedSslError(final WebView view, final SslErrorHandler handler, final SslError error); @RequiresApi(api = Build.VERSION_CODES.N) void shouldOverrideUrlLoading(WebView view, WebResourceRequest request, boolean retVal); void shouldOverrideUrlLoading(WebView view, String url, boolean retVal); void onLoadResource(WebView view, String url); @TargetApi(Build.VERSION_CODES.M) void onPageCommitVisible(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) void shouldInterceptRequest(WebView view, String url, WebResourceResponse retVal); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) void shouldInterceptRequest(WebView view, WebResourceRequest request, final WebResourceResponse retVal); void onTooManyRedirects(WebView view, Message cancelMsg, Message continueMsg); void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm); void onPageStarted(WebView view, String url, Bitmap facIcon); void onPageFinished(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) void onReceivedClientCertRequest(WebView view, ClientCertRequest request); void onFormResubmission(final WebView view, final Message dontResend, final Message resend); void doUpdateVisitedHistory(final WebView view, final String url, final boolean isReload); void shouldOverrideKeyEvent(final WebView view, final KeyEvent event, boolean retVal); void onUnhandledInputEvent(final WebView view, final InputEvent event); void onUnhandledKeyEvent(final WebView view, final KeyEvent event); void onScaleChanged(final WebView view, final float oldScale, final float newScale); void onReceivedLoginRequest(final WebView view, final String realm, final String account, final String args); @RequiresApi(api = Build.VERSION_CODES.O) void onRenderProcessGone(final WebView view, final RenderProcessGoneDetail detail, boolean retVal); @RequiresApi(api = Build.VERSION_CODES.O_MR1) void onSafeBrowsingHit(final WebView view, final WebResourceRequest request, final int threatType, final SafeBrowsingResponse callback); @Override boolean isLoggingEnabled(); @Override void setLoggingEnabled(final boolean enabled); @Override boolean isLogKeyEventsEnabled(); @Override void setLogKeyEventsEnabled(final boolean enabled); }### Answer: @Test public void onTooManyRedirects() { final Message cancelMsg = Mockito.mock(Message.class); final Message continueMsg = Mockito.mock(Message.class); logger.setLoggingEnabled(false); logger.onTooManyRedirects(webView, cancelMsg, continueMsg); verifyLogNotCalled(); logger.setLoggingEnabled(true); logger.onTooManyRedirects(webView, cancelMsg, continueMsg); verifyLogEngine().logError(Mockito.anyString()); }
### Question: DebugWebViewClientLogger implements LogControl { public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) { if (loggingEnabled) { logger.logSecurity(String.format(LOCALE, "%s onReceivedHttpAuthRequest() %s %s %s", SPACE, host, realm, handler)); } } DebugWebViewClientLogger(); DebugWebViewClientLogger(@NonNull final String tag); @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE) protected DebugWebViewClientLogger(@NonNull final LogEngine logEngine); @RequiresApi(api = Build.VERSION_CODES.M) void onReceivedError(final WebView view, final WebResourceRequest request, final WebResourceError error); void onReceivedError(final WebView view, final int errorCode, final String description, final String failingUrl); @RequiresApi(api = Build.VERSION_CODES.M) void onReceivedHttpError(final WebView view, final WebResourceRequest request, final WebResourceResponse errorResponse); void onReceivedSslError(final WebView view, final SslErrorHandler handler, final SslError error); @RequiresApi(api = Build.VERSION_CODES.N) void shouldOverrideUrlLoading(WebView view, WebResourceRequest request, boolean retVal); void shouldOverrideUrlLoading(WebView view, String url, boolean retVal); void onLoadResource(WebView view, String url); @TargetApi(Build.VERSION_CODES.M) void onPageCommitVisible(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) void shouldInterceptRequest(WebView view, String url, WebResourceResponse retVal); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) void shouldInterceptRequest(WebView view, WebResourceRequest request, final WebResourceResponse retVal); void onTooManyRedirects(WebView view, Message cancelMsg, Message continueMsg); void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm); void onPageStarted(WebView view, String url, Bitmap facIcon); void onPageFinished(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) void onReceivedClientCertRequest(WebView view, ClientCertRequest request); void onFormResubmission(final WebView view, final Message dontResend, final Message resend); void doUpdateVisitedHistory(final WebView view, final String url, final boolean isReload); void shouldOverrideKeyEvent(final WebView view, final KeyEvent event, boolean retVal); void onUnhandledInputEvent(final WebView view, final InputEvent event); void onUnhandledKeyEvent(final WebView view, final KeyEvent event); void onScaleChanged(final WebView view, final float oldScale, final float newScale); void onReceivedLoginRequest(final WebView view, final String realm, final String account, final String args); @RequiresApi(api = Build.VERSION_CODES.O) void onRenderProcessGone(final WebView view, final RenderProcessGoneDetail detail, boolean retVal); @RequiresApi(api = Build.VERSION_CODES.O_MR1) void onSafeBrowsingHit(final WebView view, final WebResourceRequest request, final int threatType, final SafeBrowsingResponse callback); @Override boolean isLoggingEnabled(); @Override void setLoggingEnabled(final boolean enabled); @Override boolean isLogKeyEventsEnabled(); @Override void setLogKeyEventsEnabled(final boolean enabled); }### Answer: @Test public void onReceivedHttpAuthRequest() { final HttpAuthHandler handler = Mockito.mock(HttpAuthHandler.class); final String host = "foo"; final String realm = "bar"; logger.setLoggingEnabled(false); logger.onReceivedHttpAuthRequest(webView, handler, host, realm); verifyLogNotCalled(); logger.setLoggingEnabled(true); logger.onReceivedHttpAuthRequest(webView, handler, host, realm); verifyLogEngine().logSecurity(Mockito.anyString()); }
### Question: DebugWebViewClientLogger implements LogControl { public void onPageStarted(WebView view, String url, Bitmap facIcon) { if (loggingEnabled) { logger.log(String.format(LOCALE, "%s onPageStarted() %s", IN, url)); } } DebugWebViewClientLogger(); DebugWebViewClientLogger(@NonNull final String tag); @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE) protected DebugWebViewClientLogger(@NonNull final LogEngine logEngine); @RequiresApi(api = Build.VERSION_CODES.M) void onReceivedError(final WebView view, final WebResourceRequest request, final WebResourceError error); void onReceivedError(final WebView view, final int errorCode, final String description, final String failingUrl); @RequiresApi(api = Build.VERSION_CODES.M) void onReceivedHttpError(final WebView view, final WebResourceRequest request, final WebResourceResponse errorResponse); void onReceivedSslError(final WebView view, final SslErrorHandler handler, final SslError error); @RequiresApi(api = Build.VERSION_CODES.N) void shouldOverrideUrlLoading(WebView view, WebResourceRequest request, boolean retVal); void shouldOverrideUrlLoading(WebView view, String url, boolean retVal); void onLoadResource(WebView view, String url); @TargetApi(Build.VERSION_CODES.M) void onPageCommitVisible(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) void shouldInterceptRequest(WebView view, String url, WebResourceResponse retVal); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) void shouldInterceptRequest(WebView view, WebResourceRequest request, final WebResourceResponse retVal); void onTooManyRedirects(WebView view, Message cancelMsg, Message continueMsg); void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm); void onPageStarted(WebView view, String url, Bitmap facIcon); void onPageFinished(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) void onReceivedClientCertRequest(WebView view, ClientCertRequest request); void onFormResubmission(final WebView view, final Message dontResend, final Message resend); void doUpdateVisitedHistory(final WebView view, final String url, final boolean isReload); void shouldOverrideKeyEvent(final WebView view, final KeyEvent event, boolean retVal); void onUnhandledInputEvent(final WebView view, final InputEvent event); void onUnhandledKeyEvent(final WebView view, final KeyEvent event); void onScaleChanged(final WebView view, final float oldScale, final float newScale); void onReceivedLoginRequest(final WebView view, final String realm, final String account, final String args); @RequiresApi(api = Build.VERSION_CODES.O) void onRenderProcessGone(final WebView view, final RenderProcessGoneDetail detail, boolean retVal); @RequiresApi(api = Build.VERSION_CODES.O_MR1) void onSafeBrowsingHit(final WebView view, final WebResourceRequest request, final int threatType, final SafeBrowsingResponse callback); @Override boolean isLoggingEnabled(); @Override void setLoggingEnabled(final boolean enabled); @Override boolean isLogKeyEventsEnabled(); @Override void setLogKeyEventsEnabled(final boolean enabled); }### Answer: @Test public void onPageStarted() { final String url = "foo"; final Bitmap bitmap = Mockito.mock(Bitmap.class); logger.setLoggingEnabled(false); logger.onPageStarted(webView, url, bitmap); verifyLogNotCalled(); logger.setLoggingEnabled(true); logger.onPageStarted(webView, url, bitmap); verifyLogEngine().log(Mockito.anyString()); }
### Question: DebugWebViewClientLogger implements LogControl { public void onPageFinished(WebView view, String url) { if (loggingEnabled) { logger.log(String.format(LOCALE, "%s onPageFinished() %s", OUT, url)); } } DebugWebViewClientLogger(); DebugWebViewClientLogger(@NonNull final String tag); @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE) protected DebugWebViewClientLogger(@NonNull final LogEngine logEngine); @RequiresApi(api = Build.VERSION_CODES.M) void onReceivedError(final WebView view, final WebResourceRequest request, final WebResourceError error); void onReceivedError(final WebView view, final int errorCode, final String description, final String failingUrl); @RequiresApi(api = Build.VERSION_CODES.M) void onReceivedHttpError(final WebView view, final WebResourceRequest request, final WebResourceResponse errorResponse); void onReceivedSslError(final WebView view, final SslErrorHandler handler, final SslError error); @RequiresApi(api = Build.VERSION_CODES.N) void shouldOverrideUrlLoading(WebView view, WebResourceRequest request, boolean retVal); void shouldOverrideUrlLoading(WebView view, String url, boolean retVal); void onLoadResource(WebView view, String url); @TargetApi(Build.VERSION_CODES.M) void onPageCommitVisible(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) void shouldInterceptRequest(WebView view, String url, WebResourceResponse retVal); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) void shouldInterceptRequest(WebView view, WebResourceRequest request, final WebResourceResponse retVal); void onTooManyRedirects(WebView view, Message cancelMsg, Message continueMsg); void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm); void onPageStarted(WebView view, String url, Bitmap facIcon); void onPageFinished(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) void onReceivedClientCertRequest(WebView view, ClientCertRequest request); void onFormResubmission(final WebView view, final Message dontResend, final Message resend); void doUpdateVisitedHistory(final WebView view, final String url, final boolean isReload); void shouldOverrideKeyEvent(final WebView view, final KeyEvent event, boolean retVal); void onUnhandledInputEvent(final WebView view, final InputEvent event); void onUnhandledKeyEvent(final WebView view, final KeyEvent event); void onScaleChanged(final WebView view, final float oldScale, final float newScale); void onReceivedLoginRequest(final WebView view, final String realm, final String account, final String args); @RequiresApi(api = Build.VERSION_CODES.O) void onRenderProcessGone(final WebView view, final RenderProcessGoneDetail detail, boolean retVal); @RequiresApi(api = Build.VERSION_CODES.O_MR1) void onSafeBrowsingHit(final WebView view, final WebResourceRequest request, final int threatType, final SafeBrowsingResponse callback); @Override boolean isLoggingEnabled(); @Override void setLoggingEnabled(final boolean enabled); @Override boolean isLogKeyEventsEnabled(); @Override void setLogKeyEventsEnabled(final boolean enabled); }### Answer: @Test public void onPageFinished() { final String url = "foo"; logger.setLoggingEnabled(false); logger.onPageFinished(webView, url); verifyLogNotCalled(); logger.setLoggingEnabled(true); logger.onPageFinished(webView, url); verifyLogEngine().log(Mockito.anyString()); }
### Question: DebugWebViewClientLogger implements LogControl { @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) public void onReceivedClientCertRequest(WebView view, ClientCertRequest request) { if (loggingEnabled) { logger.logSecurity(String.format(LOCALE, "%s onReceivedClientCertRequest() %s", SPACE, StringUtils.toString(request))); } } DebugWebViewClientLogger(); DebugWebViewClientLogger(@NonNull final String tag); @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE) protected DebugWebViewClientLogger(@NonNull final LogEngine logEngine); @RequiresApi(api = Build.VERSION_CODES.M) void onReceivedError(final WebView view, final WebResourceRequest request, final WebResourceError error); void onReceivedError(final WebView view, final int errorCode, final String description, final String failingUrl); @RequiresApi(api = Build.VERSION_CODES.M) void onReceivedHttpError(final WebView view, final WebResourceRequest request, final WebResourceResponse errorResponse); void onReceivedSslError(final WebView view, final SslErrorHandler handler, final SslError error); @RequiresApi(api = Build.VERSION_CODES.N) void shouldOverrideUrlLoading(WebView view, WebResourceRequest request, boolean retVal); void shouldOverrideUrlLoading(WebView view, String url, boolean retVal); void onLoadResource(WebView view, String url); @TargetApi(Build.VERSION_CODES.M) void onPageCommitVisible(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) void shouldInterceptRequest(WebView view, String url, WebResourceResponse retVal); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) void shouldInterceptRequest(WebView view, WebResourceRequest request, final WebResourceResponse retVal); void onTooManyRedirects(WebView view, Message cancelMsg, Message continueMsg); void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm); void onPageStarted(WebView view, String url, Bitmap facIcon); void onPageFinished(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) void onReceivedClientCertRequest(WebView view, ClientCertRequest request); void onFormResubmission(final WebView view, final Message dontResend, final Message resend); void doUpdateVisitedHistory(final WebView view, final String url, final boolean isReload); void shouldOverrideKeyEvent(final WebView view, final KeyEvent event, boolean retVal); void onUnhandledInputEvent(final WebView view, final InputEvent event); void onUnhandledKeyEvent(final WebView view, final KeyEvent event); void onScaleChanged(final WebView view, final float oldScale, final float newScale); void onReceivedLoginRequest(final WebView view, final String realm, final String account, final String args); @RequiresApi(api = Build.VERSION_CODES.O) void onRenderProcessGone(final WebView view, final RenderProcessGoneDetail detail, boolean retVal); @RequiresApi(api = Build.VERSION_CODES.O_MR1) void onSafeBrowsingHit(final WebView view, final WebResourceRequest request, final int threatType, final SafeBrowsingResponse callback); @Override boolean isLoggingEnabled(); @Override void setLoggingEnabled(final boolean enabled); @Override boolean isLogKeyEventsEnabled(); @Override void setLogKeyEventsEnabled(final boolean enabled); }### Answer: @Test public void onReceivedClientCertRequest() { final ClientCertRequest request = Mockito.mock(ClientCertRequest.class); logger.setLoggingEnabled(false); logger.onReceivedClientCertRequest(webView, request); verifyLogNotCalled(); logger.setLoggingEnabled(true); logger.onReceivedClientCertRequest(webView, request); verifyLogEngine().logSecurity(Mockito.anyString()); }
### Question: DebugWebViewClientLogger implements LogControl { public void onFormResubmission(final WebView view, final Message dontResend, final Message resend) { if (loggingEnabled) { logger.log(String.format(LOCALE, "%s onFormResubmission()", SPACE)); } } DebugWebViewClientLogger(); DebugWebViewClientLogger(@NonNull final String tag); @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE) protected DebugWebViewClientLogger(@NonNull final LogEngine logEngine); @RequiresApi(api = Build.VERSION_CODES.M) void onReceivedError(final WebView view, final WebResourceRequest request, final WebResourceError error); void onReceivedError(final WebView view, final int errorCode, final String description, final String failingUrl); @RequiresApi(api = Build.VERSION_CODES.M) void onReceivedHttpError(final WebView view, final WebResourceRequest request, final WebResourceResponse errorResponse); void onReceivedSslError(final WebView view, final SslErrorHandler handler, final SslError error); @RequiresApi(api = Build.VERSION_CODES.N) void shouldOverrideUrlLoading(WebView view, WebResourceRequest request, boolean retVal); void shouldOverrideUrlLoading(WebView view, String url, boolean retVal); void onLoadResource(WebView view, String url); @TargetApi(Build.VERSION_CODES.M) void onPageCommitVisible(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) void shouldInterceptRequest(WebView view, String url, WebResourceResponse retVal); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) void shouldInterceptRequest(WebView view, WebResourceRequest request, final WebResourceResponse retVal); void onTooManyRedirects(WebView view, Message cancelMsg, Message continueMsg); void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm); void onPageStarted(WebView view, String url, Bitmap facIcon); void onPageFinished(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) void onReceivedClientCertRequest(WebView view, ClientCertRequest request); void onFormResubmission(final WebView view, final Message dontResend, final Message resend); void doUpdateVisitedHistory(final WebView view, final String url, final boolean isReload); void shouldOverrideKeyEvent(final WebView view, final KeyEvent event, boolean retVal); void onUnhandledInputEvent(final WebView view, final InputEvent event); void onUnhandledKeyEvent(final WebView view, final KeyEvent event); void onScaleChanged(final WebView view, final float oldScale, final float newScale); void onReceivedLoginRequest(final WebView view, final String realm, final String account, final String args); @RequiresApi(api = Build.VERSION_CODES.O) void onRenderProcessGone(final WebView view, final RenderProcessGoneDetail detail, boolean retVal); @RequiresApi(api = Build.VERSION_CODES.O_MR1) void onSafeBrowsingHit(final WebView view, final WebResourceRequest request, final int threatType, final SafeBrowsingResponse callback); @Override boolean isLoggingEnabled(); @Override void setLoggingEnabled(final boolean enabled); @Override boolean isLogKeyEventsEnabled(); @Override void setLogKeyEventsEnabled(final boolean enabled); }### Answer: @Test public void onFormResubmission() { final Message dontResend = Mockito.mock(Message.class); final Message resend = Mockito.mock(Message.class); logger.setLoggingEnabled(false); logger.onFormResubmission(webView, dontResend, resend); verifyLogNotCalled(); logger.setLoggingEnabled(true); logger.onFormResubmission(webView, dontResend, resend); verifyLogEngine().log(Mockito.anyString()); }
### Question: DebugWebViewClientLogger implements LogControl { public void doUpdateVisitedHistory(final WebView view, final String url, final boolean isReload) { if (loggingEnabled) { logger.log(String.format(LOCALE, "%s doUpdateVisitedHistory() %s, isReload: %s", SPACE, url, isReload)); } } DebugWebViewClientLogger(); DebugWebViewClientLogger(@NonNull final String tag); @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE) protected DebugWebViewClientLogger(@NonNull final LogEngine logEngine); @RequiresApi(api = Build.VERSION_CODES.M) void onReceivedError(final WebView view, final WebResourceRequest request, final WebResourceError error); void onReceivedError(final WebView view, final int errorCode, final String description, final String failingUrl); @RequiresApi(api = Build.VERSION_CODES.M) void onReceivedHttpError(final WebView view, final WebResourceRequest request, final WebResourceResponse errorResponse); void onReceivedSslError(final WebView view, final SslErrorHandler handler, final SslError error); @RequiresApi(api = Build.VERSION_CODES.N) void shouldOverrideUrlLoading(WebView view, WebResourceRequest request, boolean retVal); void shouldOverrideUrlLoading(WebView view, String url, boolean retVal); void onLoadResource(WebView view, String url); @TargetApi(Build.VERSION_CODES.M) void onPageCommitVisible(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) void shouldInterceptRequest(WebView view, String url, WebResourceResponse retVal); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) void shouldInterceptRequest(WebView view, WebResourceRequest request, final WebResourceResponse retVal); void onTooManyRedirects(WebView view, Message cancelMsg, Message continueMsg); void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm); void onPageStarted(WebView view, String url, Bitmap facIcon); void onPageFinished(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) void onReceivedClientCertRequest(WebView view, ClientCertRequest request); void onFormResubmission(final WebView view, final Message dontResend, final Message resend); void doUpdateVisitedHistory(final WebView view, final String url, final boolean isReload); void shouldOverrideKeyEvent(final WebView view, final KeyEvent event, boolean retVal); void onUnhandledInputEvent(final WebView view, final InputEvent event); void onUnhandledKeyEvent(final WebView view, final KeyEvent event); void onScaleChanged(final WebView view, final float oldScale, final float newScale); void onReceivedLoginRequest(final WebView view, final String realm, final String account, final String args); @RequiresApi(api = Build.VERSION_CODES.O) void onRenderProcessGone(final WebView view, final RenderProcessGoneDetail detail, boolean retVal); @RequiresApi(api = Build.VERSION_CODES.O_MR1) void onSafeBrowsingHit(final WebView view, final WebResourceRequest request, final int threatType, final SafeBrowsingResponse callback); @Override boolean isLoggingEnabled(); @Override void setLoggingEnabled(final boolean enabled); @Override boolean isLogKeyEventsEnabled(); @Override void setLogKeyEventsEnabled(final boolean enabled); }### Answer: @Test public void doUpdateVisitedHistory() { final String url = "foo"; final boolean reload = true; logger.setLoggingEnabled(false); logger.doUpdateVisitedHistory(webView, url, reload); verifyLogNotCalled(); logger.setLoggingEnabled(true); logger.doUpdateVisitedHistory(webView, url, reload); verifyLogEngine().log(Mockito.anyString()); }
### Question: DebugWebViewClientLogger implements LogControl { public void onUnhandledInputEvent(final WebView view, final InputEvent event) { if (loggingEnabled && logKeyEventsEnabled) { logger.logKeyEvent(String.format(LOCALE, "%s onUnhandledInputEvent() %s", SPACE, event)); } } DebugWebViewClientLogger(); DebugWebViewClientLogger(@NonNull final String tag); @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE) protected DebugWebViewClientLogger(@NonNull final LogEngine logEngine); @RequiresApi(api = Build.VERSION_CODES.M) void onReceivedError(final WebView view, final WebResourceRequest request, final WebResourceError error); void onReceivedError(final WebView view, final int errorCode, final String description, final String failingUrl); @RequiresApi(api = Build.VERSION_CODES.M) void onReceivedHttpError(final WebView view, final WebResourceRequest request, final WebResourceResponse errorResponse); void onReceivedSslError(final WebView view, final SslErrorHandler handler, final SslError error); @RequiresApi(api = Build.VERSION_CODES.N) void shouldOverrideUrlLoading(WebView view, WebResourceRequest request, boolean retVal); void shouldOverrideUrlLoading(WebView view, String url, boolean retVal); void onLoadResource(WebView view, String url); @TargetApi(Build.VERSION_CODES.M) void onPageCommitVisible(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) void shouldInterceptRequest(WebView view, String url, WebResourceResponse retVal); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) void shouldInterceptRequest(WebView view, WebResourceRequest request, final WebResourceResponse retVal); void onTooManyRedirects(WebView view, Message cancelMsg, Message continueMsg); void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm); void onPageStarted(WebView view, String url, Bitmap facIcon); void onPageFinished(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) void onReceivedClientCertRequest(WebView view, ClientCertRequest request); void onFormResubmission(final WebView view, final Message dontResend, final Message resend); void doUpdateVisitedHistory(final WebView view, final String url, final boolean isReload); void shouldOverrideKeyEvent(final WebView view, final KeyEvent event, boolean retVal); void onUnhandledInputEvent(final WebView view, final InputEvent event); void onUnhandledKeyEvent(final WebView view, final KeyEvent event); void onScaleChanged(final WebView view, final float oldScale, final float newScale); void onReceivedLoginRequest(final WebView view, final String realm, final String account, final String args); @RequiresApi(api = Build.VERSION_CODES.O) void onRenderProcessGone(final WebView view, final RenderProcessGoneDetail detail, boolean retVal); @RequiresApi(api = Build.VERSION_CODES.O_MR1) void onSafeBrowsingHit(final WebView view, final WebResourceRequest request, final int threatType, final SafeBrowsingResponse callback); @Override boolean isLoggingEnabled(); @Override void setLoggingEnabled(final boolean enabled); @Override boolean isLogKeyEventsEnabled(); @Override void setLogKeyEventsEnabled(final boolean enabled); }### Answer: @Test public void onUnhandledInputEvent() { final InputEvent inputEvent = Mockito.mock(InputEvent.class); logger.setLoggingEnabled(false); logger.setLogKeyEventsEnabled(false); logger.onUnhandledInputEvent(webView, inputEvent); verifyLogNotCalled(); logger.setLoggingEnabled(false); logger.setLogKeyEventsEnabled(true); logger.onUnhandledInputEvent(webView, inputEvent); verifyLogNotCalled(); logger.setLoggingEnabled(true); logger.setLogKeyEventsEnabled(false); logger.onUnhandledInputEvent(webView, inputEvent); verifyLogNotCalled(); logger.setLoggingEnabled(true); logger.setLogKeyEventsEnabled(true); logger.onUnhandledInputEvent(webView, inputEvent); verifyLogEngine().logKeyEvent(Mockito.anyString()); }
### Question: DebugWebViewClientLogger implements LogControl { public void onUnhandledKeyEvent(final WebView view, final KeyEvent event) { if (loggingEnabled && logKeyEventsEnabled) { logger.logKeyEvent(String.format(LOCALE, "%s onUnhandledKeyEvent() %s", SPACE, event)); } } DebugWebViewClientLogger(); DebugWebViewClientLogger(@NonNull final String tag); @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE) protected DebugWebViewClientLogger(@NonNull final LogEngine logEngine); @RequiresApi(api = Build.VERSION_CODES.M) void onReceivedError(final WebView view, final WebResourceRequest request, final WebResourceError error); void onReceivedError(final WebView view, final int errorCode, final String description, final String failingUrl); @RequiresApi(api = Build.VERSION_CODES.M) void onReceivedHttpError(final WebView view, final WebResourceRequest request, final WebResourceResponse errorResponse); void onReceivedSslError(final WebView view, final SslErrorHandler handler, final SslError error); @RequiresApi(api = Build.VERSION_CODES.N) void shouldOverrideUrlLoading(WebView view, WebResourceRequest request, boolean retVal); void shouldOverrideUrlLoading(WebView view, String url, boolean retVal); void onLoadResource(WebView view, String url); @TargetApi(Build.VERSION_CODES.M) void onPageCommitVisible(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) void shouldInterceptRequest(WebView view, String url, WebResourceResponse retVal); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) void shouldInterceptRequest(WebView view, WebResourceRequest request, final WebResourceResponse retVal); void onTooManyRedirects(WebView view, Message cancelMsg, Message continueMsg); void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm); void onPageStarted(WebView view, String url, Bitmap facIcon); void onPageFinished(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) void onReceivedClientCertRequest(WebView view, ClientCertRequest request); void onFormResubmission(final WebView view, final Message dontResend, final Message resend); void doUpdateVisitedHistory(final WebView view, final String url, final boolean isReload); void shouldOverrideKeyEvent(final WebView view, final KeyEvent event, boolean retVal); void onUnhandledInputEvent(final WebView view, final InputEvent event); void onUnhandledKeyEvent(final WebView view, final KeyEvent event); void onScaleChanged(final WebView view, final float oldScale, final float newScale); void onReceivedLoginRequest(final WebView view, final String realm, final String account, final String args); @RequiresApi(api = Build.VERSION_CODES.O) void onRenderProcessGone(final WebView view, final RenderProcessGoneDetail detail, boolean retVal); @RequiresApi(api = Build.VERSION_CODES.O_MR1) void onSafeBrowsingHit(final WebView view, final WebResourceRequest request, final int threatType, final SafeBrowsingResponse callback); @Override boolean isLoggingEnabled(); @Override void setLoggingEnabled(final boolean enabled); @Override boolean isLogKeyEventsEnabled(); @Override void setLogKeyEventsEnabled(final boolean enabled); }### Answer: @Test public void onUnhandledKeyEvent() { final KeyEvent keyEvent = Mockito.mock(KeyEvent.class); logger.setLoggingEnabled(false); logger.setLogKeyEventsEnabled(false); logger.onUnhandledKeyEvent(webView, keyEvent); verifyLogNotCalled(); logger.setLoggingEnabled(false); logger.setLogKeyEventsEnabled(true); logger.onUnhandledKeyEvent(webView, keyEvent); verifyLogNotCalled(); logger.setLoggingEnabled(true); logger.setLogKeyEventsEnabled(false); logger.onUnhandledKeyEvent(webView, keyEvent); verifyLogNotCalled(); logger.setLoggingEnabled(true); logger.setLogKeyEventsEnabled(true); logger.onUnhandledKeyEvent(webView, keyEvent); verifyLogEngine().logKeyEvent(Mockito.anyString()); }
### Question: DebugWebViewClient extends WebViewClient implements LogControl { @Override public void onReceivedSslError(final WebView view, final SslErrorHandler handler, final SslError error) { logger.onReceivedSslError(view, handler, error); client.onReceivedSslError(view, handler, error); } DebugWebViewClient(); DebugWebViewClient(@NonNull final WebViewClient client); @SuppressWarnings("WeakerAccess") DebugWebViewClient( @NonNull final WebViewClient client, @NonNull final DebugWebViewClientLogger logger); @RequiresApi(api = Build.VERSION_CODES.M) @Override void onReceivedError(final WebView view, final WebResourceRequest request, final WebResourceError error); @Override @Deprecated void onReceivedError(final WebView view, final int errorCode, final String description, final String failingUrl); @RequiresApi(api = Build.VERSION_CODES.M) @Override void onReceivedHttpError(final WebView view, final WebResourceRequest request, final WebResourceResponse errorResponse); @Override void onReceivedSslError(final WebView view, final SslErrorHandler handler, final SslError error); @RequiresApi(api = Build.VERSION_CODES.N) @Override boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request); @Override boolean shouldOverrideUrlLoading(WebView view, String url); @Override void onLoadResource(WebView view, String url); @TargetApi(Build.VERSION_CODES.M) @Override void onPageCommitVisible(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Deprecated WebResourceResponse shouldInterceptRequest(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request); @Override @Deprecated @SuppressWarnings("deprecation") //for use with older versions void onTooManyRedirects(WebView view, Message cancelMsg, Message continueMsg); @Override void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm); @Override void onPageStarted(WebView view, String url, Bitmap facIcon); @Override void onPageFinished(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override void onReceivedClientCertRequest(WebView view, ClientCertRequest request); @Override void onFormResubmission(final WebView view, final Message dontResend, final Message resend); @Override void doUpdateVisitedHistory(final WebView view, final String url, final boolean isReload); @Override boolean shouldOverrideKeyEvent(final WebView view, final KeyEvent event); @SuppressWarnings("unused") void onUnhandledInputEvent(final WebView view, final InputEvent event); @Override void onUnhandledKeyEvent(final WebView view, final KeyEvent event); @Override void onScaleChanged(final WebView view, final float oldScale, final float newScale); @Override void onReceivedLoginRequest(final WebView view, final String realm, final String account, final String args); @RequiresApi(api = Build.VERSION_CODES.O) @Override boolean onRenderProcessGone(final WebView view, final RenderProcessGoneDetail detail); @RequiresApi(api = Build.VERSION_CODES.O_MR1) @Override void onSafeBrowsingHit(final WebView view, final WebResourceRequest request, final int threatType, final SafeBrowsingResponse callback); @Override boolean isLoggingEnabled(); @Override void setLoggingEnabled(final boolean enabled); @Override boolean isLogKeyEventsEnabled(); @Override void setLogKeyEventsEnabled(final boolean enabled); }### Answer: @Test public void onReceivedSslError() { final SslErrorHandler errorHandler = Mockito.mock(SslErrorHandler.class); final SslError sslError = Mockito.mock(SslError.class); debugClient.onReceivedSslError(webView, errorHandler, sslError); verifyLogger().onReceivedSslError(webView, errorHandler, sslError); verifyWrappedClient().onReceivedSslError(webView, errorHandler, sslError); }
### Question: DebugWebViewClientLogger implements LogControl { public void onScaleChanged(final WebView view, final float oldScale, final float newScale) { if (loggingEnabled) { logger.log(String.format(LOCALE, "%s onScaleChanged() old: %s, new: %s", SPACE, oldScale, newScale)); } } DebugWebViewClientLogger(); DebugWebViewClientLogger(@NonNull final String tag); @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE) protected DebugWebViewClientLogger(@NonNull final LogEngine logEngine); @RequiresApi(api = Build.VERSION_CODES.M) void onReceivedError(final WebView view, final WebResourceRequest request, final WebResourceError error); void onReceivedError(final WebView view, final int errorCode, final String description, final String failingUrl); @RequiresApi(api = Build.VERSION_CODES.M) void onReceivedHttpError(final WebView view, final WebResourceRequest request, final WebResourceResponse errorResponse); void onReceivedSslError(final WebView view, final SslErrorHandler handler, final SslError error); @RequiresApi(api = Build.VERSION_CODES.N) void shouldOverrideUrlLoading(WebView view, WebResourceRequest request, boolean retVal); void shouldOverrideUrlLoading(WebView view, String url, boolean retVal); void onLoadResource(WebView view, String url); @TargetApi(Build.VERSION_CODES.M) void onPageCommitVisible(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) void shouldInterceptRequest(WebView view, String url, WebResourceResponse retVal); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) void shouldInterceptRequest(WebView view, WebResourceRequest request, final WebResourceResponse retVal); void onTooManyRedirects(WebView view, Message cancelMsg, Message continueMsg); void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm); void onPageStarted(WebView view, String url, Bitmap facIcon); void onPageFinished(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) void onReceivedClientCertRequest(WebView view, ClientCertRequest request); void onFormResubmission(final WebView view, final Message dontResend, final Message resend); void doUpdateVisitedHistory(final WebView view, final String url, final boolean isReload); void shouldOverrideKeyEvent(final WebView view, final KeyEvent event, boolean retVal); void onUnhandledInputEvent(final WebView view, final InputEvent event); void onUnhandledKeyEvent(final WebView view, final KeyEvent event); void onScaleChanged(final WebView view, final float oldScale, final float newScale); void onReceivedLoginRequest(final WebView view, final String realm, final String account, final String args); @RequiresApi(api = Build.VERSION_CODES.O) void onRenderProcessGone(final WebView view, final RenderProcessGoneDetail detail, boolean retVal); @RequiresApi(api = Build.VERSION_CODES.O_MR1) void onSafeBrowsingHit(final WebView view, final WebResourceRequest request, final int threatType, final SafeBrowsingResponse callback); @Override boolean isLoggingEnabled(); @Override void setLoggingEnabled(final boolean enabled); @Override boolean isLogKeyEventsEnabled(); @Override void setLogKeyEventsEnabled(final boolean enabled); }### Answer: @Test public void onScaleChanged() { final float oldScale = 1.0f; final float newScale = 2.0f; logger.setLoggingEnabled(false); logger.onScaleChanged(webView, oldScale, newScale); verifyLogNotCalled(); logger.setLoggingEnabled(true); logger.onScaleChanged(webView, oldScale, newScale); verifyLogEngine().log(Mockito.anyString()); }
### Question: DebugWebViewClientLogger implements LogControl { public void onReceivedLoginRequest(final WebView view, final String realm, final String account, final String args) { if (loggingEnabled) { logger.logSecurity(String.format(LOCALE, "%s onReceivedLoginRequest() %s, %s, %s", SPACE, realm, account, args)); } } DebugWebViewClientLogger(); DebugWebViewClientLogger(@NonNull final String tag); @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE) protected DebugWebViewClientLogger(@NonNull final LogEngine logEngine); @RequiresApi(api = Build.VERSION_CODES.M) void onReceivedError(final WebView view, final WebResourceRequest request, final WebResourceError error); void onReceivedError(final WebView view, final int errorCode, final String description, final String failingUrl); @RequiresApi(api = Build.VERSION_CODES.M) void onReceivedHttpError(final WebView view, final WebResourceRequest request, final WebResourceResponse errorResponse); void onReceivedSslError(final WebView view, final SslErrorHandler handler, final SslError error); @RequiresApi(api = Build.VERSION_CODES.N) void shouldOverrideUrlLoading(WebView view, WebResourceRequest request, boolean retVal); void shouldOverrideUrlLoading(WebView view, String url, boolean retVal); void onLoadResource(WebView view, String url); @TargetApi(Build.VERSION_CODES.M) void onPageCommitVisible(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) void shouldInterceptRequest(WebView view, String url, WebResourceResponse retVal); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) void shouldInterceptRequest(WebView view, WebResourceRequest request, final WebResourceResponse retVal); void onTooManyRedirects(WebView view, Message cancelMsg, Message continueMsg); void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm); void onPageStarted(WebView view, String url, Bitmap facIcon); void onPageFinished(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) void onReceivedClientCertRequest(WebView view, ClientCertRequest request); void onFormResubmission(final WebView view, final Message dontResend, final Message resend); void doUpdateVisitedHistory(final WebView view, final String url, final boolean isReload); void shouldOverrideKeyEvent(final WebView view, final KeyEvent event, boolean retVal); void onUnhandledInputEvent(final WebView view, final InputEvent event); void onUnhandledKeyEvent(final WebView view, final KeyEvent event); void onScaleChanged(final WebView view, final float oldScale, final float newScale); void onReceivedLoginRequest(final WebView view, final String realm, final String account, final String args); @RequiresApi(api = Build.VERSION_CODES.O) void onRenderProcessGone(final WebView view, final RenderProcessGoneDetail detail, boolean retVal); @RequiresApi(api = Build.VERSION_CODES.O_MR1) void onSafeBrowsingHit(final WebView view, final WebResourceRequest request, final int threatType, final SafeBrowsingResponse callback); @Override boolean isLoggingEnabled(); @Override void setLoggingEnabled(final boolean enabled); @Override boolean isLogKeyEventsEnabled(); @Override void setLogKeyEventsEnabled(final boolean enabled); }### Answer: @Test public void onReceivedLoginRequest() { final String realm = "realm"; final String account = "account"; final String args = "args"; logger.setLoggingEnabled(false); logger.onReceivedLoginRequest(webView, realm, account, args); verifyLogNotCalled(); logger.setLoggingEnabled(true); logger.onReceivedLoginRequest(webView, realm, account, args); verifyLogEngine().logSecurity(Mockito.anyString()); }
### Question: DebugWebViewClientLogger implements LogControl { @RequiresApi(api = Build.VERSION_CODES.O) public void onRenderProcessGone(final WebView view, final RenderProcessGoneDetail detail, boolean retVal) { if (loggingEnabled) { logger.log(String.format(LOCALE, "%s onRenderProcessGone() 1/2 DETAIL: %s", SPACE, detail)); logger.log(String.format(LOCALE, "%s onRenderProcessGone() 2/2 RESULT: %s", SPACE, retVal)); } } DebugWebViewClientLogger(); DebugWebViewClientLogger(@NonNull final String tag); @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE) protected DebugWebViewClientLogger(@NonNull final LogEngine logEngine); @RequiresApi(api = Build.VERSION_CODES.M) void onReceivedError(final WebView view, final WebResourceRequest request, final WebResourceError error); void onReceivedError(final WebView view, final int errorCode, final String description, final String failingUrl); @RequiresApi(api = Build.VERSION_CODES.M) void onReceivedHttpError(final WebView view, final WebResourceRequest request, final WebResourceResponse errorResponse); void onReceivedSslError(final WebView view, final SslErrorHandler handler, final SslError error); @RequiresApi(api = Build.VERSION_CODES.N) void shouldOverrideUrlLoading(WebView view, WebResourceRequest request, boolean retVal); void shouldOverrideUrlLoading(WebView view, String url, boolean retVal); void onLoadResource(WebView view, String url); @TargetApi(Build.VERSION_CODES.M) void onPageCommitVisible(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) void shouldInterceptRequest(WebView view, String url, WebResourceResponse retVal); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) void shouldInterceptRequest(WebView view, WebResourceRequest request, final WebResourceResponse retVal); void onTooManyRedirects(WebView view, Message cancelMsg, Message continueMsg); void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm); void onPageStarted(WebView view, String url, Bitmap facIcon); void onPageFinished(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) void onReceivedClientCertRequest(WebView view, ClientCertRequest request); void onFormResubmission(final WebView view, final Message dontResend, final Message resend); void doUpdateVisitedHistory(final WebView view, final String url, final boolean isReload); void shouldOverrideKeyEvent(final WebView view, final KeyEvent event, boolean retVal); void onUnhandledInputEvent(final WebView view, final InputEvent event); void onUnhandledKeyEvent(final WebView view, final KeyEvent event); void onScaleChanged(final WebView view, final float oldScale, final float newScale); void onReceivedLoginRequest(final WebView view, final String realm, final String account, final String args); @RequiresApi(api = Build.VERSION_CODES.O) void onRenderProcessGone(final WebView view, final RenderProcessGoneDetail detail, boolean retVal); @RequiresApi(api = Build.VERSION_CODES.O_MR1) void onSafeBrowsingHit(final WebView view, final WebResourceRequest request, final int threatType, final SafeBrowsingResponse callback); @Override boolean isLoggingEnabled(); @Override void setLoggingEnabled(final boolean enabled); @Override boolean isLogKeyEventsEnabled(); @Override void setLogKeyEventsEnabled(final boolean enabled); }### Answer: @Test public void onRenderProcessGone() { final RenderProcessGoneDetail detail = Mockito.mock(RenderProcessGoneDetail.class); logger.setLoggingEnabled(false); logger.onRenderProcessGone(webView, detail, false); verifyLogNotCalled(); logger.setLoggingEnabled(true); logger.onRenderProcessGone(webView, detail, false); verifyLogEngine().log(Mockito.anyString()); }
### Question: DebugWebViewClient extends WebViewClient implements LogControl { @RequiresApi(api = Build.VERSION_CODES.N) @Override public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) { final boolean retVal = client.shouldOverrideUrlLoading(view, request); logger.shouldOverrideUrlLoading(view, request, retVal); return retVal; } DebugWebViewClient(); DebugWebViewClient(@NonNull final WebViewClient client); @SuppressWarnings("WeakerAccess") DebugWebViewClient( @NonNull final WebViewClient client, @NonNull final DebugWebViewClientLogger logger); @RequiresApi(api = Build.VERSION_CODES.M) @Override void onReceivedError(final WebView view, final WebResourceRequest request, final WebResourceError error); @Override @Deprecated void onReceivedError(final WebView view, final int errorCode, final String description, final String failingUrl); @RequiresApi(api = Build.VERSION_CODES.M) @Override void onReceivedHttpError(final WebView view, final WebResourceRequest request, final WebResourceResponse errorResponse); @Override void onReceivedSslError(final WebView view, final SslErrorHandler handler, final SslError error); @RequiresApi(api = Build.VERSION_CODES.N) @Override boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request); @Override boolean shouldOverrideUrlLoading(WebView view, String url); @Override void onLoadResource(WebView view, String url); @TargetApi(Build.VERSION_CODES.M) @Override void onPageCommitVisible(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Deprecated WebResourceResponse shouldInterceptRequest(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request); @Override @Deprecated @SuppressWarnings("deprecation") //for use with older versions void onTooManyRedirects(WebView view, Message cancelMsg, Message continueMsg); @Override void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm); @Override void onPageStarted(WebView view, String url, Bitmap facIcon); @Override void onPageFinished(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override void onReceivedClientCertRequest(WebView view, ClientCertRequest request); @Override void onFormResubmission(final WebView view, final Message dontResend, final Message resend); @Override void doUpdateVisitedHistory(final WebView view, final String url, final boolean isReload); @Override boolean shouldOverrideKeyEvent(final WebView view, final KeyEvent event); @SuppressWarnings("unused") void onUnhandledInputEvent(final WebView view, final InputEvent event); @Override void onUnhandledKeyEvent(final WebView view, final KeyEvent event); @Override void onScaleChanged(final WebView view, final float oldScale, final float newScale); @Override void onReceivedLoginRequest(final WebView view, final String realm, final String account, final String args); @RequiresApi(api = Build.VERSION_CODES.O) @Override boolean onRenderProcessGone(final WebView view, final RenderProcessGoneDetail detail); @RequiresApi(api = Build.VERSION_CODES.O_MR1) @Override void onSafeBrowsingHit(final WebView view, final WebResourceRequest request, final int threatType, final SafeBrowsingResponse callback); @Override boolean isLoggingEnabled(); @Override void setLoggingEnabled(final boolean enabled); @Override boolean isLogKeyEventsEnabled(); @Override void setLogKeyEventsEnabled(final boolean enabled); }### Answer: @Test public void shouldOverrideUrlLoading() { final String url = "foo"; final boolean retVal = debugClient.shouldOverrideUrlLoading(webView, url); verifyLogger().shouldOverrideUrlLoading(webView, url, retVal); verifyWrappedClient().shouldOverrideUrlLoading(webView, url); } @Test public void shouldOverrideUrlLoading1() { final WebResourceRequest request = Mockito.mock(WebResourceRequest.class); final boolean retVal = debugClient.shouldOverrideUrlLoading(webView, request); verifyLogger().shouldOverrideUrlLoading(webView, request, retVal); verifyWrappedClient().shouldOverrideUrlLoading(webView, request); }
### Question: DebugWebViewClient extends WebViewClient implements LogControl { @Override public void onLoadResource(WebView view, String url) { logger.onLoadResource(view, url); client.onLoadResource(view, url); } DebugWebViewClient(); DebugWebViewClient(@NonNull final WebViewClient client); @SuppressWarnings("WeakerAccess") DebugWebViewClient( @NonNull final WebViewClient client, @NonNull final DebugWebViewClientLogger logger); @RequiresApi(api = Build.VERSION_CODES.M) @Override void onReceivedError(final WebView view, final WebResourceRequest request, final WebResourceError error); @Override @Deprecated void onReceivedError(final WebView view, final int errorCode, final String description, final String failingUrl); @RequiresApi(api = Build.VERSION_CODES.M) @Override void onReceivedHttpError(final WebView view, final WebResourceRequest request, final WebResourceResponse errorResponse); @Override void onReceivedSslError(final WebView view, final SslErrorHandler handler, final SslError error); @RequiresApi(api = Build.VERSION_CODES.N) @Override boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request); @Override boolean shouldOverrideUrlLoading(WebView view, String url); @Override void onLoadResource(WebView view, String url); @TargetApi(Build.VERSION_CODES.M) @Override void onPageCommitVisible(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Deprecated WebResourceResponse shouldInterceptRequest(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request); @Override @Deprecated @SuppressWarnings("deprecation") //for use with older versions void onTooManyRedirects(WebView view, Message cancelMsg, Message continueMsg); @Override void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm); @Override void onPageStarted(WebView view, String url, Bitmap facIcon); @Override void onPageFinished(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override void onReceivedClientCertRequest(WebView view, ClientCertRequest request); @Override void onFormResubmission(final WebView view, final Message dontResend, final Message resend); @Override void doUpdateVisitedHistory(final WebView view, final String url, final boolean isReload); @Override boolean shouldOverrideKeyEvent(final WebView view, final KeyEvent event); @SuppressWarnings("unused") void onUnhandledInputEvent(final WebView view, final InputEvent event); @Override void onUnhandledKeyEvent(final WebView view, final KeyEvent event); @Override void onScaleChanged(final WebView view, final float oldScale, final float newScale); @Override void onReceivedLoginRequest(final WebView view, final String realm, final String account, final String args); @RequiresApi(api = Build.VERSION_CODES.O) @Override boolean onRenderProcessGone(final WebView view, final RenderProcessGoneDetail detail); @RequiresApi(api = Build.VERSION_CODES.O_MR1) @Override void onSafeBrowsingHit(final WebView view, final WebResourceRequest request, final int threatType, final SafeBrowsingResponse callback); @Override boolean isLoggingEnabled(); @Override void setLoggingEnabled(final boolean enabled); @Override boolean isLogKeyEventsEnabled(); @Override void setLogKeyEventsEnabled(final boolean enabled); }### Answer: @Test public void onLoadResource() { final String url = "foo"; debugClient.onLoadResource(webView, url); verifyLogger().onLoadResource(webView, url); verifyWrappedClient().onLoadResource(webView, url); }
### Question: DebugWebViewClient extends WebViewClient implements LogControl { @TargetApi(Build.VERSION_CODES.M) @Override public void onPageCommitVisible(WebView view, String url) { logger.onPageCommitVisible(view, url); client.onPageCommitVisible(view, url); } DebugWebViewClient(); DebugWebViewClient(@NonNull final WebViewClient client); @SuppressWarnings("WeakerAccess") DebugWebViewClient( @NonNull final WebViewClient client, @NonNull final DebugWebViewClientLogger logger); @RequiresApi(api = Build.VERSION_CODES.M) @Override void onReceivedError(final WebView view, final WebResourceRequest request, final WebResourceError error); @Override @Deprecated void onReceivedError(final WebView view, final int errorCode, final String description, final String failingUrl); @RequiresApi(api = Build.VERSION_CODES.M) @Override void onReceivedHttpError(final WebView view, final WebResourceRequest request, final WebResourceResponse errorResponse); @Override void onReceivedSslError(final WebView view, final SslErrorHandler handler, final SslError error); @RequiresApi(api = Build.VERSION_CODES.N) @Override boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request); @Override boolean shouldOverrideUrlLoading(WebView view, String url); @Override void onLoadResource(WebView view, String url); @TargetApi(Build.VERSION_CODES.M) @Override void onPageCommitVisible(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Deprecated WebResourceResponse shouldInterceptRequest(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request); @Override @Deprecated @SuppressWarnings("deprecation") //for use with older versions void onTooManyRedirects(WebView view, Message cancelMsg, Message continueMsg); @Override void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm); @Override void onPageStarted(WebView view, String url, Bitmap facIcon); @Override void onPageFinished(WebView view, String url); @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override void onReceivedClientCertRequest(WebView view, ClientCertRequest request); @Override void onFormResubmission(final WebView view, final Message dontResend, final Message resend); @Override void doUpdateVisitedHistory(final WebView view, final String url, final boolean isReload); @Override boolean shouldOverrideKeyEvent(final WebView view, final KeyEvent event); @SuppressWarnings("unused") void onUnhandledInputEvent(final WebView view, final InputEvent event); @Override void onUnhandledKeyEvent(final WebView view, final KeyEvent event); @Override void onScaleChanged(final WebView view, final float oldScale, final float newScale); @Override void onReceivedLoginRequest(final WebView view, final String realm, final String account, final String args); @RequiresApi(api = Build.VERSION_CODES.O) @Override boolean onRenderProcessGone(final WebView view, final RenderProcessGoneDetail detail); @RequiresApi(api = Build.VERSION_CODES.O_MR1) @Override void onSafeBrowsingHit(final WebView view, final WebResourceRequest request, final int threatType, final SafeBrowsingResponse callback); @Override boolean isLoggingEnabled(); @Override void setLoggingEnabled(final boolean enabled); @Override boolean isLogKeyEventsEnabled(); @Override void setLogKeyEventsEnabled(final boolean enabled); }### Answer: @Test public void onPageCommitVisible() { final String url = "foo"; debugClient.onPageCommitVisible(webView, url); verifyLogger().onPageCommitVisible(webView, url); verifyWrappedClient().onPageCommitVisible(webView, url); }
### Question: AbstractCloudConnector implements CloudConnector { @Override public List<ServiceInfo> getServiceInfos() { List<ServiceInfo> serviceInfos = new ArrayList<ServiceInfo>(); for (SD serviceData : getServicesData()) { serviceInfos.add(getServiceInfo(serviceData)); } return serviceInfos; } AbstractCloudConnector(Class<? extends ServiceInfoCreator<? extends ServiceInfo, ?>> serviceInfoCreatorClass); @Override List<ServiceInfo> getServiceInfos(); }### Answer: @Test public void fallbacksCorrectly() { TestServiceData acceptableServiceData = new TestServiceData("my-service1", "test-tag"); TestServiceData unAcceptableServiceData = new TestServiceData("my-service2", "unknown-tag"); CloudConnector testCloudConnector = new TestCloudConnector(acceptableServiceData, unAcceptableServiceData); List<ServiceInfo> serviceInfos = testCloudConnector.getServiceInfos(); assertNotNull(serviceInfos); assertEquals(2, serviceInfos.size()); assertThat(serviceInfos.get(0), is(instanceOf(TestServiceInfo.class))); assertThat(serviceInfos.get(0), is(instanceOf(BaseServiceInfo.class))); }
### Question: RelationalServiceInfo extends UriBasedServiceInfo { @ServiceProperty(category = "connection") public String getJdbcUrl() { return jdbcUrl == null ? buildJdbcUrl() : jdbcUrl; } RelationalServiceInfo(String id, String uriString, String jdbcUrlDatabaseType); RelationalServiceInfo(String id, String uriString, String jdbcUrl, String jdbcUrlDatabaseType); @ServiceProperty(category = "connection") String getJdbcUrl(); static final String JDBC_PREFIX; }### Answer: @Test public void jdbcUrlWithQueryNoUsernamePassword() { RelationalServiceInfo serviceInfo = createServiceInfo("dbtype: assertEquals("jdbc:jdbcdbtype: } @Test public void jdbcUrl() { RelationalServiceInfo serviceInfo = createServiceInfoWithJdbcUrl("bad: "jdbc:jdbcdbtype: assertEquals("jdbc:jdbcdbtype: } @Test public void jdbcFullUrl() { RelationalServiceInfo serviceInfo = createServiceInfo("dbtype: assertEquals("jdbc:jdbcdbtype: } @Test public void jdbcUrlNoPort() { RelationalServiceInfo serviceInfo = createServiceInfo("dbtype: assertEquals("jdbc:jdbcdbtype: } @Test public void jdbcUrlNoUsernamePassword() { RelationalServiceInfo serviceInfo = createServiceInfo("dbtype: assertEquals("jdbc:jdbcdbtype: } @Test public void jdbcUrlNoPassword() { RelationalServiceInfo serviceInfo = createServiceInfo("dbtype: assertEquals("jdbc:jdbcdbtype: } @Test public void jdbcUrlWithQuery() { RelationalServiceInfo serviceInfo = createServiceInfo("dbtype: assertEquals("jdbc:jdbcdbtype: }
### Question: Cloud { public <SC> SC getServiceConnector(String serviceId, Class<SC> serviceConnectorType, ServiceConnectorConfig serviceConnectorConfig) { ServiceInfo serviceInfo = getServiceInfo(serviceId); return getServiceConnector(serviceInfo, serviceConnectorType, serviceConnectorConfig); } Cloud(CloudConnector cloudConnector, List<ServiceConnectorCreator<?, ? extends ServiceInfo>> serviceConnectorCreators); ApplicationInstanceInfo getApplicationInstanceInfo(); ServiceInfo getServiceInfo(String serviceId); List<ServiceInfo> getServiceInfos(); List<ServiceInfo> getServiceInfos(Class<T> serviceConnectorType); @SuppressWarnings("unchecked") List<T> getServiceInfosByType(Class<T> serviceInfoType); T getSingletonServiceInfoByType(Class<T> serviceInfoType); SC getServiceConnector(String serviceId, Class<SC> serviceConnectorType, ServiceConnectorConfig serviceConnectorConfig); SC getSingletonServiceConnector(Class<SC> serviceConnectorType, ServiceConnectorConfig serviceConnectorConfig); void registerServiceConnectorCreator(ServiceConnectorCreator<?, ? extends ServiceInfo> serviceConnectorCreator); Properties getCloudProperties(); }### Answer: @Test public void serviceConnectorCreationDefaultTypeAndConfig() { StubServiceInfo testServiceInfo = new StubServiceInfo("test-id", "test-host", 1000, "test-username", "test-password"); StubCloudConnector stubCloudConnector = CloudTestUtil.getTestCloudConnector(testServiceInfo); serviceConnectorCreators.add(new StubServiceConnectorCreator()); Cloud testCloud = new Cloud(stubCloudConnector, serviceConnectorCreators); StubServiceConnector connector = testCloud.getServiceConnector(testServiceInfo.getId(), null, null); assertStubService(testServiceInfo, connector, null); } @Test public void serviceConnectorCreationSpecifiedTypeAndConfig() { StubServiceInfo testServiceInfo = new StubServiceInfo("test-id", "test-host", 1000, "test-username", "test-password"); StubCloudConnector stubCloudConnector = CloudTestUtil.getTestCloudConnector(testServiceInfo); serviceConnectorCreators.add(new StubServiceConnectorCreator()); Cloud testCloud = new Cloud(stubCloudConnector, serviceConnectorCreators); StubServiceConnectorConfig config = new StubServiceConnectorConfig("test-config"); StubServiceConnector connector = testCloud.getServiceConnector(testServiceInfo.getId(), StubServiceConnector.class, config); assertStubService(testServiceInfo, connector, config); }
### Question: Cloud { public <SC> SC getSingletonServiceConnector(Class<SC> serviceConnectorType, ServiceConnectorConfig serviceConnectorConfig) { List<ServiceInfo> matchingServiceInfos = getServiceInfos(serviceConnectorType); if (matchingServiceInfos.size() != 1) { throw new CloudException("No unique service matching " + serviceConnectorType + " found. Expected 1, found " + matchingServiceInfos.size()); } ServiceInfo matchingServiceInfo = matchingServiceInfos.get(0); return getServiceConnector(matchingServiceInfo, serviceConnectorType, serviceConnectorConfig); } Cloud(CloudConnector cloudConnector, List<ServiceConnectorCreator<?, ? extends ServiceInfo>> serviceConnectorCreators); ApplicationInstanceInfo getApplicationInstanceInfo(); ServiceInfo getServiceInfo(String serviceId); List<ServiceInfo> getServiceInfos(); List<ServiceInfo> getServiceInfos(Class<T> serviceConnectorType); @SuppressWarnings("unchecked") List<T> getServiceInfosByType(Class<T> serviceInfoType); T getSingletonServiceInfoByType(Class<T> serviceInfoType); SC getServiceConnector(String serviceId, Class<SC> serviceConnectorType, ServiceConnectorConfig serviceConnectorConfig); SC getSingletonServiceConnector(Class<SC> serviceConnectorType, ServiceConnectorConfig serviceConnectorConfig); void registerServiceConnectorCreator(ServiceConnectorCreator<?, ? extends ServiceInfo> serviceConnectorCreator); Properties getCloudProperties(); }### Answer: @Test public void getSingletonServiceConnectorSingleService() { StubServiceInfo testServiceInfo = new StubServiceInfo("test-id", "test-host", 1000, "test-username", "test-password"); StubCloudConnector stubCloudConnector = CloudTestUtil.getTestCloudConnector(testServiceInfo); serviceConnectorCreators.add(new StubServiceConnectorCreator()); Cloud testCloud = new Cloud(stubCloudConnector, serviceConnectorCreators); StubServiceConnector connector = testCloud.getSingletonServiceConnector(null, null); assertStubService(testServiceInfo, connector, null); } @Test(expected=CloudException.class) public void getSingletonServiceConnectorNoService() { StubCloudConnector stubCloudConnector = CloudTestUtil.getTestCloudConnector(); Cloud testCloud = new Cloud(stubCloudConnector, serviceConnectorCreators); testCloud.getSingletonServiceConnector(null, null); } @Test(expected=CloudException.class) public void getSingletonServiceConnectorMultipleServices() { StubServiceInfo testServiceInfo1 = new StubServiceInfo("test-id", "test-host", 1000, "test-username", "test-password"); StubServiceInfo testServiceInfo2 = new StubServiceInfo("test-id", "test-host", 1000, "test-username", "test-password"); StubCloudConnector stubCloudConnector = CloudTestUtil.getTestCloudConnector(testServiceInfo1, testServiceInfo2); serviceConnectorCreators.add(new StubServiceConnectorCreator()); Cloud testCloud = new Cloud(stubCloudConnector, serviceConnectorCreators); testCloud.getSingletonServiceConnector(null, null); } @Test(expected=CloudException.class) public void getSingletonServiceConnectorNoMatchingServiceConnectorCreator() { BaseServiceInfo testServiceInfo = new BaseServiceInfo("user-service"); StubCloudConnector stubCloudConnector = CloudTestUtil.getTestCloudConnector(testServiceInfo); serviceConnectorCreators.add(new StubServiceConnectorCreator()); Cloud testCloud = new Cloud(stubCloudConnector, serviceConnectorCreators); testCloud.getSingletonServiceConnector(StubServiceConnector.class, null); }
### Question: Cloud { public List<ServiceInfo> getServiceInfos() { return flatten(cloudConnector.getServiceInfos()); } Cloud(CloudConnector cloudConnector, List<ServiceConnectorCreator<?, ? extends ServiceInfo>> serviceConnectorCreators); ApplicationInstanceInfo getApplicationInstanceInfo(); ServiceInfo getServiceInfo(String serviceId); List<ServiceInfo> getServiceInfos(); List<ServiceInfo> getServiceInfos(Class<T> serviceConnectorType); @SuppressWarnings("unchecked") List<T> getServiceInfosByType(Class<T> serviceInfoType); T getSingletonServiceInfoByType(Class<T> serviceInfoType); SC getServiceConnector(String serviceId, Class<SC> serviceConnectorType, ServiceConnectorConfig serviceConnectorConfig); SC getSingletonServiceConnector(Class<SC> serviceConnectorType, ServiceConnectorConfig serviceConnectorConfig); void registerServiceConnectorCreator(ServiceConnectorCreator<?, ? extends ServiceInfo> serviceConnectorCreator); Properties getCloudProperties(); }### Answer: @Test public void serviceInfoNoServices() { StubCloudConnector stubCloudConnector = CloudTestUtil.getTestCloudConnector(); Cloud testCloud = new Cloud(stubCloudConnector, serviceConnectorCreators); assertEquals(0, testCloud.getServiceInfos().size()); assertEquals(0, testCloud.getServiceInfos(StubServiceInfo.class).size()); } @Test public void serviceInfoMultipleServicesOfTheSameType() { StubServiceInfo testServiceInfo1 = new StubServiceInfo("test-id1", "test-host", 1000, "test-username", "test-password"); StubServiceInfo testServiceInfo2 = new StubServiceInfo("test-id2", "test-host", 1000, "test-username", "test-password"); StubCloudConnector stubCloudConnector = CloudTestUtil.getTestCloudConnector(testServiceInfo1, testServiceInfo2); serviceConnectorCreators.add(new StubServiceConnectorCreator()); Cloud testCloud = new Cloud(stubCloudConnector, serviceConnectorCreators); assertEquals(2, testCloud.getServiceInfos().size()); assertEquals(2, testCloud.getServiceInfos(StubServiceConnector.class).size()); }
### Question: CloudFactory { List<CloudConnector> getCloudConnectors() { return cloudConnectors; } CloudFactory(); Cloud getCloud(); void registerCloudConnector(CloudConnector cloudConnector); }### Answer: @Test public void cloudConnectorRegistration() { CloudFactory cloudFactory = new CloudFactory(); List<CloudConnector> registeredConnectors = cloudFactory.getCloudConnectors(); assertEquals("One connector registered", 1, registeredConnectors.size()); assertEquals("Registered connector is stub connector", StubCloudConnector.class, registeredConnectors.get(0).getClass()); }
### Question: Cloud { @SuppressWarnings("unchecked") public <T extends ServiceInfo> List<T> getServiceInfosByType(Class<T> serviceInfoType) { List<ServiceInfo> allServiceInfos = getServiceInfos(); List<T> matchingServiceInfos = new ArrayList<>(); for (ServiceInfo serviceInfo : allServiceInfos) { if (serviceInfoType.isAssignableFrom(serviceInfo.getClass())) { matchingServiceInfos.add((T) serviceInfo); } } return matchingServiceInfos; } Cloud(CloudConnector cloudConnector, List<ServiceConnectorCreator<?, ? extends ServiceInfo>> serviceConnectorCreators); ApplicationInstanceInfo getApplicationInstanceInfo(); ServiceInfo getServiceInfo(String serviceId); List<ServiceInfo> getServiceInfos(); List<ServiceInfo> getServiceInfos(Class<T> serviceConnectorType); @SuppressWarnings("unchecked") List<T> getServiceInfosByType(Class<T> serviceInfoType); T getSingletonServiceInfoByType(Class<T> serviceInfoType); SC getServiceConnector(String serviceId, Class<SC> serviceConnectorType, ServiceConnectorConfig serviceConnectorConfig); SC getSingletonServiceConnector(Class<SC> serviceConnectorType, ServiceConnectorConfig serviceConnectorConfig); void registerServiceConnectorCreator(ServiceConnectorCreator<?, ? extends ServiceInfo> serviceConnectorCreator); Properties getCloudProperties(); }### Answer: @Test public void getServiceInfosByType() { StubServiceInfo testServiceInfo = new StubServiceInfo("test-id", "test-host", 1000, "test-username", "test-password"); TestServiceInfoTypeA testServiceInfoTypeA1 = new TestServiceInfoTypeA("test-id-a1"); TestServiceInfoTypeA testServiceInfoTypeA2 = new TestServiceInfoTypeA("test-id-a2"); TestServiceInfoTypeB testServiceInfoTypeB = new TestServiceInfoTypeB("test-id-b"); StubCloudConnector stubCloudConnector = CloudTestUtil.getTestCloudConnector(testServiceInfo, testServiceInfoTypeA1, testServiceInfoTypeA2, testServiceInfoTypeB); Cloud testCloud = new Cloud(stubCloudConnector, serviceConnectorCreators); List<TestServiceInfoTypeA> actualServiceInfoTypeA = testCloud.getServiceInfosByType(TestServiceInfoTypeA.class); assertEquals(2, actualServiceInfoTypeA.size()); assertEquals(1, testCloud.getServiceInfosByType(TestServiceInfoTypeB.class).size()); }
### Question: Cloud { public <T extends ServiceInfo> T getSingletonServiceInfoByType(Class<T> serviceInfoType) { List<T> serviceInfos = getServiceInfosByType(serviceInfoType); if (serviceInfos.size() != 1) { throw new CloudException( "No unique service info " + serviceInfoType + " found. Expected 1, found " + serviceInfos.size()); } return serviceInfos.get(0); } Cloud(CloudConnector cloudConnector, List<ServiceConnectorCreator<?, ? extends ServiceInfo>> serviceConnectorCreators); ApplicationInstanceInfo getApplicationInstanceInfo(); ServiceInfo getServiceInfo(String serviceId); List<ServiceInfo> getServiceInfos(); List<ServiceInfo> getServiceInfos(Class<T> serviceConnectorType); @SuppressWarnings("unchecked") List<T> getServiceInfosByType(Class<T> serviceInfoType); T getSingletonServiceInfoByType(Class<T> serviceInfoType); SC getServiceConnector(String serviceId, Class<SC> serviceConnectorType, ServiceConnectorConfig serviceConnectorConfig); SC getSingletonServiceConnector(Class<SC> serviceConnectorType, ServiceConnectorConfig serviceConnectorConfig); void registerServiceConnectorCreator(ServiceConnectorCreator<?, ? extends ServiceInfo> serviceConnectorCreator); Properties getCloudProperties(); }### Answer: @Test(expected=CloudException.class) public void getSingletonServiceInfoByTypeNoService() { StubCloudConnector stubCloudConnector = CloudTestUtil.getTestCloudConnector(); Cloud testCloud = new Cloud(stubCloudConnector, serviceConnectorCreators); testCloud.getSingletonServiceInfoByType(StubServiceInfo.class); } @Test(expected=CloudException.class) public void getSingletonServiceInfoByTypeMultipleServices() { StubServiceInfo testServiceInfo1 = new StubServiceInfo("test-id", "test-host", 1000, "test-username", "test-password"); StubServiceInfo testServiceInfo2 = new StubServiceInfo("test-id", "test-host", 1000, "test-username", "test-password"); StubCloudConnector stubCloudConnector = CloudTestUtil.getTestCloudConnector(testServiceInfo1, testServiceInfo2); Cloud testCloud = new Cloud(stubCloudConnector, serviceConnectorCreators); testCloud.getSingletonServiceInfoByType(StubServiceInfo.class); } @Test public void getSingletonServiceInfoByTypeSingleService() { StubServiceInfo testServiceInfo = new StubServiceInfo("test-id", "test-host", 1000, "test-username", "test-password"); StubCloudConnector stubCloudConnector = CloudTestUtil.getTestCloudConnector(testServiceInfo); Cloud testCloud = new Cloud(stubCloudConnector, serviceConnectorCreators); assertNotNull(testCloud.getSingletonServiceInfoByType(StubServiceInfo.class)); }
### Question: CloudFactory { List<ServiceConnectorCreator<?, ? extends ServiceInfo>> getServiceCreators() { return serviceCreators; } CloudFactory(); Cloud getCloud(); void registerCloudConnector(CloudConnector cloudConnector); }### Answer: @Test public void cloudServiceConnectorCreatorRegistration() { CloudFactory cloudFactory = new CloudFactory(); List<ServiceConnectorCreator<?, ? extends ServiceInfo>> registeredServiceConnectorCreators = cloudFactory.getServiceCreators(); assertEquals("One serviceCreators registered", 2, registeredServiceConnectorCreators.size()); assertEquals("First registered connector is a stub", StubServiceConnectorCreator.class, registeredServiceConnectorCreators.get(0).getClass()); assertEquals("Second egistered connector is a non-parameterized stub", NonParameterizedStubServiceConnectorCreator.class, registeredServiceConnectorCreators.get(1).getClass()); }
### Question: LocalConfigUtil { static Map<String, String> readServices(Properties properties) { Map<String, String> services = new HashMap<String, String>(); for (String propertyName : properties.stringPropertyNames()) { if (LocalConfigConnector.META_PROPERTIES.contains(propertyName)) { logger.finer("skipping meta property " + propertyName); continue; } Matcher m = LocalConfigConnector.SERVICE_PROPERTY_PATTERN.matcher(propertyName); if (!m.matches()) { logger.finest("skipping non-Spring-Cloud property " + propertyName); continue; } String serviceId = m.group(1); String serviceUri = properties.getProperty(propertyName); logger.fine("found service URI for service " + serviceId); services.put(serviceId, serviceUri); } return services; } private LocalConfigUtil(); }### Answer: @Test public void testPropertyParsing() { first.setProperty("spring.cloud.appId", "should skip me because I'm meta"); first.setProperty("spring.cloud.service1", "one"); first.setProperty("spring.cloud.", "should skip me because I don't have an ID"); first.setProperty("spring.cloud.service.two", "two"); first.setProperty("foobar", "should skip me because I don't match the prefix"); Map<String, String> services = LocalConfigUtil.readServices(first); assertEquals(2, services.size()); assertEquals("one", services.get("service1")); assertEquals("two", services.get("service.two")); }
### Question: LocalConfigUtil { static List<UriBasedServiceData> readServicesData(LinkedHashMap<String, Properties> propertySources) { Map<String, String> collectedServices = new HashMap<String, String>(); for (Map.Entry<String, Properties> propertySource : propertySources.entrySet()) { if (propertySource.getValue().isEmpty()) { logger.info("no " + propertySource.getKey()); continue; } logger.info("reading services from " + propertySource.getKey()); Map<String, String> services = readServices(propertySource.getValue()); for (Map.Entry<String, String> service : services.entrySet()) { String oldUri = collectedServices.put(service.getKey(), service.getValue()); if (oldUri == null) logger.info("added service '" + service.getKey() + "' from " + propertySource.getKey()); else logger.warning("replaced service '" + service.getKey() + "' with new URI from " + propertySource.getKey()); } } List<UriBasedServiceData> serviceData = new ArrayList<UriBasedServiceData>(collectedServices.size()); for (Map.Entry<String, String> serviceInfo : collectedServices.entrySet()) { serviceData.add(new UriBasedServiceData(serviceInfo.getKey(), serviceInfo.getValue())); } return serviceData; } private LocalConfigUtil(); }### Answer: @Test public void testCollation() { first.setProperty("spring.cloud.first", "firstUri"); second.setProperty("spring.cloud.second", "secondUri"); List<UriBasedServiceData> serviceData = LocalConfigUtil.readServicesData(propertySources); assertEquals(2, serviceData.size()); boolean foundFirst = false; for (UriBasedServiceData kvp : serviceData) { if (kvp.getKey().equals("first")) { assertEquals("firstUri", kvp.getUri()); foundFirst = true; } } assertTrue(foundFirst); } @Test public void testOverride() { first.setProperty("spring.cloud.duplicate", "firstUri"); second.setProperty("spring.cloud.duplicate", "secondUri"); List<UriBasedServiceData> serviceData = LocalConfigUtil.readServicesData(propertySources); assertEquals(1, serviceData.size()); UriBasedServiceData kvp = serviceData.get(0); assertEquals("duplicate", kvp.getKey()); assertEquals("secondUri", kvp.getUri()); }
### Question: LocalConfigConnector extends AbstractCloudConnector<UriBasedServiceData> { @Override public boolean isInMatchingCloud() { if (fileProperties == null) readFileProperties(); String appId = findProperty(APP_ID_PROPERTY); if (appId == null) logger.info("the property " + APP_ID_PROPERTY + " was not found in the system properties or configuration file"); return appId != null; } @SuppressWarnings({"unchecked", "rawtypes"}) LocalConfigConnector(); @Override boolean isInMatchingCloud(); @Override ApplicationInstanceInfo getApplicationInstanceInfo(); static final String PROPERTY_PREFIX; static final Pattern SERVICE_PROPERTY_PATTERN; static final String APP_ID_PROPERTY; static final String PROPERTIES_FILE_PROPERTY; static final List<String> META_PROPERTIES; }### Answer: @Test public void testNoAppIdAnywhere() { assertFalse(connector.isInMatchingCloud()); }
### Question: PropertiesFileResolver { File findCloudPropertiesFileFromSystem() { String filename = null; try { filename = env.getSystemProperty(LocalConfigConnector.PROPERTIES_FILE_PROPERTY); } catch (SecurityException e) { logger.log(Level.WARNING, "SecurityManager prevented reading system property " + LocalConfigConnector.PROPERTIES_FILE_PROPERTY, e); return null; } if (filename == null) { logger.fine("didn't find system property for a configuration file"); return null; } File file = new File(filename); logger.info("found system property for a configuration file: " + file); return file; } PropertiesFileResolver(final EnvironmentAccessor env, final String classpathPropertiesFilename); PropertiesFileResolver(final EnvironmentAccessor env); PropertiesFileResolver(); static final String BOOTSTRAP_PROPERTIES_FILENAME; }### Answer: @Test public void testSecurityExceptionHandling() { env = mock(PassthroughEnvironmentAccessor.class); resolver = new PropertiesFileResolver(env); when(env.getSystemProperty(LocalConfigConnector.PROPERTIES_FILE_PROPERTY)).thenThrow(new SecurityException()); assertNull(resolver.findCloudPropertiesFileFromSystem()); verify(env).getSystemProperty(LocalConfigConnector.PROPERTIES_FILE_PROPERTY); } @Test public void testMissingSystemProperty() { assertNull(resolver.findCloudPropertiesFileFromSystem()); } @Test public void testSystemProperty() { env.setSystemProperty(LocalConfigConnector.PROPERTIES_FILE_PROPERTY, PROPERTIES_FILE_NAME); assertEquals(PROPERTIES_FILE_NAME, resolver.findCloudPropertiesFileFromSystem().getPath()); }
### Question: PropertiesFileResolver { File findCloudPropertiesFileFromClasspath() { InputStream in = getClass().getClassLoader().getResourceAsStream(classpathPropertiesFilename); if (in == null) { logger.info("no " + classpathPropertiesFilename + " found on the classpath to direct us to an external properties file"); return null; } Properties properties = new Properties(); try { properties.load(in); } catch (IOException e) { logger.log(Level.SEVERE, "found " + classpathPropertiesFilename + " on the classpath but couldn't load it as a properties file", e); return null; } String template = properties.getProperty(LocalConfigConnector.PROPERTIES_FILE_PROPERTY); if (template == null) { logger.log(Level.SEVERE, "found properties file " + classpathPropertiesFilename + " on the classpath, but it didn't contain a property named " + LocalConfigConnector.PROPERTIES_FILE_PROPERTY); return null; } if (properties.entrySet().size() > 1) logger.warning("the properties file " + classpathPropertiesFilename + " contained properties besides " + LocalConfigConnector.PROPERTIES_FILE_PROPERTY + "; ignoring"); logger.fine("substituting system properties into '" + template + "'"); File configFile = new File(new StrSubstitutor(systemPropertiesLookup(env)).replace(template)); logger.info("derived configuration file name: " + configFile); return configFile; } PropertiesFileResolver(final EnvironmentAccessor env, final String classpathPropertiesFilename); PropertiesFileResolver(final EnvironmentAccessor env); PropertiesFileResolver(); static final String BOOTSTRAP_PROPERTIES_FILENAME; }### Answer: @Test public void testNoClasspathFile() { resolver = new PropertiesFileResolver(env, "bazquux.properties"); assertNull(resolver.findCloudPropertiesFileFromClasspath()); } @Test public void testClasspathFileWithoutKey() { resolver = new PropertiesFileResolver(env, "localconfig.testuris.properties"); assertNull(resolver.findCloudPropertiesFileFromClasspath()); } @Test public void testLiteral() { resolver = new PropertiesFileResolver(env, "spring-cloud-literal.properties"); assertEquals(PROPERTIES_FILE_NAME, resolver.findCloudPropertiesFileFromClasspath().getPath()); } @Test public void testTemplate() { resolver = new PropertiesFileResolver(env, "spring-cloud-template.properties"); env.setSystemProperty("user.home", "/foo"); assertEquals(PROPERTIES_FILE_NAME, resolver.findCloudPropertiesFileFromClasspath().getPath()); }
### Question: CloudFactory { public Cloud getCloud() { CloudConnector suitableCloudConnector = null; for (CloudConnector cloudConnector : cloudConnectors) { if (cloudConnector.isInMatchingCloud()) { suitableCloudConnector = cloudConnector; break; } } if (suitableCloudConnector == null) { throw new CloudException("No suitable cloud connector found"); } return new Cloud(suitableCloudConnector, serviceCreators); } CloudFactory(); Cloud getCloud(); void registerCloudConnector(CloudConnector cloudConnector); }### Answer: @Test public void cloudRetriveal() { CloudFactory cloudFactory = new CloudFactory(); Cloud cloud = cloudFactory.getCloud(); assertNotNull(cloud); }
### Question: PropertiesFileResolver { File findCloudPropertiesFile() { File file = findCloudPropertiesFileFromSystem(); if (file != null) { logger.info("using configuration file from system properties"); return file; } file = findCloudPropertiesFileFromClasspath(); if (file != null) logger.info("using configuration file derived from " + classpathPropertiesFilename); else logger.info("did not find any Spring Cloud configuration file"); return file; } PropertiesFileResolver(final EnvironmentAccessor env, final String classpathPropertiesFilename); PropertiesFileResolver(final EnvironmentAccessor env); PropertiesFileResolver(); static final String BOOTSTRAP_PROPERTIES_FILENAME; }### Answer: @Test public void testFromSystem() { env.setSystemProperty(LocalConfigConnector.PROPERTIES_FILE_PROPERTY, PROPERTIES_FILE_NAME); assertEquals(PROPERTIES_FILE_NAME, resolver.findCloudPropertiesFile().getPath()); } @Test public void testFromClasspath() { resolver = new PropertiesFileResolver(env, "spring-cloud-template.properties"); env.setSystemProperty("user.home", "/foo"); assertEquals(PROPERTIES_FILE_NAME, resolver.findCloudPropertiesFile().getPath()); } @Test public void testNowhere() { assertNull(resolver.findCloudPropertiesFile()); } @Test public void testPrecedence() { env.setSystemProperty(LocalConfigConnector.PROPERTIES_FILE_PROPERTY, PROPERTIES_FILE_NAME); resolver = new PropertiesFileResolver(env, "spring-cloud-literal.properties"); assertEquals(PROPERTIES_FILE_NAME, resolver.findCloudPropertiesFile().getPath()); }
### Question: CassandraClusterCreator extends AbstractServiceConnectorCreator<Cluster, CassandraServiceInfo> { @Override public Cluster create(CassandraServiceInfo serviceInfo, ServiceConnectorConfig serviceConnectorConfig) { Builder builder = Cluster.builder() .addContactPoints(serviceInfo.getContactPoints().toArray(new String[0])) .withPort(serviceInfo.getPort()); if (StringUtils.hasText(serviceInfo.getUsername())) { builder.withCredentials(serviceInfo.getUsername(), serviceInfo.getPassword()); } if (serviceConnectorConfig instanceof CassandraClusterConfig) { CassandraClusterConfig config = (CassandraClusterConfig) serviceConnectorConfig; if (config.getCompression() != null) { builder.withCompression(config.getCompression()); } builder.withPoolingOptions(config.getPoolingOptions()); builder.withSocketOptions(config.getSocketOptions()); builder.withQueryOptions(config.getQueryOptions()); builder.withNettyOptions(config.getNettyOptions()); builder.withLoadBalancingPolicy(config.getLoadBalancingPolicy()); builder.withReconnectionPolicy(config.getReconnectionPolicy()); builder.withRetryPolicy(config.getRetryPolicy()); if (config.getProtocolVersion() != null) { builder.withProtocolVersion(config.getProtocolVersion()); } if (!config.isMetricsEnabled()) { builder.withoutMetrics(); } if (!config.isJmxReportingEnabled()) { builder.withoutJMXReporting(); } } return builder.build(); } @Override Cluster create(CassandraServiceInfo serviceInfo, ServiceConnectorConfig serviceConnectorConfig); }### Answer: @Test public void shouldCreateCluster() throws Exception { CassandraServiceInfo info = new CassandraServiceInfo("local", Collections.singletonList("127.0.0.1"), 9142); Cluster cluster = creator.create(info, null); Configuration configuration = cluster.getConfiguration(); assertThat(configuration.getProtocolOptions().getAuthProvider(), is(AuthProvider.NONE)); } @Test public void shouldCreateClusterWithAuthentication() throws Exception { CassandraServiceInfo info = new CassandraServiceInfo("local", Collections.singletonList("127.0.0.1"), 9142, "walter", "white"); Cluster cluster = creator.create(info, null); Configuration configuration = cluster.getConfiguration(); assertThat(configuration.getProtocolOptions().getAuthProvider(), is(instanceOf(PlainTextAuthProvider.class))); } @Test public void shouldCreateClusterWithConfig() throws Exception { CassandraServiceInfo info = new CassandraServiceInfo("local", Collections.singletonList("127.0.0.1"), 9142); CassandraClusterConfig config = new CassandraClusterConfig(); config.setCompression(ProtocolOptions.Compression.NONE); config.setPoolingOptions(new PoolingOptions().setPoolTimeoutMillis(1234)); config.setQueryOptions(new QueryOptions()); config.setProtocolVersion(ProtocolVersion.NEWEST_SUPPORTED); config.setLoadBalancingPolicy(new RoundRobinPolicy()); config.setReconnectionPolicy(new ConstantReconnectionPolicy(1)); config.setRetryPolicy(DowngradingConsistencyRetryPolicy.INSTANCE); config.setSocketOptions(new SocketOptions()); Cluster cluster = creator.create(info, config); Configuration configuration = cluster.getConfiguration(); assertThat(configuration.getProtocolOptions().getCompression(), is(config.getCompression())); assertThat(configuration.getQueryOptions(), is(config.getQueryOptions())); assertThat(configuration.getSocketOptions(), is(config.getSocketOptions())); Policies policies = configuration.getPolicies(); assertThat(policies.getLoadBalancingPolicy(), is(config.getLoadBalancingPolicy())); assertThat(policies.getReconnectionPolicy(), is(config.getReconnectionPolicy())); assertThat(policies.getRetryPolicy(), is(config.getRetryPolicy())); }
### Question: UrlDecodingDataSource extends DelegatingDataSource { @Override public Connection getConnection() throws SQLException { if (successfullyConnected) return super.getConnection(); synchronized (this) { Connection connection; try { connection = super.getConnection(); successfullyConnected = true; } catch (SQLException e) { logger.info("Database connection failed. Trying again with url-decoded jdbc url"); DataSource targetDataSource = getTargetDataSource(); if (targetDataSource == null) throw new IllegalStateException("target DataSource should never be null"); BeanWrapper dataSourceWrapper = new BeanWrapperImpl(targetDataSource); String decodedJdbcUrl = decode((String) dataSourceWrapper.getPropertyValue(urlPropertyName)); DataSource urlDecodedConnectionTestDataSource = connectionTestDataSourceFactory.apply(decodedJdbcUrl); urlDecodedConnectionTestDataSource.getConnection(); logger.info("Connection test successful. Continuing with url-decoded jdbc url"); dataSourceWrapper.setPropertyValue(urlPropertyName, decodedJdbcUrl); connection = super.getConnection(); successfullyConnected = true; } return connection; } } UrlDecodingDataSource(String jdbcUrl); UrlDecodingDataSource(DataSource targetDataSource, String urlPropertyName); UrlDecodingDataSource(DataSource targetDataSource, String urlPropertyName, Function<String, DataSource> connectionTestDataSourceFactory); @Override Connection getConnection(); }### Answer: @Test public void whenConnectionToEncodedUrlIsSuccessful() throws SQLException { MockDataSource delegateDataSource = pooledDataSourceRequiringEncodedUrl(); UrlDecodingDataSource urlDecodingDataSource = new UrlDecodingDataSource(delegateDataSource, "url"); Connection connection = urlDecodingDataSource.getConnection(); assertNotNull("Returned connection must not be null", connection); assertEquals(ENCODED_URL, delegateDataSource.url); assertEquals("Connection must be made using the pooled (delegate) data source", TRUE, connection.getClientInfo(IS_POOLED)); } @Test public void whenConnectionToDecodedUrlIsSuccessful() throws SQLException { MockDataSource delegateDataSource = pooledDataSourceRequiringDecodedUrl(); UrlDecodingDataSource urlDecodingDataSource = new UrlDecodingDataSource(delegateDataSource, URL_PROPERTY_NAME, UrlDecodingDataSourceTest::dataSourceRequiringDecodedUrl); Connection connection = urlDecodingDataSource.getConnection(); assertNotNull("Returned connection must not be null", connection); assertEquals(DECODED_URL, delegateDataSource.url); assertEquals("Connection must be made using the pooled (delegate) data source", TRUE, connection.getClientInfo(IS_POOLED)); } @Test(expected = SQLException.class) public void whenNoConnectionIsSuccessful() throws SQLException { MockDataSource delegateDataSource = pooledDataSourceUnableToConnectToAnyUrl(); UrlDecodingDataSource urlDecodingDataSource = new UrlDecodingDataSource(delegateDataSource, URL_PROPERTY_NAME, UrlDecodingDataSourceTest::dataSourceUnableToConnectToAnyUrl); try { urlDecodingDataSource.getConnection(); } catch (SQLException e) { assertEquals(ENCODED_URL, delegateDataSource.url); throw e; } } @Test public void successfulUrlDecodedConnectionTestIsOnlyPerformedOnce() throws SQLException { MockDataSource delegateDataSource = pooledDataSourceRequiringDecodedUrl(); DataSource decodedUrlConnectionTestDataSource = mock(DataSource.class); when(decodedUrlConnectionTestDataSource.getConnection()).thenReturn(mock(Connection.class)); UrlDecodingDataSource urlDecodingDataSource = new UrlDecodingDataSource(delegateDataSource, URL_PROPERTY_NAME, url -> decodedUrlConnectionTestDataSource); urlDecodingDataSource.getConnection(); urlDecodingDataSource.getConnection(); verify(decodedUrlConnectionTestDataSource, times(1)).getConnection(); } @Test public void unsuccessfulUrlDecodedConnectionTestIsTriedAgain() throws SQLException { MockDataSource delegateDataSource = pooledDataSourceRequiringDecodedUrl(); DataSource decodedUrlConnectionTestDataSource = mock(DataSource.class); when(decodedUrlConnectionTestDataSource.getConnection()).thenThrow(new SQLException("unable to connect")); UrlDecodingDataSource urlDecodingDataSource = new UrlDecodingDataSource(delegateDataSource, URL_PROPERTY_NAME, url -> decodedUrlConnectionTestDataSource); try { urlDecodingDataSource.getConnection(); } catch (SQLException e) {} try { urlDecodingDataSource.getConnection(); } catch (SQLException e) {} verify(decodedUrlConnectionTestDataSource, times(2)).getConnection(); }
### Question: CloudFoundryServiceInfoCreator implements ServiceInfoCreator<SI, Map<String, Object>> { @SuppressWarnings("unchecked") protected boolean tagsMatch(Map<String, Object> serviceData) { List<String> serviceTags = (List<String>) serviceData.get("tags"); return tags.containsOne(serviceTags); } CloudFoundryServiceInfoCreator(Tags tags, String... uriSchemes); boolean accept(Map<String, Object> serviceData); String[] getUriSchemes(); String getDefaultUriScheme(); }### Answer: @Test public void tagsMatch() { DummyServiceInfoCreator serviceInfoCreator = new DummyServiceInfoCreator(new Tags("firstTag", "secondTag")); assertAcceptedWithTags(serviceInfoCreator, "firstTag", "noMatchTag"); assertAcceptedWithTags(serviceInfoCreator, "noMatchTag", "secondTag"); assertAcceptedWithTags(serviceInfoCreator, "firstTag", "secondTag"); assertNotAcceptedWithTags(serviceInfoCreator, "noMatchTag"); assertNotAcceptedWithTags(serviceInfoCreator); }
### Question: CloudFoundryServiceInfoCreator implements ServiceInfoCreator<SI, Map<String, Object>> { protected boolean uriKeyMatchesScheme(Map<String, Object> serviceData) { if (uriSchemes == null) { return false; } Map<String, Object> credentials = getCredentials(serviceData); if (credentials != null) { for (String uriScheme : uriSchemes) { if (credentials.containsKey(uriScheme + "Uri") || credentials.containsKey(uriScheme + "uri") || credentials.containsKey(uriScheme + "Url") || credentials.containsKey(uriScheme + "url")) { return true; } } } return false; } CloudFoundryServiceInfoCreator(Tags tags, String... uriSchemes); boolean accept(Map<String, Object> serviceData); String[] getUriSchemes(); String getDefaultUriScheme(); }### Answer: @Test public void uriKeyMatchesScheme() { DummyServiceInfoCreator serviceInfoCreator = new DummyServiceInfoCreator(new Tags(), "amqp", "amqps"); assertAcceptedWithCredentials(serviceInfoCreator, "amqpUri", "https: assertAcceptedWithCredentials(serviceInfoCreator, "amqpsUri", "https: assertAcceptedWithCredentials(serviceInfoCreator, "amqpUrl", "https: assertAcceptedWithCredentials(serviceInfoCreator, "amqpsUrl", "https: assertAcceptedWithCredentials(serviceInfoCreator, "amqpuri", "https: assertAcceptedWithCredentials(serviceInfoCreator, "amqpsuri", "https: assertAcceptedWithCredentials(serviceInfoCreator, "amqpurl", "https: assertAcceptedWithCredentials(serviceInfoCreator, "amqpsurl", "https: }
### Question: Tags { public boolean containsOne(List<String> tags) { if (tags != null) { for (String value : values) { for (String tag : tags) { if (tag.equalsIgnoreCase(value)) { return true; } } } } return false; } Tags(String... values); String[] getTags(); boolean containsOne(List<String> tags); boolean contains(String tag); boolean startsWith(String tag); }### Answer: @Test public void containsOne() { Tags tags = new Tags("test1", "test2"); assertTrue(tags.containsOne(Arrays.asList("test1", "testx"))); assertTrue(tags.containsOne(Arrays.asList("testx", "test2"))); assertTrue(tags.containsOne(Arrays.asList("TESTX", "TEST2"))); assertFalse(tags.containsOne(Arrays.asList("testx", "testy"))); } @Test public void containsOneWithEmptyTags() { assertFalse(EMPTY_TAGS.containsOne(Arrays.asList("test"))); }
### Question: Tags { public boolean contains(String tag) { if (tag != null) { for (String value : values) { if (tag.equalsIgnoreCase(value)) { return true; } } } return false; } Tags(String... values); String[] getTags(); boolean containsOne(List<String> tags); boolean contains(String tag); boolean startsWith(String tag); }### Answer: @Test public void contains() { Tags tags = new Tags("test1", "test2"); assertTrue(tags.contains("test1")); assertTrue(tags.contains("test2")); assertTrue(tags.contains("TEST2")); assertFalse(tags.contains("testx")); } @Test public void containsWithEmptyTags() { assertFalse(EMPTY_TAGS.contains("test")); }
### Question: Tags { public boolean startsWith(String tag) { if (tag != null) { for (String value : values) { if (startsWithIgnoreCase(tag, value)) { return true; } } } return false; } Tags(String... values); String[] getTags(); boolean containsOne(List<String> tags); boolean contains(String tag); boolean startsWith(String tag); }### Answer: @Test public void startsWith() { Tags tags = new Tags("test"); assertTrue(tags.startsWith("test-123")); assertTrue(tags.startsWith("TEST-123")); assertFalse(tags.startsWith("abcd")); } @Test public void startsWithWithEmptyTags() { assertFalse(EMPTY_TAGS.startsWith("test")); }
### Question: QueryBuilderFactoryImpl implements QueryBuilderFactory { public <T> QueryBuilder<T> newQueryBuilder( final Class<T> resultType ) { NotQueryableException.throwIfNotQueryable( resultType ); final ServiceReference<EntityFinder> serviceReference; try { serviceReference = finder.findService( EntityFinder.class ); return new QueryBuilderImpl<T>( serviceReference.get(), resultType, null ); } catch( IllegalArgumentException e ) { return new QueryBuilderImpl<T>( null, resultType, null ); } } QueryBuilderFactoryImpl( ServiceFinder finder ); QueryBuilder<T> newQueryBuilder( final Class<T> resultType ); }### Answer: @Test public void givenPlainQueryWhenFindEntityExpectFirstEntityReturned() { Query<TestComposite> query = module.newQueryBuilder( TestComposite.class ).newQuery( composites ); assertEquals( "A", query.find().a().get() ); assertEquals( 6, query.count() ); } @Test public void givenPlainQueryWhenOrderByFirstPropertyExpectOrderedResult() { Query<TestComposite> query = module.newQueryBuilder( TestComposite.class ).newQuery( composites ); TestComposite template = templateFor( TestComposite.class ); query.orderBy( orderBy( template.a() ) ); verifyOrder( query, "612345" ); } @Test public void givenPlainQueryWhenOrderBySecondPropertyExpectOrderedResult() { Query<TestComposite> query = module.newQueryBuilder( TestComposite.class ).newQuery( composites ); TestComposite template = templateFor( TestComposite.class ); query.orderBy( orderBy( template.b() ) ); verifyOrder( query, "123456" ); } @Test public void givenPlainQueryWhenOrderByTwoPropertiesExpectOrderedResult() { Query<TestComposite> query = module.newQueryBuilder( TestComposite.class ).newQuery( composites ); TestComposite template = templateFor( TestComposite.class ); query.orderBy( orderBy( template.a() ), orderBy( template.b() ) ); verifyOrder( query, "162345" ); } @Test public void givenPlainQueryWhenMaxedResultExpectLimitedResult() { Query<TestComposite> query = module.newQueryBuilder( TestComposite.class ).newQuery( composites ); query.maxResults( 5 ); verifyOrder( query, "62345" ); } @Test public void givenPlainQueryWhenFirstResultIsBeyondFirstElementExpectLimitedResult() { Query<TestComposite> query = module.newQueryBuilder( TestComposite.class ).newQuery( composites ); query.firstResult( 2 ); verifyOrder( query, "3451" ); } @Test public void givenWhereQueryWhenWhereClauseLimitsToRangeExpectLimitedResult() { final QueryBuilder<TestComposite> qb = module.newQueryBuilder( TestComposite.class ); TestComposite template = templateFor( TestComposite.class ); Query<TestComposite> query = qb.where( and( ge( template.b(), 3 ), lt( template.b(), 5 ) ) ).newQuery( composites ); verifyOrder( query, "34" ); }
### Question: ValueBuilderTemplate { public T newInstance(Module module) { ValueBuilder<T> builder = module.newValueBuilder( type ); build( builder.prototype() ); return builder.newInstance(); } protected ValueBuilderTemplate( Class<T> type ); T newInstance(Module module); }### Answer: @Test public void testTemplate() { new TestBuilder( "Rickard" ).newInstance( module); } @Test public void testAnonymousTemplate() { new ValueBuilderTemplate<TestValue>(TestValue.class) { @Override protected void build( TestValue prototype ) { prototype.name().set( "Rickard" ); } }.newInstance( module ); }
### Question: Classes { public static Set<Class<?>> interfacesWithMethods( Set<Class<?>> interfaces ) { Set<Class<?>> newSet = new LinkedHashSet<Class<?>>(); for( Class type : interfaces ) { if( type.isInterface() && type.getDeclaredMethods().length > 0 ) { newSet.add( type ); } } return newSet; } static Specification<Class<?>> isAssignableFrom( final Class clazz); static Specification<Object> instanceOf( final Class clazz); static Specification<Class<?>> hasModifier( final int classModifier ); static Function<Type, Iterable<T>> forClassHierarchy( final Function<Class<?>, Iterable<T>> function ); static Function<Type, Iterable<T>> forTypes( final Function<Type, Iterable<T>> function ); static Set<Class<?>> interfacesWithMethods( Set<Class<?>> interfaces ); static String getSimpleGenericName( Type type ); static AnnotationType getAnnotationOfTypeOrAnyOfSuperTypes( Class<?> type, Class<AnnotationType> annotationClass ); static Specification<Member> memberNamed( final String name ); static Type resolveTypeVariable( TypeVariable name, Class declaringClass, Class topClass ); static String toURI( final Class clazz ); static String toURI( String className ); static String toClassName( String uri ); static String normalizeClassToURI( String className ); static String denormalizeURIToClass( String uriPart ); static final Function<Type, Type> WRAPPER_CLASS; static final Function<Type, Type> PRIMITIVE_CLASS; static final Function<Type, Class<?>> RAW_CLASS; static final Function<AccessibleObject, Type> TYPE_OF; static final Function<Type, Iterable<Class<?>>> CLASS_HIERARCHY; static final Function<Type, Iterable<Type>> INTERFACES_OF; static final Function<Type, Iterable<Type>> TYPES_OF; }### Answer: @Test public void givenClassWithInterfacesWhenGetInterfacesWithMethodsThenGetCorrectSet() { HashSet<Class<?>> interfaces = new HashSet<Class<?>>(); interfaces.add( B.class ); Set<Class<?>> types = interfacesWithMethods( interfaces ); assertThat( "one interface returned", types.size(), equalTo( 1 ) ); assertThat( "correct interface returned", types.contains( B.class ), is( true ) ); }
### Question: Classes { public static String toURI( final Class clazz ) throws NullPointerException { return toURI( clazz.getName() ); } static Specification<Class<?>> isAssignableFrom( final Class clazz); static Specification<Object> instanceOf( final Class clazz); static Specification<Class<?>> hasModifier( final int classModifier ); static Function<Type, Iterable<T>> forClassHierarchy( final Function<Class<?>, Iterable<T>> function ); static Function<Type, Iterable<T>> forTypes( final Function<Type, Iterable<T>> function ); static Set<Class<?>> interfacesWithMethods( Set<Class<?>> interfaces ); static String getSimpleGenericName( Type type ); static AnnotationType getAnnotationOfTypeOrAnyOfSuperTypes( Class<?> type, Class<AnnotationType> annotationClass ); static Specification<Member> memberNamed( final String name ); static Type resolveTypeVariable( TypeVariable name, Class declaringClass, Class topClass ); static String toURI( final Class clazz ); static String toURI( String className ); static String toClassName( String uri ); static String normalizeClassToURI( String className ); static String denormalizeURIToClass( String uriPart ); static final Function<Type, Type> WRAPPER_CLASS; static final Function<Type, Type> PRIMITIVE_CLASS; static final Function<Type, Class<?>> RAW_CLASS; static final Function<AccessibleObject, Type> TYPE_OF; static final Function<Type, Iterable<Class<?>>> CLASS_HIERARCHY; static final Function<Type, Iterable<Type>> INTERFACES_OF; static final Function<Type, Iterable<Type>> TYPES_OF; }### Answer: @Test public void givenClassNameWhenToUriThenUriIsReturned() { assertThat( "URI is correct", Classes.toURI( A.class ), equalTo( "urn:qi4j:type:org.qi4j.api.util.ClassesTest-A" ) ); }
### Question: Classes { public static String toClassName( String uri ) throws NullPointerException { uri = uri.substring( "urn:qi4j:type:".length() ); uri = denormalizeURIToClass( uri ); return uri; } static Specification<Class<?>> isAssignableFrom( final Class clazz); static Specification<Object> instanceOf( final Class clazz); static Specification<Class<?>> hasModifier( final int classModifier ); static Function<Type, Iterable<T>> forClassHierarchy( final Function<Class<?>, Iterable<T>> function ); static Function<Type, Iterable<T>> forTypes( final Function<Type, Iterable<T>> function ); static Set<Class<?>> interfacesWithMethods( Set<Class<?>> interfaces ); static String getSimpleGenericName( Type type ); static AnnotationType getAnnotationOfTypeOrAnyOfSuperTypes( Class<?> type, Class<AnnotationType> annotationClass ); static Specification<Member> memberNamed( final String name ); static Type resolveTypeVariable( TypeVariable name, Class declaringClass, Class topClass ); static String toURI( final Class clazz ); static String toURI( String className ); static String toClassName( String uri ); static String normalizeClassToURI( String className ); static String denormalizeURIToClass( String uriPart ); static final Function<Type, Type> WRAPPER_CLASS; static final Function<Type, Type> PRIMITIVE_CLASS; static final Function<Type, Class<?>> RAW_CLASS; static final Function<AccessibleObject, Type> TYPE_OF; static final Function<Type, Iterable<Class<?>>> CLASS_HIERARCHY; static final Function<Type, Iterable<Type>> INTERFACES_OF; static final Function<Type, Iterable<Type>> TYPES_OF; }### Answer: @Test public void givenUriWhenToClassNameThenClassNameIsReturned() { assertThat( "Class name is correct", Classes.toClassName( "urn:qi4j:type:org.qi4j.api.util.ClassesTest-A" ), equalTo( "org.qi4j.api.util.ClassesTest$A" ) ); }
### Question: Classes { public static Type resolveTypeVariable( TypeVariable name, Class declaringClass, Class topClass ) { Type type = resolveTypeVariable( name, declaringClass, new HashMap<TypeVariable, Type>(), topClass ); if( type == null ) { type = Object.class; } return type; } static Specification<Class<?>> isAssignableFrom( final Class clazz); static Specification<Object> instanceOf( final Class clazz); static Specification<Class<?>> hasModifier( final int classModifier ); static Function<Type, Iterable<T>> forClassHierarchy( final Function<Class<?>, Iterable<T>> function ); static Function<Type, Iterable<T>> forTypes( final Function<Type, Iterable<T>> function ); static Set<Class<?>> interfacesWithMethods( Set<Class<?>> interfaces ); static String getSimpleGenericName( Type type ); static AnnotationType getAnnotationOfTypeOrAnyOfSuperTypes( Class<?> type, Class<AnnotationType> annotationClass ); static Specification<Member> memberNamed( final String name ); static Type resolveTypeVariable( TypeVariable name, Class declaringClass, Class topClass ); static String toURI( final Class clazz ); static String toURI( String className ); static String toClassName( String uri ); static String normalizeClassToURI( String className ); static String denormalizeURIToClass( String uriPart ); static final Function<Type, Type> WRAPPER_CLASS; static final Function<Type, Type> PRIMITIVE_CLASS; static final Function<Type, Class<?>> RAW_CLASS; static final Function<AccessibleObject, Type> TYPE_OF; static final Function<Type, Iterable<Class<?>>> CLASS_HIERARCHY; static final Function<Type, Iterable<Type>> INTERFACES_OF; static final Function<Type, Iterable<Type>> TYPES_OF; }### Answer: @Test public void givenTypeVariableWhenResolveThenResolved() { for( Method method : Type1.class.getMethods() ) { Type type = method.getGenericReturnType(); TypeVariable typeVariable = (TypeVariable) type; Type resolvedType = Classes.resolveTypeVariable( typeVariable, method.getDeclaringClass(), Type1.class ); System.out.println( type + "=" + resolvedType ); } }
### Question: UnitOfWorkTemplate { public RESULT withModule(Module module) throws ThrowableType, UnitOfWorkCompletionException { int loop = 0; ThrowableType ex = null; do { UnitOfWork uow = module.newUnitOfWork( usecase ); try { RESULT result = withUnitOfWork( uow ); if (complete) { try { uow.complete(); return result; } catch( ConcurrentEntityModificationException e ) { ex = (ThrowableType) e; } } } catch (Throwable e) { ex = (ThrowableType) e; } finally { uow.discard(); } } while (loop++ < retries); throw ex; } protected UnitOfWorkTemplate(); protected UnitOfWorkTemplate( int retries, boolean complete ); protected UnitOfWorkTemplate( Usecase usecase, int retries, boolean complete ); RESULT withModule(Module module); }### Answer: @Test public void testTemplate() throws UnitOfWorkCompletionException { new UnitOfWorkTemplate<Void, RuntimeException>() { @Override protected Void withUnitOfWork( UnitOfWork uow ) throws RuntimeException { new EntityBuilderTemplate<TestEntity>(TestEntity.class) { @Override protected void build( TestEntity prototype ) { prototype.name().set( "Rickard" ); } }.newInstance( module ); return null; } }.withModule( module ); }
### Question: QualifiedName implements Comparable<QualifiedName>, Serializable { public String type() { return typeName.normalized(); } QualifiedName( TypeName typeName, String name ); static QualifiedName fromAccessor( AccessibleObject method ); static QualifiedName fromClass( Class type, String name ); static QualifiedName fromName( String type, String name ); static QualifiedName fromQN( String qualifiedName ); String type(); String name(); String toURI(); String toNamespace(); @Override String toString(); @Override boolean equals( Object o ); @Override int hashCode(); int compareTo( QualifiedName other ); }### Answer: @Test public void testQualifiedNameWithDollar() { assertEquals( "Name containing dollar is modified", "Test-Test", new QualifiedName( TypeName.nameOf( "Test$Test" ), "satisfiedBy" ).type() ); }