method2testcases
stringlengths 118
3.08k
|
---|
### Question:
ResponseWriter { public void write(final Response response) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); mapper.writeValue(out, response); out.write('\n'); this.out.write(out.toByteArray()); } ResponseWriter(final OutputStream out); void setContent(String content); void write(final Response response); }### Answer:
@Test public void error() throws IOException { final ByteArrayOutputStream out = new ByteArrayOutputStream(); final ResponseWriter writer = new ResponseWriter(out); Response response; response = new Response(); response.status = "fatal"; response.errors = new ArrayList<>(); response.errors.add("error"); writer.write(response); final String result = new String(out.toByteArray()); final String expected = "{\"status\":\"fatal\",\"errors\":[\"error\"]}\n"; assertThat(result).isEqualTo(expected); }
@Test public void valid() throws IOException { final ByteArrayOutputStream out = new ByteArrayOutputStream(); final ResponseWriter writer = new ResponseWriter(out); final EclipseParser parser = new EclipseParser(); Response response; final String source = IOUtils.toString( getClass().getResourceAsStream("/helloWorld.java"), StandardCharsets.UTF_8); response = new Response(); response.status = "ok"; response.ast = parser.parse(source); writer.write(response); }
|
### Question:
DateUtils { public static String toStandardDate(int year, int month, int day) { String yearStr = Integer.toString(year); String monthStr = Integer.toString(month); String dayStr = Integer.toString(day); if (month < 10) { monthStr = "0" + monthStr; } if (day < 10) { dayStr = "0" + dayStr; } StringBuilder builder = new StringBuilder(); builder.append(yearStr); builder.append('-'); builder.append(monthStr); builder.append('-'); builder.append(dayStr); return builder.toString(); } static String toStandardDate(int year, int month, int day); static int[] fromStandardDate(String standardDate); }### Answer:
@Test public void testToStandardDate() { int y = 1990; int m = 5; int d = 3; assertEquals("1990-05-03", DateUtils.toStandardDate(y, m, d)); y = 1990; m = 11; d = 3; assertEquals("1990-11-03", DateUtils.toStandardDate(y, m, d)); y = 1990; m = 5; d = 31; assertEquals("1990-05-31", DateUtils.toStandardDate(y, m, d)); y = 2018; m = 12; d = 31; assertEquals("2018-12-31", DateUtils.toStandardDate(y, m, d)); }
|
### Question:
CultureItem implements Parcelable { public void setLatitude(String latitude) { this.latitude = latitude; } CultureItem(); @SuppressWarnings("unchecked") CultureItem(Parcel in); @Override void writeToParcel(Parcel out, int flags); @Override int describeContents(); long getId(); void setId(long id); long getUser(); void setUser(long user); String getTitle(); void setTitle(String title); String getDescription(); void setDescription(String description); String getPlaceName(); void setPlaceName(String placeName); Integer getStartYear(); void setStartYear(int startYear); Integer getEndYear(); void setEndYear(int endYear); void setStartYear(Integer startYear); void setEndYear(Integer endYear); String getLatitude(); void setLatitude(String latitude); String getLongitude(); void setLongitude(String longitude); boolean isPublicAccessibility(); void setPublicAccessibility(boolean publicAccessibility); boolean isFavorite(); void setFavorite(boolean favorite); ArrayList<Image> getImageList(); void setImageList(ArrayList<Image> imageList); ArrayList<Tag> getTagList(); void setTagList(ArrayList<Tag> tagList); Boolean getPublicAccessibility(); void setPublicAccessibility(Boolean publicAccessibility); String getFavoriteCount(); void setFavoriteCount(String favoriteCount); UserResponse getUserInfo(); void setUserInfo(UserResponse userInfo); FeedRow toFeedRow(); ArrayList<Comment> getCommentList(); void setCommentList(ArrayList<Comment> commentList); @Override boolean equals(Object obj); @SerializedName("public_accessibility")
@Expose
private boolean publicAccessibility; static final Parcelable.Creator<CultureItem> CREATOR; }### Answer:
@Test public void testLatLongEquals() { CultureItem firstItem = new CultureItem(); CultureItem secondItem = new CultureItem(); firstItem.setLatitude("17.010010"); secondItem.setLatitude("17.010010"); assertEquals(firstItem, secondItem); }
|
### Question:
Tag implements Serializable { @Override public boolean equals(Object obj) { if (!(obj instanceof Tag)) { return false; } Tag other = (Tag)obj; return Utils.objectEquals(this.name, other.name); } Tag(String name); String getName(); void setName(String name); @Override boolean equals(Object obj); }### Answer:
@Test public void testEquals() { Tag t1 = null; Tag t2 = null; assertEquals(t1, t2); t1 = new Tag("tag1"); assertNotEquals(t1, t2); t2 = new Tag("tag2"); assertNotEquals(t1, t2); t2.setName(t1.getName()); assertEquals(t1, t2); }
|
### Question:
RetrofitBuilder { public RetrofitBuilder() { this.retrofitBuilder = new Retrofit.Builder(); this.okhttpBuilder = new OkHttpClient.Builder(); } RetrofitBuilder(); RetrofitBuilder baseUrl(String baseUrl); RetrofitBuilder readTimeout(long timeout, TimeUnit unit); RetrofitBuilder writeTimeout(long timeout, TimeUnit unit); RetrofitBuilder connectTimeout(long timeout, TimeUnit unit); RetrofitBuilder addConverterFactory(Converter.Factory factory); RetrofitBuilder addInterceptor(); Retrofit build(); }### Answer:
@Test public void testRetrofitBuilder() { assertNotNull(retrofit); assertEquals(TEST_URL, retrofit.baseUrl().toString()); boolean inside = false; for (Converter.Factory currFactory : retrofit.converterFactories()) { if (factory == currFactory) inside = true; } assertTrue(inside); }
|
### Question:
APIUtils { public static API serverAPI() { return serverAPI; } static API serverAPI(); static void setServerAPI(API api); }### Answer:
@Test public void testServerAPI() { API api = APIUtils.serverAPI(); assertNotNull(api); }
|
### Question:
APIUtils { public static void setServerAPI(API api) { serverAPI = api; } static API serverAPI(); static void setServerAPI(API api); }### Answer:
@Test public void testSetServerAPI() { API newAPI = new RetrofitBuilder().baseUrl("http: APIUtils.setServerAPI(newAPI); assertTrue(newAPI == APIUtils.serverAPI()); }
|
### Question:
FeedRow { public static String toYearFormat(int startYear, int endYear) { return String.format("%d/%d", startYear, endYear); } FeedRow(); FeedRow(String imageUrl,
String title,
String description,
String location,
String year,
List<String> tagList,
String favoriteCount,
boolean isFavorite,
String creatorUsername); static String toYearFormat(int startYear, int endYear); static int[] fromYearFormat(String yearFormat); String getImageUrl(); void setImageUrl(String imageUrl); String getTitle(); void setTitle(String title); String getDescription(); void setDescription(String description); String getLocation(); void setLocation(String location); String getYear(); void setYear(String year); void setTagList(List<String> tagList); List<String> getTagList(); String getFavoriteCount(); void setFavoriteCount(String favoriteCount); String getCreatorUsername(); void setCreatorUsername(String creatorUsername); boolean isFavorite(); void setFavorite(boolean favorite); }### Answer:
@Test public void testToYearFormat() { int firstYear = 0; int secondYear = 0; assertEquals(FeedRow.toYearFormat(firstYear, secondYear), "0/0"); firstYear = -5; secondYear = -30; assertEquals(FeedRow.toYearFormat(firstYear, secondYear), "-5/-30"); firstYear = 2000; secondYear = -30; assertEquals(FeedRow.toYearFormat(firstYear, secondYear), "2000/-30"); }
|
### Question:
FeedRow { public static int[] fromYearFormat(String yearFormat) { String[] parts = yearFormat.split("/"); if (parts.length != 2) { throw new IllegalArgumentException("Given string is not in expected format: " + yearFormat); } int[] intParts = {Integer.parseInt(parts[0]), Integer.parseInt(parts[1])}; return intParts; } FeedRow(); FeedRow(String imageUrl,
String title,
String description,
String location,
String year,
List<String> tagList,
String favoriteCount,
boolean isFavorite,
String creatorUsername); static String toYearFormat(int startYear, int endYear); static int[] fromYearFormat(String yearFormat); String getImageUrl(); void setImageUrl(String imageUrl); String getTitle(); void setTitle(String title); String getDescription(); void setDescription(String description); String getLocation(); void setLocation(String location); String getYear(); void setYear(String year); void setTagList(List<String> tagList); List<String> getTagList(); String getFavoriteCount(); void setFavoriteCount(String favoriteCount); String getCreatorUsername(); void setCreatorUsername(String creatorUsername); boolean isFavorite(); void setFavorite(boolean favorite); }### Answer:
@Test public void testFromYearFormat() { String year = "-30/2000"; int[] yearPair = {-30, 2000}; assertArrayEquals(yearPair, FeedRow.fromYearFormat(year)); year = "0/0"; yearPair = new int[]{0, 0}; assertArrayEquals(yearPair, FeedRow.fromYearFormat(year)); thrown.expect(IllegalArgumentException.class); year = "5/4/"; FeedRow.fromYearFormat(year); year = "205-2077"; FeedRow.fromYearFormat(year); }
|
### Question:
DateUtils { public static int[] fromStandardDate(String standardDate) { int[] parts = new int[3]; String[] sParts = standardDate.split("-"); for (int i = 0; i < sParts.length; ++i) { parts[i] = Integer.parseInt(sParts[i]); } return parts; } static String toStandardDate(int year, int month, int day); static int[] fromStandardDate(String standardDate); }### Answer:
@Test public void testFromStandardDate() { String date = "2013-05-01"; int[] expected = new int[]{2013, 5, 1}; int[] actual = DateUtils.fromStandardDate(date); assertArrayEquals(expected, actual); date = "2013-11-12"; expected = new int[]{2013, 11, 12}; actual = DateUtils.fromStandardDate(date); assertArrayEquals(expected, actual); date = "1990-05-30"; expected = new int[]{1990, 5, 30}; actual = DateUtils.fromStandardDate(date); assertArrayEquals(expected, actual); date = "1990-11-01"; expected = new int[]{1990, 11, 1}; actual = DateUtils.fromStandardDate(date); assertArrayEquals(expected, actual); }
|
### Question:
Utils { public static String tokenToAuthString(String token) { return "JWT " + token; } static String tokenToAuthString(String token); static void showToast(Context context, String errorMessage); static SharedPreferences.Editor getSharedPrefEditor(Context context); static SharedPreferences getSharedPref(Context context); static void logout(Context context); static Uri getNewImageUri(Context context); static boolean isLocalUrl(String url); static boolean isClose(double a, double b); static boolean objectEquals(Object a, Object b); static double roundToDecimals(double num, int precision); static boolean isValidYear(String s); static String yearString(int year); }### Answer:
@Test public void testTokenToAuthString() { String token = ""; assertEquals("JWT " + token, Utils.tokenToAuthString(token)); token = "aoesnutda"; assertEquals("JWT " + token, Utils.tokenToAuthString(token)); }
|
### Question:
Utils { public static boolean isLocalUrl(String url) { return url.startsWith("content: } static String tokenToAuthString(String token); static void showToast(Context context, String errorMessage); static SharedPreferences.Editor getSharedPrefEditor(Context context); static SharedPreferences getSharedPref(Context context); static void logout(Context context); static Uri getNewImageUri(Context context); static boolean isLocalUrl(String url); static boolean isClose(double a, double b); static boolean objectEquals(Object a, Object b); static double roundToDecimals(double num, int precision); static boolean isValidYear(String s); static String yearString(int year); }### Answer:
@Test public void testIsLocalUrl() { String url = "http: assertFalse(Utils.isLocalUrl(url)); url = ""; assertFalse(Utils.isLocalUrl(url)); url = "content: assertTrue(Utils.isLocalUrl(url)); url = "content:"; assertFalse(Utils.isLocalUrl(url)); }
|
### Question:
Utils { public static boolean isClose(double a, double b) { return Math.abs(a - b) <= Constants.DOUBLE_EQUALITY_EPSILON; } static String tokenToAuthString(String token); static void showToast(Context context, String errorMessage); static SharedPreferences.Editor getSharedPrefEditor(Context context); static SharedPreferences getSharedPref(Context context); static void logout(Context context); static Uri getNewImageUri(Context context); static boolean isLocalUrl(String url); static boolean isClose(double a, double b); static boolean objectEquals(Object a, Object b); static double roundToDecimals(double num, int precision); static boolean isValidYear(String s); static String yearString(int year); }### Answer:
@Test public void testIsClose() { double a = 5; double b = 6; assertFalse(Utils.isClose(a, b)); a = b; assertTrue(Utils.isClose(a, b)); double remainingPrecision = 1e-14/Constants.DOUBLE_EQUALITY_EPSILON; a = b + (1 - remainingPrecision)*Constants.DOUBLE_EQUALITY_EPSILON; assertTrue(Utils.isClose(a, b)); a = b - (1 - remainingPrecision)*Constants.DOUBLE_EQUALITY_EPSILON; assertTrue(Utils.isClose(a, b)); a = b + (1 + remainingPrecision)*Constants.DOUBLE_EQUALITY_EPSILON; assertFalse(Utils.isClose(a, b)); a = b - (1 + remainingPrecision)*Constants.DOUBLE_EQUALITY_EPSILON; assertFalse(Utils.isClose(a, b)); }
|
### Question:
Utils { public static boolean objectEquals(Object a, Object b) { if (a == null && b != null) { return false; } else if (a != null && b == null) { return false; } else if (a != null && b != null) { return a.equals(b); } return true; } static String tokenToAuthString(String token); static void showToast(Context context, String errorMessage); static SharedPreferences.Editor getSharedPrefEditor(Context context); static SharedPreferences getSharedPref(Context context); static void logout(Context context); static Uri getNewImageUri(Context context); static boolean isLocalUrl(String url); static boolean isClose(double a, double b); static boolean objectEquals(Object a, Object b); static double roundToDecimals(double num, int precision); static boolean isValidYear(String s); static String yearString(int year); }### Answer:
@Test public void testObjectEquals() { Integer a = null; Integer b = new Integer(5); assertFalse(Utils.objectEquals(a, b)); assertTrue(Utils.objectEquals(a, null)); a = new Integer(6); assertFalse(Utils.objectEquals(a, b)); a = new Integer(b.intValue()); assertTrue(Utils.objectEquals(a, b)); }
|
### Question:
Utils { public static double roundToDecimals(double num, int precision) { if (precision < 0 || precision > 8) { throw new IllegalArgumentException("Precision must be an int from 0 to 8."); } long multiplier = (long)Math.pow(10, (double)precision); return ((int)(num*multiplier))/(double)multiplier; } static String tokenToAuthString(String token); static void showToast(Context context, String errorMessage); static SharedPreferences.Editor getSharedPrefEditor(Context context); static SharedPreferences getSharedPref(Context context); static void logout(Context context); static Uri getNewImageUri(Context context); static boolean isLocalUrl(String url); static boolean isClose(double a, double b); static boolean objectEquals(Object a, Object b); static double roundToDecimals(double num, int precision); static boolean isValidYear(String s); static String yearString(int year); }### Answer:
@Test public void testRoundToDecimals() { double a = 3; assertTrue(Utils.isClose(a, Utils.roundToDecimals(a, 0))); assertTrue(Utils.isClose(a, Utils.roundToDecimals(a, 1))); a = 3.00001; assertTrue(Utils.isClose(3, Utils.roundToDecimals(a, 4))); assertFalse(Utils.isClose(3, Utils.roundToDecimals(a, 5))); a = 3.14723; assertTrue(Utils.isClose(3.14, Utils.roundToDecimals(a, 2))); assertFalse(Utils.isClose(3.14, Utils.roundToDecimals(a, 3))); assertTrue(Utils.isClose(a, Utils.roundToDecimals(a, 8))); thrown.expect(IllegalArgumentException.class); Utils.roundToDecimals(a, -1); Utils.roundToDecimals(a, 9); }
|
### Question:
Utils { public static boolean isValidYear(String s) { int year = 0; try { year = Integer.parseInt(s); } catch (NumberFormatException e) { return false; } return year >= Constants.MIN_YEAR && year <= Constants.MAX_YEAR; } static String tokenToAuthString(String token); static void showToast(Context context, String errorMessage); static SharedPreferences.Editor getSharedPrefEditor(Context context); static SharedPreferences getSharedPref(Context context); static void logout(Context context); static Uri getNewImageUri(Context context); static boolean isLocalUrl(String url); static boolean isClose(double a, double b); static boolean objectEquals(Object a, Object b); static double roundToDecimals(double num, int precision); static boolean isValidYear(String s); static String yearString(int year); }### Answer:
@Test public void testIsValidYear() { String s = ""; assertFalse(Utils.isValidYear(s)); s = "what"; assertFalse(Utils.isValidYear(s)); s = "" + (Constants.MIN_YEAR - 1); assertFalse(Utils.isValidYear(s)); s = "" + (Constants.MAX_YEAR + 1); assertFalse(Utils.isValidYear(s)); s = "" + (Constants.MIN_YEAR + Constants.MAX_YEAR)/2; assertTrue(Utils.isValidYear(s)); }
|
### Question:
Comment implements Serializable { @Override public boolean equals(Object obj) { if (!(obj instanceof Comment)) { return false; } Comment other = (Comment)obj; return Utils.objectEquals(this.user, other.user) && Utils.objectEquals(this.text, other.text) && Utils.objectEquals(this.createTime, other.createTime) && Utils.objectEquals(this.updateTime, other.updateTime) && Utils.objectEquals(this.itemKey, other.itemKey); } String getUser(); void setUser(String user); String getText(); void setText(String text); String getCreateTime(); void setCreateTime(String createTime); String getUpdateTime(); void setUpdateTime(String updateTime); String getItemKey(); void setItemKey(String itemKey); CommentRow toCommentRow(); UserInfo getUserInfo(); void setUserInfo(UserInfo userInfo); @Override boolean equals(Object obj); }### Answer:
@Test public void testEquals() { Comment c1 = null; Comment c2 = null; assertEquals(c1, c2); c1 = new Comment(); assertNotEquals(c1, c2); c2 = new Comment(); assertEquals(c1, c2); c1.setText("comment1"); assertNotEquals(c1, c2); c2.setText(c1.getText()); assertEquals(c1, c2); c1.setUser("user1"); assertNotEquals(c1, c2); c2.setUser(c1.getUser()); assertEquals(c1, c2); }
|
### Question:
Image implements Serializable { @Override public boolean equals(Object obj) { if (!(obj instanceof Image)) { return false; } Image other = (Image)obj; return Utils.objectEquals(this.url, other.url); } boolean isMain(); void setMain(boolean main); String getUrl(); void setUrl(String url); ImageRow toImageRow(); @Override boolean equals(Object obj); }### Answer:
@Test public void testEquals() { Image img1 = null; Image img2 = null; assertEquals(img1, img2); img1 = new Image(); assertNotEquals(img1, img2); img2 = new Image(); assertEquals(img1, img2); img1.setUrl("url1"); assertNotEquals(img1, img2); img2.setUrl(img1.getUrl()); assertEquals(img1, img2); }
|
### Question:
UDPHeader implements TransportHeader { @Override public UDPHeader copyTo(ByteBuffer target) { raw.rewind(); ByteBuffer slice = Binary.slice(target, target.position(), getHeaderLength()); target.put(raw); return new UDPHeader(slice); } UDPHeader(ByteBuffer raw); @Override int getSourcePort(); @Override int getDestinationPort(); @Override void setSourcePort(int sourcePort); @Override void setDestinationPort(int destinationPort); @Override int getHeaderLength(); @Override void setPayloadLength(int payloadLength); @Override ByteBuffer getRaw(); @Override UDPHeader copyTo(ByteBuffer target); @Override void computeChecksum(IPv4Header ipv4Header, ByteBuffer payload); }### Answer:
@Test public void testCopyTo() { ByteBuffer buffer = createMockHeaders(); UDPHeader header = new UDPHeader(buffer); ByteBuffer target = ByteBuffer.allocate(32); target.position(12); UDPHeader copy = header.copyTo(target); copy.setSourcePort(9999); Assert.assertEquals(20, target.position()); Assert.assertEquals("Header must modify target", 9999, target.getShort(12)); Assert.assertEquals("Header must not modify buffer", 1234, buffer.getShort(0)); }
|
### Question:
TCPHeader implements TransportHeader { @Override public TCPHeader copyTo(ByteBuffer target) { raw.rewind(); ByteBuffer slice = Binary.slice(target, target.position(), getHeaderLength()); target.put(raw); return new TCPHeader(slice); } TCPHeader(ByteBuffer raw); int getWindow(); @Override int getSourcePort(); @Override int getDestinationPort(); @Override void setSourcePort(int sourcePort); @Override void setDestinationPort(int destinationPort); int getSequenceNumber(); void setSequenceNumber(int sequenceNumber); int getAcknowledgementNumber(); void setAcknowledgementNumber(int acknowledgementNumber); @Override int getHeaderLength(); @Override void setPayloadLength(int payloadLength); int getFlags(); void setFlags(int flags); void shrinkOptions(); boolean isFin(); boolean isSyn(); boolean isRst(); boolean isPsh(); boolean isAck(); boolean isUrg(); @Override ByteBuffer getRaw(); @Override TCPHeader copyTo(ByteBuffer target); TCPHeader copy(); @Override void computeChecksum(IPv4Header ipv4Header, ByteBuffer payload); short getChecksum(); static final int FLAG_FIN; static final int FLAG_SYN; static final int FLAG_RST; static final int FLAG_PSH; static final int FLAG_ACK; static final int FLAG_URG; }### Answer:
@Test public void testCopyTo() { ByteBuffer buffer = createMockTCPHeader(); TCPHeader header = new TCPHeader(buffer); ByteBuffer target = ByteBuffer.allocate(40); target.position(12); TCPHeader copy = header.copyTo(target); copy.setSourcePort(9999); Assert.assertEquals(32, target.position()); Assert.assertEquals("Header must modify target", 9999, target.getShort(12)); Assert.assertEquals("Header must not modify buffer", 0x1234, buffer.getShort(0)); }
|
### Question:
AdbMonitor { static String readPacket(ByteBuffer input) { if (input.remaining() < LENGTH_FIELD_SIZE) { return null; } input.get(BUFFER, 0, LENGTH_FIELD_SIZE); int length = parseLength(BUFFER); if (length > BUFFER.length) { throw new IllegalArgumentException("Packet size should not be that big: " + length); } if (input.remaining() < length) { input.rewind(); return null; } input.get(BUFFER, 0, length); return new String(BUFFER, 0, length, StandardCharsets.UTF_8); } AdbMonitor(AdbDevicesCallback callback); void monitor(); }### Answer:
@Test public void testReadValidPacket() { String data = "00180123456789ABCDEF\tdevice\n"; String result = AdbMonitor.readPacket(toByteBuffer(data)); Assert.assertEquals("0123456789ABCDEF\tdevice\n", result); }
@Test public void testReadValidPackets() { String data = "00300123456789ABCDEF\tdevice\nFEDCBA9876543210\tdevice\n"; String result = AdbMonitor.readPacket(toByteBuffer(data)); Assert.assertEquals("0123456789ABCDEF\tdevice\nFEDCBA9876543210\tdevice\n", result); }
@Test public void testReadValidPacketWithGarbage() { String data = "00180123456789ABCDEF\tdevice\ngarbage"; String result = AdbMonitor.readPacket(toByteBuffer(data)); Assert.assertEquals("0123456789ABCDEF\tdevice\n", result); }
@Test public void testReadShortPacket() { String data = "00180123456789ABCDEF\tdevi"; String result = AdbMonitor.readPacket(toByteBuffer(data)); Assert.assertNull(result); }
|
### Question:
IPv4Header { public static int readVersion(ByteBuffer buffer) { if (buffer.limit() == 0) { return -1; } byte versionAndIHL = buffer.get(0); return (versionAndIHL & 0xf0) >> 4; } IPv4Header(ByteBuffer raw); boolean isSupported(); Protocol getProtocol(); int getHeaderLength(); int getTotalLength(); void setTotalLength(int totalLength); int getSource(); int getDestination(); void setSource(int source); void setDestination(int destination); void swapSourceAndDestination(); ByteBuffer getRaw(); IPv4Header copyTo(ByteBuffer target); IPv4Header copy(); void computeChecksum(); short getChecksum(); static int readVersion(ByteBuffer buffer); static int readLength(ByteBuffer buffer); }### Answer:
@Test public void testReadIPVersionUnavailable() { ByteBuffer buffer = ByteBuffer.allocate(20); buffer.flip(); int firstPacketVersion = IPv4Header.readVersion(buffer); Assert.assertEquals("IPv4 packet version must be unknown", -1, firstPacketVersion); }
@Test public void testReadIPVersionAvailable() { ByteBuffer buffer = ByteBuffer.allocate(20); byte versionAndIHL = (4 << 4) | 5; buffer.put(versionAndIHL); buffer.flip(); int firstPacketVersion = IPv4Header.readVersion(buffer); Assert.assertEquals("Wrong IP version field value", 4, firstPacketVersion); }
|
### Question:
IPv4Header { public static int readLength(ByteBuffer buffer) { if (buffer.limit() < 4) { return -1; } return Short.toUnsignedInt(buffer.getShort(2)); } IPv4Header(ByteBuffer raw); boolean isSupported(); Protocol getProtocol(); int getHeaderLength(); int getTotalLength(); void setTotalLength(int totalLength); int getSource(); int getDestination(); void setSource(int source); void setDestination(int destination); void swapSourceAndDestination(); ByteBuffer getRaw(); IPv4Header copyTo(ByteBuffer target); IPv4Header copy(); void computeChecksum(); short getChecksum(); static int readVersion(ByteBuffer buffer); static int readLength(ByteBuffer buffer); }### Answer:
@Test public void testReadLengthUnavailable() { ByteBuffer buffer = ByteBuffer.allocate(20); buffer.flip(); int firstPacketLength = IPv4Header.readLength(buffer); Assert.assertEquals("IPv4 packet length must be unknown", -1, firstPacketLength); }
@Test public void testReadLengthAvailable() { ByteBuffer buffer = ByteBuffer.allocate(20); buffer.put(2, (byte) 0x01); buffer.put(3, (byte) 0x23); buffer.position(20); buffer.flip(); int firstPacketLength = IPv4Header.readLength(buffer); Assert.assertEquals("Wrong IP length field value", 0x123, firstPacketLength); }
|
### Question:
IPv4Packet { public ByteBuffer getPayload() { int headersLength = ipv4Header.getHeaderLength() + transportHeader.getHeaderLength(); raw.position(headersLength); return raw.slice(); } IPv4Packet(ByteBuffer raw); boolean isValid(); IPv4Header getIpv4Header(); TransportHeader getTransportHeader(); void swapSourceAndDestination(); ByteBuffer getRaw(); int getRawLength(); ByteBuffer getPayload(); int getPayloadLength(); void computeChecksums(); @SuppressWarnings("checkstyle:MagicNumber")
static final int MAX_PACKET_LENGTH; }### Answer:
@Test public void testPayload() { ByteBuffer buffer = createMockPacket(); IPv4Packet packet = new IPv4Packet(buffer); ByteBuffer payload = packet.getPayload(); Assert.assertEquals(0x11223344, payload.getInt(0)); }
|
### Question:
AlternativeUriNavigator { @Deprecated public boolean hasAlternativeUris(String uri) { String canonicalURI = uriMapping.getCanonicalURI(uri); List<String> alternativeURIs = getAlternativeUriMap().get(canonicalURI); return alternativeURIs != null && alternativeURIs.size() > 1; } AlternativeUriNavigator(UriMappingIterable uriMapping); @Deprecated List<String> listAlternativeUris(String uri); List<URI> listAlternativeUris(URI uri); @Deprecated boolean hasAlternativeUris(String uri); boolean hasAlternativeUris(URI uri); }### Answer:
@Test public void hasAlternativeUrisWorksCorrectly() throws Exception { UriMappingIterableImpl uriMapping = new UriMappingIterableImpl(ImmutableSet.of( "http: "http: "http: )); uriMapping.addLink("http: uriMapping.addLink("http: uriMapping.addLink("http: uriMapping.addLink("http: uriMapping.addLink("http: Set<String> setA = ImmutableSet.of("http: Set<String> setB = ImmutableSet.of("http: Set<String> setC = ImmutableSet.of("http: Set<String> setD = ImmutableSet.of("http: AlternativeUriNavigator alternativeURINavigator = new AlternativeUriNavigator(uriMapping); assertThat(alternativeURINavigator.hasAlternativeUris("http: assertThat(alternativeURINavigator.hasAlternativeUris("http: assertThat(alternativeURINavigator.hasAlternativeUris("http: assertThat(alternativeURINavigator.hasAlternativeUris("http: assertThat(alternativeURINavigator.hasAlternativeUris("http: assertThat(alternativeURINavigator.hasAlternativeUris("http: assertThat(alternativeURINavigator.hasAlternativeUris("http: }
|
### Question:
LDFusionToolUtils { public static <E extends Exception> void closeQuietly(Closeable<E> resource) { if (resource != null) { try { resource.close(); } catch (Exception ignore) { } } } private LDFusionToolUtils(); static String humanReadableSize(long byteCount); static String formatTime(long timeInMs); static File ensureParentsExists(File file); static String getVirtuosoConnectionString(String host, String port); static RDFFormat getSesameSerializationFormat(String serializationFormat, String fileName); static File createTempFile(File directory, String filePrefix); static void closeQuietly(Closeable<E> resource); static Set<URI> getResourceDescriptionProperties(ConfigConflictResolution config); static String buildPrefixDecl(Map<String, String> prefixes); static final int KB_BYTES; static final long MB_BYTES; static final long GB_BYTES; }### Answer:
@Test public void closeQuietlyClosesResourceAndSwallowsException() throws Exception { Closeable<Exception> closeable = mock(Closeable.class); Mockito.doThrow(new Exception("test exception")).when(closeable).close(); LDFusionToolUtils.closeQuietly(closeable); Mockito.verify(closeable).close(); }
@Test public void closeQuietlyDoesNotThrowForNullResource() throws Exception { LDFusionToolUtils.closeQuietly(null); }
|
### Question:
CloseableRepositoryConnection implements AutoCloseable { @Override public void close() throws RepositoryException { connection.close(); } CloseableRepositoryConnection(RepositoryConnection connection); RepositoryConnection get(); @Override void close(); void closeQuietly(); }### Answer:
@Test public void closesConnection() throws Exception { RepositoryConnection connection = mock(RepositoryConnection.class); CloseableRepositoryConnection closeableRepositoryConnection = new CloseableRepositoryConnection(connection); closeableRepositoryConnection.close(); verify(connection).close(); }
|
### Question:
ClusterIterator implements Iterator<List<T>> { @Override public boolean hasNext() { return hasNextElement(); } @SuppressWarnings("unchecked") ClusterIterator(List<T> elements, Comparator<T> comparator); @Override boolean hasNext(); @Override List<T> next(); @Override void remove(); }### Answer:
@Test public void iteratesOverEmptyCollection() throws Exception { List<String> elements = Collections.emptyList(); ClusterIterator<String> clusterIterator = new ClusterIterator<String>(elements, String.CASE_INSENSITIVE_ORDER); assertThat(clusterIterator.hasNext(), is(false)); }
|
### Question:
ParamReader { public String getStringValue(String paramName) { return params.get(paramName); } ParamReader(Map<String, String> params, String parametrizedObjectLabel); String getLabel(); String getRequiredStringValue(String paramName); String getStringValue(String paramName); String getStringValue(String paramName, String defaultValue); Integer getRequiredIntValue(String paramName); Integer getIntValue(String paramName); int getIntValue(String paramName, int defaultValue); Long getRequiredLongValue(String paramName); Long getLongValue(String paramName); long getLongValue(String paramName, long defaultValue); }### Answer:
@Test public void returnsStringValueWhenStringParamPresent() throws Exception { Map<String, String> params = newHashMap(); params.put("key1", "value1"); params.put("key2", "value2"); ParamReader paramReader = new ParamReader(params, "object"); String result = paramReader.getStringValue("key1"); assertThat(result, equalTo("value1")); }
@Test() public void returnsNullWhenNonRequiredStringParamMissing() throws Exception { Map<String, String> params = newHashMap(); params.put("key2", "value2"); ParamReader paramReader = new ParamReader(params, "object"); String result = paramReader.getStringValue("key1"); assertThat(result, nullValue()); }
@Test public void returnsStringValueWhenStringParamPresentAndDefaultGiven() throws Exception { Map<String, String> params = newHashMap(); params.put("key1", "value1"); params.put("key2", "value2"); ParamReader paramReader = new ParamReader(params, "object"); String result = paramReader.getStringValue("key1", "default"); assertThat(result, equalTo("value1")); }
@Test public void returnsDefaultValueWhenStringParamNotPresentAndDefaultGiven() throws Exception { Map<String, String> params = newHashMap(); params.put("key2", "value2"); ParamReader paramReader = new ParamReader(params, "object"); String result = paramReader.getStringValue("key1", "default"); assertThat(result, equalTo("default")); }
|
### Question:
ParamReader { public String getRequiredStringValue(String paramName) throws LDFusionToolException { return getRequiredValue(paramName); } ParamReader(Map<String, String> params, String parametrizedObjectLabel); String getLabel(); String getRequiredStringValue(String paramName); String getStringValue(String paramName); String getStringValue(String paramName, String defaultValue); Integer getRequiredIntValue(String paramName); Integer getIntValue(String paramName); int getIntValue(String paramName, int defaultValue); Long getRequiredLongValue(String paramName); Long getLongValue(String paramName); long getLongValue(String paramName, long defaultValue); }### Answer:
@Test(expected = LDFusionToolException.class) public void throwsWhenRequiredStringParamMissing() throws Exception { Map<String, String> params = newHashMap(); params.put("key2", "value2"); ParamReader paramReader = new ParamReader(params, "object"); paramReader.getRequiredStringValue("key1"); }
@Test(expected = LDFusionToolException.class) public void throwsWhenRequiredStringParamEmpty() throws Exception { Map<String, String> params = newHashMap(); params.put("key1", ""); ParamReader paramReader = new ParamReader(params, "object"); paramReader.getRequiredStringValue("key1"); }
|
### Question:
ParamReader { public Integer getRequiredIntValue(String paramName) throws LDFusionToolException { String value = getRequiredValue(paramName); try { return Integer.parseInt(value); } catch (NumberFormatException e) { throw new LDFusionToolException(getNumberFormatErrorMessage(paramName, value)); } } ParamReader(Map<String, String> params, String parametrizedObjectLabel); String getLabel(); String getRequiredStringValue(String paramName); String getStringValue(String paramName); String getStringValue(String paramName, String defaultValue); Integer getRequiredIntValue(String paramName); Integer getIntValue(String paramName); int getIntValue(String paramName, int defaultValue); Long getRequiredLongValue(String paramName); Long getLongValue(String paramName); long getLongValue(String paramName, long defaultValue); }### Answer:
@Test(expected = LDFusionToolException.class) public void throwsWhenRequiredIntParamMissing() throws Exception { Map<String, String> params = newHashMap(); params.put("key2", "value2"); ParamReader paramReader = new ParamReader(params, "object"); paramReader.getRequiredIntValue("key1"); }
@Test(expected = LDFusionToolException.class) public void throwsWhenRequiredIntParamMalformed() throws Exception { Map<String, String> params = newHashMap(); params.put("key1", "123s4"); params.put("key2", "value2"); ParamReader paramReader = new ParamReader(params, "object"); paramReader.getRequiredIntValue("key1"); }
|
### Question:
ParamReader { public Long getRequiredLongValue(String paramName) throws LDFusionToolException { String value = getRequiredValue(paramName); try { return Long.parseLong(value); } catch (NumberFormatException e) { throw new LDFusionToolException(getNumberFormatErrorMessage(paramName, value)); } } ParamReader(Map<String, String> params, String parametrizedObjectLabel); String getLabel(); String getRequiredStringValue(String paramName); String getStringValue(String paramName); String getStringValue(String paramName, String defaultValue); Integer getRequiredIntValue(String paramName); Integer getIntValue(String paramName); int getIntValue(String paramName, int defaultValue); Long getRequiredLongValue(String paramName); Long getLongValue(String paramName); long getLongValue(String paramName, long defaultValue); }### Answer:
@Test(expected = LDFusionToolException.class) public void throwsWhenRequiredLongParamMissing() throws Exception { Map<String, String> params = newHashMap(); params.put("key2", "value2"); ParamReader paramReader = new ParamReader(params, "object"); paramReader.getRequiredLongValue("key1"); }
@Test(expected = LDFusionToolException.class) public void throwsWhenRequiredLongParamMalformed() throws Exception { Map<String, String> params = newHashMap(); params.put("key1", "123s4"); params.put("key2", "value2"); ParamReader paramReader = new ParamReader(params, "object"); paramReader.getRequiredLongValue("key1"); }
|
### Question:
CloseableRepository implements AutoCloseable { @Override public void close() throws RepositoryException { repository.shutDown(); } CloseableRepository(Repository repository); Repository get(); @Override void close(); }### Answer:
@Test public void shutsDownRepository() throws Exception { Repository repository = mock(Repository.class); CloseableRepository closeableRepository = new CloseableRepository(repository); closeableRepository.close(); verify(repository).shutDown(); }
|
### Question:
DeepLinkAnnotationCompiler extends AbstractProcessor { @Override public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { System.out.println("[FlowR]: generating deep Link Handler..."); MethodSpec.Builder constructorBuilder = generateConstructor(); for (Element element : roundEnv.getElementsAnnotatedWith(DeepLink.class)) { String[] value = element.getAnnotation(DeepLink.class).value(); for (String url : value) { constructorBuilder.addStatement(deeplinkFormat, url, ClassName.get(element.asType())); } } for (Element element : roundEnv.getElementsAnnotatedWith(DeepLinkHandler.class)) { String packageName = processingEnv.getElementUtils().getPackageOf(element) .getQualifiedName().toString(); String className = element.getAnnotation(DeepLinkHandler.class).value(); if (className.isEmpty()) { className = element.getSimpleName().toString() + HANDLER_FILE_NAME_POST_FIX; } generateDeepLinkHandler(packageName, className, constructorBuilder); } return true; } @Override boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv); }### Answer:
@Test public void process() throws Exception { assertAbout(javaSources()) .that(Arrays.asList(TEST_DEEP_LINK_FRAGMENT, TEST_DEEP_LINK_HANDLER)) .processedWith(new DeepLinkAnnotationCompiler()) .compilesWithoutError() .and() .generatesSources(TEST_DEEP_GENERATED_HANDLER); }
|
### Question:
Form extends MultiValueMap<String, String> { public Form fromString(String s) { for (String param : s.split("&")) { String[] nv = param.split("=", 2); if (nv.length == 2) { try { add(URLDecoder.decode(nv[0], "UTF-8"), URLDecoder.decode(nv[1], "UTF-8")); } catch (UnsupportedEncodingException uee) { throw new IllegalStateException(uee); } } } return this; } Form(); Form fromString(String s); @Override String toString(); Form fromRequestQuery(Request request); void toRequestQuery(Request request); void appendRequestQuery(Request request); Form fromRequestEntity(Request request); void toRequestEntity(Request request); }### Answer:
@Test public void fromString() { Form f = new Form().fromString("x=%3D&y=z"); assertThat(f.get("x").get(0)).isEqualTo("="); assertThat(f.get("y").get(0)).isEqualTo("z"); }
|
### Question:
FieldMap implements FullMap<String, Object> { @Override public boolean containsKey(Object key) { return fields.containsKey(key); } FieldMap(); FieldMap(Object object); @Override Object get(Object key); @Override boolean containsKey(Object key); @Override int size(); @Override Set<String> keySet(); @Override Object put(String key, Object value); @Override Object remove(Object key); @Override void clear(); }### Answer:
@Test public void notContainsNonExistentField() { assertThat(map.containsKey("notField")).isFalse(); }
@Test public void containsField() { assertThat(map.containsKey("stringField")).isTrue(); }
@Test public void notContainsStaticField() { assertThat(map.containsKey("staticField")).isFalse(); }
@Test public void notContainsPrimitiveField() { assertThat(map.containsKey("primitiveField")).isFalse(); }
@Test public void notContainsPrivateField() { assertThat(map.containsKey("privateField")).isFalse(); }
|
### Question:
FieldMap implements FullMap<String, Object> { @Override public Object get(Object key) { try { return fields.get(key).get(object); } catch (IllegalAccessException iae) { throw new IllegalStateException(iae); } catch (NullPointerException npe) { } return null; } FieldMap(); FieldMap(Object object); @Override Object get(Object key); @Override boolean containsKey(Object key); @Override int size(); @Override Set<String> keySet(); @Override Object put(String key, Object value); @Override Object remove(Object key); @Override void clear(); }### Answer:
@Test public void booleanType() { assertThat(map.get("booleanField")).isInstanceOf(Boolean.class); }
@Test public void booleanFieldValue() { assertThat(map.get("booleanField")).isEqualTo(fields.booleanField); }
@Test public void stringFieldValue() { assertThat(map.get("stringField")).isEqualTo(fields.stringField); }
|
### Question:
URIUtil { public static URI create(String scheme, String rawUserInfo, String host, int port, String rawPath, String rawQuery, String rawFragment) throws URISyntaxException { StringBuilder sb = new StringBuilder(); if (scheme != null) { sb.append(scheme).append(':'); } if (host != null) { sb.append(" } if (rawUserInfo != null) { sb.append(rawUserInfo).append('@'); } if (host != null) { sb.append(host); if (port != -1) { sb.append(':').append(Integer.toString(port)); } } if (rawPath != null) { sb.append(rawPath); } if (rawQuery != null) { sb.append('?').append(rawQuery); } if (rawFragment != null) { sb.append("#").append(rawFragment); } return new URI(sb.toString()); } private URIUtil(); static URI create(String scheme, String rawUserInfo, String host, int port,
String rawPath, String rawQuery, String rawFragment); static URI rebase(URI uri, URI base); }### Answer:
@Test public void toURIandBack() throws URISyntaxException { URI u1 = URIUtil.create("a", "b", "c", 4, "/e%3D", "x=%3D", "g%3D"); URI u2 = URIUtil.create(u1.getScheme(), u1.getRawUserInfo(), u1.getHost(), u1.getPort(), u1.getRawPath(), u1.getRawQuery(), u1.getRawFragment()); assertThat(u1).isEqualTo(u2); }
@Test public void rawParams() throws URISyntaxException { URI uri = URIUtil.create("http", "user", "example.com", 80, "/raw%3Dpath", "x=%3D", "frag%3Dment"); assertThat(uri.toString()).isEqualTo("http: }
|
### Question:
URIUtil { public static URI rebase(URI uri, URI base) throws URISyntaxException { if (base == null) { return uri; } String scheme = base.getScheme(); String host = base.getHost(); int port = base.getPort(); if (scheme == null || host == null) { return uri; } return create(scheme, uri.getRawUserInfo(), host, port, uri.getRawPath(), uri.getRawQuery(), uri.getRawFragment()); } private URIUtil(); static URI create(String scheme, String rawUserInfo, String host, int port,
String rawPath, String rawQuery, String rawFragment); static URI rebase(URI uri, URI base); }### Answer:
@Test public void rebase() throws URISyntaxException { URI uri = new URI("https: URI base = new URI("http: URI rebased = URIUtil.rebase(uri, base); assertThat(rebased.toString()).isEqualTo("http: }
|
### Question:
BranchingStreamWrapper extends BranchingInputStream { @Override public int read() throws IOException { byte[] b = new byte[1]; return (read(b, 0, 1) > 0 ? (b[0] & 0xff) : -1); } BranchingStreamWrapper(InputStream in, Factory<Buffer> bufferFactory); @Override BranchingStreamWrapper branch(); @Override boolean isClosed(); @Override BranchingStreamWrapper getParent(); @Override int read(); @Override int read(byte[] b); @Override int read(byte[] b, int off, int len); @Override long skip(long n); @Override int available(); @Override void close(); @Override void closeBranches(); @Override void finalize(); }### Answer:
@Test public void noBranch_byteAtATime() throws IOException { for (int n = 0; n < BUFSIZE; n++) { assertThat(trunk.read()).isEqualTo(bytes[n] & 0xff); } assertThat(trunk.read()).isEqualTo(-1); }
@Test public void noBranch_allBytes() throws IOException { assertThat(trunk.read(buffers[0])).isEqualTo(BUFSIZE); assertThat(buffers[0]).isEqualTo(bytes); assertThat(trunk.read(buffers[0])).isEqualTo(-1); }
@Test public void noBranch_bytesLength() throws IOException { assertThat(trunk.read(buffers[0], 0, BUFSIZE)).isEqualTo(BUFSIZE); assertThat(buffers[0]).isEqualTo(bytes); assertThat(trunk.read(buffers[0], 0, BUFSIZE)).isEqualTo(-1); }
@Test public void noBranch_twoReads() throws IOException { int length1 = BUFSIZE / 2; int length2 = BUFSIZE - length1; assertThat(trunk.read(buffers[0], 0, length1)).isEqualTo(length1); assertThat(trunk.read(buffers[0], length1, length2)).isEqualTo(length2); assertThat(buffers[0]).isEqualTo(bytes); assertThat(trunk.read()).isEqualTo(-1); }
|
### Question:
Form extends MultiValueMap<String, String> { public Form fromRequestQuery(Request request) { String query = request.uri.getRawQuery(); if (query != null) { fromString(query); } return this; } Form(); Form fromString(String s); @Override String toString(); Form fromRequestQuery(Request request); void toRequestQuery(Request request); void appendRequestQuery(Request request); Form fromRequestEntity(Request request); void toRequestEntity(Request request); }### Answer:
@Test public void fromRequestQuery() throws URISyntaxException { Request request = new Request(); request.uri = new URI("http: Form f = new Form().fromRequestQuery(request); assertThat(f.get("x").get(0)).isEqualTo("="); assertThat(f.get("y").get(0)).isEqualTo("?"); assertThat(f.get("z").get(0)).isEqualTo("a"); }
|
### Question:
AssignmentFilter extends GenericFilter { private void eval(Binding binding, Exchange exchange) { if (binding.condition == null || Boolean.TRUE.equals(binding.condition.eval(exchange))) { binding.target.set(exchange, binding.value != null ? binding.value.eval(exchange) : null); } } @Override void filter(Exchange exchange, Handler next); final List<Binding> onRequest; final List<Binding> onResponse; }### Answer:
@Test public void onRequest() throws ExpressionException, HandlerException, IOException { AssignmentFilter filter = new AssignmentFilter(); AssignmentFilter.Binding binding = new AssignmentFilter.Binding(); binding.target = new Expression("${exchange.newAttr}"); binding.value = new Expression("${exchange.request.method}"); filter.onRequest.add(binding); Exchange exchange = new Exchange(); exchange.request = new Request(); exchange.request.method = "DELETE"; Chain chain = new Chain(); chain.filters.add(filter); StaticResponseHandler handler = new StaticResponseHandler(); handler.status = 200; chain.handler = handler; assertThat(binding.target.eval(exchange)).isNull(); chain.handle(exchange); assertThat(exchange.get("newAttr")).isEqualTo("DELETE"); }
@Test public void onResponse() throws ExpressionException, HandlerException, IOException { AssignmentFilter filter = new AssignmentFilter(); AssignmentFilter.Binding binding = new AssignmentFilter.Binding(); binding.target = new Expression("${exchange.newAttr}"); binding.value = new Expression("${exchange.response.status}"); filter.onResponse.add(binding); Exchange exchange = new Exchange(); Chain chain = new Chain(); chain.filters.add(filter); StaticResponseHandler handler = new StaticResponseHandler(); handler.status = 200; chain.handler = handler; assertThat(binding.target.eval(exchange)).isNull(); chain.handle(exchange); assertThat(exchange.get("newAttr")).isEqualTo(200); }
|
### Question:
StaticResponseHandler extends GenericHandler { @Override public void handle(Exchange exchange) throws HandlerException, IOException { LogTimer timer = logger.getTimer().start(); Response response = new Response(); response.status = this.status; response.reason = this.reason; if (response.reason == null) { response.reason = HttpUtil.getReason(response.status); } if (response.reason == null) { response.reason = "Uncertain"; } if (this.version != null) { response.version = this.version; } for (String key : this.headers.keySet()) { for (Expression expression : this.headers.get(key)) { String eval = expression.eval(exchange, String.class); if (eval != null) { response.headers.add(key, eval); } } } if (this.entity != null) { HttpUtil.toEntity(response, entity, null); } exchange.response = response; timer.stop(); } @Override void handle(Exchange exchange); public Integer status; public String reason; public String version; final MultiValueMap<String, Expression> headers; public String entity; }### Answer:
@Test public void redirect() throws ExpressionException, HandlerException, IOException { StaticResponseHandler handler = new StaticResponseHandler(); handler.status = 302; handler.reason = "Found"; handler.headers.add("Location", new Expression("http: Exchange exchange = new Exchange(); handler.handle(exchange); assertThat(exchange.response.status).isEqualTo(302); assertThat(exchange.response.reason).isEqualTo("Found"); assertThat(exchange.response.headers.getFirst("Location")).isEqualTo("http: }
|
### Question:
Expression { public Object eval(Object scope) { try { return valueExpression.getValue(new XLContext(scope)); } catch (ELException ele) { return null; } } Expression(String expression); Object eval(Object scope); @SuppressWarnings("unchecked") T eval(Object scope, Class<T> type); void set(Object scope, Object value); }### Answer:
@Test public void bool() throws ExpressionException { Expression expr = new Expression("${1==1}"); Object o = expr.eval(null); assertThat(o).isInstanceOf(Boolean.class); assertThat(o).isEqualTo(true); }
@Test public void empty() throws ExpressionException { Expression expr = new Expression("string-literal"); Object o = expr.eval(null); assertThat(o).isInstanceOf(String.class); assertThat(o).isEqualTo("string-literal"); }
@Test public void scope() throws ExpressionException { HashMap<String, String> scope = new HashMap<String, String>(); scope.put("a", "foo"); Expression expr = new Expression("${a}bar"); Object o = expr.eval(scope); assertThat(o).isInstanceOf(String.class); assertThat(o).isEqualTo("foobar"); }
@Test public void exchangeRequestHeader() throws ExpressionException { Exchange exchange = new Exchange(); exchange.request = new Request(); exchange.request.headers.putSingle("Host", "www.example.com"); Expression expr = new Expression("${exchange.request.headers['Host'][0]}"); String host = expr.eval(exchange, String.class); assertThat(host).isEqualTo("www.example.com"); }
|
### Question:
Form extends MultiValueMap<String, String> { public void toRequestQuery(Request request) { try { request.uri = URIUtil.create(request.uri.getScheme(), request.uri.getRawUserInfo(), request.uri.getHost(), request.uri.getPort(), request.uri.getRawPath(), toString(), request.uri.getRawFragment()); } catch (URISyntaxException use) { throw new IllegalArgumentException(use); } } Form(); Form fromString(String s); @Override String toString(); Form fromRequestQuery(Request request); void toRequestQuery(Request request); void appendRequestQuery(Request request); Form fromRequestEntity(Request request); void toRequestEntity(Request request); }### Answer:
@Test void toRequestQuery() throws URISyntaxException { Request request = new Request(); request.uri = new URI("http: Form f = new Form(); f.add("foo", "bar"); f.toRequestQuery(request); assertThat(f.get("x")).isNull(); assertThat(f.get("y")).isNull(); assertThat(f.get("z")).isNull(); assertThat(f.get("foo").get(0)).isEqualTo("bar"); assertThat(request.uri.toString()).isEqualTo("http: }
|
### Question:
Form extends MultiValueMap<String, String> { public void appendRequestQuery(Request request) { StringBuilder sb = new StringBuilder(); String uriQuery = request.uri.getRawQuery(); if (uriQuery != null && uriQuery.length() > 0) { sb.append(uriQuery); } String toAppend = toString(); if (toAppend != null && toAppend.length() > 0) { if (sb.length() > 0) { sb.append('&'); } sb.append(toAppend); } String newQuery = sb.toString(); if (newQuery.length() == 0) { newQuery = null; } try { request.uri = URIUtil.create(request.uri.getScheme(), request.uri.getRawUserInfo(), request.uri.getHost(), request.uri.getPort(), request.uri.getRawPath(), newQuery, request.uri.getRawFragment()); } catch (URISyntaxException use) { throw new IllegalArgumentException(use); } } Form(); Form fromString(String s); @Override String toString(); Form fromRequestQuery(Request request); void toRequestQuery(Request request); void appendRequestQuery(Request request); Form fromRequestEntity(Request request); void toRequestEntity(Request request); }### Answer:
@Test void appendRequestQuery() throws URISyntaxException { Request request = new Request(); request.uri = new URI("http: Form f = new Form(); f.add("foo", "bar"); f.appendRequestQuery(request); f.fromRequestQuery(request); assertThat(f.get("x").get(0)).isEqualTo("="); assertThat(f.get("y").get(0)).isEqualTo("?"); assertThat(f.get("z").get(0)).isEqualTo("a"); assertThat(f.get("foo").get(0)).isEqualTo("bar"); assertThat(request.uri.toString()).isEqualTo("http: }
|
### Question:
CaseInsensitiveMap extends MapDecorator<String, V> { @Override public V put(String key, V value) { V removed = remove(key); lc.put(key.toLowerCase(), key); super.put(key, value); return removed; } CaseInsensitiveMap(); CaseInsensitiveMap(Map<String, V> map); void sync(); @Override void clear(); @Override boolean containsKey(Object key); @Override V put(String key, V value); @Override void putAll(Map<? extends String, ? extends V> m); @Override V get(Object key); @Override V remove(Object key); }### Answer:
@Test public void upperPut_keyRetainsCase() { map.put(upper, value1); assertThat(map.keySet().iterator().next()).isEqualTo(upper); }
@Test public void lowerPut_keyRetainsCase() { map.put(lower, value1); assertThat(map.keySet().iterator().next()).isEqualTo(lower); }
|
### Question:
Consumer extends Relationship { public static Consumer by(Component consumer) { return new Consumer(consumer); } @JsonCreator Consumer(@JsonProperty("component") Component component); static Consumer by(Component consumer); @Override int hashCode(); @Override boolean equals(Object o); }### Answer:
@Test public void testToString() { String toString = Consumer.by(Component.of("wolverine", "xmen")).toString(); Assert.assertTrue(toString.contains("wolverine")); Assert.assertTrue(toString.contains("xmen")); }
@Test public void staticFactoryMethodShouldReturnSameResultAsConstructor() { Component a = TestHelper.componentA(); Consumer expected = new Consumer(a); Consumer actual = Consumer.by(a); Assert.assertEquals(expected, actual); }
|
### Question:
Node { public static Node of(Component component) { return Node.of(component, randomSize()); } static Node create(String id, String label); static Node of(Component component); static Node of(Component component, int size); static Node of(ComponentRelationships rel); @Override boolean equals(Object o); @Override int hashCode(); static int randomSize(); static int randomCoordinate(); }### Answer:
@Test public void nodeFromComponent() { Node node = Node.of(Component.of("apocalypse", "villain")); Assert.assertEquals("villain:apocalypse", node.getId()); Assert.assertEquals("villain:apocalypse", node.getLabel()); Assert.assertTrue(node.getSize() > 2); Assert.assertTrue(node.getX() >= 0); Assert.assertTrue(node.getY() >= 0); }
|
### Question:
Node { public static Node create(String id, String label) { return Node.create(id, label, randomCoordinate(), randomCoordinate(), randomSize()); } static Node create(String id, String label); static Node of(Component component); static Node of(Component component, int size); static Node of(ComponentRelationships rel); @Override boolean equals(Object o); @Override int hashCode(); static int randomSize(); static int randomCoordinate(); }### Answer:
@Test(expected = NullPointerException.class) public void nullIdShouldThrowNpe() { Node.create(null, "label", 1, 2, 3); }
@Test(expected = NullPointerException.class) public void nullLabelShouldThrowNpe() { Node.create("id", null, 1, 2, 3); }
@Test public void randomCoordinatesAndSize() { Node node = Node.create("id", "label"); Assert.assertTrue(node.getX() >= 0); Assert.assertTrue(node.getY() >= 0); Assert.assertTrue(node.getSize() > 0); }
|
### Question:
Edge { public static Edge from(Component component, Consumer consumer) { String to = component.asString().toLowerCase(); String from = consumer.getComponent().asString().toLowerCase(); return Edge.create(from + "-to-" + to, from, to); } static Edge to(Component component, Dependency dependency); static Edge from(Component component, Consumer consumer); }### Answer:
@Test public void consumerToComponent() { Edge actual = Edge.from(Component.of("phoenix", "superhero"), Consumer.by(Component.of("cyclop", "superhero"))); Edge expected = Edge.create("superhero:cyclop-to-superhero:phoenix", "superhero:cyclop", "superhero:phoenix"); Assert.assertEquals(expected, actual); }
|
### Question:
Edge { public static Edge to(Component component, Dependency dependency) { String from = component.asString().toLowerCase(); String to = dependency.getComponent().asString().toLowerCase(); return Edge.create(from + "-to-" + to, from, to); } static Edge to(Component component, Dependency dependency); static Edge from(Component component, Consumer consumer); }### Answer:
@Test public void componentToDependency() { Edge actual = Edge.to(Component.of("phoenix", "superhero"), Dependency.on(Component.of("xavier", "superhero"))); Edge expected = Edge.create("superhero:phoenix-to-superhero:xavier", "superhero:phoenix", "superhero:xavier"); Assert.assertEquals(expected, actual); }
|
### Question:
StaticSnitchRegistry implements SnitchRegistry { @Override public List<Snitch> getAll() { return new ArrayList<>(registry); } StaticSnitchRegistry(Snitch... snitches); StaticSnitchRegistry(Collection<Snitch> snitches); static SnitchRegistry of(Snitch... snitches); static SnitchRegistry of(Collection<Snitch> snitches); static List<Snitch> filterDuplicateLocations(Collection<Snitch> snitches); @Override List<Snitch> getAll(); }### Answer:
@Test public void getAll() { Snitch snitch1 = Mockito.mock(Snitch.class); Mockito.when(snitch1.getUri()).thenReturn(URI.create("fake: Snitch snitch2 = Mockito.mock(Snitch.class); Mockito.when(snitch2.getUri()).thenReturn(URI.create("fake: Snitch snitchDuplicate2 = Mockito.mock(Snitch.class); Mockito.when(snitchDuplicate2.getUri()).thenReturn(URI.create("fake: SnitchRegistry registry = StaticSnitchRegistry.of(snitch1, snitch2); List<Snitch> actual = registry.getAll(); List<Snitch> expected = new ArrayList<>(Arrays.asList(snitch1, snitch2)); Assert.assertEquals(expected, actual); }
|
### Question:
StaticSnitchRegistry implements SnitchRegistry { public static SnitchRegistry of(Snitch... snitches) { return new StaticSnitchRegistry(snitches); } StaticSnitchRegistry(Snitch... snitches); StaticSnitchRegistry(Collection<Snitch> snitches); static SnitchRegistry of(Snitch... snitches); static SnitchRegistry of(Collection<Snitch> snitches); static List<Snitch> filterDuplicateLocations(Collection<Snitch> snitches); @Override List<Snitch> getAll(); }### Answer:
@Test public void testToString() { String uri = "fake: Snitch fakeSnitch = StaticSnitch.of(URI.create(uri)); SnitchRegistry registry = StaticSnitchRegistry.of(fakeSnitch); Assert.assertTrue(registry.toString().contains(uri)); }
|
### Question:
ResolutionError { public static ResolutionError of(URI snitchUri, String message, Throwable cause) { return new ResolutionError(snitchUri, message, cause); } ResolutionError(URI snitchUri, String message, Throwable cause); static ResolutionError translate(SnitchingException e); static ResolutionError of(URI snitchUri, String message, Throwable cause); static ResolutionError of(URI snitchUri, String message); @Override int hashCode(); @Override boolean equals(Object obj); String getMessage(); URI getSnitchUri(); boolean hasCause(); @JsonIgnore Optional<Throwable> getCause(); Optional<String> getCauseStackTraceString(); }### Answer:
@Test public void testToString() { ResolutionError of = ResolutionError.of(SNITCH_URI, MESSAGE, new RuntimeException("whatever")); Assertions.assertThat(of.toString()).isNotEmpty(); }
|
### Question:
ResolutionError { static void closeQuietly(Closeable... closeables) { for (Closeable closeable : closeables) { try { closeable.close(); } catch (IOException e) { LOGGER.error("Error while closing writer after printing StackTrace", e); } } } ResolutionError(URI snitchUri, String message, Throwable cause); static ResolutionError translate(SnitchingException e); static ResolutionError of(URI snitchUri, String message, Throwable cause); static ResolutionError of(URI snitchUri, String message); @Override int hashCode(); @Override boolean equals(Object obj); String getMessage(); URI getSnitchUri(); boolean hasCause(); @JsonIgnore Optional<Throwable> getCause(); Optional<String> getCauseStackTraceString(); }### Answer:
@Test public void close() throws IOException { Closeable closeableMock = Mockito.mock(Closeable.class); Mockito.doThrow(Mockito.mock(IOException.class)).when(closeableMock).close(); ResolutionError.closeQuietly(closeableMock); }
|
### Question:
CompositeSnitchRegistry implements SnitchRegistry { @Override public List<Snitch> getAll() { return registries.stream() .map(SnitchRegistry::getAll) .flatMap(Collection::stream) .collect(Collectors.toList()); } CompositeSnitchRegistry(Collection<SnitchRegistry> registries); static SnitchRegistry of(SnitchRegistry... registries); static SnitchRegistry of(Collection<SnitchRegistry> registries); @Override List<Snitch> getAll(); }### Answer:
@Test public void getAll() { Snitch s1 = new StaticSnitch(URI.create("fake: Snitch s2 = new StaticSnitch(URI.create("fake: ArrayList<SnitchRegistry> registries = Lists.newArrayList(StaticSnitchRegistry.of(s1), StaticSnitchRegistry.of(s2)); SnitchRegistry composite = CompositeSnitchRegistry.of(registries); List<Snitch> expected = Arrays.asList(s1, s2); Assert.assertEquals(expected, composite.getAll()); }
|
### Question:
DefaultSystemService implements SystemService { @Override @CacheResult(cacheName = "io.cereebro.system") public System get() { return systemResolver.resolve(name, snitchRegistry); } DefaultSystemService(String name, SystemResolver systemResolver, SnitchRegistry snitchRegistry); @Override @CacheResult(cacheName = "io.cereebro.system") System get(); }### Answer:
@Test public void getSystem() { Mockito.when(systemResolver.resolve(NAME, snitchRegistry)).thenReturn(System.empty(NAME)); Assert.assertEquals(System.empty(NAME), service.get()); }
|
### Question:
SystemFragment { public static SystemFragment empty() { return new SystemFragment(new HashSet<>()); } @JsonCreator SystemFragment(@JsonProperty("componentRelationships") Set<ComponentRelationships> rels); static SystemFragment of(Set<ComponentRelationships> rels); static SystemFragment of(ComponentRelationships... rels); static SystemFragment empty(); @Override boolean equals(Object o); @Override int hashCode(); Set<ComponentRelationships> getComponentRelationships(); }### Answer:
@Test public void testToString() { Assert.assertNotNull(SystemFragment.empty().toString()); }
|
### Question:
SnitchingException extends RuntimeException { public URI getSnitchUri() { return snitchUri; } SnitchingException(URI snitch, String message, Throwable cause); SnitchingException(URI snitch, String message); SnitchingException(URI snitch, Throwable cause); URI getSnitchUri(); }### Answer:
@Test public void uriAndMessageConstructor() { URI uri = URI.create("fake: String message = "test"; SnitchingException e = new SnitchingException(uri, message); Assert.assertEquals(uri, e.getSnitchUri()); Assert.assertEquals(message, e.getMessage()); }
@Test public void throwableAndUriConstructor() { URI uri = URI.create("fake: Throwable cause = new RuntimeException("unit test"); SnitchingException e = new SnitchingException(uri, cause); Assert.assertEquals(uri, e.getSnitchUri()); Assert.assertEquals(cause, e.getCause()); }
|
### Question:
StaticSnitch implements Snitch { @Override public URI getUri() { return uri; } StaticSnitch(URI uri); StaticSnitch(URI uri, SystemFragment systemFragment); static Snitch of(URI uri); static Snitch of(URI uri, SystemFragment systemFragment); @Override int hashCode(); @Override boolean equals(Object obj); @Override URI getUri(); @Override SystemFragment snitch(); }### Answer:
@Test public void getLocation() { Assert.assertEquals(SNITCH_URI, snitch.getUri()); }
|
### Question:
StaticSnitch implements Snitch { @Override public SystemFragment snitch() { return systemFragment; } StaticSnitch(URI uri); StaticSnitch(URI uri, SystemFragment systemFragment); static Snitch of(URI uri); static Snitch of(URI uri, SystemFragment systemFragment); @Override int hashCode(); @Override boolean equals(Object obj); @Override URI getUri(); @Override SystemFragment snitch(); }### Answer:
@Test public void snitch() { SystemFragment actual = snitch.snitch(); Assert.assertEquals(SystemFragment.empty(), actual); }
|
### Question:
Dependency extends Relationship { public static Dependency on(Component component) { return new Dependency(component); } @JsonCreator Dependency(@JsonProperty("component") Component component); static Dependency on(Component component); Set<Relationship> asRelationshipSet(); @Override int hashCode(); @Override boolean equals(Object o); }### Answer:
@Test public void testToString() { String toString = Dependency.on(Component.of("storm", "xmen")).toString(); Assert.assertTrue(toString.contains("storm")); Assert.assertTrue(toString.contains("xmen")); }
@Test public void staticFactoryMethodShouldReturnSameAsConstructor() { Component b = TestHelper.componentB(); Dependency expected = new Dependency(b); Dependency actual = Dependency.on(b); Assert.assertEquals(expected, actual); }
|
### Question:
System { public static System of(String name, Collection<ComponentRelationships> rels) { return new System(name, rels); } System(String name, Collection<ComponentRelationships> rels, Collection<ResolutionError> errors); System(String name, Collection<ComponentRelationships> rels); static System of(String name, Collection<ComponentRelationships> rels); static System of(String name, Collection<ComponentRelationships> rels, Collection<ResolutionError> errors); static System of(String name, ComponentRelationships... rels); static System empty(String name); boolean hasErrors(); @Override boolean equals(Object o); @Override int hashCode(); String getName(); Set<ComponentRelationships> getComponentRelationships(); Set<ResolutionError> getErrors(); static SystemBuilder builder(); }### Answer:
@Test(expected = NullPointerException.class) public void constructorWithNullNameShouldThrowNullPointerException() { ComponentRelationships c = ComponentRelationships.of(TestHelper.componentA(), TestHelper.relationshipSetOfDependencyBAndConsumerC()); new System(null, new HashSet<>(Arrays.asList(c))); }
|
### Question:
Dependency extends Relationship { public Set<Relationship> asRelationshipSet() { return new HashSet<>(Arrays.asList(this)); } @JsonCreator Dependency(@JsonProperty("component") Component component); static Dependency on(Component component); Set<Relationship> asRelationshipSet(); @Override int hashCode(); @Override boolean equals(Object o); }### Answer:
@Test public void asRelationshipSet() { Dependency dependency = Dependency.on(Component.of("x", "y")); Set<Relationship> rels = dependency.asRelationshipSet(); Assertions.assertThat(rels).isEqualTo(new HashSet<>(Arrays.asList(dependency))); }
|
### Question:
FixedRelationshipDetector implements RelationshipDetector { @Override public Set<Relationship> detect() { return new HashSet<>(relationships); } FixedRelationshipDetector(Collection<Relationship> rels); @Override Set<Relationship> detect(); }### Answer:
@Test public void constructorShouldCopyCollection() { Dependency a = Dependency.on(TestHelper.componentA()); List<Relationship> originalCollection = new ArrayList<>(); originalCollection.add(a); FixedRelationshipDetector detector = new FixedRelationshipDetector(originalCollection); Dependency b = Dependency.on(TestHelper.componentB()); originalCollection.add(b); Set<Relationship> actual = detector.detect(); Set<Relationship> expected = new HashSet<>(); expected.add(a); Assert.assertEquals(expected, actual); }
|
### Question:
ComponentRelationships { public static Set<Dependency> filterDependencies(Collection<Relationship> relationships) { Objects.requireNonNull(relationships, "relationship collection required"); return relationships.stream() .filter(rel -> rel instanceof Dependency) .map(rel -> (Dependency) rel) .collect(Collectors.toSet()); } @JsonCreator ComponentRelationships(@JsonProperty("component") Component component,
@JsonProperty("dependencies") Set<Dependency> dependencies,
@JsonProperty("consumers") Set<Consumer> consumers); static ComponentRelationships of(Component component, Set<Dependency> dependencies,
Set<Consumer> consumers); static ComponentRelationships of(Component component, Collection<Relationship> relationships); static ComponentRelationships of(Component component, Relationship... relationships); static Set<Consumer> filterConsumers(Collection<Relationship> relationships); static Set<Dependency> filterDependencies(Collection<Relationship> relationships); boolean hasRelationships(); @Override int hashCode(); @Override boolean equals(Object o); Component getComponent(); Set<Dependency> getDependencies(); Set<Consumer> getConsumers(); @JsonIgnore Set<Relationship> getRelationships(); static ComponentRelationshipsBuilder builder(); }### Answer:
@Test public void filterDependenciesShouldReturnOnlyDependency() { Set<Dependency> actual = ComponentRelationships .filterDependencies(Arrays.asList(Dependency.on(dependencyComponent), Consumer.by(consumerComponent))); Assert.assertEquals(dependencies, actual); }
|
### Question:
ComponentRelationships { public static Set<Consumer> filterConsumers(Collection<Relationship> relationships) { Objects.requireNonNull(relationships, "relationship collection required"); return relationships.stream() .filter(rel -> rel instanceof Consumer) .map(rel -> (Consumer) rel) .collect(Collectors.toSet()); } @JsonCreator ComponentRelationships(@JsonProperty("component") Component component,
@JsonProperty("dependencies") Set<Dependency> dependencies,
@JsonProperty("consumers") Set<Consumer> consumers); static ComponentRelationships of(Component component, Set<Dependency> dependencies,
Set<Consumer> consumers); static ComponentRelationships of(Component component, Collection<Relationship> relationships); static ComponentRelationships of(Component component, Relationship... relationships); static Set<Consumer> filterConsumers(Collection<Relationship> relationships); static Set<Dependency> filterDependencies(Collection<Relationship> relationships); boolean hasRelationships(); @Override int hashCode(); @Override boolean equals(Object o); Component getComponent(); Set<Dependency> getDependencies(); Set<Consumer> getConsumers(); @JsonIgnore Set<Relationship> getRelationships(); static ComponentRelationshipsBuilder builder(); }### Answer:
@Test public void filterConsumersShouldReturnOnlyConsumer() { Dependency dependencyB = Dependency.on(dependencyComponent); Consumer consumerC = Consumer.by(consumerComponent); Set<Consumer> expected = new HashSet<>(); expected.add(consumerC); Set<Consumer> actual = ComponentRelationships.filterConsumers(Arrays.asList(dependencyB, consumerC)); Assert.assertEquals(expected, actual); }
|
### Question:
ComponentRelationships { public static ComponentRelationships of(Component component, Set<Dependency> dependencies, Set<Consumer> consumers) { return new ComponentRelationships(component, dependencies, consumers); } @JsonCreator ComponentRelationships(@JsonProperty("component") Component component,
@JsonProperty("dependencies") Set<Dependency> dependencies,
@JsonProperty("consumers") Set<Consumer> consumers); static ComponentRelationships of(Component component, Set<Dependency> dependencies,
Set<Consumer> consumers); static ComponentRelationships of(Component component, Collection<Relationship> relationships); static ComponentRelationships of(Component component, Relationship... relationships); static Set<Consumer> filterConsumers(Collection<Relationship> relationships); static Set<Dependency> filterDependencies(Collection<Relationship> relationships); boolean hasRelationships(); @Override int hashCode(); @Override boolean equals(Object o); Component getComponent(); Set<Dependency> getDependencies(); Set<Consumer> getConsumers(); @JsonIgnore Set<Relationship> getRelationships(); static ComponentRelationshipsBuilder builder(); }### Answer:
@Test public void staticFactoryMethodUsingRelationshipsShouldReturnSameResultAsConstructor() { Set<Dependency> dependencies = new HashSet<>(); dependencies.add(Dependency.on(dependencyComponent)); Set<Consumer> consumers = new HashSet<>(); consumers.add(Consumer.by(consumerComponent)); ComponentRelationships expected = new ComponentRelationships(component, dependencies, consumers); ComponentRelationships actual = ComponentRelationships.of(component, Arrays.asList(Dependency.on(dependencyComponent), Consumer.by(consumerComponent))); Assert.assertEquals(expected, actual); }
@Test public void staticFactoryMethodUsingDependenciesAndConsumersShouldReturnSameResultAsConstructor() { ComponentRelationships expected = new ComponentRelationships(component, dependencies, consumers); ComponentRelationships actual = ComponentRelationships.of(component, dependencies, consumers); Assert.assertEquals(expected, actual); }
|
### Question:
ComponentRelationships { public static ComponentRelationshipsBuilder builder() { return new ComponentRelationshipsBuilder(); } @JsonCreator ComponentRelationships(@JsonProperty("component") Component component,
@JsonProperty("dependencies") Set<Dependency> dependencies,
@JsonProperty("consumers") Set<Consumer> consumers); static ComponentRelationships of(Component component, Set<Dependency> dependencies,
Set<Consumer> consumers); static ComponentRelationships of(Component component, Collection<Relationship> relationships); static ComponentRelationships of(Component component, Relationship... relationships); static Set<Consumer> filterConsumers(Collection<Relationship> relationships); static Set<Dependency> filterDependencies(Collection<Relationship> relationships); boolean hasRelationships(); @Override int hashCode(); @Override boolean equals(Object o); Component getComponent(); Set<Dependency> getDependencies(); Set<Consumer> getConsumers(); @JsonIgnore Set<Relationship> getRelationships(); static ComponentRelationshipsBuilder builder(); }### Answer:
@Test public void builderShouldReturnSameResultAsConstructor() { ComponentRelationships expected = new ComponentRelationships(component, dependencies, consumers); ComponentRelationships actual = ComponentRelationships.builder() .component(component) .dependencies(dependencies) .consumers(consumers) .build(); Assert.assertEquals(expected, actual); }
@Test public void builderAddConsumerShouldAppend() { ComponentRelationships expected = new ComponentRelationships(component, dependencies, consumers); ComponentRelationships actual = ComponentRelationships.builder() .component(component) .dependencies(dependencies) .addConsumer(Consumer.by(consumerComponent)) .build(); Assert.assertEquals(expected, actual); }
@Test public void builderAddDependencyShouldAppend() { ComponentRelationships expected = new ComponentRelationships(component, dependencies, consumers); ComponentRelationships actual = ComponentRelationships.builder() .component(component) .addDependency(Dependency.on(dependencyComponent)) .consumers(consumers) .build(); Assert.assertEquals(expected, actual); }
|
### Question:
CompositeRelationshipDetector implements RelationshipDetector { @Override public Set<Relationship> detect() { return detectors.stream() .map(RelationshipDetector::detect) .flatMap(Collection::stream) .collect(Collectors.toSet()); } CompositeRelationshipDetector(Collection<RelationshipDetector> detectors); @Override Set<Relationship> detect(); }### Answer:
@Test public void detectShouldContainRelationshipDetectedByBothSources() { FixedRelationshipDetector detector1 = new FixedRelationshipDetector(Arrays.asList(TestHelper.dependencyOnB())); FixedRelationshipDetector detector2 = new FixedRelationshipDetector( TestHelper.relationshipSetOfDependencyBAndConsumerC()); CompositeRelationshipDetector compositeDetector = new CompositeRelationshipDetector( Arrays.asList(detector1, detector2)); Set<Relationship> expected = TestHelper.relationshipSetOfDependencyBAndConsumerC(); Assert.assertEquals(expected, compositeDetector.detect()); }
|
### Question:
System { public static System empty(String name) { return System.of(name); } System(String name, Collection<ComponentRelationships> rels, Collection<ResolutionError> errors); System(String name, Collection<ComponentRelationships> rels); static System of(String name, Collection<ComponentRelationships> rels); static System of(String name, Collection<ComponentRelationships> rels, Collection<ResolutionError> errors); static System of(String name, ComponentRelationships... rels); static System empty(String name); boolean hasErrors(); @Override boolean equals(Object o); @Override int hashCode(); String getName(); Set<ComponentRelationships> getComponentRelationships(); Set<ResolutionError> getErrors(); static SystemBuilder builder(); }### Answer:
@Test public void testToString() { String toString = System.empty("xmen").toString(); Assertions.assertThat(toString).contains("xmen"); }
|
### Question:
ConsumerProperties { public Consumer toConsumer() { return Consumer.by(component.toComponent()); } Consumer toConsumer(); }### Answer:
@Test public void toConsumerModel() { ConsumerProperties c = new ConsumerProperties(); ComponentProperties cmp = new ComponentProperties(); c.setComponent(cmp); cmp.setName("gambit"); cmp.setType("superhero"); Assert.assertEquals(Consumer.by(Component.of("gambit", "superhero")), c.toConsumer()); }
|
### Question:
DependencyProperties { public Dependency toDependency() { return Dependency.on(component.toComponent()); } Dependency toDependency(); }### Answer:
@Test public void toDependency() { DependencyProperties c = new DependencyProperties(); ComponentProperties cmp = new ComponentProperties(); c.setComponent(cmp); cmp.setName("magneto"); cmp.setType("villain"); Assert.assertEquals(Dependency.on(Component.of("magneto", "villain")), c.toDependency()); }
|
### Question:
CereebroSnitchMvcEndpoint extends AbstractMvcEndpoint implements SnitchEndpoint { @Override public URI getUri() { return URI.create(getPath()); } CereebroSnitchMvcEndpoint(ApplicationAnalyzer analyzer); @Override URI getUri(); @RequestMapping(method = RequestMethod.GET) @ResponseBody @Override SystemFragment snitch(); static final String DEFAULT_PATH; }### Answer:
@Test public void location() { Assert.assertEquals(URI.create("/cereebro/snitch"), endpoint.getUri()); }
|
### Question:
CereebroSnitchMvcEndpoint extends AbstractMvcEndpoint implements SnitchEndpoint { @RequestMapping(method = RequestMethod.GET) @ResponseBody @Override public SystemFragment snitch() { return applicationAnalyzer.analyzeSystem(); } CereebroSnitchMvcEndpoint(ApplicationAnalyzer analyzer); @Override URI getUri(); @RequestMapping(method = RequestMethod.GET) @ResponseBody @Override SystemFragment snitch(); static final String DEFAULT_PATH; }### Answer:
@Test public void snitch() { Dependency d1 = Dependency.on(Component.of("cards", "game")); Consumer c1 = Consumer.by(Component.of("angel", "superhero")); ComponentRelationships rels = ComponentRelationships.builder().component(Component.of("gambit", "xmen")) .addDependency(d1).addConsumer(c1).build(); Mockito.when(analyzer.analyzeSystem()).thenReturn(SystemFragment.of(rels)); SystemFragment actual = endpoint.snitch(); Set<Dependency> dependencies = new HashSet<>(Arrays.asList(d1)); Set<Consumer> consumers = new HashSet<>(Arrays.asList(c1)); ComponentRelationships r = ComponentRelationships.of(Component.of("gambit", "xmen"), dependencies, consumers); SystemFragment expected = SystemFragment.of(r); Assert.assertEquals(expected, actual); }
|
### Question:
Slf4jSnitchLogger implements CommandLineRunner { public void log() { if (LOGGER.isInfoEnabled()) { try { SystemFragment frag = analyzer.analyzeSystem(); String fragString = objectMapper.writeValueAsString(frag); LOGGER.info("System fragment : {}", fragString); } catch (IOException | RuntimeException e) { LOGGER.error("Error while logging system fragment", e); } } } Slf4jSnitchLogger(ApplicationAnalyzer analyzer, ObjectMapper objectMapper); void log(); @Override void run(String... args); }### Answer:
@Test public void log() throws IOException { Level previousLogLevel = setLogLevel(Slf4jSnitchLogger.class, Level.INFO); SystemFragment frag = SystemFragment.empty(); Mockito.when(analyzerMock.analyzeSystem()).thenReturn(frag); Mockito.when(objectMapperMock.writeValueAsString(frag)).thenReturn(""); logSnitch.log(); Mockito.verify(analyzerMock).analyzeSystem(); Mockito.verify(objectMapperMock).writeValueAsString(frag); setLogLevel(Slf4jSnitchLogger.class, previousLogLevel); }
@Test public void logInfoDisabledShouldNotLog() throws IOException { Level previousLogLevel = setLogLevel(Slf4jSnitchLogger.class, Level.ERROR); logSnitch.log(); Mockito.verify(analyzerMock, Mockito.never()).analyzeSystem(); Mockito.verify(objectMapperMock, Mockito.never()).writeValueAsString(Mockito.any()); setLogLevel(Slf4jSnitchLogger.class, previousLogLevel); }
@Test public void logShouldSwallowExceptions() throws JsonProcessingException { SystemFragment frag = SystemFragment.empty(); Mockito.when(analyzerMock.analyzeSystem()).thenReturn(frag); Mockito.when(objectMapperMock.writeValueAsString(frag)).thenThrow(Mockito.mock(JsonGenerationException.class)); logSnitch.log(); Mockito.verify(analyzerMock).analyzeSystem(); Mockito.verify(objectMapperMock).writeValueAsString(frag); }
|
### Question:
ComponentProperties { public Component toComponent() { return Component.of(name, type); } Component toComponent(); }### Answer:
@Test public void toComponent() { ComponentProperties c = new ComponentProperties(); c.setName("wolverine"); c.setType("superhero"); Component expected = Component.of("wolverine", "superhero"); Component actual = c.toComponent(); Assert.assertEquals(expected, actual); }
|
### Question:
SpringBootApplicationAnalyzer implements ApplicationAnalyzer { @Override public SystemFragment analyzeSystem() { return SystemFragment.of(Collections.singleton(analyzeApplication())); } SpringBootApplicationAnalyzer(CereebroProperties cereebroProperties,
Collection<RelationshipDetector> detectors); @Override ComponentRelationships analyzeApplication(); @Override SystemFragment analyzeSystem(); }### Answer:
@Test public void analyzeSystem() { Mockito.when(detectorMock.detect()).thenReturn(new HashSet<>()); SystemFragment result = analyzer.analyzeSystem(); ComponentRelationships rels = ComponentRelationships.builder().component(Component.of("name", "type")).build(); Assertions.assertThat(result).isEqualTo(SystemFragment.of(rels)); }
|
### Question:
ConfigurationPropertiesRelationshipDetector implements RelationshipDetector { @Override public Set<Relationship> detect() { return properties.getApplication().getRelationships(); } ConfigurationPropertiesRelationshipDetector(CereebroProperties properties); @Override Set<Relationship> detect(); }### Answer:
@Test public void detectRelationshipsBasedOnPropertiesShouldReturnDependenciesAndConsumers() { CereebroProperties properties = new CereebroProperties(); ComponentRelationshipsProperties application = new ComponentRelationshipsProperties(); DependencyProperties d = new DependencyProperties(); ConsumerProperties c = new ConsumerProperties(); ComponentProperties consumer = new ComponentProperties(); consumer.setName("apocalypse"); consumer.setType("villain"); c.setComponent(consumer); application.setConsumers(Arrays.asList(c)); ComponentProperties dependency = new ComponentProperties(); dependency.setName("wolverine"); dependency.setType("superhero"); d.setComponent(dependency); application.setDependencies(Arrays.asList(d)); properties.setApplication(application); Set<Relationship> expected = new HashSet<>(Arrays.asList(Dependency.on(Component.of("wolverine", "superhero")), Consumer.by(Component.of("apocalypse", "villain")))); ConfigurationPropertiesRelationshipDetector detector = new ConfigurationPropertiesRelationshipDetector( properties); Set<Relationship> actual = detector.detect(); Assert.assertEquals(expected, actual); }
@Test public void detectPropertiesWithoutRelationshipsShouldReturnEmptySet() { Set<Relationship> expected = new HashSet<>(); ConfigurationPropertiesRelationshipDetector detector = new ConfigurationPropertiesRelationshipDetector( new CereebroProperties()); Set<Relationship> actual = detector.detect(); Assert.assertEquals(expected, actual); }
|
### Question:
System { public static SystemBuilder builder() { return new SystemBuilder(); } System(String name, Collection<ComponentRelationships> rels, Collection<ResolutionError> errors); System(String name, Collection<ComponentRelationships> rels); static System of(String name, Collection<ComponentRelationships> rels); static System of(String name, Collection<ComponentRelationships> rels, Collection<ResolutionError> errors); static System of(String name, ComponentRelationships... rels); static System empty(String name); boolean hasErrors(); @Override boolean equals(Object o); @Override int hashCode(); String getName(); Set<ComponentRelationships> getComponentRelationships(); Set<ResolutionError> getErrors(); static SystemBuilder builder(); }### Answer:
@Test public void builderTest() { System actual = System.builder().name(NAME).componentRelationships(new HashSet<>()).errors(new HashSet<>()) .build(); Assertions.assertThat(System.empty(NAME)).isEqualTo(actual); }
|
### Question:
ComponentRelationshipsProperties { public Set<Dependency> dependencies() { return dependencies.stream().map(DependencyProperties::toDependency).collect(Collectors.toSet()); } Set<Dependency> dependencies(); Set<Consumer> consumers(); Set<Relationship> getRelationships(); }### Answer:
@Test public void dependenciesEmptyByDefault() { ComponentRelationshipsProperties c = new ComponentRelationshipsProperties(); Assert.assertNotNull(c.dependencies()); Assert.assertTrue(c.dependencies().isEmpty()); }
@Test public void dependencies() { ComponentRelationshipsProperties c = new ComponentRelationshipsProperties(); DependencyProperties d = createDependency("iceman", "superhero"); c.setDependencies(Arrays.asList(d)); Set<Dependency> expected = new HashSet<>(Arrays.asList(Dependency.on(Component.of("iceman", "superhero")))); Set<Dependency> actual = c.dependencies(); Assert.assertEquals(expected, actual); }
|
### Question:
ComponentRelationshipsProperties { public Set<Consumer> consumers() { return consumers.stream().map(ConsumerProperties::toConsumer).collect(Collectors.toSet()); } Set<Dependency> dependencies(); Set<Consumer> consumers(); Set<Relationship> getRelationships(); }### Answer:
@Test public void consumers() { ComponentRelationshipsProperties c = new ComponentRelationshipsProperties(); ConsumerProperties consumer = createConsumer("galactus", "villain"); c.setConsumers(Arrays.asList(consumer)); Set<Consumer> expected = new HashSet<>(Arrays.asList(Consumer.by(Component.of("galactus", "villain")))); Set<Consumer> actual = c.consumers(); Assert.assertEquals(expected, actual); }
|
### Question:
ComponentRelationshipsProperties { public Set<Relationship> getRelationships() { return Stream.concat(dependencies().stream(), consumers().stream()).collect(Collectors.toSet()); } Set<Dependency> dependencies(); Set<Consumer> consumers(); Set<Relationship> getRelationships(); }### Answer:
@Test public void relationships() { ComponentRelationshipsProperties c = new ComponentRelationshipsProperties(); DependencyProperties d = createDependency("iceman", "superhero"); ConsumerProperties consumer = createConsumer("galactus", "villain"); c.setConsumers(Arrays.asList(consumer)); c.setDependencies(Arrays.asList(d)); Set<Relationship> actual = c.getRelationships(); Set<Relationship> expected = new HashSet<>(Arrays.asList(Consumer.by(Component.of("galactus", "villain")), Dependency.on(Component.of("iceman", "superhero")))); Assert.assertEquals(expected, actual); }
|
### Question:
Component { public static Component of(String name, String type) { return new Component(name, type); } @JsonCreator Component(@JsonProperty("name") String name, @JsonProperty("type") String type); static Component of(String name, String type); @Override int hashCode(); @Override boolean equals(Object o); String asString(); String getName(); String getType(); }### Answer:
@Test(expected = NullPointerException.class) public void constructorWithNullNameShouldThrowNullPointerException() { Component.of(null, "type"); }
@Test(expected = NullPointerException.class) public void constructorWithNullTypeShouldThrowNullPointerException() { Component.of("name", null); }
@Test public void testToString() { String toString = Component.of("cyclop", "superhero").toString(); java.lang.System.out.println(toString); Assert.assertTrue(toString.contains("cyclop")); Assert.assertTrue(toString.contains("superhero")); }
@Test public void equalsShouldIgnoreNameCase() { Assertions.assertThat(Component.of("C", "c")).isEqualTo(Component.of("c", "c")); }
|
### Question:
RabbitRelationshipDetector implements RelationshipDetector { @Override public Set<Relationship> detect() { if (connectionFactories.isEmpty()) { return Collections.emptySet(); } return connectionFactories.stream().map(factory -> createRabbitDependency(factory.getVirtualHost())) .collect(Collectors.toSet()); } RabbitRelationshipDetector(List<ConnectionFactory> rabbitConnectionFactories); @Override Set<Relationship> detect(); }### Answer:
@Test public void nullConnectionsShouldReturnEmptyRelationships() { RabbitRelationshipDetector detector = new RabbitRelationshipDetector(null); Assertions.assertThat(detector.detect()).isEmpty(); }
@Test public void emptyConnectionsShouldReturnEmptyRelationships() { RabbitRelationshipDetector detector = new RabbitRelationshipDetector(new ArrayList<>()); Assertions.assertThat(detector.detect()).isEmpty(); }
@Test public void connectionsShouldReturnDependenciesOnRabbitMqVhost() { ConnectionFactory factory = Mockito.mock(ConnectionFactory.class); Mockito.when(factory.getVirtualHost()).thenReturn("vhost"); RabbitRelationshipDetector detector = new RabbitRelationshipDetector(Arrays.asList(factory)); Dependency dependency = Dependency.on(Component.of("vhost", ComponentType.RABBITMQ)); Assertions.assertThat(detector.detect()).isEqualTo(new HashSet<>(Arrays.asList(dependency))); }
|
### Question:
AuthorizationServerRelationshipDetector implements RelationshipDetector { @Override public Set<Relationship> detect() { if (tokenService instanceof RemoteTokenServices || tokenService instanceof UserInfoTokenServices) { return Dependency.on(Component.of(getDefaultName(), ComponentType.HTTP_APPLICATION)).asRelationshipSet(); } return Collections.emptySet(); } AuthorizationServerRelationshipDetector(ResourceServerTokenServices tokenService); @Override Set<Relationship> detect(); }### Answer:
@Test public void usingRemoteTokenServicesShouldReturnDependency() { ResourceServerTokenServices tokenService = new RemoteTokenServices(); detector = new AuthorizationServerRelationshipDetector(tokenService); Set<Relationship> expected = new HashSet<>(Arrays .asList(Dependency.on(Component.of("oauth2-authorization-server", ComponentType.HTTP_APPLICATION)))); Set<Relationship> result = detector.detect(); Assertions.assertThat(result).isEqualTo(expected); }
@Test public void usingRemoteTokenServicesWithCustomName() { ResourceServerTokenServices tokenService = new RemoteTokenServices(); detector = new AuthorizationServerRelationshipDetector(tokenService); String customName = "authz"; detector.setDefaultName(customName); Set<Relationship> expected = new HashSet<>( Arrays.asList(Dependency.on(Component.of(customName, ComponentType.HTTP_APPLICATION)))); Set<Relationship> result = detector.detect(); Assertions.assertThat(result).isEqualTo(expected); }
@Test public void usingUserInfoTokenServicesShouldReturnDependency() { ResourceServerTokenServices tokenService = new UserInfoTokenServices("/info", "nope"); detector = new AuthorizationServerRelationshipDetector(tokenService); Set<Relationship> expected = new HashSet<>(Arrays .asList(Dependency.on(Component.of("oauth2-authorization-server", ComponentType.HTTP_APPLICATION)))); Set<Relationship> result = detector.detect(); Assertions.assertThat(result).isEqualTo(expected); }
@Test public void nullTokenServicesShouldReturnEmptyRelationships() { detector = new AuthorizationServerRelationshipDetector(null); Assertions.assertThat(detector.detect()).isEmpty(); }
|
### Question:
MongoDbRelationshipDetector implements RelationshipDetector { @Override public Set<Relationship> detect() { Set<Relationship> result = new HashSet<>(); for (MongoClient client : clients) { for (String db : client.listDatabaseNames()) { result.add(Dependency.on(Component.of(db, ComponentType.MONGODB))); } } return result; } MongoDbRelationshipDetector(Collection<MongoClient> clients); @Override Set<Relationship> detect(); }### Answer:
@Test public void mongoRelationshipWithSessionAvailable() { Assertions.assertThat(detector.detect()).contains(Dependency.on(Component.of("local", ComponentType.MONGODB))); }
|
### Question:
RedisRelationshipDetector implements RelationshipDetector { @Override public Set<Relationship> detect() { if (CollectionUtils.isEmpty(connectionFactories)) { return Collections.emptySet(); } String sentinelMaster = getRedisSentinelMasterName(); String name = StringUtils.hasText(sentinelMaster) ? sentinelMaster : defaultName; return Dependency.on(Component.of(name, ComponentType.REDIS)).asRelationshipSet(); } RedisRelationshipDetector(RedisProperties redisProperties,
List<RedisConnectionFactory> redisConnectionFactories); @Override Set<Relationship> detect(); }### Answer:
@Test public void nullSentinelShouldReturnDefaultComponentName() { RedisConnectionFactory factory = Mockito.mock(RedisConnectionFactory.class); RedisRelationshipDetector detector = new RedisRelationshipDetector(new RedisProperties(), Arrays.asList(factory)); Set<Relationship> rels = new HashSet<>(); rels.add(Dependency.on(Component.of("default", ComponentType.REDIS))); Assertions.assertThat(detector.detect()).isEqualTo(rels); }
@Test public void nullArgsShouldReturnEmptyRels() { RedisRelationshipDetector detector = new RedisRelationshipDetector(null, null); Assertions.assertThat(detector.detect()).isEmpty(); }
@Test public void shouldUseSentinelMasterName() { String name = "name"; RedisConnectionFactory factory = Mockito.mock(RedisConnectionFactory.class); RedisProperties props = new RedisProperties(); props.setSentinel(new Sentinel()); props.getSentinel().setMaster(name); RedisRelationshipDetector detector = new RedisRelationshipDetector(props, Arrays.asList(factory)); Set<Relationship> rels = new HashSet<>(); rels.add(Dependency.on(Component.of(name, ComponentType.REDIS))); Assertions.assertThat(detector.detect()).isEqualTo(rels); }
|
### Question:
EurekaServerRelationshipDetector implements RelationshipDetector { @Override public Set<Relationship> detect() { if (eurekaClients.isEmpty()) { return Collections.emptySet(); } return Dependency.on(Component.of(defaultName, ComponentType.HTTP_APPLICATION_REGISTRY)).asRelationshipSet(); } EurekaServerRelationshipDetector(List<EurekaClient> eurekaClients); @Override Set<Relationship> detect(); }### Answer:
@Test public void nullEurekaClientListShouldReturnEmptyRels() { EurekaServerRelationshipDetector detector = new EurekaServerRelationshipDetector(null); Assertions.assertThat(detector.detect()).isEmpty(); }
@Test public void emptyEurekaClientListShouldReturnEmptyRels() { EurekaServerRelationshipDetector detector = new EurekaServerRelationshipDetector(new ArrayList<>()); Assertions.assertThat(detector.detect()).isEmpty(); }
@Test public void multipleEurekaClientsShouldReturnSingleDependencyOnEurekaServer() { EurekaClient eurekaClientMock = Mockito.mock(EurekaClient.class); EurekaServerRelationshipDetector detector = new EurekaServerRelationshipDetector( Arrays.asList(eurekaClientMock)); Dependency dependency = Dependency.on(Component.of("eureka-server", ComponentType.HTTP_APPLICATION_REGISTRY)); Set<Relationship> expected = new HashSet<>(Arrays.asList(dependency)); Assertions.assertThat(detector.detect()).isEqualTo(expected); }
|
### Question:
CassandraRelationshipDetector implements RelationshipDetector { @Override public Set<Relationship> detect() { final Set<Relationship> result = new HashSet<>(); for (Session s : sessions) { result.add(Dependency.on(Component.of(extractName(s), ComponentType.CASSANDRA))); } return result; } CassandraRelationshipDetector(Collection<Session> sessions); @Override Set<Relationship> detect(); }### Answer:
@Test public void cassandraRelationshipWithSessionAvailable() { Assertions.assertThat(detector.detect()) .contains(Dependency.on(Component.of("keyspace", ComponentType.CASSANDRA))); }
|
### Question:
DataSourceRelationshipDetector implements RelationshipDetector { @Override public Set<Relationship> detect() { if (relationsCache == null) { final Set<Relationship> result = new HashSet<>(); for (DataSource ds : dataSources) { try (Connection connection = ds.getConnection()) { result.add(Dependency.on(Component.of(extractName(connection), extractDatabaseType(connection)))); } catch (SQLException e) { LOGGER.error("Could not fetch the default catalog of the database connection", e); } } relationsCache = result; } return new HashSet<>(relationsCache); } DataSourceRelationshipDetector(Collection<DataSource> dataSources); @Override Set<Relationship> detect(); }### Answer:
@Test public void dataSourceRelationshipWithDataSourceAvailable() throws SQLException { Assertions.assertThat(detector.detect()) .contains(Dependency.on(Component.of("catalog", ComponentType.RELATIONAL_DATABASE))); }
|
### Question:
ZuulRouteRelationshipDetector implements RelationshipDetector { protected boolean containsComponentName(Route route) { return !routeLocationExclusion.matcher(route.getLocation()).matches(); } ZuulRouteRelationshipDetector(RouteLocator routeLocator); @Override Set<Relationship> detect(); }### Answer:
@Test public void routeWithLocationUrlShouldNotContainName() { Route route = routeWithLocation("http: Assertions.assertThat(detector.containsComponentName(route)).isFalse(); }
@Test public void routeWithHttpsUrlLocationShouldNotContainName() { Route route = routeWithLocation("https: Assertions.assertThat(detector.containsComponentName(route)).isFalse(); }
@Test public void routeShouldContainName() { Route route = routeWithLocation("yass"); Assertions.assertThat(detector.containsComponentName(route)).isTrue(); }
|
### Question:
ZuulRouteRelationshipDetector implements RelationshipDetector { @Override public Set<Relationship> detect() { return routeLocator.getRoutes().stream() .filter(this::containsComponentName) .map(this::createDependency) .collect(Collectors.toSet()); } ZuulRouteRelationshipDetector(RouteLocator routeLocator); @Override Set<Relationship> detect(); }### Answer:
@Test public void detect() { String name = "yass"; List<Route> routes = Arrays.asList(routeWithLocation(name), routeWithLocation("https: routeWithLocation("http: Mockito.when(routeLocatorMock.getRoutes()).thenReturn(routes); Set<Relationship> result = detector.detect(); Component expectedComponent = Component.of(name, ComponentType.HTTP_APPLICATION); Set<Relationship> expected = new HashSet<>(Arrays.asList(Dependency.on(expectedComponent))); Assertions.assertThat(result).isEqualTo(expected); }
|
### Question:
ElasticSearchRelationshipDetector implements RelationshipDetector { @Override public Set<Relationship> detect() { return clients.stream() .map(c -> Dependency.on(Component.of(c.settings().get("cluster.name"), ComponentType.ELASTIC_SEARCH))) .collect(Collectors.toSet()); } ElasticSearchRelationshipDetector(Collection<Client> esClients); @Override Set<Relationship> detect(); }### Answer:
@Test public void testElasticSearchDetector() { Assertions.assertThat(detector.detect()) .contains(Dependency.on(Component.of("mycluster", ComponentType.ELASTIC_SEARCH))); }
|
### Question:
CereebroProperties implements EnvironmentAware { @Override public void setEnvironment(Environment env) { if (!StringUtils.hasText(application.getComponent().getName())) { RelaxedPropertyResolver springPropertyResolver = new RelaxedPropertyResolver(env, "spring.application."); String appName = springPropertyResolver.getProperty("name"); application.getComponent().setName(StringUtils.hasText(appName) ? appName : generateName()); } } @Override void setEnvironment(Environment env); }### Answer:
@Test public void setEnvironmentWithSpringApplicationNameShouldSetComponentName() { CereebroProperties c = new CereebroProperties(); MockEnvironment env = new MockEnvironment(); env.setProperty("spring.application.name", "cyclop"); c.setEnvironment(env); Assert.assertEquals("cyclop", c.getApplication().getComponent().getName()); }
@Test public void setEnvironmentWithoutSpringApplicationNameShouldntChangeComponentName() { CereebroProperties c = new CereebroProperties(); c.getApplication().getComponent().setName("storm"); c.setEnvironment(new MockEnvironment()); Assert.assertEquals("storm", c.getApplication().getComponent().getName()); }
|
### Question:
FileWriterSnitch implements CommandLineRunner, Snitch { @Override public void run(String... args) throws Exception { String location = properties.getSnitch().getFile().getLocation(); try { file = StringUtils.hasText(location) ? new File(location) : File.createTempFile(properties.getApplication().getComponent().getName(), ".json"); write(file); } catch (IOException e) { LOGGER.error("Error while writing JSON to file : " + location, e); } } FileWriterSnitch(ApplicationAnalyzer analyzer, ObjectMapper objectMapper, CereebroProperties properties); @Override void run(String... args); void write(File f); @Override URI getUri(); @Override SystemFragment snitch(); }### Answer:
@Test public void writeToRandomTemporaryFileWhenNoLocationDefined() throws Exception { CereebroProperties properties = new CereebroProperties(); final String componentName = "cereebro-unit-tests"; properties.getApplication().getComponent().setName(componentName); properties.getSnitch().getFile().setLocation(null); FileWriterSnitch snitch = new FileWriterSnitch(analyzerMock, objectMapper, properties); snitch.run(); File tempRoot = new File(System.getProperty("java.io.tmpdir")); File[] tempFiles = tempRoot.listFiles((FilenameFilter) (dir, fileName) -> fileName.contains(componentName)); Assertions.assertThat(tempFiles).isNotEmpty(); Stream.of(tempFiles).forEach(f -> f.deleteOnExit()); }
@Test public void ioExceptionShouldBeSwallowed() throws Exception { CereebroProperties properties = new CereebroProperties(); File temp = temporaryFolder.newFile(); properties.getSnitch().getFile().setLocation(temp.getAbsolutePath()); ObjectMapper messedUpMapperMock = Mockito.mock(ObjectMapper.class); Mockito.when(messedUpMapperMock.writeValueAsString(SystemFragment.empty())) .thenThrow(Mockito.mock(JsonProcessingException.class)); FileWriterSnitch snitch = new FileWriterSnitch(analyzerMock, messedUpMapperMock, properties); snitch.run(); Assertions.assertThat(temp.length()).isEqualTo(0); }
|
### Question:
Component { public String asString() { return new StringJoiner(":").add(type).add(name).toString(); } @JsonCreator Component(@JsonProperty("name") String name, @JsonProperty("type") String type); static Component of(String name, String type); @Override int hashCode(); @Override boolean equals(Object o); String asString(); String getName(); String getType(); }### Answer:
@Test public void testAsString() { Assert.assertEquals("type:name", Component.of("name", "type").asString()); }
|
### Question:
FileWriterSnitch implements CommandLineRunner, Snitch { @Override public URI getUri() { if (file == null) { URI uri = URI.create("file: LOGGER.warn("File hasn't been written for some reason, returning default URI : {}", uri); return uri; } return file.toURI(); } FileWriterSnitch(ApplicationAnalyzer analyzer, ObjectMapper objectMapper, CereebroProperties properties); @Override void run(String... args); void write(File f); @Override URI getUri(); @Override SystemFragment snitch(); }### Answer:
@Test public void fileNotWrittenShouldYieldDefaultUri() { FileWriterSnitch snitch = new FileWriterSnitch(analyzerMock, objectMapper, new CereebroProperties()); Assertions.assertThat(snitch.getUri()).isEqualTo(URI.create("file: }
|
### Question:
DiscoveryClientSnitchRegistry implements SnitchRegistry { @Override public List<Snitch> getAll() { return discoveryClient.getServices().stream() .map(discoveryClient::getInstances) .flatMap(List::stream) .map(instance -> new ServiceInstanceSnitch(objectMapper, instance)) .collect(Collectors.toList()); } DiscoveryClientSnitchRegistry(DiscoveryClient discoveryClient, ObjectMapper mapper); @Override List<Snitch> getAll(); }### Answer:
@Test public void getAllWithSystemFragmentStringShouldReturnStaticSnitch() throws IOException { String serviceId = "fakeServiceId"; Mockito.when(discoveryClientMock.getServices()).thenReturn(Arrays.asList(serviceId)); Mockito.when(discoveryClientMock.getInstances(serviceId)).thenReturn(Arrays.asList(serviceInstanceMock)); Map<String, String> metadata = new HashMap<>(); final String fakeJsonThatWorks = "{ \"valid\" : true }"; final String url = "http: metadata.put(CereebroMetadata.KEY_SNITCH_SYSTEM_FRAGMENT_JSON, fakeJsonThatWorks); metadata.put(CereebroMetadata.KEY_SNITCH_URI, url); Mockito.when(serviceInstanceMock.getMetadata()).thenReturn(metadata); Mockito.when(serviceInstanceMock.getInstanceInfo()).thenReturn(instanceInfoMock); Mockito.when(objectMapperMock.readValue(fakeJsonThatWorks, SystemFragment.class)) .thenReturn(SystemFragment.empty()); List<Snitch> result = registry.getAll(); Assertions.assertThat(result.size()).isEqualTo(1); Snitch snitch = result.get(0); Assertions.assertThat(snitch).isInstanceOf(ServiceInstanceSnitch.class); Assertions.assertThat(URI.create("http: }
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.