method2testcases
stringlengths 118
3.08k
|
---|
### Question:
TcpClientConnectionPool extends AbstractTcpClientConnectionPool<TcpClientConnection> { @Override protected TcpClientConnection create(String endpoint) { return new TcpClientConnection(context, netClientWrapper, endpoint); } TcpClientConnectionPool(Context context, NetClientWrapper netClientWrapper); }### Answer:
@Test public void create() { Assert.assertThat(pool.create("rest: } |
### Question:
TcpClientConfig extends NetClientOptions { public TcpClientConfig() { msLoginTimeout = DEFAULT_LOGIN_TIMEOUT; } TcpClientConfig(); long getMsLoginTimeout(); void setMsLoginTimeout(long msLoginTimeout); static final int DEFAULT_LOGIN_TIMEOUT; }### Answer:
@Test public void testTcpClientConfig() { TcpClientConfig config = new TcpClientConfig(); Assert.assertEquals(config.getMsLoginTimeout(), 30000); Assert.assertEquals(config.isSsl(), false); config.setMsLoginTimeout(500); Assert.assertEquals(config.getMsLoginTimeout(), 500); } |
### Question:
NetClientWrapper { public TcpClientConfig getClientConfig(boolean ssl) { if (ssl) { return sslClientConfig; } return normalClientConfig; } NetClientWrapper(Vertx vertx, TcpClientConfig normalClientConfig, TcpClientConfig sslClientConfig); TcpClientConfig getClientConfig(boolean ssl); void connect(boolean ssl, int port, String host, Handler<AsyncResult<NetSocket>> connectHandler); }### Answer:
@Test public void getClientConfig() { Assert.assertSame(normalClientConfig, netClientWrapper.getClientConfig(false)); Assert.assertSame(sslClientConfig, netClientWrapper.getClientConfig(true)); } |
### Question:
NetClientWrapper { public void connect(boolean ssl, int port, String host, Handler<AsyncResult<NetSocket>> connectHandler) { if (ssl) { sslNetClient.connect(port, host, connectHandler); return; } normalNetClient.connect(port, host, connectHandler); } NetClientWrapper(Vertx vertx, TcpClientConfig normalClientConfig, TcpClientConfig sslClientConfig); TcpClientConfig getClientConfig(boolean ssl); void connect(boolean ssl, int port, String host, Handler<AsyncResult<NetSocket>> connectHandler); }### Answer:
@Test public void connect(@Mocked NetSocket normalSocket, @Mocked NetSocket sslSocket) { int port = 8000; String host = "localhost"; FutureFactoryImpl futureFactory = new FutureFactoryImpl(); new MockUp<NetClient>(normalNetClient) { @Mock NetClient connect(int port, String host, Handler<AsyncResult<NetSocket>> connectHandler) { connectHandler.handle(futureFactory.succeededFuture(normalSocket)); return null; } }; new MockUp<NetClient>(sslNetClient) { @Mock NetClient connect(int port, String host, Handler<AsyncResult<NetSocket>> connectHandler) { connectHandler.handle(futureFactory.succeededFuture(sslSocket)); return null; } }; List<NetSocket> socks = new ArrayList<>(); netClientWrapper.connect(false, port, host, asyncSocket -> { socks.add(asyncSocket.result()); }); netClientWrapper.connect(true, port, host, asyncSocket -> { socks.add(asyncSocket.result()); }); Assert.assertThat(socks, Matchers.contains(normalSocket, sslSocket)); } |
### Question:
ClientVerticle extends AbstractVerticle { @SuppressWarnings("unchecked") @Override public void start() throws Exception { try { ClientPoolManager<CLIENT_POOL> clientMgr = (ClientPoolManager<CLIENT_POOL>) config().getValue(CLIENT_MGR); clientMgr.createClientPool(context); } catch (Throwable e) { LOGGER.error("", e); throw e; } } @SuppressWarnings("unchecked") @Override void start(); static final String CLIENT_MGR; }### Answer:
@Test public void start(@Mocked Context context) throws Exception { AtomicInteger count = new AtomicInteger(); ClientPoolManager<HttpClientWithContext> clientMgr = new MockUp<ClientPoolManager<HttpClientWithContext>>() { @Mock HttpClientWithContext createClientPool(Context context) { count.incrementAndGet(); return null; } }.getMockInstance(); clientVerticle.init(null, context); JsonObject config = new SimpleJsonObject(); config.put(ClientVerticle.CLIENT_MGR, clientMgr); new Expectations() { { context.config(); result = config; } }; clientVerticle.start(); Assert.assertEquals(1, count.get()); } |
### Question:
TcpParser implements Handler<Buffer> { public void handle(Buffer buf) { parser.handle(buf); } TcpParser(TcpBufferHandler output); boolean firstNEqual(byte[] a, byte[] b, int n); void handle(Buffer buf); static final byte[] TCP_MAGIC; static final int TCP_MAX_REQUEST_LENGTH; static final int TCP_HEADER_LENGTH; }### Answer:
@Test public void test() throws UnsupportedEncodingException { TcpBufferHandler output = new TcpBufferHandler() { @Override public void handle(long _msgId, Buffer _headerBuffer, Buffer _bodyBuffer) { msgId = _msgId; headerBuffer = _headerBuffer; bodyBuffer = _bodyBuffer; } }; byte[] header = new byte[] {1, 2, 3}; byte[] body = new byte[] {1, 2, 3, 4}; TcpOutputStream os = new TcpOutputStream(1); os.writeInt(header.length + body.length); os.writeInt(header.length); os.write(header); os.write(body); TcpParser parser = new TcpParser(output); parser.handle(os.getBuffer()); os.close(); Assert.assertEquals(1, msgId); Assert.assertArrayEquals(header, headerBuffer.getBytes()); Assert.assertArrayEquals(body, bodyBuffer.getBytes()); } |
### Question:
TcpServerConnection extends TcpConnection { public void init(NetSocket netSocket) { this.initNetSocket((NetSocketImpl) netSocket); String remoteAddress = netSocket.remoteAddress().toString(); LOGGER.info("connect from {}, in thread {}", remoteAddress, Thread.currentThread().getName()); netSocket.exceptionHandler(e -> { LOGGER.error("disconected from {}, in thread {}, cause {}", remoteAddress, Thread.currentThread().getName(), e.getMessage()); }); netSocket.closeHandler(Void -> { LOGGER.error("disconected from {}, in thread {}", remoteAddress, Thread.currentThread().getName()); }); netSocket.handler(splitter); } void init(NetSocket netSocket); }### Answer:
@Test public void test(@Mocked NetSocketImpl netSocket) { TcpServerConnection connection = new TcpServerConnection(); connection.setProtocol("p"); connection.setZipName("z"); connection.init(netSocket); Assert.assertEquals(netSocket, connection.getNetSocket()); } |
### Question:
CreateServiceResponse { public String getServiceId() { return serviceId; } String getServiceId(); void setServiceId(String serviceId); }### Answer:
@Test public void testDefaultValues() { Assert.assertNull(oCreateServiceResponse.getServiceId()); }
@Test public void testInitializedValues() { initFields(); Assert.assertEquals("testServiceId", oCreateServiceResponse.getServiceId()); } |
### Question:
VertxTLSBuilder { public static NetServerOptions buildNetServerOptions(SSLOption sslOption, SSLCustom sslCustom, NetServerOptions netServerOptions) { buildTCPSSLOptions(sslOption, sslCustom, netServerOptions); if (sslOption.isAuthPeer()) { netServerOptions.setClientAuth(ClientAuth.REQUIRED); } else { netServerOptions.setClientAuth(ClientAuth.REQUEST); } return netServerOptions; } private VertxTLSBuilder(); static NetServerOptions buildNetServerOptions(SSLOption sslOption, SSLCustom sslCustom,
NetServerOptions netServerOptions); static void buildHttpClientOptions(String sslKey, HttpClientOptions httpClientOptions); static HttpClientOptions buildHttpClientOptions(SSLOption sslOption, SSLCustom sslCustom,
HttpClientOptions httpClientOptions); static ClientOptionsBase buildClientOptionsBase(SSLOption sslOption, SSLCustom sslCustom,
ClientOptionsBase clientOptionsBase); }### Answer:
@Test public void testbuildHttpServerOptions() { SSLOption option = SSLOption.buildFromYaml("rest.provider"); SSLCustom custom = SSLCustom.createSSLCustom(option.getSslCustomClass()); HttpServerOptions serverOptions = new HttpServerOptions(); VertxTLSBuilder.buildNetServerOptions(option, custom, serverOptions); Assert.assertEquals(serverOptions.getEnabledSecureTransportProtocols().toArray().length, 1); Assert.assertEquals(serverOptions.getClientAuth(), ClientAuth.REQUEST); }
@Test public void testbuildHttpServerOptionsRequest() { SSLOption option = SSLOption.buildFromYaml("rest.provider"); SSLCustom custom = SSLCustom.createSSLCustom(option.getSslCustomClass()); HttpServerOptions serverOptions = new HttpServerOptions(); new MockUp<SSLOption>() { @Mock public boolean isAuthPeer() { return false; } }; VertxTLSBuilder.buildNetServerOptions(option, custom, serverOptions); Assert.assertEquals(serverOptions.getEnabledSecureTransportProtocols().toArray().length, 1); Assert.assertEquals(serverOptions.getClientAuth(), ClientAuth.REQUEST); } |
### Question:
SimpleJsonObject extends JsonObject { @Override public JsonObject put(String key, Object value) { getMap().put(key, value); return this; } @Override JsonObject put(String key, Object value); @Override JsonObject copy(); }### Answer:
@Test public void testPutObject() { Object value = new Object(); SimpleJsonObject json = new SimpleJsonObject(); json.put("k", value); Assert.assertSame(value, json.getValue("k")); } |
### Question:
SimpleJsonObject extends JsonObject { @Override public JsonObject copy() { return this; } @Override JsonObject put(String key, Object value); @Override JsonObject copy(); }### Answer:
@Test public void testCopy() { SimpleJsonObject json = new SimpleJsonObject(); Assert.assertSame(json, json.copy()); } |
### Question:
MarkerFilter extends AbstractMatcherFilter<ILoggingEvent> { public MarkerFilter() { setOnMatch(FilterReply.ACCEPT); setOnMismatch(FilterReply.DENY); } MarkerFilter(); @Override FilterReply decide(ILoggingEvent event); void setMarker(String marker); @Override void start(); }### Answer:
@Test public void testMarkerFilter() { MarkerFilter filter = new MarkerFilter(); filter.setMarker("hello"); filter.start(); Assert.assertEquals(filter.getOnMatch(), FilterReply.ACCEPT); Assert.assertEquals(filter.getOnMismatch(), FilterReply.DENY); ILoggingEvent event = Mockito.mock(ILoggingEvent.class); Marker marker = Mockito.mock(Marker.class); Mockito.when(event.getMarker()).thenReturn(marker); Mockito.when(marker.getName()).thenReturn("hello"); Assert.assertEquals(FilterReply.ACCEPT, filter.decide(event)); Mockito.when(event.getMarker()).thenReturn(null); Assert.assertEquals(FilterReply.DENY, filter.decide(event)); } |
### Question:
HttpStatus implements StatusType { public static boolean isSuccess(int code) { return Status.Family.SUCCESSFUL.equals(Status.Family.familyOf(code)); } HttpStatus(final int statusCode, final String reasonPhrase); static boolean isSuccess(int code); static boolean isSuccess(StatusType status); @Override int getStatusCode(); @Override Family getFamily(); @Override String getReasonPhrase(); }### Answer:
@Test public void testIsSuccessCode() { Assert.assertTrue(HttpStatus.isSuccess(200)); Assert.assertFalse(HttpStatus.isSuccess(300)); }
@Test public void testIsSuccessType() { Assert.assertTrue(HttpStatus.isSuccess(Status.OK)); Assert.assertFalse(HttpStatus.isSuccess(Status.BAD_REQUEST)); } |
### Question:
HttpStatus implements StatusType { @Override public int getStatusCode() { return statusCode; } HttpStatus(final int statusCode, final String reasonPhrase); static boolean isSuccess(int code); static boolean isSuccess(StatusType status); @Override int getStatusCode(); @Override Family getFamily(); @Override String getReasonPhrase(); }### Answer:
@Test public void testGetStatusCode() { HttpStatus status = new HttpStatus(200, "ok"); Assert.assertEquals(200, status.getStatusCode()); } |
### Question:
HttpStatus implements StatusType { @Override public Family getFamily() { return Family.familyOf(statusCode); } HttpStatus(final int statusCode, final String reasonPhrase); static boolean isSuccess(int code); static boolean isSuccess(StatusType status); @Override int getStatusCode(); @Override Family getFamily(); @Override String getReasonPhrase(); }### Answer:
@Test public void testGetFamily() { HttpStatus status = new HttpStatus(200, "ok"); Assert.assertEquals(Family.familyOf(200), status.getFamily()); } |
### Question:
HttpStatus implements StatusType { @Override public String getReasonPhrase() { return reason; } HttpStatus(final int statusCode, final String reasonPhrase); static boolean isSuccess(int code); static boolean isSuccess(StatusType status); @Override int getStatusCode(); @Override Family getFamily(); @Override String getReasonPhrase(); }### Answer:
@Test public void testGetReasonPhrase() { HttpStatus status = new HttpStatus(200, "ok"); Assert.assertEquals("ok", status.getReasonPhrase()); } |
### Question:
HttpUtils { public static String parseParamFromHeaderValue(String headerValue, String paramName) { if (StringUtils.isEmpty(headerValue)) { return null; } for (String value : headerValue.split(";")) { int idx = value.indexOf('='); if (idx == -1) { continue; } if (paramName.equalsIgnoreCase(value.substring(0, idx))) { return value.substring(idx + 1); } } return null; } private HttpUtils(); static String parseParamFromHeaderValue(String headerValue, String paramName); static String uriEncodePath(String path); static String encodePathParam(String pathParam); static String uriDecodePath(String path); static String parseFileNameFromHeaderValue(String headerValue); static String getCharsetFromContentType(String contentType); }### Answer:
@Test public void parseParamFromHeaderValue_normal() { Assert.assertEquals("v", HttpUtils.parseParamFromHeaderValue("xx;k=v", "k")); }
@Test public void parseParamFromHeaderValue_normal_ignoreCase() { Assert.assertEquals("v", HttpUtils.parseParamFromHeaderValue("xx;K=v", "k")); }
@Test public void parseParamFromHeaderValue_null() { Assert.assertNull(HttpUtils.parseParamFromHeaderValue(null, "k")); }
@Test public void parseParamFromHeaderValue_noKv() { Assert.assertNull(HttpUtils.parseParamFromHeaderValue("xx", "k")); }
@Test public void parseParamFromHeaderValue_noV() { Assert.assertEquals("", HttpUtils.parseParamFromHeaderValue("xx;k=", "k")); }
@Test public void parseParamFromHeaderValue_keyNotFound() { Assert.assertNull(HttpUtils.parseParamFromHeaderValue("xx;k=", "kk")); } |
### Question:
GetAllServicesResponse { public List<Microservice> getServices() { return services; } List<Microservice> getServices(); void setServices(List<Microservice> services); }### Answer:
@Test public void testDefaultValues() { Assert.assertNull(oGetAllServicesResponse.getServices()); }
@Test public void testInitializedValues() { initFields(); List<Microservice> list = oGetAllServicesResponse.getServices(); Assert.assertEquals(oMockMicroservice, list.get(0)); } |
### Question:
HttpUtils { public static String uriEncodePath(String path) { try { URI uri = new URI(null, null, path, null); return uri.toASCIIString(); } catch (URISyntaxException e) { throw new IllegalArgumentException(String.format("uriEncode failed, path=\"%s\".", path), e); } } private HttpUtils(); static String parseParamFromHeaderValue(String headerValue, String paramName); static String uriEncodePath(String path); static String encodePathParam(String pathParam); static String uriDecodePath(String path); static String parseFileNameFromHeaderValue(String headerValue); static String getCharsetFromContentType(String contentType); }### Answer:
@Test public void uriEncode_null() { Assert.assertEquals("", HttpUtils.uriEncodePath(null)); }
@Test public void uriEncode_chineseAndSpace() { String encoded = HttpUtils.uriEncodePath("测 试"); Assert.assertEquals("%E6%B5%8B%20%E8%AF%95", encoded); Assert.assertEquals("测 试", HttpUtils.uriDecodePath(encoded)); }
@Test public void uriEncode_failed() { expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage(Matchers.is("uriEncode failed, path=\":\".")); expectedException.expectCause(Matchers.instanceOf(URISyntaxException.class)); HttpUtils.uriEncodePath(":"); }
@Test public void uriEncode_encodeEntirePath() { String encoded = HttpUtils.uriEncodePath("a%%'+b/def"); Assert.assertEquals("a%25%25'+b/def", encoded); } |
### Question:
HttpUtils { public static String uriDecodePath(String path) { if (path == null) { return null; } try { return new URI(path).getPath(); } catch (URISyntaxException e) { throw new IllegalArgumentException(String.format("uriDecode failed, path=\"%s\".", path), e); } } private HttpUtils(); static String parseParamFromHeaderValue(String headerValue, String paramName); static String uriEncodePath(String path); static String encodePathParam(String pathParam); static String uriDecodePath(String path); static String parseFileNameFromHeaderValue(String headerValue); static String getCharsetFromContentType(String contentType); }### Answer:
@Test public void uriDecode_null() { Assert.assertNull(HttpUtils.uriDecodePath(null)); }
@Test public void uriDecode_failed() { expectedException.expect(IllegalArgumentException.class); expectedException .expectMessage(Matchers.is("uriDecode failed, path=\":\".")); expectedException.expectCause(Matchers.instanceOf(URISyntaxException.class)); HttpUtils.uriDecodePath(":"); } |
### Question:
HttpUtils { public static String encodePathParam(String pathParam) { return UrlEscapers.urlPathSegmentEscaper().escape(pathParam); } private HttpUtils(); static String parseParamFromHeaderValue(String headerValue, String paramName); static String uriEncodePath(String path); static String encodePathParam(String pathParam); static String uriDecodePath(String path); static String parseFileNameFromHeaderValue(String headerValue); static String getCharsetFromContentType(String contentType); }### Answer:
@Test public void pathParamEncode() { Assert.assertEquals("a+b", HttpUtils.encodePathParam("a+b")); Assert.assertEquals("a%25b", HttpUtils.encodePathParam("a%b")); Assert.assertEquals("a%25%25b", HttpUtils.encodePathParam("a%%b")); Assert.assertEquals("%3C%20%3E'%22%EF%BC%88)&%2F%20%20", HttpUtils.encodePathParam("< >'\"()&/ ")); Assert.assertEquals("%E6%B5%8B%20%E8%AF%95", HttpUtils.encodePathParam("测 试")); }
@Test public void pathParamEncode_SafeChar() { Assert.assertEquals("-._~!$'()*,;&=@:+", HttpUtils.encodePathParam("-._~!$'()*,;&=@:+")); } |
### Question:
HttpUtils { public static String parseFileNameFromHeaderValue(String headerValue) { String fileName = parseParamFromHeaderValue(headerValue, "filename"); fileName = StringUtils.isEmpty(fileName) ? "default" : fileName; fileName = uriDecodePath(fileName); return new File(fileName).getName(); } private HttpUtils(); static String parseParamFromHeaderValue(String headerValue, String paramName); static String uriEncodePath(String path); static String encodePathParam(String pathParam); static String uriDecodePath(String path); static String parseFileNameFromHeaderValue(String headerValue); static String getCharsetFromContentType(String contentType); }### Answer:
@Test public void parseFileNameFromHeaderValue() { String fileName = "测 试.txt"; String encoded = HttpUtils.uriEncodePath(fileName); Assert.assertEquals(fileName, HttpUtils.parseFileNameFromHeaderValue("xx;filename=" + encoded)); }
@Test public void parseFileNameFromHeaderValue_defaultName() { Assert.assertEquals("default", HttpUtils.parseFileNameFromHeaderValue("xx")); }
@Test public void parseFileNameFromHeaderValue_ignorePath() { Assert.assertEquals("a.txt", HttpUtils.parseFileNameFromHeaderValue("xx;filename=../../a.txt")); } |
### Question:
RegisterInstanceResponse { public String getInstanceId() { return instanceId; } String getInstanceId(); void setInstanceId(String instanceId); }### Answer:
@Test public void testDefaultValues() { Assert.assertNull(oRegisterInstanceResponse.getInstanceId()); }
@Test public void testInitializedValues() { initFields(); Assert.assertEquals("testInstanceID", oRegisterInstanceResponse.getInstanceId()); } |
### Question:
HttpStatusUtils { public static StatusType getOrCreateByStatusCode(int code) { return MGR.getOrCreateByStatusCode(code); } private HttpStatusUtils(); static StatusType getOrCreateByStatusCode(int code); }### Answer:
@Test public void testStandard() { st = HttpStatusUtils.getOrCreateByStatusCode(200); Assert.assertEquals(200, st.getStatusCode()); }
@Test public void testNotStandard() { st = mgr.getOrCreateByStatusCode(250); Assert.assertEquals(250, st.getStatusCode()); } |
### Question:
FilePart extends AbstractPart implements FilePartForSend { @Override public InputStream getInputStream() throws IOException { return new FileInputStream(file); } FilePart(String name, String file); FilePart(String name, File file); @Override InputStream getInputStream(); @Override long getSize(); @Override void write(String fileName); @Override void delete(); @Override boolean isDeleteAfterFinished(); FilePart setDeleteAfterFinished(boolean deleteAfterFinished); @Override String getAbsolutePath(); }### Answer:
@Test public void getInputStream() throws IOException { try (InputStream is = part.getInputStream()) { Assert.assertEquals(content, IOUtils.toString(is, StandardCharsets.UTF_8)); } } |
### Question:
FilePart extends AbstractPart implements FilePartForSend { @Override public long getSize() { return file.length(); } FilePart(String name, String file); FilePart(String name, File file); @Override InputStream getInputStream(); @Override long getSize(); @Override void write(String fileName); @Override void delete(); @Override boolean isDeleteAfterFinished(); FilePart setDeleteAfterFinished(boolean deleteAfterFinished); @Override String getAbsolutePath(); }### Answer:
@Test public void getSize() { Assert.assertEquals(content.length(), part.getSize()); } |
### Question:
FilePart extends AbstractPart implements FilePartForSend { @Override public void write(String fileName) throws IOException { FileUtils.copyFile(file, new File(fileName)); } FilePart(String name, String file); FilePart(String name, File file); @Override InputStream getInputStream(); @Override long getSize(); @Override void write(String fileName); @Override void delete(); @Override boolean isDeleteAfterFinished(); FilePart setDeleteAfterFinished(boolean deleteAfterFinished); @Override String getAbsolutePath(); }### Answer:
@Test public void write() throws IOException { File destFile = new File("testFilePartCopy.txt"); part.write(destFile.getPath()); Assert.assertEquals(content, FileUtils.readFileToString(destFile, StandardCharsets.UTF_8)); FilePart destPart = new FilePart(null, destFile); destPart.delete(); Assert.assertFalse(destFile.exists()); } |
### Question:
FilePart extends AbstractPart implements FilePartForSend { @Override public String getAbsolutePath() { return file.getAbsolutePath(); } FilePart(String name, String file); FilePart(String name, File file); @Override InputStream getInputStream(); @Override long getSize(); @Override void write(String fileName); @Override void delete(); @Override boolean isDeleteAfterFinished(); FilePart setDeleteAfterFinished(boolean deleteAfterFinished); @Override String getAbsolutePath(); }### Answer:
@Test public void getAbsolutePath() { Assert.assertEquals(file.getAbsolutePath(), part.getAbsolutePath()); } |
### Question:
AbstractPart implements Part { @Override public InputStream getInputStream() throws IOException { throw new Error("not supported method"); } @Override InputStream getInputStream(); @Override String getContentType(); @SuppressWarnings("unchecked") T contentType(String contentType); @Override String getName(); @Override String getSubmittedFileName(); AbstractPart setSubmittedFileName(String submittedFileName); @Override long getSize(); @Override void write(String fileName); @Override void delete(); @Override String getHeader(String name); @Override Collection<String> getHeaders(String name); @Override Collection<String> getHeaderNames(); }### Answer:
@Test public void getInputStream() throws IOException { initExpectedException(); part.getInputStream(); } |
### Question:
AbstractPart implements Part { @Override public String getContentType() { return contentType != null ? contentType : MediaType.APPLICATION_OCTET_STREAM; } @Override InputStream getInputStream(); @Override String getContentType(); @SuppressWarnings("unchecked") T contentType(String contentType); @Override String getName(); @Override String getSubmittedFileName(); AbstractPart setSubmittedFileName(String submittedFileName); @Override long getSize(); @Override void write(String fileName); @Override void delete(); @Override String getHeader(String name); @Override Collection<String> getHeaders(String name); @Override Collection<String> getHeaderNames(); }### Answer:
@Test public void getContentType() throws IOException { Assert.assertEquals(MediaType.APPLICATION_OCTET_STREAM, part.getContentType()); String contentType = "abc"; part.contentType(contentType); Assert.assertEquals(contentType, part.getContentType()); } |
### Question:
AbstractPart implements Part { @Override public String getName() { return name; } @Override InputStream getInputStream(); @Override String getContentType(); @SuppressWarnings("unchecked") T contentType(String contentType); @Override String getName(); @Override String getSubmittedFileName(); AbstractPart setSubmittedFileName(String submittedFileName); @Override long getSize(); @Override void write(String fileName); @Override void delete(); @Override String getHeader(String name); @Override Collection<String> getHeaders(String name); @Override Collection<String> getHeaderNames(); }### Answer:
@Test public void getName() throws IOException { Assert.assertNull(part.getName()); String name = "abc"; part.name = name; Assert.assertEquals(name, part.getName()); } |
### Question:
AbstractPart implements Part { @Override public String getSubmittedFileName() { return submittedFileName; } @Override InputStream getInputStream(); @Override String getContentType(); @SuppressWarnings("unchecked") T contentType(String contentType); @Override String getName(); @Override String getSubmittedFileName(); AbstractPart setSubmittedFileName(String submittedFileName); @Override long getSize(); @Override void write(String fileName); @Override void delete(); @Override String getHeader(String name); @Override Collection<String> getHeaders(String name); @Override Collection<String> getHeaderNames(); }### Answer:
@Test public void getSubmittedFileName() throws IOException { Assert.assertNull(part.getSubmittedFileName()); String submittedFileName = "abc"; part.setSubmittedFileName(submittedFileName); Assert.assertEquals(submittedFileName, part.getSubmittedFileName()); } |
### Question:
AbstractPart implements Part { @Override public long getSize() { throw new Error("not supported method"); } @Override InputStream getInputStream(); @Override String getContentType(); @SuppressWarnings("unchecked") T contentType(String contentType); @Override String getName(); @Override String getSubmittedFileName(); AbstractPart setSubmittedFileName(String submittedFileName); @Override long getSize(); @Override void write(String fileName); @Override void delete(); @Override String getHeader(String name); @Override Collection<String> getHeaders(String name); @Override Collection<String> getHeaderNames(); }### Answer:
@Test public void getSize() { initExpectedException(); part.getSize(); } |
### Question:
AbstractPart implements Part { @Override public void write(String fileName) throws IOException { throw new Error("not supported method"); } @Override InputStream getInputStream(); @Override String getContentType(); @SuppressWarnings("unchecked") T contentType(String contentType); @Override String getName(); @Override String getSubmittedFileName(); AbstractPart setSubmittedFileName(String submittedFileName); @Override long getSize(); @Override void write(String fileName); @Override void delete(); @Override String getHeader(String name); @Override Collection<String> getHeaders(String name); @Override Collection<String> getHeaderNames(); }### Answer:
@Test public void write() throws IOException { initExpectedException(); part.write("file"); } |
### Question:
AbstractPart implements Part { @Override public void delete() throws IOException { throw new Error("not supported method"); } @Override InputStream getInputStream(); @Override String getContentType(); @SuppressWarnings("unchecked") T contentType(String contentType); @Override String getName(); @Override String getSubmittedFileName(); AbstractPart setSubmittedFileName(String submittedFileName); @Override long getSize(); @Override void write(String fileName); @Override void delete(); @Override String getHeader(String name); @Override Collection<String> getHeaders(String name); @Override Collection<String> getHeaderNames(); }### Answer:
@Test public void delete() throws IOException { initExpectedException(); part.delete(); } |
### Question:
AbstractPart implements Part { @Override public String getHeader(String name) { throw new Error("not supported method"); } @Override InputStream getInputStream(); @Override String getContentType(); @SuppressWarnings("unchecked") T contentType(String contentType); @Override String getName(); @Override String getSubmittedFileName(); AbstractPart setSubmittedFileName(String submittedFileName); @Override long getSize(); @Override void write(String fileName); @Override void delete(); @Override String getHeader(String name); @Override Collection<String> getHeaders(String name); @Override Collection<String> getHeaderNames(); }### Answer:
@Test public void getHeader() { initExpectedException(); part.getHeader("header"); } |
### Question:
AbstractPart implements Part { @Override public Collection<String> getHeaders(String name) { throw new Error("not supported method"); } @Override InputStream getInputStream(); @Override String getContentType(); @SuppressWarnings("unchecked") T contentType(String contentType); @Override String getName(); @Override String getSubmittedFileName(); AbstractPart setSubmittedFileName(String submittedFileName); @Override long getSize(); @Override void write(String fileName); @Override void delete(); @Override String getHeader(String name); @Override Collection<String> getHeaders(String name); @Override Collection<String> getHeaderNames(); }### Answer:
@Test public void getHeaders() { initExpectedException(); part.getHeaders("header"); } |
### Question:
AbstractPart implements Part { @Override public Collection<String> getHeaderNames() { throw new Error("not supported method"); } @Override InputStream getInputStream(); @Override String getContentType(); @SuppressWarnings("unchecked") T contentType(String contentType); @Override String getName(); @Override String getSubmittedFileName(); AbstractPart setSubmittedFileName(String submittedFileName); @Override long getSize(); @Override void write(String fileName); @Override void delete(); @Override String getHeader(String name); @Override Collection<String> getHeaders(String name); @Override Collection<String> getHeaderNames(); }### Answer:
@Test public void getHeaderNames() { initExpectedException(); part.getHeaderNames(); } |
### Question:
ResourcePart extends AbstractPart { @Override public InputStream getInputStream() throws IOException { return resource.getInputStream(); } ResourcePart(String name, Resource resource); @Override InputStream getInputStream(); }### Answer:
@Test public void getInputStream() throws IOException { try (InputStream is = part.getInputStream()) { byte[] content = IOUtils.toByteArray(is); Assert.assertArrayEquals(bytes, content); } } |
### Question:
GetServiceResponse { public Microservice getService() { return service; } Microservice getService(); void setService(Microservice service); }### Answer:
@Test public void testDefaultValues() { Assert.assertNull(oGetServiceResponse.getService()); }
@Test public void testInitializedValues() { initFields(); Assert.assertEquals(oMockMicroservice, oGetServiceResponse.getService()); } |
### Question:
NetUtils { public static String getRealListenAddress(String schema, String address) { if (address == null) { return null; } try { URI originalURI = new URI(schema + ": IpPort ipPort = NetUtils.parseIpPort(originalURI); if (ipPort == null) { LOGGER.error("address {} is not valid.", address); return null; } return originalURI.toString(); } catch (URISyntaxException e) { LOGGER.error("address {} is not valid.", address); return null; } } private NetUtils(); static IpPort parseIpPort(String address); static IpPort parseIpPort(URI uri); static IpPort parseIpPort(URI uri, boolean ignorePortUndefined); static IpPort parseIpPortFromURI(String uriAddress); static IpPort parseIpPort(String scheme, String authority); static String getRealListenAddress(String schema, String address); static String getHostName(); static String getHostAddress(); static InetAddress getInterfaceAddress(String interfaceName); static InetAddress ensureGetInterfaceAddress(String interfaceName); @SuppressWarnings({"unused", "try"}) static boolean canTcpListen(InetAddress address, int port); static String humanReadableBytes(long bytes); }### Answer:
@Test public void testGetRealListenAddress() { Assert.assertNull(NetUtils.getRealListenAddress("http", null)); Assert.assertEquals("http: checkException(v -> NetUtils.getRealListenAddress("http:1", "1.1.1.1:8080")); } |
### Question:
NetUtils { @SuppressWarnings({"unused", "try"}) public static boolean canTcpListen(InetAddress address, int port) { try (ServerSocket ss = new ServerSocket(port, 0, address)) { return true; } catch (IOException e) { return false; } } private NetUtils(); static IpPort parseIpPort(String address); static IpPort parseIpPort(URI uri); static IpPort parseIpPort(URI uri, boolean ignorePortUndefined); static IpPort parseIpPortFromURI(String uriAddress); static IpPort parseIpPort(String scheme, String authority); static String getRealListenAddress(String schema, String address); static String getHostName(); static String getHostAddress(); static InetAddress getInterfaceAddress(String interfaceName); static InetAddress ensureGetInterfaceAddress(String interfaceName); @SuppressWarnings({"unused", "try"}) static boolean canTcpListen(InetAddress address, int port); static String humanReadableBytes(long bytes); }### Answer:
@Test public void testCanTcpListenNo() throws IOException { InetAddress address = InetAddress.getByName("127.0.0.1"); try (ServerSocket ss = new ServerSocket(0, 0, address)) { Assert.assertFalse(NetUtils.canTcpListen(address, ss.getLocalPort())); } }
@Test public void testCanTcpListenYes() throws IOException { InetAddress address = InetAddress.getByName("127.0.0.1"); ServerSocket ss = new ServerSocket(0, 0, address); int port = ss.getLocalPort(); ss.close(); Assert.assertTrue(NetUtils.canTcpListen(address, port)); } |
### Question:
NetUtils { public static String getHostName() { if (hostName == null) { doGetHostNameAndHostAddress(); } return hostName; } private NetUtils(); static IpPort parseIpPort(String address); static IpPort parseIpPort(URI uri); static IpPort parseIpPort(URI uri, boolean ignorePortUndefined); static IpPort parseIpPortFromURI(String uriAddress); static IpPort parseIpPort(String scheme, String authority); static String getRealListenAddress(String schema, String address); static String getHostName(); static String getHostAddress(); static InetAddress getInterfaceAddress(String interfaceName); static InetAddress ensureGetInterfaceAddress(String interfaceName); @SuppressWarnings({"unused", "try"}) static boolean canTcpListen(InetAddress address, int port); static String humanReadableBytes(long bytes); }### Answer:
@Test public void testGetHostName() { Assert.assertNotEquals(null, NetUtils.getHostName()); Deencapsulation.setField(NetUtils.class, "hostName", null); Assert.assertNotEquals(null, NetUtils.getHostName()); } |
### Question:
NetUtils { public static String getHostAddress() { if (hostAddress == null) { doGetHostNameAndHostAddress(); } return hostAddress; } private NetUtils(); static IpPort parseIpPort(String address); static IpPort parseIpPort(URI uri); static IpPort parseIpPort(URI uri, boolean ignorePortUndefined); static IpPort parseIpPortFromURI(String uriAddress); static IpPort parseIpPort(String scheme, String authority); static String getRealListenAddress(String schema, String address); static String getHostName(); static String getHostAddress(); static InetAddress getInterfaceAddress(String interfaceName); static InetAddress ensureGetInterfaceAddress(String interfaceName); @SuppressWarnings({"unused", "try"}) static boolean canTcpListen(InetAddress address, int port); static String humanReadableBytes(long bytes); }### Answer:
@Test public void testGetHostAddress() { Assert.assertNotEquals(null, NetUtils.getHostAddress()); Deencapsulation.setField(NetUtils.class, "hostAddress", null); Assert.assertNotEquals(null, NetUtils.getHostAddress()); } |
### Question:
IpPort { public IpPort() { } IpPort(); IpPort(String hostOrIp, int port); String getHostOrIp(); void setHostOrIp(String hostOrIp); int getPort(); void setPort(int port); @Override int hashCode(); @Override boolean equals(Object o); @Override String toString(); InetSocketAddress getSocketAddress(); }### Answer:
@Test public void testIpPort() { IpPort inst1 = new IpPort(); inst1.setHostOrIp("localhost"); inst1.setPort(3333); IpPort inst2 = new IpPort("localhost", 3333); Assert.assertEquals(inst1.getHostOrIp(), inst2.getHostOrIp()); Assert.assertEquals(inst1.getPort(), inst2.getPort()); Assert.assertEquals(inst1.getSocketAddress().getHostName(), inst2.getSocketAddress().getHostName()); Assert.assertEquals(inst1, inst1); Assert.assertEquals(inst1, inst2); Assert.assertEquals(inst1.toString(), "localhost:3333"); Assert.assertNotEquals(inst1, new Object()); } |
### Question:
FortifyUtils { private FortifyUtils() { } private FortifyUtils(); static String getErrorMsg(Throwable e); static String getErrorStack(Throwable e); static String getErrorInfo(Throwable e); static String getErrorInfo(Throwable e, boolean isPrintMsg); static DocumentBuilderFactory getSecurityXmlDocumentFactory(); }### Answer:
@Test public void testFortifyUtils() throws IOException { Assert.assertEquals("", FortifyUtils.getErrorMsg(null)); Assert.assertEquals("", FortifyUtils.getErrorStack(null)); } |
### Question:
FortifyUtils { public static String getErrorMsg(Throwable e) { if (e == null) { return ""; } try { return (String) getMessageMethod.invoke(e); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) { return ""; } } private FortifyUtils(); static String getErrorMsg(Throwable e); static String getErrorStack(Throwable e); static String getErrorInfo(Throwable e); static String getErrorInfo(Throwable e, boolean isPrintMsg); static DocumentBuilderFactory getSecurityXmlDocumentFactory(); }### Answer:
@Test public void testGetErrorMsg() { Throwable e = new Throwable(); FortifyUtils.getErrorMsg(e); assertNull(FortifyUtils.getErrorMsg(e)); } |
### Question:
FortifyUtils { public static DocumentBuilderFactory getSecurityXmlDocumentFactory() throws ParserConfigurationException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setFeature("http: factory.setXIncludeAware(false); factory.setExpandEntityReferences(false); factory.setFeature("http: factory.setFeature("http: factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); factory.setValidating(true); return factory; } private FortifyUtils(); static String getErrorMsg(Throwable e); static String getErrorStack(Throwable e); static String getErrorInfo(Throwable e); static String getErrorInfo(Throwable e, boolean isPrintMsg); static DocumentBuilderFactory getSecurityXmlDocumentFactory(); }### Answer:
@Test public void testGetSecurityXmlDocumentFactory() { try { FortifyUtils.getSecurityXmlDocumentFactory(); assertNotNull(FortifyUtils.getSecurityXmlDocumentFactory()); } catch (Exception e) { Assert.assertTrue(false); } } |
### Question:
FortifyUtils { public static String getErrorStack(Throwable e) { if (null == e) { return ""; } try { StringWriter errors = new StringWriter(); printStackTraceMethod.invoke(e, new PrintWriter(errors)); return errors.toString(); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) { return ""; } } private FortifyUtils(); static String getErrorMsg(Throwable e); static String getErrorStack(Throwable e); static String getErrorInfo(Throwable e); static String getErrorInfo(Throwable e, boolean isPrintMsg); static DocumentBuilderFactory getSecurityXmlDocumentFactory(); }### Answer:
@Test public void testGetErrorStack() { Throwable e = new Throwable(); FortifyUtils.getErrorStack(e); Assert.assertNotEquals(true, FortifyUtils.getErrorStack(e)); } |
### Question:
FortifyUtils { public static String getErrorInfo(Throwable e) { return getErrorInfo(e, true); } private FortifyUtils(); static String getErrorMsg(Throwable e); static String getErrorStack(Throwable e); static String getErrorInfo(Throwable e); static String getErrorInfo(Throwable e, boolean isPrintMsg); static DocumentBuilderFactory getSecurityXmlDocumentFactory(); }### Answer:
@Test public void testGetErrorInfo() { Throwable e = new Throwable(); FortifyUtils.getErrorInfo(e, true); Assert.assertNotEquals(true, FortifyUtils.getErrorInfo(e, true)); } |
### Question:
GetInstancesResponse { public List<MicroserviceInstance> getInstances() { return instances; } List<MicroserviceInstance> getInstances(); void setInstances(List<MicroserviceInstance> instances); }### Answer:
@Test public void testDefaultValues() { Assert.assertNull(oGetInstancesResponse.getInstances()); }
@Test public void testInitializedValues() { initFields(); Assert.assertEquals(1, oGetInstancesResponse.getInstances().size()); } |
### Question:
NetMeter { public void calcMeasurements(List<Measurement> measurements, long msNow, long secondInterval) { refreshNet(secondInterval); interfaceUsageMap.values().forEach(interfaceUsage -> { interfaceUsage.calcMeasurements(measurements, msNow); }); } NetMeter(Id id); void calcMeasurements(List<Measurement> measurements, long msNow, long secondInterval); Map<String, InterfaceUsage> getInterfaceUsageMap(); static final String STATISTIC; static final String INTERFACE; static final Tag TAG_RECEIVE; static final Tag TAG_PACKETS_RECEIVE; static final Tag TAG_SEND; static final Tag TAG_PACKETS_SEND; }### Answer:
@Test public void testCalcMeasurements(@Mocked Id id) { List<String> list = new ArrayList<>(); list.add("useless"); list.add("useless"); list.add("eth0: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0"); new MockUp<FileUtils>() { @Mock public List<String> readLines(File file, Charset encoding) { return list; } }; NetMeter netMeter = new NetMeter(id); list.remove(2); list.add("eth0: 3 1 0 0 0 0 0 1 3 1 1 0 0 0 0 0"); List<Measurement> measurements = new ArrayList<>(); netMeter.calcMeasurements(measurements, 0L, 1); Assert.assertEquals(4, measurements.size()); Measurement receive = measurements.get(0); Measurement send = measurements.get(1); Measurement receivePackets = measurements.get(2); Measurement sendPackets = measurements.get(3); Assert.assertEquals(3.0, send.value(), 0.0); Assert.assertEquals(1.0, sendPackets.value(), 0.0); Assert.assertEquals(3.0, receive.value(), 0.0); Assert.assertEquals(1.0, receivePackets.value(), 0.0); } |
### Question:
SPIServiceUtils { public static <T> T getTargetService(Class<T> serviceType) { List<T> services = getOrLoadSortedService(serviceType); if (services.isEmpty()) { LOGGER.info("Can not find SPI service for {}", serviceType.getName()); return null; } return services.get(0); } private SPIServiceUtils(); static List<T> loadSortedService(Class<T> serviceType); @SuppressWarnings("unchecked") static List<T> getOrLoadSortedService(Class<T> serviceType); static T getTargetService(Class<T> serviceType); static List<T> getAllService(Class<T> serviceType); static List<T> getSortedService(Class<T> serviceType); static T getPriorityHighestService(Class<T> serviceType); static Collection<T> getPriorityHighestServices(Function<T, String> keyFunc, Class<T> serviceType); @SuppressWarnings("unchecked") static IMPL getTargetService(Class<T> serviceType, Class<IMPL> implType); }### Answer:
@Test public void testGetTargetServiceNull() { SPIServiceDef0 service = SPIServiceUtils.getTargetService(SPIServiceDef0.class); Assert.assertNull(service); }
@Test public void testGetTargetServiceNotNull() { SPIServiceDef service = SPIServiceUtils.getTargetService(SPIServiceDef.class); Assert.assertTrue(SPIServiceDef.class.isInstance(service)); Assert.assertSame(service, SPIServiceUtils.getTargetService(SPIServiceDef.class)); }
@Test public void testGetTargetService_special_null() { Assert.assertNull(SPIServiceUtils.getTargetService(SPIServiceDef0.class, SPIServiceDef0Impl.class)); }
@Test public void testGetTargetService_special_notNull() { SPIServiceDef service = SPIServiceUtils.getTargetService(SPIServiceDef.class, SPIServiceDefImpl.class); Assert.assertTrue(SPIServiceDefImpl.class.isInstance(service)); } |
### Question:
SPIServiceUtils { public static <T> T getPriorityHighestService(Class<T> serviceType) { List<T> services = getOrLoadSortedService(serviceType); if (services.isEmpty()) { LOGGER.info("Can not find SPI service for {}", serviceType.getName()); return null; } return services.get(0); } private SPIServiceUtils(); static List<T> loadSortedService(Class<T> serviceType); @SuppressWarnings("unchecked") static List<T> getOrLoadSortedService(Class<T> serviceType); static T getTargetService(Class<T> serviceType); static List<T> getAllService(Class<T> serviceType); static List<T> getSortedService(Class<T> serviceType); static T getPriorityHighestService(Class<T> serviceType); static Collection<T> getPriorityHighestServices(Function<T, String> keyFunc, Class<T> serviceType); @SuppressWarnings("unchecked") static IMPL getTargetService(Class<T> serviceType, Class<IMPL> implType); }### Answer:
@Test public void getPriorityHighestService_null() { Assert.assertNull(SPIServiceUtils.getPriorityHighestService(SPIServiceDef0.class)); } |
### Question:
GenericsUtils { public static boolean isGenericResponseType(Type type) { if (type instanceof ParameterizedType) { return false; } if (type instanceof Class<?>) { return ((Class<?>) type).getTypeParameters().length > 0; } return true; } static boolean isGenericResponseType(Type type); }### Answer:
@Test public void testIsGenerics() { Assert.assertTrue(GenericsUtils.isGenericResponseType(List.class)); Assert.assertTrue(GenericsUtils.isGenericResponseType(Map.class)); Assert.assertTrue(GenericsUtils.isGenericResponseType(Person.class)); Assert.assertFalse(GenericsUtils.isGenericResponseType(Man.class)); Assert.assertFalse(GenericsUtils.isGenericResponseType(String.class)); Assert.assertFalse(GenericsUtils.isGenericResponseType(GenericsUtils.class)); Assert.assertFalse(GenericsUtils.isGenericResponseType(new ParameterizedTypeReference<List<Man>>() { }.getType())); } |
### Question:
ExceptionUtils { private ExceptionUtils() { } private ExceptionUtils(); static String getExceptionMessageWithoutTrace(Throwable e); }### Answer:
@Test public void testExceptionUtils() { Exception e = new Exception("Hello"); Assert.assertEquals("cause:Exception,message:Hello", ExceptionUtils.getExceptionMessageWithoutTrace(e)); Exception e2 = new Exception("FAIL", new IOException("IO")); Assert.assertEquals("cause:Exception,message:FAIL;cause:IOException,message:IO", ExceptionUtils.getExceptionMessageWithoutTrace(e2)); } |
### Question:
ResourceUtil { public static List<URI> findResources(String resourceLocation) throws IOException, URISyntaxException { return findResources(resourceLocation, p -> true); } private ResourceUtil(); static List<URI> findResourcesBySuffix(String resourceLocation, String fileNameSuffix); static List<URI> findResources(String resourceLocation); static List<URI> findResources(String resourceLocation, Predicate<Path> filter); }### Answer:
@Test public void loadResources_in_jar() throws IOException, URISyntaxException { List<URI> uris = ResourceUtil.findResources("META-INF", p -> p.toString().endsWith("spring.factories")); Assert.assertEquals(1, uris.size()); Assert.assertTrue(uris.get(0).toString().startsWith("jar:file:")); Assert.assertTrue(uris.get(0).toString().endsWith("!/META-INF/spring.factories")); }
@Test public void loadResources_exact_file_in_disk() throws IOException, URISyntaxException { List<URI> uris = ResourceUtil.findResources("META-INF/spring/config.bean.xml"); Assert.assertEquals(1, uris.size()); URI uri = uris.get(0); Assert.assertTrue("unexpected uri: " + uri, uri.toString().startsWith("file:")); Assert.assertTrue("unexpected uri: " + uri, uri.toString().endsWith("META-INF/spring/config.bean.xml")); } |
### Question:
ResourceUtil { public static List<URI> findResourcesBySuffix(String resourceLocation, String fileNameSuffix) throws IOException, URISyntaxException { return findResources(resourceLocation, path -> path.toString().endsWith(fileNameSuffix)); } private ResourceUtil(); static List<URI> findResourcesBySuffix(String resourceLocation, String fileNameSuffix); static List<URI> findResources(String resourceLocation); static List<URI> findResources(String resourceLocation, Predicate<Path> filter); }### Answer:
@Test public void loadResources_in_disk() throws IOException, URISyntaxException { List<URI> uris = ResourceUtil.findResourcesBySuffix("META-INF/spring", ".xml"); Assert.assertEquals(1, uris.size()); URI uri = uris.get(0); Assert.assertTrue("unexpected uri: " + uri, uri.toString().startsWith("file:")); Assert.assertTrue("unexpected uri: " + uri, uri.toString().endsWith("META-INF/spring/config.bean.xml")); } |
### Question:
AsyncUtils { public static <T> T toSync(CompletableFuture<T> future) { try { return future.get(); } catch (Throwable e) { rethrow(e.getCause()); return null; } } private AsyncUtils(); static CompletableFuture<T> tryCatch(Supplier<CompletableFuture<T>> supplier); static CompletableFuture<T> completeExceptionally(Throwable throwable); @SuppressWarnings("unchecked") static void rethrow(Throwable exception); static T toSync(CompletableFuture<T> future); }### Answer:
@Test void should_convert_success_async_to_sync() { CompletableFuture<String> future = CompletableFuture.completedFuture("value"); assertThat(AsyncUtils.toSync(future)).isEqualTo("value"); } |
### Question:
BeanUtils { public static Class<?> getImplClassFromBean(Object bean) { return AopProxyUtils.ultimateTargetClass(bean); } private BeanUtils(); static void init(); static void init(String... configLocations); static void addBeanLocation(Set<String> locationSet, String... location); static void addBeanLocation(Set<String> locationSet, String location); static void prepareServiceCombScanPackage(); static ApplicationContext getContext(); static void setContext(ApplicationContext applicationContext); @SuppressWarnings("unchecked") static T getBean(String name); static Map<String, T> getBeansOfType(Class<T> type); static Class<?> getImplClassFromBean(Object bean); static final String DEFAULT_BEAN_CORE_RESOURCE; static final String DEFAULT_BEAN_NORMAL_RESOURCE; static final String[] DEFAULT_BEAN_RESOURCE; static final String SCB_SCAN_PACKAGE; }### Answer:
@Test public void test() { Intf target = new Impl(); AspectJProxyFactory factory = new AspectJProxyFactory(target); MyAspect aspect = new MyAspect(); factory.addAspect(aspect); Intf proxy = factory.getProxy(); Assert.assertEquals(Impl.class, BeanUtils.getImplClassFromBean(proxy)); Assert.assertEquals(Impl.class, BeanUtils.getImplClassFromBean(new Impl())); }
@Test public void testGetImplClassFromBeanFromCglib(){ TestBean testBeanByCGLIB = new TestBean$$TestBeanByCGLIB$$e1a36bab(); Class<?> generatedClass = BeanUtils.getImplClassFromBean(testBeanByCGLIB); Assert.assertNotNull(generatedClass); Assert.assertEquals(TestBean.class, generatedClass); } |
### Question:
BeanUtils { public static void init() { init(DEFAULT_BEAN_RESOURCE); } private BeanUtils(); static void init(); static void init(String... configLocations); static void addBeanLocation(Set<String> locationSet, String... location); static void addBeanLocation(Set<String> locationSet, String location); static void prepareServiceCombScanPackage(); static ApplicationContext getContext(); static void setContext(ApplicationContext applicationContext); @SuppressWarnings("unchecked") static T getBean(String name); static Map<String, T> getBeansOfType(Class<T> type); static Class<?> getImplClassFromBean(Object bean); static final String DEFAULT_BEAN_CORE_RESOURCE; static final String DEFAULT_BEAN_NORMAL_RESOURCE; static final String[] DEFAULT_BEAN_RESOURCE; static final String SCB_SCAN_PACKAGE; }### Answer:
@Test public void init(@Mocked ClassPathXmlApplicationContext context) { System.clearProperty(BeanUtils.SCB_SCAN_PACKAGE); new Expectations(JvmUtils.class) { { JvmUtils.findMainClass(); result = TestBeanUtils.class; JvmUtils.findMainClassByStackTrace(); result = TestBeanUtils.class; } }; BeanUtils.init(); Assert.assertEquals("org.apache.servicecomb", System.getProperty(BeanUtils.SCB_SCAN_PACKAGE)); } |
### Question:
VersionedCache { public <T extends VersionedCache> T autoCacheVersion() { this.cacheVersion = VERSION.incrementAndGet(); return (T) this; } int cacheVersion(); T autoCacheVersion(); T cacheVersion(int cacheVersion); String name(); T name(String name); T subName(VersionedCache parent, String subName); T data(); Map<K, V> mapData(); Collection<T> collectionData(); T[] arrayData(); T data(Object data); boolean isExpired(VersionedCache newCache); boolean isSameVersion(VersionedCache newCache); boolean isEmpty(); }### Answer:
@Test public void autoCacheVersion() { VersionedCache cache = new VersionedCache().autoCacheVersion(); Assert.assertEquals(VERSION.get(), cache.cacheVersion()); } |
### Question:
VersionedCache { public String name() { return name; } int cacheVersion(); T autoCacheVersion(); T cacheVersion(int cacheVersion); String name(); T name(String name); T subName(VersionedCache parent, String subName); T data(); Map<K, V> mapData(); Collection<T> collectionData(); T[] arrayData(); T data(Object data); boolean isExpired(VersionedCache newCache); boolean isSameVersion(VersionedCache newCache); boolean isEmpty(); }### Answer:
@Test public void setName() { VersionedCache cache = new VersionedCache().name("n"); Assert.assertEquals("n", cache.name()); } |
### Question:
VersionedCache { public boolean isExpired(VersionedCache newCache) { return newCache.cacheVersion - cacheVersion > 0; } int cacheVersion(); T autoCacheVersion(); T cacheVersion(int cacheVersion); String name(); T name(String name); T subName(VersionedCache parent, String subName); T data(); Map<K, V> mapData(); Collection<T> collectionData(); T[] arrayData(); T data(Object data); boolean isExpired(VersionedCache newCache); boolean isSameVersion(VersionedCache newCache); boolean isEmpty(); }### Answer:
@Test public void isExpired() { VersionedCache cacheOld = new VersionedCache().autoCacheVersion(); VersionedCache cacheNew = new VersionedCache().autoCacheVersion(); Assert.assertTrue(cacheOld.isExpired(cacheNew)); Assert.assertFalse(cacheOld.isExpired(cacheOld)); Assert.assertFalse(cacheNew.isExpired(cacheOld)); } |
### Question:
VersionedCache { public boolean isSameVersion(VersionedCache newCache) { return newCache.cacheVersion == cacheVersion; } int cacheVersion(); T autoCacheVersion(); T cacheVersion(int cacheVersion); String name(); T name(String name); T subName(VersionedCache parent, String subName); T data(); Map<K, V> mapData(); Collection<T> collectionData(); T[] arrayData(); T data(Object data); boolean isExpired(VersionedCache newCache); boolean isSameVersion(VersionedCache newCache); boolean isEmpty(); }### Answer:
@Test public void isSameVersion() { VersionedCache cacheOld = new VersionedCache().autoCacheVersion(); VersionedCache cacheNew = new VersionedCache().autoCacheVersion(); VersionedCache cacheSame = new VersionedCache().cacheVersion(cacheNew.cacheVersion()); Assert.assertFalse(cacheOld.isSameVersion(cacheNew)); Assert.assertTrue(cacheSame.isSameVersion(cacheNew)); } |
### Question:
PaasNamespaceHandler extends NamespaceHandlerSupport { public void init() { Properties properties = null; try { properties = PaaSResourceUtils.loadMergedProperties(NAMESPACE_RES); } catch (Exception e) { LOGGER.error("Failed to load namespace handler define, {}, {}", NAMESPACE_RES, FortifyUtils.getErrorInfo(e)); return; } for (Entry<Object, Object> entry : properties.entrySet()) { String className = entry.getValue().toString(); try { Class<?> clazz = Class.forName(className); Object instance = clazz.newInstance(); registerBeanDefinitionParser(entry.getKey().toString(), (BeanDefinitionParser) instance); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) { LOGGER.info("Failed to create BeanDefinitionParser instance of {}", className); } } } void init(); }### Answer:
@Test public void testInit() { boolean status = false; try { paasNamespaceHandler.init(); } catch (Exception e) { status = true; } Assert.assertFalse(status); } |
### Question:
DynamicObject { @JsonAnyGetter public Map<String, Object> getDynamic() { return dynamic; } @JsonAnyGetter Map<String, Object> getDynamic(); @SuppressWarnings("unchecked") T getDynamic(String key); void setDynamic(Map<String, Object> dynamic); @JsonAnySetter DynamicObject putDynamic(String key, Object value); }### Answer:
@Test void should_support_json_encode_decode() { Map<String, Object> map = new HashMap<>(); map.put("k", "v"); DynamicObject dynamicObject = DatabindCodec.mapper().convertValue(map, DynamicObject.class); assertThat(dynamicObject.getDynamic()).isNotSameAs(map); assertThat(dynamicObject.getDynamic()).isEqualTo(map); assertThat(Json.encode(dynamicObject)).isEqualTo("{\"k\":\"v\"}"); } |
### Question:
SSLManager { public static SSLSocketFactory createSSLSocketFactory(SSLOption option, SSLCustom custom) { SSLContext context = createSSLContext(option, custom); SSLSocketFactory factory = context.getSocketFactory(); String[] supported = factory.getSupportedCipherSuites(); String[] eanbled = option.getCiphers().split(","); return new SSLSocketFactoryExt(factory, getEnabledCiphers(supported, eanbled), option.getProtocols().split(",")); } private SSLManager(); static SSLContext createSSLContext(SSLOption option, SSLCustom custom); static SSLSocketFactory createSSLSocketFactory(SSLOption option, SSLCustom custom); static SSLEngine createSSLEngine(SSLOption option, SSLCustom custom); static SSLEngine createSSLEngine(SSLOption option, SSLCustom custom, String peerHost, int peerPort); static SSLServerSocket createSSLServerSocket(SSLOption option,
SSLCustom custom); static SSLSocket createSSLSocket(SSLOption option, SSLCustom custom); static String[] getEnalbedCiphers(String enabledCiphers); }### Answer:
@Test public void testCreateSSLSocketFactory() { SSLOption option = SSLOption.build(DIR + "/server.ssl.properties"); SSLCustom custom = new SSLCustom() { @Override public String getFullPath(String filename) { return DIR + "/ssl/" + filename; } @Override public char[] decode(char[] encrypted) { return encrypted; } }; SSLSocketFactory aSSLSocketFactory = SSLManager.createSSLSocketFactory(option, custom); Assert.assertNotNull(aSSLSocketFactory.getDefaultCipherSuites()[0]); } |
### Question:
TrustManagerExt extends X509ExtendedTrustManager { @Override public X509Certificate[] getAcceptedIssuers() { return trustManager.getAcceptedIssuers(); } TrustManagerExt(X509ExtendedTrustManager manager, SSLOption option,
SSLCustom custom); @Override void checkClientTrusted(X509Certificate[] chain, String authType); @Override void checkServerTrusted(X509Certificate[] chain, String authType); @Override X509Certificate[] getAcceptedIssuers(); @Override void checkClientTrusted(X509Certificate[] chain, String authType,
Socket socket); @Override void checkClientTrusted(X509Certificate[] chain, String authType,
SSLEngine engine); @Override void checkServerTrusted(X509Certificate[] chain, String authType,
Socket socket); @Override void checkServerTrusted(X509Certificate[] chain, String authType,
SSLEngine engine); }### Answer:
@SuppressWarnings("unused") @Test public void testConstructor() { String keyStoreName = custom.getFullPath(option.getKeyStore()); char[] keyStoreValue = custom.decode(option.getKeyStoreValue().toCharArray()); String trustStoreName = custom.getFullPath(option.getTrustStore()); char[] trustStoreValue = custom.decode(option.getTrustStoreValue().toCharArray()); KeyStore trustStore = KeyStoreUtil.createKeyStore(trustStoreName, option.getTrustStoreType(), trustStoreValue); TrustManager[] trustManager = KeyStoreUtil.createTrustManagers(trustStore); TrustManagerExt trustManagerExt = new TrustManagerExt((X509ExtendedTrustManager) trustManager[0], option, custom); Assert.assertEquals(3, trustManagerExt.getAcceptedIssuers()[0].getVersion()); Assert.assertNotNull(trustManagerExt); } |
### Question:
SSLSocketFactoryExt extends SSLSocketFactory { @Override public Socket createSocket(Socket s, String host, int port, boolean autoClose) throws IOException { return wrapSocket((SSLSocket) this.sslSocketFactory.createSocket(s, host, port, autoClose)); } SSLSocketFactoryExt(SSLSocketFactory factory, String[] ciphers, String[] protos); @Override Socket createSocket(Socket s, String host, int port, boolean autoClose); @Override String[] getDefaultCipherSuites(); @Override String[] getSupportedCipherSuites(); @Override Socket createSocket(String host, int port); @Override Socket createSocket(InetAddress host, int port); @Override Socket createSocket(String host, int port, InetAddress localHost,
int localPort); @Override Socket createSocket(InetAddress address, int port, InetAddress localAddress,
int localPort); }### Answer:
@Test public void testCreateSocketException() { boolean validAssert = true; try { instance.createSocket("host", 8080); } catch (Exception e) { validAssert = false; } Assert.assertFalse(validAssert); } |
### Question:
KeyStoreUtil { public static KeyStore createKeyStore(String storename, String storetype, char[] storevalue) { InputStream is = null; try { KeyStore keystore = KeyStore.getInstance(storetype); is = new FileInputStream(storename); keystore.load(is, storevalue); return keystore; } catch (Exception e) { throw new IllegalArgumentException("Bad key store or value." + e.getMessage()); } finally { if (is != null) { try { is.close(); } catch (IOException e) { ignore(); } } } } private KeyStoreUtil(); static KeyStore createKeyStore(String storename, String storetype,
char[] storevalue); @SuppressWarnings({"rawtypes", "unchecked"}) static CRL[] createCRL(String crlfile); static KeyManager[] createKeyManagers(final KeyStore keystore,
char[] keyvalue); static TrustManager[] createTrustManagers(final KeyStore keystore); }### Answer:
@Test public void testCreateKeyStoreException() { String storename = ""; String storetype = "testType"; char[] storevalue = "Changeme_123".toCharArray(); try { KeyStoreUtil.createKeyStore(storename, storetype, storevalue); } catch (IllegalArgumentException e) { Assert.assertEquals("Bad key store or value.testType not found", e.getMessage()); } }
@Test public void testCreateKeyStoreException2() { String storename = strFilePath + "/ssl/trust.jks"; String storetype = "PKCS12"; char[] storevalue = "Changeme_123".toCharArray(); try { KeyStoreUtil.createKeyStore(storename, storetype, storevalue); } catch (IllegalArgumentException e) { Assert.assertEquals("Bad key store or value.DerInputStream.getLength(): lengthTag=109, too big.", e.getMessage()); } } |
### Question:
ProtoParser { public Proto parse(String name) { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); try { if (classLoader == null) { Thread.currentThread().setContextClassLoader(ProtoParser.class.getClassLoader()); } ProtoContext context = loader.load(defaultReader, name); return context.getProto(); } finally { Thread.currentThread().setContextClassLoader(classLoader); } } Proto parseFromContent(String content); Proto parse(String name); }### Answer:
@Test public void parse() throws IOException { URL url = Thread.currentThread().getContextClassLoader().getResource("protobufRoot.proto"); String content = IOUtils.toString(url, StandardCharsets.UTF_8); ProtoParser parser = new ProtoParser(); Proto protoFromContent = parser.parseFromContent(content); Proto protoFromName = parser.parse("protobufRoot.proto"); Assert.assertNotNull(protoFromContent.getMessage("Root")); Assert.assertNotNull(protoFromContent.getMessage("User")); Assert.assertEquals(MoreObjects.toStringHelper(protoFromContent) .omitNullValues() .add("messages", protoFromContent.getMessages()) .toString(), MoreObjects.toStringHelper(protoFromName) .omitNullValues() .add("messages", protoFromName.getMessages()) .toString()); } |
### Question:
BeanDescriptorManager { public BeanDescriptor getOrCreateBeanDescriptor(Type type) { return beanDescriptors.computeIfAbsent(type, this::createBeanDescriptor); } BeanDescriptorManager(SerializationConfig serializationConfig); BeanDescriptor getOrCreateBeanDescriptor(Type type); }### Answer:
@Test public void generic() { Method method = ReflectUtils.findMethod(GenericSchema.class, "genericMethod"); BeanDescriptor beanDescriptor = beanDescriptorManager .getOrCreateBeanDescriptor(method.getGenericParameterTypes()[0]); Assert.assertEquals(String.class, beanDescriptor.getPropertyDescriptors().get("value").getJavaType().getRawClass()); }
@Test public void getOrCreate() { Assert.assertSame(beanDescriptor, beanDescriptorManager.getOrCreateBeanDescriptor(Model.class)); Assert.assertSame(Model.class, beanDescriptor.getJavaType().getRawClass()); } |
### Question:
LatencyDistributionConfig { public List<LatencyScopeConfig> getScopeConfigs() { return scopeConfigs; } LatencyDistributionConfig(String config); List<LatencyScopeConfig> getScopeConfigs(); }### Answer:
@Test public void testValidProperty() { String validProperty1 = "0,1,2,10"; String validProperty2 = "0,1, 2 , 10 "; String validProperty3 = "0,1,2,10,"; LatencyDistributionConfig config1 = new LatencyDistributionConfig(validProperty1); LatencyDistributionConfig config2 = new LatencyDistributionConfig(validProperty2); LatencyDistributionConfig config3 = new LatencyDistributionConfig(validProperty3); Assert.assertEquals(4, config1.getScopeConfigs().size()); Assert.assertEquals(4, config2.getScopeConfigs().size()); Assert.assertEquals(4, config3.getScopeConfigs().size()); }
@Test public void testInValidProperty1() { expectedException.expect(IllegalStateException.class); expectedException.expectMessage("invalid latency scope, min=2, max=1."); LatencyDistributionConfig latencyDistributionConfig = new LatencyDistributionConfig("2,1,10"); Assert.assertEquals(0, latencyDistributionConfig.getScopeConfigs().size()); }
@Test public void testInValidProperty2() { expectedException.expect(NumberFormatException.class); expectedException.expectMessage("For input string: \"a\""); LatencyDistributionConfig latencyDistributionConfig = new LatencyDistributionConfig("a,1,10"); Assert.assertEquals(0, latencyDistributionConfig.getScopeConfigs().size()); } |
### Question:
DefaultTagFinder implements TagFinder { @Override public String getTagKey() { return tagKey; } DefaultTagFinder(String tagKey); DefaultTagFinder(String tagKey, boolean skipOnNull); @Override boolean skipOnNull(); @Override String getTagKey(); @Override Tag find(Iterable<Tag> tags); }### Answer:
@Test public void getTagKey() { Assert.assertEquals("key", finder.getTagKey()); } |
### Question:
DefaultTagFinder implements TagFinder { @Override public Tag find(Iterable<Tag> tags) { for (Tag tag : tags) { if (tag.key().equals(tagKey)) { return tag; } } return null; } DefaultTagFinder(String tagKey); DefaultTagFinder(String tagKey, boolean skipOnNull); @Override boolean skipOnNull(); @Override String getTagKey(); @Override Tag find(Iterable<Tag> tags); }### Answer:
@Test public void readSucc() { Tag tag = new BasicTag("key", "value"); List<Tag> tags = Arrays.asList(new BasicTag("t1", "t1v"), tag); Assert.assertSame(tag, finder.find(tags)); }
@Test public void readFail() { List<Tag> tags = Arrays.asList(new BasicTag("t1", "t1v")); Assert.assertNull(finder.find(tags)); } |
### Question:
MeasurementGroupConfig { public void addGroup(String idName, Object... tagNameOrFinders) { groups.put(idName, Arrays .asList(tagNameOrFinders) .stream() .map(r -> TagFinder.build(r)) .collect(Collectors.toList())); } MeasurementGroupConfig(); MeasurementGroupConfig(String idName, Object... tagNameOrFinders); void addGroup(String idName, Object... tagNameOrFinders); List<TagFinder> findTagFinders(String idName); }### Answer:
@Test public void addGroup() { config.addGroup("id1", "tag1.1", "tag1.2"); config.addGroup("id2", "tag2.1", "tag2.2"); Assert.assertThat(groups.keySet(), Matchers.contains("id2", "id1")); Assert.assertThat(groups.get("id1").stream().map(e -> { return e.getTagKey(); }).toArray(), Matchers.arrayContaining("tag1.1", "tag1.2")); Assert.assertThat(groups.get("id2").stream().map(e -> { return e.getTagKey(); }).toArray(), Matchers.arrayContaining("tag2.1", "tag2.2")); } |
### Question:
MeasurementTree extends MeasurementNode { public void from(Iterator<Meter> meters, MeasurementGroupConfig groupConfig) { meters.forEachRemaining(meter -> { Iterable<Measurement> measurements = meter.measure(); from(measurements, groupConfig); }); } MeasurementTree(); void from(Iterator<Meter> meters, MeasurementGroupConfig groupConfig); void from(Iterable<Measurement> measurements, MeasurementGroupConfig groupConfig); }### Answer:
@Test public void from() { timer.record(10, TimeUnit.NANOSECONDS); timer.record(2, TimeUnit.NANOSECONDS); MeasurementGroupConfig config = new MeasurementGroupConfig("id", "g1", "g2", Statistic.count.key()); tree.from(registry.iterator(), config); Assert.assertEquals(2, tree.getChildren().size()); MeasurementNode node = tree.findChild("id", "g1v", "g2v"); Assert.assertEquals(2d, node.findChild(Statistic.count.value()).getMeasurements().get(0).value(), 0); Assert.assertEquals(12d, node.findChild(Statistic.totalTime.value()).getMeasurements().get(0).value(), 0); Assert.assertEquals(0d, tree.findChild("id_notCare").summary(), 0); }
@Test public void from_withSkipOnNull() { try { MeasurementGroupConfig config = new MeasurementGroupConfig("id", new DefaultTagFinder("notExist", true)); tree.from(registry.iterator(), config); } catch (Exception e) { Assert.fail("should not throw exception"); } }
@Test public void from_failed() { expectedException.expect(IllegalStateException.class); expectedException.expectMessage(Matchers .is("tag key \"notExist\" not exist in Measurement(id:g1=g1v:g2=g2v:statistic=count:t3=t3v:t4=t4v,0,0.0)")); MeasurementGroupConfig config = new MeasurementGroupConfig("id", "notExist"); tree.from(registry.iterator(), config); } |
### Question:
MeasurementNode { public String getName() { return name; } MeasurementNode(String name, Map<String, MeasurementNode> children); String getName(); Map<String, MeasurementNode> getChildren(); MeasurementNode findChild(String childName); MeasurementNode findChild(String... childNames); MeasurementNode addChild(String childName, Measurement measurement); List<Measurement> getMeasurements(); void addMeasurement(Measurement measurement); double summary(); }### Answer:
@Test public void getName() { Assert.assertEquals("name", node.getName()); } |
### Question:
MeasurementNode { public Map<String, MeasurementNode> getChildren() { return children; } MeasurementNode(String name, Map<String, MeasurementNode> children); String getName(); Map<String, MeasurementNode> getChildren(); MeasurementNode findChild(String childName); MeasurementNode findChild(String... childNames); MeasurementNode addChild(String childName, Measurement measurement); List<Measurement> getMeasurements(); void addMeasurement(Measurement measurement); double summary(); }### Answer:
@Test public void getChildren() { Map<String, MeasurementNode> children = new HashMap<>(); node = new MeasurementNode("name", children); Assert.assertSame(children, node.getChildren()); } |
### Question:
MeasurementNode { public MeasurementNode findChild(String childName) { if (children == null) { return null; } return children.get(childName); } MeasurementNode(String name, Map<String, MeasurementNode> children); String getName(); Map<String, MeasurementNode> getChildren(); MeasurementNode findChild(String childName); MeasurementNode findChild(String... childNames); MeasurementNode addChild(String childName, Measurement measurement); List<Measurement> getMeasurements(); void addMeasurement(Measurement measurement); double summary(); }### Answer:
@Test public void findChild_noChildren() { Assert.assertNull(node.findChild("child")); } |
### Question:
MeasurementNode { public MeasurementNode addChild(String childName, Measurement measurement) { if (children == null) { children = new LinkedHashMap<>(); } MeasurementNode node = children.computeIfAbsent(childName, name -> new MeasurementNode(name, null)); node.addMeasurement(measurement); return node; } MeasurementNode(String name, Map<String, MeasurementNode> children); String getName(); Map<String, MeasurementNode> getChildren(); MeasurementNode findChild(String childName); MeasurementNode findChild(String... childNames); MeasurementNode addChild(String childName, Measurement measurement); List<Measurement> getMeasurements(); void addMeasurement(Measurement measurement); double summary(); }### Answer:
@Test public void addChild(@Mocked Measurement measurement) { MeasurementNode c1 = node.addChild("c1", measurement); MeasurementNode c2 = node.addChild("c2", measurement); Assert.assertSame(c1, node.findChild("c1")); Assert.assertSame(c2, node.findChild("c2")); } |
### Question:
MeasurementNode { public List<Measurement> getMeasurements() { return measurements; } MeasurementNode(String name, Map<String, MeasurementNode> children); String getName(); Map<String, MeasurementNode> getChildren(); MeasurementNode findChild(String childName); MeasurementNode findChild(String... childNames); MeasurementNode addChild(String childName, Measurement measurement); List<Measurement> getMeasurements(); void addMeasurement(Measurement measurement); double summary(); }### Answer:
@Test public void getMeasurements(@Mocked Measurement measurement) { node.addMeasurement(measurement); Assert.assertThat(node.getMeasurements(), Matchers.contains(measurement)); } |
### Question:
MeasurementNode { public double summary() { double result = 0; for (Measurement measurement : measurements) { result += measurement.value(); } return result; } MeasurementNode(String name, Map<String, MeasurementNode> children); String getName(); Map<String, MeasurementNode> getChildren(); MeasurementNode findChild(String childName); MeasurementNode findChild(String... childNames); MeasurementNode addChild(String childName, Measurement measurement); List<Measurement> getMeasurements(); void addMeasurement(Measurement measurement); double summary(); }### Answer:
@Test public void summary(@Mocked Measurement measurement) { new Expectations() { { measurement.value(); result = 10; } }; node.addMeasurement(measurement); node.addMeasurement(measurement); Assert.assertEquals(20, node.summary(), 0); } |
### Question:
MetricsBootstrap { protected void loadMetricsInitializers() { SPIServiceUtils.getSortedService(MetricsInitializer.class) .forEach(initializer -> initializer.init(globalRegistry, eventBus, config)); } void start(GlobalRegistry globalRegistry, EventBus eventBus); void shutdown(); synchronized void pollMeters(); }### Answer:
@Test public void loadMetricsInitializers() { List<MetricsInitializer> initList = new ArrayList<>(); MetricsInitializer metricsInitializer = new MetricsInitializer() { @Override public void init(GlobalRegistry globalRegistry, EventBus eventBus, MetricsBootstrapConfig config) { initList.add(this); } }; new Expectations(SPIServiceUtils.class) { { SPIServiceUtils.getSortedService(MetricsInitializer.class); result = Arrays.asList(metricsInitializer, metricsInitializer); } }; bootstrap.start(globalRegistry, eventBus); bootstrap.shutdown(); Assert.assertThat(initList, Matchers.contains(metricsInitializer, metricsInitializer)); } |
### Question:
MetricsBootstrap { public synchronized void pollMeters() { try { long secondInterval = TimeUnit.MILLISECONDS.toSeconds(config.getMsPollInterval()); PolledEvent polledEvent = globalRegistry.poll(secondInterval); eventBus.post(polledEvent); } catch (Throwable e) { LOGGER.error("poll meters error. ", e); } } void start(GlobalRegistry globalRegistry, EventBus eventBus); void shutdown(); synchronized void pollMeters(); }### Answer:
@Test public void pollMeters(@Mocked Registry registry, @Mocked Meter meter, @Mocked Measurement measurement, @Mocked ScheduledExecutorService executor) { List<Meter> meters = Arrays.asList(meter); globalRegistry.add(registry); new Expectations(Executors.class) { { Executors.newScheduledThreadPool(1, (ThreadFactory) any); result = executor; registry.iterator(); result = meters.iterator(); meter.measure(); result = Arrays.asList(measurement); } }; bootstrap.start(globalRegistry, eventBus); PolledEvent result = new PolledEvent(null, null); eventBus.register(new Object() { @Subscribe public void onEvent(PolledEvent event) { result.setMeters(event.getMeters()); result.setMeasurements(event.getMeasurements()); } }); bootstrap.pollMeters(); bootstrap.shutdown(); Assert.assertEquals(meters, result.getMeters()); Assert.assertThat(result.getMeasurements(), Matchers.contains(measurement)); } |
### Question:
MetricsBootstrap { public void shutdown() { if (executorService != null) { executorService.shutdown(); } List<MetricsInitializer> initializers = new ArrayList<>(SPIServiceUtils.getSortedService(MetricsInitializer.class)); Collections.reverse(initializers); initializers.forEach(initializer -> initializer.destroy()); } void start(GlobalRegistry globalRegistry, EventBus eventBus); void shutdown(); synchronized void pollMeters(); }### Answer:
@Test public void shutdown(@Mocked ScheduledExecutorService scheduledExecutorService) { List<MetricsInitializer> destroyList = new ArrayList<>(); MetricsInitializer initializer1 = new MetricsInitializer() { @Override public int getOrder() { return 1; } @Override public void init(GlobalRegistry globalRegistry, EventBus eventBus, MetricsBootstrapConfig config) { } @Override public void destroy() { destroyList.add(this); } }; MetricsInitializer initializer2 = new MetricsInitializer() { @Override public int getOrder() { return 2; } @Override public void init(GlobalRegistry globalRegistry, EventBus eventBus, MetricsBootstrapConfig config) { } @Override public void destroy() { destroyList.add(this); } }; new Expectations(SPIServiceUtils.class) { { SPIServiceUtils.getSortedService(MetricsInitializer.class); result = Arrays.asList(initializer1, initializer2); } }; Deencapsulation.setField(bootstrap, "executorService", scheduledExecutorService); bootstrap.shutdown(); Assert.assertThat(destroyList, Matchers.contains(initializer2, initializer1)); }
@Test public void shutdown_notStart() { Assert.assertNull(Deencapsulation.getField(bootstrap, "executorService")); bootstrap.shutdown(); } |
### Question:
ConfigUtil { public static void addConfig(String key, Object value) { localConfig.put(key, value); } private ConfigUtil(); static void setConfigs(Map<String, Object> config); static void addConfig(String key, Object value); static Object getProperty(String key); static Object getProperty(Object config, String key); static List<String> getStringList(@Nonnull Configuration config, @Nonnull String key); static MicroserviceConfigLoader getMicroserviceConfigLoader(); static MicroserviceConfigLoader getMicroserviceConfigLoader(Configuration config); static ConcurrentCompositeConfiguration createLocalConfig(); static AbstractConfiguration convertEnvVariable(AbstractConfiguration source); static AbstractConfiguration createDynamicConfig(); static void installDynamicConfig(); static void destroyConfigCenterConfigurationSource(); static void addExtraConfig(String extraConfigName, Map<String, Object> extraConfig); static void clearExtraConfig(); @SuppressWarnings("unchecked") static ConcurrentHashMap<String, DynamicProperty> getAllDynamicProperties(); @SuppressWarnings("unchecked") static CopyOnWriteArraySet<Runnable> getCallbacks(DynamicProperty property); }### Answer:
@Test public void testAddConfig() { Map<String, Object> config = new HashMap<>(); config.put("service_description.name", "service_name_test"); ConfigUtil.setConfigs(config); ConfigUtil.addConfig("service_description.version", "1.0.2"); ConfigUtil.addConfig("cse.test.enabled", true); ConfigUtil.addConfig("cse.test.num", 10); AbstractConfiguration configuration = ConfigUtil.createDynamicConfig(); Assert.assertEquals(configuration.getString("service_description.name"), "service_name_test"); Assert.assertTrue(configuration.getBoolean("cse.test.enabled")); Assert.assertEquals(configuration.getInt("cse.test.num"), 10); } |
### Question:
ConfigUtil { public static AbstractConfiguration createDynamicConfig() { ConcurrentCompositeConfiguration compositeConfig = ConfigUtil.createLocalConfig(); ConfigCenterConfigurationSource configCenterConfigurationSource = createConfigCenterConfigurationSource(compositeConfig); if (configCenterConfigurationSource != null) { createDynamicWatchedConfiguration(compositeConfig, configCenterConfigurationSource); } return compositeConfig; } private ConfigUtil(); static void setConfigs(Map<String, Object> config); static void addConfig(String key, Object value); static Object getProperty(String key); static Object getProperty(Object config, String key); static List<String> getStringList(@Nonnull Configuration config, @Nonnull String key); static MicroserviceConfigLoader getMicroserviceConfigLoader(); static MicroserviceConfigLoader getMicroserviceConfigLoader(Configuration config); static ConcurrentCompositeConfiguration createLocalConfig(); static AbstractConfiguration convertEnvVariable(AbstractConfiguration source); static AbstractConfiguration createDynamicConfig(); static void installDynamicConfig(); static void destroyConfigCenterConfigurationSource(); static void addExtraConfig(String extraConfigName, Map<String, Object> extraConfig); static void clearExtraConfig(); @SuppressWarnings("unchecked") static ConcurrentHashMap<String, DynamicProperty> getAllDynamicProperties(); @SuppressWarnings("unchecked") static CopyOnWriteArraySet<Runnable> getCallbacks(DynamicProperty property); }### Answer:
@Test public void testCreateDynamicConfigHasConfigCenter() { AbstractConfiguration dynamicConfig = ConfigUtil.createDynamicConfig(); Assert.assertEquals(DynamicWatchedConfiguration.class, ((ConcurrentCompositeConfiguration) dynamicConfig).getConfiguration(0).getClass()); } |
### Question:
ConfigUtil { public static Object getProperty(String key) { Object config = DynamicPropertyFactory.getBackingConfigurationSource(); return getProperty(config, key); } private ConfigUtil(); static void setConfigs(Map<String, Object> config); static void addConfig(String key, Object value); static Object getProperty(String key); static Object getProperty(Object config, String key); static List<String> getStringList(@Nonnull Configuration config, @Nonnull String key); static MicroserviceConfigLoader getMicroserviceConfigLoader(); static MicroserviceConfigLoader getMicroserviceConfigLoader(Configuration config); static ConcurrentCompositeConfiguration createLocalConfig(); static AbstractConfiguration convertEnvVariable(AbstractConfiguration source); static AbstractConfiguration createDynamicConfig(); static void installDynamicConfig(); static void destroyConfigCenterConfigurationSource(); static void addExtraConfig(String extraConfigName, Map<String, Object> extraConfig); static void clearExtraConfig(); @SuppressWarnings("unchecked") static ConcurrentHashMap<String, DynamicProperty> getAllDynamicProperties(); @SuppressWarnings("unchecked") static CopyOnWriteArraySet<Runnable> getCallbacks(DynamicProperty property); }### Answer:
@Test public void testGetPropertyInvalidConfig() { Assert.assertNull(ConfigUtil.getProperty(null, "any")); Assert.assertNull(ConfigUtil.getProperty(new Object(), "any")); }
@Test public void duplicateServiceCombConfigToCseListValue() { List<String> list = Arrays.asList("a", "b"); AbstractConfiguration config = new DynamicConfiguration(); config.addProperty("cse.list", list); Deencapsulation.invoke(ConfigUtil.class, "duplicateCseConfigToServicecomb", config); Object result = config.getProperty("servicecomb.list"); assertThat(result, instanceOf(List.class)); assertThat(result, equalTo(list)); } |
### Question:
ConfigUtil { public static AbstractConfiguration convertEnvVariable(AbstractConfiguration source) { Iterator<String> keys = source.getKeys(); while (keys.hasNext()) { String key = keys.next(); String[] separatedKey = key.split(CONFIG_KEY_SPLITER); if (separatedKey.length == 1) { continue; } String newKey = String.join(".", separatedKey); source.addProperty(newKey, source.getProperty(key)); } return source; } private ConfigUtil(); static void setConfigs(Map<String, Object> config); static void addConfig(String key, Object value); static Object getProperty(String key); static Object getProperty(Object config, String key); static List<String> getStringList(@Nonnull Configuration config, @Nonnull String key); static MicroserviceConfigLoader getMicroserviceConfigLoader(); static MicroserviceConfigLoader getMicroserviceConfigLoader(Configuration config); static ConcurrentCompositeConfiguration createLocalConfig(); static AbstractConfiguration convertEnvVariable(AbstractConfiguration source); static AbstractConfiguration createDynamicConfig(); static void installDynamicConfig(); static void destroyConfigCenterConfigurationSource(); static void addExtraConfig(String extraConfigName, Map<String, Object> extraConfig); static void clearExtraConfig(); @SuppressWarnings("unchecked") static ConcurrentHashMap<String, DynamicProperty> getAllDynamicProperties(); @SuppressWarnings("unchecked") static CopyOnWriteArraySet<Runnable> getCallbacks(DynamicProperty property); }### Answer:
@Test public void testConvertEnvVariable() { String someProperty = "cse_service_registry_address"; AbstractConfiguration config = new DynamicConfiguration(); config.addProperty(someProperty, "testing"); AbstractConfiguration result = ConfigUtil.convertEnvVariable(config); assertThat(result.getString("cse.service.registry.address"), equalTo("testing")); assertThat(result.getString("cse_service_registry_address"), equalTo("testing")); } |
### Question:
ConfigUtil { public static void destroyConfigCenterConfigurationSource() { SPIServiceUtils.getAllService(ConfigCenterConfigurationSource.class).forEach(source -> { try { source.destroy(); } catch (Throwable e) { LOGGER.error("Failed to destroy {}", source.getClass().getName()); } }); } private ConfigUtil(); static void setConfigs(Map<String, Object> config); static void addConfig(String key, Object value); static Object getProperty(String key); static Object getProperty(Object config, String key); static List<String> getStringList(@Nonnull Configuration config, @Nonnull String key); static MicroserviceConfigLoader getMicroserviceConfigLoader(); static MicroserviceConfigLoader getMicroserviceConfigLoader(Configuration config); static ConcurrentCompositeConfiguration createLocalConfig(); static AbstractConfiguration convertEnvVariable(AbstractConfiguration source); static AbstractConfiguration createDynamicConfig(); static void installDynamicConfig(); static void destroyConfigCenterConfigurationSource(); static void addExtraConfig(String extraConfigName, Map<String, Object> extraConfig); static void clearExtraConfig(); @SuppressWarnings("unchecked") static ConcurrentHashMap<String, DynamicProperty> getAllDynamicProperties(); @SuppressWarnings("unchecked") static CopyOnWriteArraySet<Runnable> getCallbacks(DynamicProperty property); }### Answer:
@Test public void destroyConfigCenterConfigurationSource() { AtomicInteger count = new AtomicInteger(); ConfigCenterConfigurationSource source = new MockUp<ConfigCenterConfigurationSource>() { @Mock void destroy() { count.incrementAndGet(); } }.getMockInstance(); new Expectations(SPIServiceUtils.class) { { SPIServiceUtils.getAllService(ConfigCenterConfigurationSource.class); result = Arrays.asList(source, source); } }; ConfigUtil.destroyConfigCenterConfigurationSource(); Assert.assertEquals(2, count.get()); } |
### Question:
DiscoveryTree { public void loadFromSPI(Class<? extends DiscoveryFilter> cls) { filters.addAll(SPIServiceUtils.getSortedService(cls)); } void loadFromSPI(Class<? extends DiscoveryFilter> cls); void addFilter(DiscoveryFilter filter); void sort(); DiscoveryTreeNode discovery(DiscoveryContext context, String appId, String microserviceName,
String versionRule); DiscoveryTreeNode discovery(DiscoveryContext context, VersionedCache inputCache); }### Answer:
@Test public void loadFromSPI(@Mocked DiscoveryFilter f1, @Mocked DiscoveryFilter f2) { Class<? extends DiscoveryFilter> cls = DiscoveryFilter.class; new Expectations(SPIServiceUtils.class) { { SPIServiceUtils.getSortedService(cls); result = Arrays.asList(f1, f2); } }; discoveryTree.loadFromSPI(cls); Assert.assertThat(filters, Matchers.contains(f1, f2)); } |
### Question:
DiscoveryTree { public void sort() { filters.sort(Comparator.comparingInt(DiscoveryFilter::getOrder)); Iterator<DiscoveryFilter> iterator = filters.iterator(); while (iterator.hasNext()) { DiscoveryFilter filter = iterator.next(); if (!filter.enabled()) { iterator.remove(); } LOGGER.info("DiscoveryFilter {}, enabled {}.", filter.getClass().getName(), filter.enabled()); } } void loadFromSPI(Class<? extends DiscoveryFilter> cls); void addFilter(DiscoveryFilter filter); void sort(); DiscoveryTreeNode discovery(DiscoveryContext context, String appId, String microserviceName,
String versionRule); DiscoveryTreeNode discovery(DiscoveryContext context, VersionedCache inputCache); }### Answer:
@Test public void sort(@Mocked DiscoveryFilter f1, @Mocked DiscoveryFilter f2, @Mocked DiscoveryFilter f3) { new Expectations() { { f1.getOrder(); result = -1; f1.enabled(); result = true; f2.getOrder(); result = 0; f2.enabled(); result = true; f3.getOrder(); result = 0; f3.enabled(); result = false; } }; discoveryTree.addFilter(f3); discoveryTree.addFilter(f2); discoveryTree.addFilter(f1); discoveryTree.sort(); Assert.assertThat(filters, Matchers.contains(f1, f2)); } |
### Question:
DiscoveryTree { protected boolean isMatch(VersionedCache existing, VersionedCache inputCache) { return existing != null && existing.isSameVersion(inputCache); } void loadFromSPI(Class<? extends DiscoveryFilter> cls); void addFilter(DiscoveryFilter filter); void sort(); DiscoveryTreeNode discovery(DiscoveryContext context, String appId, String microserviceName,
String versionRule); DiscoveryTreeNode discovery(DiscoveryContext context, VersionedCache inputCache); }### Answer:
@Test public void isMatch_existingNull() { Assert.assertFalse(discoveryTree.isMatch(null, null)); }
@Test public void isMatch_yes() { parent.cacheVersion(1); Assert.assertTrue(discoveryTree.isMatch(new DiscoveryTreeNode().cacheVersion(1), parent)); } |
### Question:
DiscoveryTree { protected boolean isExpired(VersionedCache existing, VersionedCache inputCache) { return existing == null || existing.isExpired(inputCache); } void loadFromSPI(Class<? extends DiscoveryFilter> cls); void addFilter(DiscoveryFilter filter); void sort(); DiscoveryTreeNode discovery(DiscoveryContext context, String appId, String microserviceName,
String versionRule); DiscoveryTreeNode discovery(DiscoveryContext context, VersionedCache inputCache); }### Answer:
@Test public void isMatch_no() { parent.cacheVersion(0); Assert.assertFalse(discoveryTree.isExpired(new DiscoveryTreeNode().cacheVersion(1), parent)); }
@Test public void isExpired_existingNull() { Assert.assertTrue(discoveryTree.isExpired(null, null)); }
@Test public void isExpired_yes() { parent.cacheVersion(1); Assert.assertTrue(discoveryTree.isExpired(new DiscoveryTreeNode().cacheVersion(0), parent)); }
@Test public void isExpired_no() { parent.cacheVersion(0); Assert.assertFalse(discoveryTree.isExpired(new DiscoveryTreeNode().cacheVersion(0), parent)); } |
### Question:
DiscoveryTree { public DiscoveryTreeNode discovery(DiscoveryContext context, String appId, String microserviceName, String versionRule) { VersionedCache instanceVersionedCache = DiscoveryManager.INSTANCE .getInstanceCacheManager() .getOrCreateVersionedCache(appId, microserviceName, versionRule); return discovery(context, instanceVersionedCache); } void loadFromSPI(Class<? extends DiscoveryFilter> cls); void addFilter(DiscoveryFilter filter); void sort(); DiscoveryTreeNode discovery(DiscoveryContext context, String appId, String microserviceName,
String versionRule); DiscoveryTreeNode discovery(DiscoveryContext context, VersionedCache inputCache); }### Answer:
@Test public void easyDiscovery(@Mocked InstanceCacheManager instanceCacheManager) { new Expectations(DiscoveryManager.class) { { DiscoveryManager.INSTANCE.getInstanceCacheManager(); result = instanceCacheManager; instanceCacheManager.getOrCreateVersionedCache(anyString, anyString, anyString); result = parent; } }; result = discoveryTree.discovery(context, null, null, null); Assert.assertEquals(parent.name(), result.name()); Assert.assertEquals(parent.cacheVersion(), result.cacheVersion()); }
@Test public void avoidConcurrentProblem() { Deencapsulation.setField(discoveryTree, "root", parent.cacheVersion(1)); Assert.assertTrue(parent.children().isEmpty()); discoveryTree.discovery(context, new VersionedCache().cacheVersion(0).name("input")); Assert.assertTrue(parent.children().isEmpty()); } |
### Question:
DiscoveryTree { protected DiscoveryTreeNode getOrCreateRoot(VersionedCache inputCache) { DiscoveryTreeNode tmpRoot = root; if (isMatch(tmpRoot, inputCache)) { return tmpRoot; } synchronized (lock) { if (isExpired(root, inputCache)) { root = new DiscoveryTreeNode().cacheVersion(inputCache.cacheVersion()); return root; } if (root.isSameVersion(inputCache)) { return root; } } return new DiscoveryTreeNode().cacheVersion(inputCache.cacheVersion()); } void loadFromSPI(Class<? extends DiscoveryFilter> cls); void addFilter(DiscoveryFilter filter); void sort(); DiscoveryTreeNode discovery(DiscoveryContext context, String appId, String microserviceName,
String versionRule); DiscoveryTreeNode discovery(DiscoveryContext context, VersionedCache inputCache); }### Answer:
@Test public void getOrCreateRoot_match() { Deencapsulation.setField(discoveryTree, "root", parent); DiscoveryTreeNode root = discoveryTree.getOrCreateRoot(parent); Assert.assertSame(parent, root); }
@Test public void getOrCreateRoot_expired() { Deencapsulation.setField(discoveryTree, "root", parent); VersionedCache inputCache = new VersionedCache().cacheVersion(parent.cacheVersion() + 1); DiscoveryTreeNode root = discoveryTree.getOrCreateRoot(inputCache); Assert.assertEquals(inputCache.cacheVersion(), root.cacheVersion()); Assert.assertSame(Deencapsulation.getField(discoveryTree, "root"), root); }
@Test public void getOrCreateRoot_tempRoot() { Deencapsulation.setField(discoveryTree, "root", parent); VersionedCache inputCache = new VersionedCache().cacheVersion(parent.cacheVersion() - 1); DiscoveryTreeNode root = discoveryTree.getOrCreateRoot(inputCache); Assert.assertEquals(inputCache.cacheVersion(), root.cacheVersion()); Assert.assertNotSame(Deencapsulation.getField(discoveryTree, "root"), root); } |
### Question:
DiscoveryTreeNode extends VersionedCache { public boolean childrenInited() { return childrenInited; } boolean childrenInited(); DiscoveryTreeNode childrenInited(boolean childrenInited); int level(); DiscoveryTreeNode level(int level); @SuppressWarnings("unchecked") T attribute(String key); DiscoveryTreeNode attribute(String key, Object value); Map<String, DiscoveryTreeNode> children(); DiscoveryTreeNode children(Map<String, DiscoveryTreeNode> children); DiscoveryTreeNode child(String childName); DiscoveryTreeNode child(String childName, DiscoveryTreeNode child); DiscoveryTreeNode fromCache(VersionedCache other); }### Answer:
@Test public void childrenInited() { Assert.assertFalse(node.childrenInited()); node.childrenInited(true); Assert.assertTrue(node.childrenInited()); } |
### Question:
DiscoveryTreeNode extends VersionedCache { public int level() { return level; } boolean childrenInited(); DiscoveryTreeNode childrenInited(boolean childrenInited); int level(); DiscoveryTreeNode level(int level); @SuppressWarnings("unchecked") T attribute(String key); DiscoveryTreeNode attribute(String key, Object value); Map<String, DiscoveryTreeNode> children(); DiscoveryTreeNode children(Map<String, DiscoveryTreeNode> children); DiscoveryTreeNode child(String childName); DiscoveryTreeNode child(String childName, DiscoveryTreeNode child); DiscoveryTreeNode fromCache(VersionedCache other); }### Answer:
@Test public void level() { node.level(1); Assert.assertEquals(1, node.level()); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.