method2testcases
stringlengths
118
3.08k
### Question: IpInterval implements Interval<K> { public static IpInterval<?> parse(final CIString prefix) { return parse(prefix.toString()); } static String removeTrailingDot(final String address); abstract AttributeType getAttributeType(); static IpInterval<?> parse(final CIString prefix); static IpInterval<?> parse(final String prefix); static IpInterval<?> parseReverseDomain(final String reverse); static IpInterval<?> asIpInterval(final InetAddress address); abstract InetAddress beginAsInetAddress(); abstract InetAddress endAsInetAddress(); abstract int getPrefixLength(); }### Answer: @Test public void parse() { assertThat(IpInterval.parse("193.0.0/24").toString(), is("193.0.0.0/24")); assertThat(IpInterval.parse("00ab:cd::").toString(), is("ab:cd::/128")); }
### Question: Ipv6Resource extends IpInterval<Ipv6Resource> implements Comparable<Ipv6Resource> { @Override public Ipv6Resource singletonIntervalAtLowerBound() { return new Ipv6Resource(beginMsb, beginLsb, IPV6_BITCOUNT); } private Ipv6Resource(final long msb, final long lsb, final int prefixLength); Ipv6Resource(final BigInteger begin, final BigInteger end); static long lsb(final BigInteger begin); static long msb(final BigInteger begin); static Ipv6Resource parseFromStrings(final String msb, final String lsb, final int len); static Ipv6Resource parse(final InetAddress ipv6Address); static Ipv6Resource parse(final CIString prefixOrAddress); static Ipv6Resource parse(final String prefixOrAddress); static Ipv6Resource parseReverseDomain(final String address); @Override final AttributeType getAttributeType(); BigInteger begin(); BigInteger end(); static int compare(final long aMsb, final long aLsb, final long bMsb, final long bLsb); @Override int compareTo(final Ipv6Resource that); @Override boolean contains(final Ipv6Resource that); @Override boolean intersects(final Ipv6Resource that); @Override Ipv6Resource singletonIntervalAtLowerBound(); @Override int compareUpperBound(final Ipv6Resource that); @Override InetAddress beginAsInetAddress(); @Override InetAddress endAsInetAddress(); @Override int getPrefixLength(); @Override String toString(); @Override int hashCode(); @Override boolean equals(final Object obj); static Ipv6Resource parseIPv6Resource(final String resource); static final String IPV6_REVERSE_DOMAIN; static final Ipv6Resource MAX_RANGE; }### Answer: @Test public void singletonIntervalAtLowerBound() { assertEquals(Ipv6Resource.parse("2001::/128"), Ipv6Resource.parse("2001::/77").singletonIntervalAtLowerBound()); }
### Question: CIString implements Comparable<CIString>, CharSequence { @Nullable public static CIString ciString(final String value) { if (value == null) { return null; } return new CIString(value); } private CIString(final String value); @Nullable static CIString ciString(final String value); static Set<CIString> ciSet(final String... values); static Set<CIString> ciImmutableSet(final String... values); static Set<CIString> ciSet(final Iterable<String> values); static Set<CIString> ciImmutableSet(final Iterable<String> values); static boolean isBlank(final CIString ciString); @Override boolean equals(@Nullable final Object o); @Override int hashCode(); @Override int compareTo(@Nonnull final CIString o); @Override @Nonnull String toString(); String toLowerCase(); String toUpperCase(); int toInt(); @Override int length(); @Override char charAt(final int index); @Override CharSequence subSequence(final int start, final int end); boolean startsWith(final CIString value); boolean startsWith(final String value); boolean contains(final CIString value); boolean contains(final String value); boolean endsWith(final CIString value); boolean endsWith(final String value); CIString append(final CIString other); }### Answer: @Test public void create_null() { assertNull(ciString(null)); }
### Question: CIString implements Comparable<CIString>, CharSequence { @Override public boolean equals(@Nullable final Object o) { if (this == o) { return true; } if (o == null) { return false; } if (o instanceof String) { return value.equalsIgnoreCase((String) o); } return getClass() == o.getClass() && lcValue.equals(((CIString) o).lcValue); } private CIString(final String value); @Nullable static CIString ciString(final String value); static Set<CIString> ciSet(final String... values); static Set<CIString> ciImmutableSet(final String... values); static Set<CIString> ciSet(final Iterable<String> values); static Set<CIString> ciImmutableSet(final Iterable<String> values); static boolean isBlank(final CIString ciString); @Override boolean equals(@Nullable final Object o); @Override int hashCode(); @Override int compareTo(@Nonnull final CIString o); @Override @Nonnull String toString(); String toLowerCase(); String toUpperCase(); int toInt(); @Override int length(); @Override char charAt(final int index); @Override CharSequence subSequence(final int start, final int end); boolean startsWith(final CIString value); boolean startsWith(final String value); boolean contains(final CIString value); boolean contains(final String value); boolean endsWith(final CIString value); boolean endsWith(final String value); CIString append(final CIString other); }### Answer: @Test public void equals() { assertThat(ciString("ABC"), is(ciString("ABC"))); assertThat(ciString("ABC"), is(ciString("abc"))); assertThat(ciString("ABC"), is(ciString("aBc"))); final CIString ripe = CIString.ciString("RIPE"); assertFalse(ripe.equals(null)); assertTrue(ripe.equals(ripe)); assertTrue(ripe.equals(CIString.ciString("RIPE"))); assertTrue(ripe.equals("ripe")); assertTrue(ripe.equals("RIPE")); }
### Question: CIString implements Comparable<CIString>, CharSequence { public static Set<CIString> ciSet(final String... values) { final Set<CIString> result = Sets.newLinkedHashSetWithExpectedSize(values.length); for (final String value : values) { result.add(ciString(value)); } return result; } private CIString(final String value); @Nullable static CIString ciString(final String value); static Set<CIString> ciSet(final String... values); static Set<CIString> ciImmutableSet(final String... values); static Set<CIString> ciSet(final Iterable<String> values); static Set<CIString> ciImmutableSet(final Iterable<String> values); static boolean isBlank(final CIString ciString); @Override boolean equals(@Nullable final Object o); @Override int hashCode(); @Override int compareTo(@Nonnull final CIString o); @Override @Nonnull String toString(); String toLowerCase(); String toUpperCase(); int toInt(); @Override int length(); @Override char charAt(final int index); @Override CharSequence subSequence(final int start, final int end); boolean startsWith(final CIString value); boolean startsWith(final String value); boolean contains(final CIString value); boolean contains(final String value); boolean endsWith(final CIString value); boolean endsWith(final String value); CIString append(final CIString other); }### Answer: @Test public void ciset() { assertThat(ciSet("a", "b"), is(ciSet("A", "b"))); assertThat(ciSet("a", "b").contains(ciString("A")), is(true)); assertThat(ciSet("a", "b").contains(ciString("c")), is(false)); }
### Question: CIString implements Comparable<CIString>, CharSequence { @Override @Nonnull public String toString() { return value; } private CIString(final String value); @Nullable static CIString ciString(final String value); static Set<CIString> ciSet(final String... values); static Set<CIString> ciImmutableSet(final String... values); static Set<CIString> ciSet(final Iterable<String> values); static Set<CIString> ciImmutableSet(final Iterable<String> values); static boolean isBlank(final CIString ciString); @Override boolean equals(@Nullable final Object o); @Override int hashCode(); @Override int compareTo(@Nonnull final CIString o); @Override @Nonnull String toString(); String toLowerCase(); String toUpperCase(); int toInt(); @Override int length(); @Override char charAt(final int index); @Override CharSequence subSequence(final int start, final int end); boolean startsWith(final CIString value); boolean startsWith(final String value); boolean contains(final CIString value); boolean contains(final String value); boolean endsWith(final CIString value); boolean endsWith(final String value); CIString append(final CIString other); }### Answer: @Test public void tostring() { assertThat(ciString("SoMe WeIrd CasIng").toString(), is("SoMe WeIrd CasIng")); }
### Question: CIString implements Comparable<CIString>, CharSequence { @Override public CharSequence subSequence(final int start, final int end) { return value.subSequence(start, end); } private CIString(final String value); @Nullable static CIString ciString(final String value); static Set<CIString> ciSet(final String... values); static Set<CIString> ciImmutableSet(final String... values); static Set<CIString> ciSet(final Iterable<String> values); static Set<CIString> ciImmutableSet(final Iterable<String> values); static boolean isBlank(final CIString ciString); @Override boolean equals(@Nullable final Object o); @Override int hashCode(); @Override int compareTo(@Nonnull final CIString o); @Override @Nonnull String toString(); String toLowerCase(); String toUpperCase(); int toInt(); @Override int length(); @Override char charAt(final int index); @Override CharSequence subSequence(final int start, final int end); boolean startsWith(final CIString value); boolean startsWith(final String value); boolean contains(final CIString value); boolean contains(final String value); boolean endsWith(final CIString value); boolean endsWith(final String value); CIString append(final CIString other); }### Answer: @Test public void subsequence() { assertThat(ciString("abcdef").subSequence(1, 3), is((CharSequence) "bc")); assertThat(ciString("ABCDEF").subSequence(1, 3), is((CharSequence) "BC")); }
### Question: CIString implements Comparable<CIString>, CharSequence { @Override public char charAt(final int index) { return value.charAt(index); } private CIString(final String value); @Nullable static CIString ciString(final String value); static Set<CIString> ciSet(final String... values); static Set<CIString> ciImmutableSet(final String... values); static Set<CIString> ciSet(final Iterable<String> values); static Set<CIString> ciImmutableSet(final Iterable<String> values); static boolean isBlank(final CIString ciString); @Override boolean equals(@Nullable final Object o); @Override int hashCode(); @Override int compareTo(@Nonnull final CIString o); @Override @Nonnull String toString(); String toLowerCase(); String toUpperCase(); int toInt(); @Override int length(); @Override char charAt(final int index); @Override CharSequence subSequence(final int start, final int end); boolean startsWith(final CIString value); boolean startsWith(final String value); boolean contains(final CIString value); boolean contains(final String value); boolean endsWith(final CIString value); boolean endsWith(final String value); CIString append(final CIString other); }### Answer: @Test public void charAt() { assertThat(ciString("abcdef").charAt(1), is('b')); assertThat(ciString("ABCDEF").charAt(1), is('B')); }
### Question: CIString implements Comparable<CIString>, CharSequence { @Override public int length() { return value.length(); } private CIString(final String value); @Nullable static CIString ciString(final String value); static Set<CIString> ciSet(final String... values); static Set<CIString> ciImmutableSet(final String... values); static Set<CIString> ciSet(final Iterable<String> values); static Set<CIString> ciImmutableSet(final Iterable<String> values); static boolean isBlank(final CIString ciString); @Override boolean equals(@Nullable final Object o); @Override int hashCode(); @Override int compareTo(@Nonnull final CIString o); @Override @Nonnull String toString(); String toLowerCase(); String toUpperCase(); int toInt(); @Override int length(); @Override char charAt(final int index); @Override CharSequence subSequence(final int start, final int end); boolean startsWith(final CIString value); boolean startsWith(final String value); boolean contains(final CIString value); boolean contains(final String value); boolean endsWith(final CIString value); boolean endsWith(final String value); CIString append(final CIString other); }### Answer: @Test public void length() { assertThat(ciString("").length(), is(0)); assertThat(ciString("abcdef").length(), is(6)); }
### Question: CIString implements Comparable<CIString>, CharSequence { public boolean contains(final CIString value) { return lcValue.contains(value.lcValue); } private CIString(final String value); @Nullable static CIString ciString(final String value); static Set<CIString> ciSet(final String... values); static Set<CIString> ciImmutableSet(final String... values); static Set<CIString> ciSet(final Iterable<String> values); static Set<CIString> ciImmutableSet(final Iterable<String> values); static boolean isBlank(final CIString ciString); @Override boolean equals(@Nullable final Object o); @Override int hashCode(); @Override int compareTo(@Nonnull final CIString o); @Override @Nonnull String toString(); String toLowerCase(); String toUpperCase(); int toInt(); @Override int length(); @Override char charAt(final int index); @Override CharSequence subSequence(final int start, final int end); boolean startsWith(final CIString value); boolean startsWith(final String value); boolean contains(final CIString value); boolean contains(final String value); boolean endsWith(final CIString value); boolean endsWith(final String value); CIString append(final CIString other); }### Answer: @Test public void contains() { assertThat(ciString("ABCDEF").contains(ciString("abcdef")), is(true)); assertThat(ciString("ABCDEF").contains(ciString("cd")), is(true)); assertThat(ciString("ABCDEF").contains(ciString("CD")), is(true)); assertThat(ciString("ABCDEF").contains("abcdef"), is(true)); assertThat(ciString("ABCDEF").contains("cd"), is(true)); assertThat(ciString("ABCDEF").contains("CD"), is(true)); }
### Question: CIString implements Comparable<CIString>, CharSequence { public boolean endsWith(final CIString value) { return lcValue.endsWith(value.lcValue); } private CIString(final String value); @Nullable static CIString ciString(final String value); static Set<CIString> ciSet(final String... values); static Set<CIString> ciImmutableSet(final String... values); static Set<CIString> ciSet(final Iterable<String> values); static Set<CIString> ciImmutableSet(final Iterable<String> values); static boolean isBlank(final CIString ciString); @Override boolean equals(@Nullable final Object o); @Override int hashCode(); @Override int compareTo(@Nonnull final CIString o); @Override @Nonnull String toString(); String toLowerCase(); String toUpperCase(); int toInt(); @Override int length(); @Override char charAt(final int index); @Override CharSequence subSequence(final int start, final int end); boolean startsWith(final CIString value); boolean startsWith(final String value); boolean contains(final CIString value); boolean contains(final String value); boolean endsWith(final CIString value); boolean endsWith(final String value); CIString append(final CIString other); }### Answer: @Test public void endsWith() { assertThat(ciString("ABCDEF").endsWith(ciString("def")), is(true)); assertThat(ciString("ABCDEF").endsWith(ciString("DEF")), is(true)); assertThat(ciString("ABCDEF").endsWith(ciString("ABC")), is(false)); assertThat(ciString("ABCDEF").endsWith("def"), is(true)); assertThat(ciString("ABCDEF").endsWith("DEF"), is(true)); assertThat(ciString("ABCDEF").endsWith("ABC"), is(false)); }
### Question: CIString implements Comparable<CIString>, CharSequence { public CIString append(final CIString other) { return ciString(value + other.value); } private CIString(final String value); @Nullable static CIString ciString(final String value); static Set<CIString> ciSet(final String... values); static Set<CIString> ciImmutableSet(final String... values); static Set<CIString> ciSet(final Iterable<String> values); static Set<CIString> ciImmutableSet(final Iterable<String> values); static boolean isBlank(final CIString ciString); @Override boolean equals(@Nullable final Object o); @Override int hashCode(); @Override int compareTo(@Nonnull final CIString o); @Override @Nonnull String toString(); String toLowerCase(); String toUpperCase(); int toInt(); @Override int length(); @Override char charAt(final int index); @Override CharSequence subSequence(final int start, final int end); boolean startsWith(final CIString value); boolean startsWith(final String value); boolean contains(final CIString value); boolean contains(final String value); boolean endsWith(final CIString value); boolean endsWith(final String value); CIString append(final CIString other); }### Answer: @Test public void append() { assertThat(ciString("").append(ciString("")), is(ciString(""))); assertThat(ciString("a").append(ciString("b")), is(ciString("ab"))); assertThat(ciString("a").append(ciString("b")), is(ciString("AB"))); }
### Question: CIString implements Comparable<CIString>, CharSequence { public int toInt() { return Integer.parseInt(value); } private CIString(final String value); @Nullable static CIString ciString(final String value); static Set<CIString> ciSet(final String... values); static Set<CIString> ciImmutableSet(final String... values); static Set<CIString> ciSet(final Iterable<String> values); static Set<CIString> ciImmutableSet(final Iterable<String> values); static boolean isBlank(final CIString ciString); @Override boolean equals(@Nullable final Object o); @Override int hashCode(); @Override int compareTo(@Nonnull final CIString o); @Override @Nonnull String toString(); String toLowerCase(); String toUpperCase(); int toInt(); @Override int length(); @Override char charAt(final int index); @Override CharSequence subSequence(final int start, final int end); boolean startsWith(final CIString value); boolean startsWith(final String value); boolean contains(final CIString value); boolean contains(final String value); boolean endsWith(final CIString value); boolean endsWith(final String value); CIString append(final CIString other); }### Answer: @Test public void toInt() { assertThat(ciString("1").toInt(), is(1)); assertThat(ciString("312").toInt(), is(312)); }
### Question: QueryParser { public static boolean hasFlags(final String queryString) { return PARSER.parse(Iterables.toArray(SPACE_SPLITTER.split(queryString), String.class)).hasOptions(); } QueryParser(final String query); String getSearchKey(); boolean hasOptions(); boolean hasOption(final QueryFlag queryFlag); String getOptionValue(final QueryFlag queryFlag); Set<String> getOptionValues(final QueryFlag queryFlag); Set<CIString> getOptionValuesCI(final QueryFlag queryFlag); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); boolean hasOnlyQueryFlag(final QueryFlag queryFlag); static boolean hasFlags(final String queryString); boolean hasSubstitutions(); static final Pattern FLAG_PATTERN; }### Answer: @Test public void hasflags() { assertThat(QueryParser.hasFlags("--abuse-contact 193.0.0.1"), is(true)); assertThat(QueryParser.hasFlags("-L 193.0.0.1"), is(true)); assertThat(QueryParser.hasFlags("193.0.0.1"), is(false)); } @Test public void hasflags_invalid_option_supplied() { try { QueryParser.hasFlags("--this-is-an-invalid-flag"); fail(); } catch (IllegalArgumentExceptionMessage e) { assertThat(e.getExceptionMessage(), is(QueryMessages.malformedQuery("Invalid option: --this-is-an-invalid-flag"))); } }
### Question: StreamingRestClient implements Iterator<WhoisObject>, Closeable { public static WhoisResources unMarshalError(final InputStream inputStream) { return (WhoisResources) (new StreamingRestClient(inputStream)).unmarshal(); } StreamingRestClient(final InputStream inputStream); @Override boolean hasNext(); @Override WhoisObject next(); @Override void remove(); @Override void close(); static WhoisResources unMarshalError(final InputStream inputStream); }### Answer: @Test public void read_error_response() { final WhoisResources whoisResources = StreamingRestClient.unMarshalError( new ByteArrayInputStream(( "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>" + "<whois-resources xmlns:xlink=\"http: "<link xlink:type=\"locator\" xlink:href=\"http: "<errormessages><errormessage severity=\"Error\" text=\"Query param 'query-string' cannot be empty\"/></errormessages>" + "<terms-and-conditions xlink:type=\"locator\" xlink:href=\"http: "</whois-resources>\n").getBytes())); assertThat(whoisResources.getErrorMessages(), hasSize(1)); assertThat(whoisResources.getErrorMessages().get(0).getText(), is("Query param 'query-string' cannot be empty")); }
### Question: ErrorMessage implements Comparable<ErrorMessage> { @Override public String toString() { return (args == null || args.isEmpty() || text == null) ? text : String.format(text, args.toArray()); } ErrorMessage(final String severity, final Attribute attribute, final String text, final List<Arg> args); ErrorMessage(final Message message); ErrorMessage(final Message message, final RpslAttribute attribute); ErrorMessage(); @Nullable String getSeverity(); @Nullable Attribute getAttribute(); @Nullable String getText(); @Nullable List<Arg> getArgs(); @Override String toString(); @Override boolean equals(final Object o); @Override int hashCode(); @Override int compareTo(final ErrorMessage errorMessage); }### Answer: @Test public void to_string_no_arguments() { assertThat(new ErrorMessage(new Message(Messages.Type.INFO, "message")).toString(), is("message")); } @Test public void to_string_with_single_argument() { assertThat(new ErrorMessage(new Message(Messages.Type.INFO, "message with %s", "argument")).toString(), is("message with argument")); } @Test public void to_string_with_multiple_arguments() { assertThat(new ErrorMessage(new Message(Messages.Type.INFO, "message with %s %s", "argument", "ending")).toString(), is("message with argument ending")); } @Test public void to_string_default_constructor() { assertThat(new ErrorMessage().toString(), is(nullValue())); }
### Question: GrsImporterJmx extends JmxBase { @ManagedAttribute(description = "Comma separated list of default GRS sources") public String getGrsDefaultSources() { return grsDefaultSources; } @Autowired GrsImporterJmx(final GrsImporter grsImporter); @ManagedAttribute(description = "Comma separated list of default GRS sources") String getGrsDefaultSources(); @ManagedOperation(description = "Download new dumps and update GRS sources") @ManagedOperationParameters({ @ManagedOperationParameter(name = "sources", description = "Comma separated list of GRS sources to import (or 'all')"), @ManagedOperationParameter(name = "comment", description = "Optional comment for invoking the operation") }) String grsImport(final String sources, final String comment); @ManagedOperation(description = "Download new dumps and rebuild GRS sources") @ManagedOperationParameters({ @ManagedOperationParameter(name = "sources", description = "Comma separated list of GRS sources to import (or 'all')"), @ManagedOperationParameter(name = "passphrase", description = "The passphrase to prevent accidental invocation"), @ManagedOperationParameter(name = "comment", description = "Optional comment for invoking the operation") }) String grsRebuild(final String sources, final String passphrase, final String comment); }### Answer: @Test public void getGrsDefaultSources() { final String defaultSources = subject.getGrsDefaultSources(); assertThat(defaultSources, is("ARIN-GRS,APNIC-GRS")); }
### Question: SyncUpdateUtils { public static String encode(final String value) { return encode(value, StandardCharsets.UTF_8); } private SyncUpdateUtils(); static String encode(final String value); static String encode(final String value, final Charset charset); }### Answer: @Test public void encode() { assertThat(SyncUpdateUtils.encode(""), is("")); assertThat(SyncUpdateUtils.encode("123"), is("123")); assertThat(SyncUpdateUtils.encode("{}"), is("%7B%7D")); assertThat(SyncUpdateUtils.encode("{"), is("%7B")); assertThat(SyncUpdateUtils.encode("{%7D"), is("%7B%257D")); assertThat(SyncUpdateUtils.encode("a b c"), is("a+b+c")); assertThat(SyncUpdateUtils.encode("a+b+c"), is("a%2Bb%2Bc")); }
### Question: CrowdClient { public UserSession getUserSession(final String token) throws CrowdClientException { try { final CrowdSession crowdSession = client.target(restUrl) .path(CROWD_SESSION_PATH) .path(token) .queryParam("validate-password", "false") .queryParam("expand", "user") .request(MediaType.APPLICATION_XML) .post(Entity.xml("<?xml version=\"1.0\" encoding=\"UTF-8\"?><validation-factors/>"), CrowdSession.class); final CrowdUser user = crowdSession.getUser(); return new UserSession(user.getName(), user.getDisplayName(), user.getActive(), crowdSession.getExpiryDate()); } catch (BadRequestException e) { throw new CrowdClientException("Unknown RIPE NCC Access token: " + token); } catch (WebApplicationException | ProcessingException e) { throw new CrowdClientException(e); } catch (Exception e) { LOGGER.error(e.getMessage(), e); throw new CrowdClientException(e); } } @Autowired CrowdClient(@Value("${crowd.rest.url}") final String translatorUrl, @Value("${crowd.rest.user}") final String crowdAuthUser, @Value("${crowd.rest.password}") final String crowdAuthPassword); String login(final String username, final String password); void logout(final String username); void invalidateToken(final String token); String getUuid(final String username); String getUsername(final String uuid); String getDisplayName(final String uuid); UserSession getUserSession(final String token); }### Answer: @Test public void get_user_session_bad_request() { when(builder.<CrowdSession>post(any(Entity.class), any(Class.class))).then(invocation -> {throw new BadRequestException("Not valid sso");}); try { subject.getUserSession("token"); fail(); } catch (CrowdClientException expected) { assertThat(expected.getMessage(), is("Unknown RIPE NCC Access token: token")); } }
### Question: AbuseCFinder { public Optional<AbuseContact> getAbuseContact(final RpslObject rpslObject) { final RpslObject role = getAbuseContactRole(rpslObject); if (role == null) { return Optional.empty(); } final boolean suspect = abuseValidationStatusDao.isSuspect(role.getValueForAttribute(AttributeType.ABUSE_MAILBOX)); return Optional.of(new AbuseContact( role, suspect, getOrgToContact(rpslObject, suspect) )); } @Autowired AbuseCFinder(@Qualifier("jdbcRpslObjectSlaveDao") final RpslObjectDao objectDao, @Value("${whois.source}") final String mainSource, @Value("${whois.nonauth.source}") final String nonAuthSource, @Value("${grs.sources}") final String grsSource, final Ipv4Tree ipv4Tree, final Ipv6Tree ipv6Tree, final Maintainers maintainers, final AbuseValidationStatusDao abuseValidationStatusDao); Optional<AbuseContact> getAbuseContact(final RpslObject rpslObject); }### Answer: @Test public void inetnum_without_org_reference() { final RpslObject inetnum = RpslObject.parse("inetnum: 10.0.0.0\nsource: RIPE"); assertThat(subject.getAbuseContact(inetnum).isPresent(), is(false)); } @Test public void getAbuseContacts_rootObject() { final RpslObject inetnum = RpslObject.parse("inetnum: 10.0.0.0\nsource: RIPE"); assertThat(subject.getAbuseContact(inetnum).isPresent(), is(false)); verifyZeroInteractions(maintainers); }
### Question: RelatedToDecorator implements PrimaryObjectDecorator { @Override public boolean appliesToQuery(final Query query) { return query.isReturningReferencedObjects(); } @Autowired RelatedToDecorator(final RpslObjectDao rpslObjectDao); @Override boolean appliesToQuery(final Query query); @Override Collection<RpslObjectInfo> decorate(final Query query, final RpslObject rpslObject); }### Answer: @Test public void appliesToQuery_empty() { assertThat(subject.appliesToQuery(Query.parse("foo")), is(true)); } @Test public void appliesToQuery_related() { assertThat(subject.appliesToQuery(Query.parse("-T inetnum 10.0.0.0")), is(true)); } @Test public void appliesToQuery_not_related() { assertThat(subject.appliesToQuery(Query.parse("-r -T inetnum 10.0.0.0")), is(false)); }
### Question: RelatedToDecorator implements PrimaryObjectDecorator { @Override public Collection<RpslObjectInfo> decorate(final Query query, final RpslObject rpslObject) { final Set<ObjectType> excludeObjectTypes = query.hasOption(QueryFlag.NO_PERSONAL) ? NO_PERSONAL_EXCLUDES : Collections.<ObjectType>emptySet(); return rpslObjectDao.relatedTo(rpslObject, excludeObjectTypes); } @Autowired RelatedToDecorator(final RpslObjectDao rpslObjectDao); @Override boolean appliesToQuery(final Query query); @Override Collection<RpslObjectInfo> decorate(final Query query, final RpslObject rpslObject); }### Answer: @Test public void decorate() { RpslObject rpslObject = RpslObject.parse("mntner: DEV-MNT"); subject.decorate(Query.parse("DEV-MNT"), rpslObject); verify(rpslObjectDao, times(1)).relatedTo(rpslObject, Collections.<ObjectType>emptySet()); } @Test public void decorate_no_personal() { RpslObject rpslObject = RpslObject.parse("mntner: DEV-MNT"); subject.decorate(Query.parse("--no-personal DEV-MNT"), rpslObject); verify(rpslObjectDao, times(1)).relatedTo(rpslObject, Sets.newEnumSet(Lists.newArrayList(ObjectType.PERSON, ObjectType.ROLE), ObjectType.class)); }
### Question: HierarchyLookupIpv6 extends HierarchyLookup<Ipv6Resource, Ipv6Entry> { @Override public ObjectType getSupportedType() { return ObjectType.INET6NUM; } @Autowired HierarchyLookupIpv6(final Ipv6Tree ipv6Tree, final RpslObjectDao rpslObjectDao); @Override ObjectType getSupportedType(); @Override Ipv6Resource createResource(final String key); }### Answer: @Test public void getSupportedType() { assertThat(subject.getSupportedType(), is(ObjectType.INET6NUM)); }
### Question: HierarchyLookupIpv6 extends HierarchyLookup<Ipv6Resource, Ipv6Entry> { @Override public Ipv6Resource createResource(final String key) { return Ipv6Resource.parse(key); } @Autowired HierarchyLookupIpv6(final Ipv6Tree ipv6Tree, final RpslObjectDao rpslObjectDao); @Override ObjectType getSupportedType(); @Override Ipv6Resource createResource(final String key); }### Answer: @Test public void createResource() { final String resource = "::0"; assertThat(subject.createResource(resource), is(Ipv6Resource.parse(resource))); }
### Question: RelatedIrtDecorator implements PrimaryObjectDecorator { @Override public boolean appliesToQuery(final Query query) { return query.isReturningIrt(); } @Autowired RelatedIrtDecorator(final HierarchyLookupIpv4 hierarchyLookupIpv4, final HierarchyLookupIpv6 hierarchyLookupIpv6); @Override boolean appliesToQuery(final Query query); @Override Collection<RpslObjectInfo> decorate(final Query query, final RpslObject rpslObject); }### Answer: @Test public void appliesToQuery_empty() { assertThat(subject.appliesToQuery(Query.parse("foo")), is(false)); } @Test public void appliesToQuery_no_irt() { assertThat(subject.appliesToQuery(Query.parse("-T inetnum 10.0.0.0")), is(false)); } @Test public void appliesToQuery_capital_C() { assertThat(subject.appliesToQuery(Query.parse("-C -T inetnum 10.0.0.0")), is(false)); } @Test public void appliesToQuery_irt() { assertThat(subject.appliesToQuery(Query.parse("-c -T inetnum 10.0.0.0")), is(true)); }
### Question: HierarchyLookupIpv4 extends HierarchyLookup<Ipv4Resource, Ipv4Entry> { @Override public ObjectType getSupportedType() { return ObjectType.INETNUM; } @Autowired HierarchyLookupIpv4(final Ipv4Tree ipv4Tree, final RpslObjectDao rpslObjectDao); @Override ObjectType getSupportedType(); @Override Ipv4Resource createResource(final String key); }### Answer: @Test public void getSupportedType() { assertThat(subject.getSupportedType(), is(ObjectType.INETNUM)); }
### Question: HierarchyLookupIpv4 extends HierarchyLookup<Ipv4Resource, Ipv4Entry> { @Override public Ipv4Resource createResource(final String key) { return Ipv4Resource.parse(key); } @Autowired HierarchyLookupIpv4(final Ipv4Tree ipv4Tree, final RpslObjectDao rpslObjectDao); @Override ObjectType getSupportedType(); @Override Ipv4Resource createResource(final String key); }### Answer: @Test public void createResource() { final String resource = "0.0.0.0"; assertThat(subject.createResource(resource), is(Ipv4Resource.parse(resource))); }
### Question: SystemInfoQueryExecutor implements QueryExecutor { @Override public boolean supports(final Query query) { return query.isSystemInfo(); } @Autowired SystemInfoQueryExecutor(final ApplicationVersion applicationVersion, final SourceContext sourceContext); @Override boolean isAclSupported(); @Override boolean supports(final Query query); @Override void execute(final Query query, final ResponseHandler responseHandler); }### Answer: @Test public void supports_version_ignore_case() { assertThat(subject.supports(Query.parse("-q Version")), is(true)); } @Test public void supports_types_ignore_case() { assertThat(subject.supports(Query.parse("-q Types")), is(true)); } @Test public void supports_sources_ignore_case() { assertThat(subject.supports(Query.parse("-q Sources")), is(true)); }
### Question: HelpQueryExecutor implements QueryExecutor { @Override public boolean supports(final Query query) { return !query.hasOptions() && query.isHelp(); } @Override boolean isAclSupported(); @Override boolean supports(final Query query); @Override void execute(final Query query, final ResponseHandler responseHandler); }### Answer: @Test public void supports_help() { assertThat(subject.supports(Query.parse("help")), is(true)); } @Test public void supports_help_ignore_case() { assertThat(subject.supports(Query.parse("HeLp")), is(true)); } @Test public void supports_help_with_other_argument() { assertThat(subject.supports(Query.parse("help invalid")), is(false)); } @Test public void supports_help_with_other_flags() { assertThat(subject.supports(Query.parse("help -T person")), is(false)); }
### Question: HelpQueryExecutor implements QueryExecutor { @Override public void execute(final Query query, final ResponseHandler responseHandler) { responseHandler.handle(HELP_RESPONSE); } @Override boolean isAclSupported(); @Override boolean supports(final Query query); @Override void execute(final Query query, final ResponseHandler responseHandler); }### Answer: @Test public void getResponse() { final CaptureResponseHandler responseHandler = new CaptureResponseHandler(); subject.execute(null, responseHandler); final String helpText = responseHandler.getResponseObjects().get(0).toString(); assertThat(helpText, containsString("NAME")); assertThat(helpText, containsString("DESCRIPTION")); for (final QueryFlag queryFlag : QueryFlag.values()) { if (!HelpQueryExecutor.SKIPPED.contains(queryFlag)) { assertThat(helpText, containsString(queryFlag.toString())); } } for (final String line : Splitter.on('\n').split(helpText)) { if (line.length() > 0) { assertThat(line, startsWith("%")); } } assertThat(helpText, containsString("RIPE Database Reference Manual")); }
### Question: TemplateQueryExecutor implements QueryExecutor { @Override public void execute(final Query query, final ResponseHandler responseHandler) { final String objectTypeString = query.isTemplate() ? query.getTemplateOption() : query.getVerboseOption(); final ObjectType objectType = ObjectType.getByNameOrNull(objectTypeString); final MessageObject messageObject; if (objectType == null) { messageObject = new MessageObject(QueryMessages.invalidObjectType(objectTypeString)); } else { messageObject = new MessageObject(query.isTemplate() ? getTemplate(objectType) : getVerbose(objectType)); } responseHandler.handle(messageObject); } @Override boolean isAclSupported(); @Override boolean supports(final Query query); @Override void execute(final Query query, final ResponseHandler responseHandler); }### Answer: @Test public void getResponse() { for (final ObjectType objectType : ObjectType.values()) { final String name = objectType.getName(); final CaptureResponseHandler templateResponseHandler = new CaptureResponseHandler(); subject.execute(Query.parse("-t " + name), templateResponseHandler); final String templateText = templateResponseHandler.getResponseObjects().iterator().next().toString(); assertThat(templateText, containsString(name)); final CaptureResponseHandler verboseResponseHandler = new CaptureResponseHandler(); subject.execute(Query.parse("-v " + name), verboseResponseHandler); final String verboseText = verboseResponseHandler.getResponseObjects().iterator().next().toString(); assertThat(verboseText, containsString(name)); assertThat(verboseText, not(is(templateText))); } }
### Question: VersionQueryExecutor implements QueryExecutor { @Override public boolean supports(final Query query) { return query.isVersionList() || query.isObjectVersion() || query.isVersionDiff(); } @Autowired VersionQueryExecutor(final BasicSourceContext sourceContext, @Qualifier("jdbcVersionDao") final VersionDao versionDao); @Override boolean isAclSupported(); @Override boolean supports(final Query query); @Override void execute(final Query query, final ResponseHandler responseHandler); Collection<VersionLookupResult> getVersionInfo(final Query query); static final Set<ObjectType> NO_VERSION_HISTORY_FOR; }### Answer: @Test public void supportTest() { assertThat(subject.supports(Query.parse("10.0.0.0")), is(false)); assertThat(subject.supports(Query.parse("--list-versions 10.0.0.0")), is(true)); assertThat(subject.supports(Query.parse("--show-version 2 10.0.0.0")), is(true)); }
### Question: QueryDecoder extends OneToOneDecoder { @Override protected Object decode(final ChannelHandlerContext ctx, final Channel channel, final Object msg) { final Query query = Query.parse((String) msg, Query.Origin.LEGACY, isTrusted(channel)); for (final Message warning : query.getWarnings()) { channel.write(warning); } return query; } @Autowired QueryDecoder(final AccessControlListManager accessControlListManager); }### Answer: @Test public void validDecodedStringShouldReturnQuery() throws Exception { String queryString = "-Tperson DW-RIPE"; Query expectedQuery = Query.parse(queryString); when(channelMock.getRemoteAddress()).thenReturn(new InetSocketAddress(InetAddresses.forString("10.0.0.1"), 80)); Query actualQuery = (Query) subject.decode(channelHandlerContextMock, channelMock, queryString); assertEquals(expectedQuery, actualQuery); } @Test public void invalidOptionQuery() { String queryString = "-Yperson DW-RIPE"; when(channelMock.getRemoteAddress()).thenReturn(new InetSocketAddress(InetAddresses.forString("10.0.0.1"), 80)); try { subject.decode(null, channelMock, queryString); fail("Expected query exception"); } catch (QueryException e) { assertThat(e.getCompletionInfo(), is(QueryCompletionInfo.PARAMETER_ERROR)); } } @Test public void invalidProxyQuery() throws Exception { String queryString = "-Vone,two,three DW-RIPE"; when(channelMock.getRemoteAddress()).thenReturn(new InetSocketAddress(InetAddresses.forString("10.0.0.1"), 80)); try { subject.decode(null, channelMock, queryString); fail("Expected query exception"); } catch (QueryException e) { assertThat(e.getCompletionInfo(), is(QueryCompletionInfo.PARAMETER_ERROR)); } }
### Question: WhoisEncoder extends OneToOneEncoder { @Override protected Object encode(final ChannelHandlerContext ctx, final Channel channel, final Object msg) throws IOException { if (msg instanceof ResponseObject) { final ChannelBuffer result = ChannelBuffers.dynamicBuffer(DEFAULT_BUFFER_SIZE); final ChannelBufferOutputStream out = new ChannelBufferOutputStream(result); ((ResponseObject) msg).writeTo(out); out.write(OBJECT_TERMINATOR); return result; } else if (msg instanceof Message) { return ChannelBuffers.wrappedBuffer(msg.toString().getBytes(StandardCharsets.UTF_8), OBJECT_TERMINATOR); } return msg; } }### Answer: @Test public void encode_null() throws IOException { Object result = encode(null); assertThat(result, is(nullValue())); } @Test public void encode_Message() throws IOException { Message message = QueryMessages.inputTooLong(); ChannelBuffer result = encode(message); assertThat(toString(result), is(message.toString() + "\n")); } @Test public void encode_ResponseObject() throws IOException { ChannelBuffer result = encode(objectMock); verify(objectMock, times(1)).writeTo(any(OutputStream.class)); assertThat(toString(result), is("\n")); }
### Question: ServedByHandler implements ChannelDownstreamHandler { @Override public void handleDownstream(final ChannelHandlerContext ctx, final ChannelEvent e) { if (e instanceof QueryCompletedEvent) { e.getChannel().write(QueryMessages.servedByNotice(version)); } ctx.sendDownstream(e); } ServedByHandler(final String version); @Override void handleDownstream(final ChannelHandlerContext ctx, final ChannelEvent e); }### Answer: @Test public void test_handleDownstream_whois() { when(messageEventMock.getMessage()).thenReturn(new MessageObject("")); subject.handleDownstream(ctxMock, messageEventMock); verify(ctxMock, times(1)).sendDownstream(messageEventMock); subject.handleDownstream(ctxMock, queryCompletedEventMock); verify(ctxMock, times(1)).sendDownstream(queryCompletedEventMock); verify(channelMock, times(1)).write(QueryMessages.servedByNotice(anyString())); }
### Question: ExceptionHandler extends SimpleChannelUpstreamHandler { @Override public void messageReceived(final ChannelHandlerContext ctx, final MessageEvent e) { query = e.getMessage().toString(); ctx.sendUpstream(e); } @Override void messageReceived(final ChannelHandlerContext ctx, final MessageEvent e); @Override void exceptionCaught(final ChannelHandlerContext ctx, final ExceptionEvent event); }### Answer: @Test public void record_incoming_queries() throws Exception { subject.messageReceived(channelHandlerContextMock, messageEventMock); verify(channelHandlerContextMock, times(1)).sendUpstream(messageEventMock); }
### Question: TermsAndConditionsHandler extends SimpleChannelUpstreamHandler { @Override public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) { e.getChannel().write(TERMS_AND_CONDITIONS); ctx.sendUpstream(e); } @Override void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e); }### Answer: @Test public void test_terms_and_conditions() { subject.channelConnected(ctxMock, channelStateEventMock); verify(ctxMock, times(1)).sendUpstream(channelStateEventMock); verify(channelMock, times(1)).write(QueryMessages.termsAndConditions()); }
### Question: WhoisServerHandler extends SimpleChannelUpstreamHandler { @Override public void messageReceived(final ChannelHandlerContext ctx, final MessageEvent event) { final Query query = (Query) event.getMessage(); final Channel channel = event.getChannel(); queryHandler.streamResults(query, ChannelUtil.getRemoteAddress(channel), channel.getId(), new ResponseHandler() { @Override public String getApi() { return "QRY"; } @Override public void handle(final ResponseObject responseObject) { if (closed) { throw new QueryException(QueryCompletionInfo.DISCONNECTED); } channel.write(responseObject); } }); channel.getPipeline().sendDownstream(new QueryCompletedEvent(channel)); } WhoisServerHandler(final QueryHandler queryHandler); @Override void messageReceived(final ChannelHandlerContext ctx, final MessageEvent event); @Override void channelClosed(final ChannelHandlerContext ctx, final ChannelStateEvent e); }### Answer: @Test public void messageReceived_no_proxy_no_personal_object() throws Exception { final Query query = Query.parse("10.0.0.0"); when(messageEvent.getMessage()).thenReturn(query); subject.messageReceived(ctx, messageEvent); verify(channel).write(responseObject); final ArgumentCaptor<QueryCompletedEvent> channelEventCapture = ArgumentCaptor.forClass(QueryCompletedEvent.class); verify(pipeline).sendDownstream(channelEventCapture.capture()); assertNull(channelEventCapture.getValue().getCompletionInfo()); }
### Question: ConnectionPerIpLimitHandler extends SimpleChannelUpstreamHandler { private boolean connectionsExceeded(final InetAddress remoteAddress) { final Integer count = connectionCounter.increment(remoteAddress); return (count != null && count >= maxConnectionsPerIp); } @Autowired ConnectionPerIpLimitHandler( final IpResourceConfiguration ipResourceConfiguration, final WhoisLog whoisLog, @Value("${whois.limit.connectionsPerIp:3}") final int maxConnectionsPerIp, final ApplicationVersion applicationVersion); @Override void channelOpen(final ChannelHandlerContext ctx, final ChannelStateEvent e); @Override void channelClosed(final ChannelHandlerContext ctx, final ChannelStateEvent e); }### Answer: @Test public void multiple_connected_same_ip() throws Exception { final InetSocketAddress remoteAddress = new InetSocketAddress("10.0.0.0", 43); when(channel.getRemoteAddress()).thenReturn(remoteAddress); final ChannelEvent openEvent = new UpstreamChannelStateEvent(channel, ChannelState.OPEN, Boolean.TRUE); subject.handleUpstream(ctx, openEvent); subject.handleUpstream(ctx, openEvent); subject.handleUpstream(ctx, openEvent); verify(ctx, times(2)).sendUpstream(openEvent); verify(channel, times(1)).write(argThat(new ArgumentMatcher<Object>() { @Override public boolean matches(Object argument) { return QueryMessages.connectionsExceeded(MAX_CONNECTIONS_PER_IP).equals(argument); } })); verify(channelFuture, times(1)).addListener(ChannelFutureListener.CLOSE); verify(whoisLog).logQueryResult(anyString(), eq(0), eq(0), eq(QueryCompletionInfo.REJECTED), eq(0L), (InetAddress) Mockito.anyObject(), Mockito.anyInt(), eq("")); verify(ctx, times(2)).sendUpstream(openEvent); }
### Question: TagValidator implements QueryValidator { @Override public void validate(final Query query, final Messages messages) { if (query.hasOption(QueryFlag.FILTER_TAG_INCLUDE) && query.hasOption(QueryFlag.FILTER_TAG_EXCLUDE)) { final Sets.SetView<String> intersection = Sets.intersection(query.getOptionValues(QueryFlag.FILTER_TAG_INCLUDE), query.getOptionValues(QueryFlag.FILTER_TAG_EXCLUDE)); if (!intersection.isEmpty()) { final String args = " (" + Joiner.on(',').join(intersection.iterator()) + ")"; messages.add(QueryMessages.invalidCombinationOfFlags( QueryFlag.FILTER_TAG_INCLUDE.toString() + args, QueryFlag.FILTER_TAG_EXCLUDE.toString() + args)); } } } @Override void validate(final Query query, final Messages messages); }### Answer: @Test public void both_filter_tag_include_and_exclude() { try { subject.validate(Query.parse("--filter-tag-include unref --filter-tag-exclude unref TEST-MNT"), messages); } catch (QueryException e) { assertThat(e.getMessage(), containsString(QueryMessages.invalidCombinationOfFlags("--filter-tag-include (unref)", "--filter-tag-exclude (unref)").toString())); } } @Test public void both_filter_tag_include_and_exclude_different_arguments() { subject.validate(Query.parse("--filter-tag-include foo --filter-tag-exclude unref TEST-MNT"), messages); } @Test public void filter_tag_include_correct() { subject.validate(Query.parse("--filter-tag-include unref TEST-MNT"), messages); } @Test public void filter_tag_exclude_correct() { subject.validate(Query.parse("--filter-tag-exclude unref TEST-MNT"), messages); }
### Question: SearchKey { public String getValue() { return value; } SearchKey(final String value); String getValue(); IpInterval<?> getIpKeyOrNull(); IpInterval<?> getIpKeyOrNullReverse(); AsBlockRange getAsBlockRangeOrNull(); @Override String toString(); String getOrigin(); static final Pattern WHITESPACE_PATTERN; }### Answer: @Test public void parse_and_value() { subject = new SearchKey("test"); assertThat(subject.getValue(), is("test")); }
### Question: SearchKey { public IpInterval<?> getIpKeyOrNull() { return ipKey; } SearchKey(final String value); String getValue(); IpInterval<?> getIpKeyOrNull(); IpInterval<?> getIpKeyOrNullReverse(); AsBlockRange getAsBlockRangeOrNull(); @Override String toString(); String getOrigin(); static final Pattern WHITESPACE_PATTERN; }### Answer: @Test public void comma_in_search_key() { subject = new SearchKey("10,10"); assertNull(subject.getIpKeyOrNull()); } @Test public void parse_ipv6_with_v4() { final SearchKey searchKey = new SearchKey("::ffff:0.0.0.0"); final IpInterval<?> ipKeyOrNull = searchKey.getIpKeyOrNull(); assertNull(ipKeyOrNull); } @Test public void parse_ipv6_with_v4_prefix() { final SearchKey searchKey = new SearchKey("::ffff:0.0.0.0/72"); final IpInterval<?> ipKeyOrNull = searchKey.getIpKeyOrNull(); assertNull(ipKeyOrNull); }
### Question: InverseValidator implements QueryValidator { @Override public void validate(final Query query, final Messages messages) { if (query.isInverse()) { final String auth = query.getSearchValue().toUpperCase(); if ((!query.isTrusted() && auth.startsWith("SSO ")) || auth.startsWith("MD5-PW ")) { messages.add(net.ripe.db.whois.query.QueryMessages.inverseSearchNotAllowed()); } } } @Override void validate(final Query query, final Messages messages); }### Answer: @Test public void not_inverse_query() { when(query.isInverse()).thenReturn(FALSE); subject.validate(query, messages); assertThat(messages.hasMessages(), is(false)); } @Test public void searchValue_not_SSO_nor_MD5() { when(query.isInverse()).thenReturn(TRUE); when(query.getSearchValue()).thenReturn("ORG-TP1-TEST"); subject.validate(query, messages); assertThat(messages.hasMessages(), is(false)); } @Test public void searchValue_SSO() { when(query.isInverse()).thenReturn(TRUE); when(query.getSearchValue()).thenReturn("SSO test@test.net"); subject.validate(query, messages); assertThat(messages.getErrors(), contains(QueryMessages.inverseSearchNotAllowed())); } @Test public void searchValue_MD5() { when(query.isInverse()).thenReturn(TRUE); when(query.getSearchValue()).thenReturn("MD5-PW \\$1\\$fU9ZMQN9\\$QQtm3kRqZXWAuLpeOiLN7."); subject.validate(query, messages); assertThat(messages.getErrors(), contains(QueryMessages.inverseSearchNotAllowed())); }
### Question: IpResourceConfiguration { public int getLimit(final InetAddress address) { final Integer result = limit.getValue(IpInterval.asIpInterval(address)); return result == null ? DEFAULT_LIMIT : result; } @Autowired IpResourceConfiguration(final Loader loader); boolean isDenied(final InetAddress address); boolean isDenied(final IpInterval address); boolean isProxy(final InetAddress address); boolean isProxy(final IpInterval address); int getLimit(final InetAddress address); int getLimit(final IpInterval address); boolean isUnlimitedConnections(final InetAddress address); boolean isUnlimitedConnections(final IpInterval address); @PostConstruct @Scheduled(fixedDelay = TREE_UPDATE_IN_SECONDS * 1000) synchronized void reload(); }### Answer: @Test public void test_limit_default() throws Exception { assertThat(subject.getLimit(inetAddress), is(5000)); }
### Question: IpResourceConfiguration { public boolean isProxy(final InetAddress address) { final Boolean result = proxy.getValue(IpInterval.asIpInterval(address)); return result != null && result; } @Autowired IpResourceConfiguration(final Loader loader); boolean isDenied(final InetAddress address); boolean isDenied(final IpInterval address); boolean isProxy(final InetAddress address); boolean isProxy(final IpInterval address); int getLimit(final InetAddress address); int getLimit(final IpInterval address); boolean isUnlimitedConnections(final InetAddress address); boolean isUnlimitedConnections(final IpInterval address); @PostConstruct @Scheduled(fixedDelay = TREE_UPDATE_IN_SECONDS * 1000) synchronized void reload(); }### Answer: @Test public void test_proxy_default() throws Exception { assertThat(subject.isProxy(inetAddress), is(false)); }
### Question: IpResourceConfiguration { public boolean isDenied(final InetAddress address) { final Boolean result = denied.getValue(IpInterval.asIpInterval(address)); return result != null && result; } @Autowired IpResourceConfiguration(final Loader loader); boolean isDenied(final InetAddress address); boolean isDenied(final IpInterval address); boolean isProxy(final InetAddress address); boolean isProxy(final IpInterval address); int getLimit(final InetAddress address); int getLimit(final IpInterval address); boolean isUnlimitedConnections(final InetAddress address); boolean isUnlimitedConnections(final IpInterval address); @PostConstruct @Scheduled(fixedDelay = TREE_UPDATE_IN_SECONDS * 1000) synchronized void reload(); }### Answer: @Test public void test_denied_default() throws Exception { assertThat(subject.isDenied(inetAddress), is(false)); }
### Question: IpResourceConfiguration { public boolean isUnlimitedConnections(final InetAddress address) { final Boolean result = unlimitedConnections.getValue(IpInterval.asIpInterval(address)); return result != null && result; } @Autowired IpResourceConfiguration(final Loader loader); boolean isDenied(final InetAddress address); boolean isDenied(final IpInterval address); boolean isProxy(final InetAddress address); boolean isProxy(final IpInterval address); int getLimit(final InetAddress address); int getLimit(final IpInterval address); boolean isUnlimitedConnections(final InetAddress address); boolean isUnlimitedConnections(final IpInterval address); @PostConstruct @Scheduled(fixedDelay = TREE_UPDATE_IN_SECONDS * 1000) synchronized void reload(); }### Answer: @Test public void test_unlimitedConnections_default() throws Exception { assertThat(subject.isUnlimitedConnections(inetAddress), is(false)); }
### Question: AccessControlListManager { public boolean isDenied(final InetAddress remoteAddress) { return resourceConfiguration.isDenied(remoteAddress); } @Autowired AccessControlListManager(final DateTimeProvider dateTimeProvider, final IpResourceConfiguration resourceConfiguration, final AccessControlListDao accessControlListDao, final PersonalObjectAccounting personalObjectAccounting, final IpRanges ipRanges); boolean requiresAcl(final RpslObject rpslObject, final Source source); boolean isDenied(final InetAddress remoteAddress); boolean isAllowedToProxy(final InetAddress remoteAddress); boolean isUnlimited(final InetAddress remoteAddress); boolean canQueryPersonalObjects(final InetAddress remoteAddress); boolean isTrusted(final InetAddress remoteAddress); int getPersonalObjects(final InetAddress remoteAddress); void accountPersonalObjects(final InetAddress remoteAddress, final int amount); void blockTemporary(final InetAddress hostAddress, final int limit); static InetAddress mask(final InetAddress address, final int mask); }### Answer: @Test public void check_denied_restricted() throws Exception { assertTrue(subject.isDenied(ipv4Restricted)); assertTrue(subject.isDenied(ipv6Restricted)); } @Test public void check_denied_unrestricted() throws Exception { assertFalse(subject.isDenied(ipv4Unrestricted)); assertFalse(subject.isDenied(ipv6Unrestricted)); } @Test public void check_denied_unknown() throws Exception { assertFalse(subject.isDenied(ipv4Unknown)); assertFalse(subject.isDenied(ipv6Unknown)); }
### Question: AccessControlListManager { public boolean isAllowedToProxy(final InetAddress remoteAddress) { return resourceConfiguration.isProxy(remoteAddress); } @Autowired AccessControlListManager(final DateTimeProvider dateTimeProvider, final IpResourceConfiguration resourceConfiguration, final AccessControlListDao accessControlListDao, final PersonalObjectAccounting personalObjectAccounting, final IpRanges ipRanges); boolean requiresAcl(final RpslObject rpslObject, final Source source); boolean isDenied(final InetAddress remoteAddress); boolean isAllowedToProxy(final InetAddress remoteAddress); boolean isUnlimited(final InetAddress remoteAddress); boolean canQueryPersonalObjects(final InetAddress remoteAddress); boolean isTrusted(final InetAddress remoteAddress); int getPersonalObjects(final InetAddress remoteAddress); void accountPersonalObjects(final InetAddress remoteAddress, final int amount); void blockTemporary(final InetAddress hostAddress, final int limit); static InetAddress mask(final InetAddress address, final int mask); }### Answer: @Test public void check_proxy_restricted() throws Exception { assertFalse(subject.isAllowedToProxy(ipv4Restricted)); assertFalse(subject.isAllowedToProxy(ipv6Restricted)); } @Test public void check_proxy_unrestricted() throws Exception { assertTrue(subject.isAllowedToProxy(ipv4Unrestricted)); assertTrue(subject.isAllowedToProxy(ipv6Unrestricted)); } @Test public void check_proxy_unknown() throws Exception { assertFalse(subject.isAllowedToProxy(ipv4Unknown)); assertFalse(subject.isAllowedToProxy(ipv6Unknown)); }
### Question: AccessControlListManager { int getPersonalDataLimit(final InetAddress remoteAddress) { return resourceConfiguration.getLimit(remoteAddress); } @Autowired AccessControlListManager(final DateTimeProvider dateTimeProvider, final IpResourceConfiguration resourceConfiguration, final AccessControlListDao accessControlListDao, final PersonalObjectAccounting personalObjectAccounting, final IpRanges ipRanges); boolean requiresAcl(final RpslObject rpslObject, final Source source); boolean isDenied(final InetAddress remoteAddress); boolean isAllowedToProxy(final InetAddress remoteAddress); boolean isUnlimited(final InetAddress remoteAddress); boolean canQueryPersonalObjects(final InetAddress remoteAddress); boolean isTrusted(final InetAddress remoteAddress); int getPersonalObjects(final InetAddress remoteAddress); void accountPersonalObjects(final InetAddress remoteAddress, final int amount); void blockTemporary(final InetAddress hostAddress, final int limit); static InetAddress mask(final InetAddress address, final int mask); }### Answer: @Test public void check_getLimit_restricted() throws Exception { assertThat(subject.getPersonalDataLimit(ipv4Restricted), is(PERSONAL_DATA_LIMIT)); assertThat(subject.getPersonalDataLimit(ipv6Restricted), is(PERSONAL_DATA_LIMIT)); } @Test public void check_getLimit_unrestricted() throws Exception { assertThat(subject.getPersonalDataLimit(ipv4Unrestricted), is(PERSONAL_DATA_NO_LIMIT)); assertThat(subject.getPersonalDataLimit(ipv6Unrestricted), is(PERSONAL_DATA_NO_LIMIT)); } @Test public void check_getLimit_unknown() throws Exception { assertThat(subject.getPersonalDataLimit(ipv4Unknown), is(PERSONAL_DATA_LIMIT_UNKNOWN)); assertThat(subject.getPersonalDataLimit(ipv6Unknown), is(PERSONAL_DATA_LIMIT_UNKNOWN)); }
### Question: AccessControlListManager { public void blockTemporary(final InetAddress hostAddress, final int limit) { IpInterval<?> maskedAddress; if (hostAddress instanceof Inet6Address) { maskedAddress = Ipv6Resource.parse(mask(hostAddress, IPV6_NETMASK).getHostAddress() + "/" + IPV6_NETMASK); } else { maskedAddress = Ipv4Resource.asIpInterval(hostAddress); } accessControlListDao.saveAclEvent(maskedAddress, dateTimeProvider.getCurrentDate(), limit, BlockEvent.Type.BLOCK_TEMPORARY); } @Autowired AccessControlListManager(final DateTimeProvider dateTimeProvider, final IpResourceConfiguration resourceConfiguration, final AccessControlListDao accessControlListDao, final PersonalObjectAccounting personalObjectAccounting, final IpRanges ipRanges); boolean requiresAcl(final RpslObject rpslObject, final Source source); boolean isDenied(final InetAddress remoteAddress); boolean isAllowedToProxy(final InetAddress remoteAddress); boolean isUnlimited(final InetAddress remoteAddress); boolean canQueryPersonalObjects(final InetAddress remoteAddress); boolean isTrusted(final InetAddress remoteAddress); int getPersonalObjects(final InetAddress remoteAddress); void accountPersonalObjects(final InetAddress remoteAddress, final int amount); void blockTemporary(final InetAddress hostAddress, final int limit); static InetAddress mask(final InetAddress address, final int mask); }### Answer: @Test public void test_if_block_temporary_is_logged() { subject.blockTemporary(ipv6Restricted, PERSONAL_DATA_LIMIT); verify(accessControlListDao).saveAclEvent(ipv6ResourceCaptor.capture(), eq(now), eq(PERSONAL_DATA_LIMIT), eq(BlockEvent.Type.BLOCK_TEMPORARY)); Ipv6Resource ipv6Resource = ipv6ResourceCaptor.getValue(); assertThat(ipv6Resource.toString(), is("2001::/64")); }
### Question: AccessControlListManager { public boolean isTrusted(final InetAddress remoteAddress) { return ipRanges.isTrusted(IpInterval.asIpInterval(remoteAddress)); } @Autowired AccessControlListManager(final DateTimeProvider dateTimeProvider, final IpResourceConfiguration resourceConfiguration, final AccessControlListDao accessControlListDao, final PersonalObjectAccounting personalObjectAccounting, final IpRanges ipRanges); boolean requiresAcl(final RpslObject rpslObject, final Source source); boolean isDenied(final InetAddress remoteAddress); boolean isAllowedToProxy(final InetAddress remoteAddress); boolean isUnlimited(final InetAddress remoteAddress); boolean canQueryPersonalObjects(final InetAddress remoteAddress); boolean isTrusted(final InetAddress remoteAddress); int getPersonalObjects(final InetAddress remoteAddress); void accountPersonalObjects(final InetAddress remoteAddress, final int amount); void blockTemporary(final InetAddress hostAddress, final int limit); static InetAddress mask(final InetAddress address, final int mask); }### Answer: @Test public void override_from_trusted_range() { when(ipRanges.isTrusted(any(IpInterval.class))).thenReturn(true); assertThat(subject.isTrusted(InetAddresses.forString("10.0.0.1")), is(true)); } @Test public void override_from_untrusted_range() { when(ipRanges.isTrusted(any(IpInterval.class))).thenReturn(false); assertThat(subject.isTrusted(InetAddresses.forString("10.0.0.1")), is(false)); }
### Question: HazelcastPersonalObjectAccounting implements PersonalObjectAccounting { @Override public int getQueriedPersonalObjects(final InetAddress remoteAddress) { Integer count = null; try { count = counterMap.get(remoteAddress); } catch (OperationTimeoutException | IllegalStateException e) { LOGGER.debug("{}: {}", e.getClass().getName(), e.getMessage()); } if (count == null) { return 0; } return count; } @PostConstruct void startService(); @PreDestroy void stopService(); @Override int getQueriedPersonalObjects(final InetAddress remoteAddress); @Override int accountPersonalObject(final InetAddress remoteAddress, final int amount); @Override void resetAccounting(); }### Answer: @Test public void test_queried_personal_objects() { assertThat(subject.getQueriedPersonalObjects(ipv4Address), is(0)); }
### Question: HazelcastPersonalObjectAccounting implements PersonalObjectAccounting { @Override public int accountPersonalObject(final InetAddress remoteAddress, final int amount) { try { Integer count = counterMap.tryLockAndGet(remoteAddress, 3, TimeUnit.SECONDS); if (count == null) { count = amount; } else { count += amount; } counterMap.putAndUnlock(remoteAddress, count); return count; } catch (TimeoutException | IllegalStateException e) { LOGGER.info("Unable to account personal object, allowed by default. Threw " + e.getClass().getName() + ": " + e.getMessage()); } return 0; } @PostConstruct void startService(); @PreDestroy void stopService(); @Override int getQueriedPersonalObjects(final InetAddress remoteAddress); @Override int accountPersonalObject(final InetAddress remoteAddress, final int amount); @Override void resetAccounting(); }### Answer: @Test public void test_account_personal_object_amount_1() { for (int i = 1; i < 100; i++) { int balance = subject.accountPersonalObject(ipv4Address, 1); assertThat(balance, is(i)); } }
### Question: DummifierNrtm implements Dummifier { public boolean isAllowed(final int version, final RpslObject rpslObject) { return version <= 2 || !usePlaceHolder(rpslObject); } RpslObject dummify(final int version, final RpslObject rpslObject); boolean isAllowed(final int version, final RpslObject rpslObject); static RpslObject getPlaceholderPersonObject(); static RpslObject getPlaceholderRoleObject(); }### Answer: @Test public void allow_objects_version_3() { for (ObjectType objectType : ObjectType.values()) { if (DummifierNrtm.SKIPPED_OBJECT_TYPES.contains(objectType)) { continue; } final RpslObject rpslObject = createObject(objectType, "YAY", new RpslAttribute(AttributeType.REMARKS, "Remark!")); assertThat(subject.isAllowed(3, rpslObject), is(true)); } } @Test public void allow_role_with_abuse_mailbox() { final RpslObject role = RpslObject.parse( "role: Test Role\n" + "created: 2001-02-04T17:00:00Z\n" + "last-modified: 2001-02-04T17:00:00Z\n" + "nic-hdl: TR1-TEST\n" + "abuse-mailbox: abuse@mailbox.com\n" + "source: TEST"); assertThat(subject.isAllowed(3, role), is(true)); }
### Question: WhoisRestApi implements Origin { @Override public String getId() { return remoteAddress; } WhoisRestApi(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 getId() { assertThat(subject.getId(), is("127.0.0.1")); }
### Question: WhoisRestApi implements Origin { @Override public String getFrom() { return remoteAddress; } WhoisRestApi(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 getFrom() { assertThat(subject.getFrom(), is("127.0.0.1")); }
### Question: WhoisRestApi implements Origin { @Override public String getName() { return "rest api"; } WhoisRestApi(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("rest api")); }
### Question: WhoisRestApi implements Origin { @Override public String getResponseHeader() { return getHeader(); } WhoisRestApi(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() { when(dateTimeProvider.getCurrentDateTime()).thenReturn(LocalDateTime.of(2013, 3, 3, 12, 55)); assertThat(subject.getResponseHeader(), is(" - From-Host: 127.0.0.1\n - Date/Time: Sun Mar 3 12:55:00 2013\n")); }
### Question: WhoisRestApi implements Origin { @Override public String getNotificationHeader() { return getHeader(); } WhoisRestApi(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() { when(dateTimeProvider.getCurrentDateTime()).thenReturn(LocalDateTime.of(2013, 3, 3, 12, 55)); assertThat(subject.getNotificationHeader(), is(" - From-Host: 127.0.0.1\n - Date/Time: Sun Mar 3 12:55:00 2013\n")); }
### Question: RestServiceHelper { public static String getRequestURL(final HttpServletRequest request) { return request.getRequestURL().toString() + filter(request.getQueryString()); } private RestServiceHelper(); static String getRequestURL(final HttpServletRequest request); static String getRequestURI(final HttpServletRequest request); static boolean isQueryParamSet(final String queryString, final String key); static boolean isQueryParamSet(final String queryParam); static Class<? extends AttributeMapper> getServerAttributeMapper(final boolean unformatted); static Class<? extends AttributeMapper> getRestResponseAttributeMapper(String queryString); static WhoisResources createErrorEntity(final HttpServletRequest request, final Message... errorMessage); static WhoisResources createErrorEntity(final HttpServletRequest request, final List<Message> errorMessages); static List<ErrorMessage> createErrorMessages(final List<Message> messages); static WebApplicationException createWebApplicationException(final RuntimeException exception, final HttpServletRequest request); static WebApplicationException createWebApplicationException(final RuntimeException exception, final HttpServletRequest request, final List<Message> messages); }### Answer: @Test public void getRequestUrl() { assertThat(getRequestURL("http: assertThat(getRequestURL("http: assertThat(getRequestURL("http: assertThat(getRequestURL("http: assertThat(getRequestURL("http: assertThat(getRequestURL("http: assertThat(getRequestURL("http: assertThat(getRequestURL("http: assertThat(getRequestURL("http: assertThat(getRequestURL("http: assertThat(getRequestURL("http: assertThat(getRequestURL("http: assertThat(getRequestURL("http: assertThat(getRequestURL("http: assertThat(getRequestURL("http: }
### Question: SyncUpdate implements Origin { @Override public String getId() { return getFrom(); } 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 getId() { assertThat(subject.getId(), is(LOCALHOST)); }
### Question: SyncUpdate implements Origin { @Override public String getFrom() { return remoteAddress; } 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 getFrom() { assertThat(subject.getFrom(), is(LOCALHOST)); }
### 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 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: 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: 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: 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: 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: 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: 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 username@test.net"); when(updateContext.getSsoTranslationResult("username@test.net")).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: 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 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: 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: 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: 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: 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); }