method2testcases
stringlengths 118
3.08k
|
---|
### Question:
Gateway { String getApiUrl(String apiVersion) { if (Integer.valueOf(apiVersion) < MIN_API_VERSION) { throw new IllegalArgumentException("API version must be >= " + MIN_API_VERSION); } if (region == null) { throw new IllegalStateException("You must initialize the the Gateway instance with a Region before use"); } return "https: } Gateway(); String getMerchantId(); Gateway setMerchantId(String merchantId); Region getRegion(); Gateway setRegion(Region region); void updateSession(String sessionId, String apiVersion, GatewayMap payload, GatewayCallback callback); Single<GatewayMap> updateSession(String sessionId, String apiVersion, GatewayMap payload); static void start3DSecureActivity(Activity activity, String html); static void start3DSecureActivity(Activity activity, String html, String title); static boolean handle3DSecureResult(int requestCode, int resultCode, Intent data, Gateway3DSecureCallback callback); static void requestGooglePayData(PaymentsClient paymentsClient, PaymentDataRequest request, Activity activity); static boolean handleGooglePayResult(int requestCode, int resultCode, Intent data, GatewayGooglePayCallback callback); }### Answer:
@Test public void testGetApiUrlThrowsExceptionIfRegionIsNull() throws Exception { String apiVersion = "44"; gateway.region = null; try { String apiUrl = gateway.getApiUrl(apiVersion); fail("Null region should have caused illegal state exception"); } catch (Exception e) { assertTrue(e instanceof IllegalStateException); } }
@Test public void testGetApiUrlThrowsExceptionIfApiVersionIsLessThanMin() throws Exception { String apiVersion = String.valueOf(Gateway.MIN_API_VERSION - 1); try { String apiUrl = gateway.getApiUrl(apiVersion); fail("Api version less than minimum value should have caused illegal argument exception"); } catch (Exception e) { assertTrue(e instanceof IllegalArgumentException); } }
@Test public void testGetApiUrlWorksAsIntended() throws Exception { gateway.region = Gateway.Region.NORTH_AMERICA; String expectedUrl = "https: assertEquals(expectedUrl, gateway.getApiUrl(String.valueOf(Gateway.MIN_API_VERSION))); } |
### Question:
Gateway3DSecureActivity extends AppCompatActivity { String getExtraHtml() { Bundle extras = getIntent().getExtras(); if (extras != null) { return extras.getString(EXTRA_HTML); } return null; } static final String EXTRA_HTML; static final String EXTRA_TITLE; static final String EXTRA_ACS_RESULT; }### Answer:
@Test public void testGetExtraHtmlReturnsNullIfMissing() { Intent testIntent = new Intent(); doReturn(testIntent).when(activity).getIntent(); String html = activity.getExtraHtml(); assertNull(html); }
@Test public void testGetExtraHtmlReturnsValueIfExists() { String expectedHtml = "<html></html>"; Intent testIntent = new Intent(); testIntent.putExtra(Gateway3DSecureActivity.EXTRA_HTML, expectedHtml); doReturn(testIntent).when(activity).getIntent(); String html = activity.getExtraHtml(); assertEquals(expectedHtml, html); } |
### Question:
Gateway { @SuppressWarnings("unchecked") boolean handleCallbackMessage(GatewayCallback callback, Object arg) { if (callback != null) { if (arg instanceof Throwable) { callback.onError((Throwable) arg); } else { callback.onSuccess((GatewayMap) arg); } } return true; } Gateway(); String getMerchantId(); Gateway setMerchantId(String merchantId); Region getRegion(); Gateway setRegion(Region region); void updateSession(String sessionId, String apiVersion, GatewayMap payload, GatewayCallback callback); Single<GatewayMap> updateSession(String sessionId, String apiVersion, GatewayMap payload); static void start3DSecureActivity(Activity activity, String html); static void start3DSecureActivity(Activity activity, String html, String title); static boolean handle3DSecureResult(int requestCode, int resultCode, Intent data, Gateway3DSecureCallback callback); static void requestGooglePayData(PaymentsClient paymentsClient, PaymentDataRequest request, Activity activity); static boolean handleGooglePayResult(int requestCode, int resultCode, Intent data, GatewayGooglePayCallback callback); }### Answer:
@Test public void testHandleCallbackMessageCallsOnErrorWithThrowableArg() throws Exception { GatewayCallback callback = mock(GatewayCallback.class); Throwable arg = new Exception("Some exception"); gateway.handleCallbackMessage(callback, arg); verify(callback).onError(arg); }
@Test public void testHandleCallbackMessageCallsSuccessWithNonThrowableArg() throws Exception { GatewayCallback callback = mock(GatewayCallback.class); GatewayMap arg = mock(GatewayMap.class); gateway.handleCallbackMessage(callback, arg); verify(callback).onSuccess(arg); } |
### Question:
Gateway { boolean isStatusCodeOk(int statusCode) { return (statusCode >= 200 && statusCode < 300); } Gateway(); String getMerchantId(); Gateway setMerchantId(String merchantId); Region getRegion(); Gateway setRegion(Region region); void updateSession(String sessionId, String apiVersion, GatewayMap payload, GatewayCallback callback); Single<GatewayMap> updateSession(String sessionId, String apiVersion, GatewayMap payload); static void start3DSecureActivity(Activity activity, String html); static void start3DSecureActivity(Activity activity, String html, String title); static boolean handle3DSecureResult(int requestCode, int resultCode, Intent data, Gateway3DSecureCallback callback); static void requestGooglePayData(PaymentsClient paymentsClient, PaymentDataRequest request, Activity activity); static boolean handleGooglePayResult(int requestCode, int resultCode, Intent data, GatewayGooglePayCallback callback); }### Answer:
@Test public void testIsStatusOkWorksAsIntended() { int tooLow = 199; int tooHigh = 300; int justRight = 200; assertFalse(gateway.isStatusCodeOk(tooLow)); assertFalse(gateway.isStatusCodeOk(tooHigh)); assertTrue(gateway.isStatusCodeOk(justRight)); } |
### Question:
Gateway { String inputStreamToString(InputStream is) throws IOException { BufferedReader rd = new BufferedReader(new InputStreamReader(is)); StringBuilder total = new StringBuilder(); String line; while ((line = rd.readLine()) != null) { total.append(line); } return total.toString(); } Gateway(); String getMerchantId(); Gateway setMerchantId(String merchantId); Region getRegion(); Gateway setRegion(Region region); void updateSession(String sessionId, String apiVersion, GatewayMap payload, GatewayCallback callback); Single<GatewayMap> updateSession(String sessionId, String apiVersion, GatewayMap payload); static void start3DSecureActivity(Activity activity, String html); static void start3DSecureActivity(Activity activity, String html, String title); static boolean handle3DSecureResult(int requestCode, int resultCode, Intent data, Gateway3DSecureCallback callback); static void requestGooglePayData(PaymentsClient paymentsClient, PaymentDataRequest request, Activity activity); static boolean handleGooglePayResult(int requestCode, int resultCode, Intent data, GatewayGooglePayCallback callback); }### Answer:
@Test public void testInputStreamToStringWorksAsExpected() { String expectedResult = "here is some string data"; InputStream testInputStream = new StringInputStream(expectedResult); try { String result = gateway.inputStreamToString(testInputStream); assertEquals(expectedResult, result); } catch (IOException e) { fail(e.getMessage()); } } |
### Question:
Gateway { String createAuthHeader(String sessionId) { String value = "merchant." + merchantId + ":" + sessionId; return "Basic " + Base64.encodeToString(value.getBytes(), Base64.NO_WRAP); } Gateway(); String getMerchantId(); Gateway setMerchantId(String merchantId); Region getRegion(); Gateway setRegion(Region region); void updateSession(String sessionId, String apiVersion, GatewayMap payload, GatewayCallback callback); Single<GatewayMap> updateSession(String sessionId, String apiVersion, GatewayMap payload); static void start3DSecureActivity(Activity activity, String html); static void start3DSecureActivity(Activity activity, String html, String title); static boolean handle3DSecureResult(int requestCode, int resultCode, Intent data, Gateway3DSecureCallback callback); static void requestGooglePayData(PaymentsClient paymentsClient, PaymentDataRequest request, Activity activity); static boolean handleGooglePayResult(int requestCode, int resultCode, Intent data, GatewayGooglePayCallback callback); }### Answer:
@Test public void testCreateAuthHeaderWorksAsExpected() { String sessionId = "somesession"; gateway.merchantId = "MERCHANT_ID"; String expectedAuthHeader = "Basic bWVyY2hhbnQuTUVSQ0hBTlRfSUQ6c29tZXNlc3Npb24="; String authHeader = gateway.createAuthHeader(sessionId); assertEquals(expectedAuthHeader, authHeader); } |
### Question:
Gateway3DSecureActivity extends AppCompatActivity { void setWebViewHtml(String html) { String encoded = Base64.encodeToString(html.getBytes(), Base64.NO_PADDING | Base64.NO_WRAP); webView.loadData(encoded, "text/html", "base64"); } static final String EXTRA_HTML; static final String EXTRA_TITLE; static final String EXTRA_ACS_RESULT; }### Answer:
@Test public void testSetWebViewHtmlEncodesBase64() { String testHtml = "<html></html>"; String expectedEncodedHtml = "PGh0bWw+PC9odG1sPg"; activity.webView = mock(WebView.class); activity.setWebViewHtml(testHtml); verify(activity.webView).loadData(expectedEncodedHtml, "text/html", "base64"); } |
### Question:
Gateway3DSecureActivity extends AppCompatActivity { void intentToEmail(Uri uri) { Intent emailIntent = new Intent(Intent.ACTION_SENDTO); intentToEmail(uri, emailIntent); } static final String EXTRA_HTML; static final String EXTRA_TITLE; static final String EXTRA_ACS_RESULT; }### Answer:
@Test public void testIntentToEmailWorksAsExpected() { Uri testUri = mock(Uri.class); Intent testIntent = new Intent(); activity.intentToEmail(testUri, testIntent); int flags = testIntent.getFlags(); assertNotEquals(0, flags & Intent.FLAG_ACTIVITY_NEW_TASK); assertEquals(testUri, testIntent.getData()); verify(activity).startActivity(testIntent); } |
### Question:
Gateway3DSecureActivity extends AppCompatActivity { void complete(String acsResult) { Intent intent = new Intent(); complete(acsResult, intent); } static final String EXTRA_HTML; static final String EXTRA_TITLE; static final String EXTRA_ACS_RESULT; }### Answer:
@Test public void testCompleteWorksAsExpected() { String testAcsResult = "test result"; Intent testIntent = new Intent(); activity.complete(testAcsResult, testIntent); assertTrue(testIntent.hasExtra(Gateway3DSecureActivity.EXTRA_ACS_RESULT)); assertEquals(testAcsResult, testIntent.getStringExtra(Gateway3DSecureActivity.EXTRA_ACS_RESULT)); verify(activity).setResult(Activity.RESULT_OK, testIntent); verify(activity).finish(); } |
### Question:
Gateway3DSecureActivity extends AppCompatActivity { String getACSResultFromUri(Uri uri) { String result = null; Set<String> params = uri.getQueryParameterNames(); for (String param : params) { if ("acsResult".equalsIgnoreCase(param)) { result = uri.getQueryParameter(param); } } return result; } static final String EXTRA_HTML; static final String EXTRA_TITLE; static final String EXTRA_ACS_RESULT; }### Answer:
@Test public void testGetAcsResultFromUriWorksAsExpected() { Uri testUri = Uri.parse("gatewaysdk: String result = activity.getACSResultFromUri(testUri); assertEquals("{}", result); } |
### Question:
GatewaySSLContextProvider { X509Certificate readCertificate(String cert) throws CertificateException { byte[] bytes = cert.getBytes(); InputStream is = new ByteArrayInputStream(bytes); return (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(is); } GatewaySSLContextProvider(); }### Answer:
@Test public void testReadingInternalCertificateWorksAsExpected() throws Exception { X509Certificate certificate = trustProvider.readCertificate(GatewaySSLContextProvider.INTERMEDIATE_CA); String expectedSerialNo = "1372807406"; assertNotNull(certificate); assertEquals(expectedSerialNo, certificate.getSerialNumber().toString()); } |
### Question:
GatewayMap extends LinkedHashMap<String, Object> { @Override public Object put(String keyPath, Object value) { String[] properties = keyPath.split("\\."); Map<String, Object> destinationObject = this; if (properties.length > 1) { for (int i = 0; i < (properties.length - 1); i++) { String property = properties[i]; if (property.contains("[")) { destinationObject = getDestinationMap(property, destinationObject, i == properties.length - 1); } else { destinationObject = getPropertyMapFrom(property, destinationObject); } } } else if (keyPath.contains("[")) { destinationObject = getDestinationMap(keyPath, this, true); } if (destinationObject == this) { return super.put(keyPath, value); } else if (value instanceof Map) { destinationObject.clear(); GatewayMap m = new GatewayMap(); m.putAll((Map<? extends String, ? extends Object>) value); destinationObject.put(properties[properties.length - 1], m); return destinationObject; } else { return destinationObject.put(properties[properties.length - 1], value); } } GatewayMap(int initialCapacity, float loadFactor); GatewayMap(int initialCapacity); GatewayMap(); GatewayMap(Map<String, Object> map); GatewayMap(String jsonMapString); GatewayMap(String keyPath, Object value); @Override Object put(String keyPath, Object value); GatewayMap set(String keyPath, Object value); @Override Object get(Object keyPath); @Override boolean containsKey(Object keyPath); @Override Object remove(Object keyPath); static Map<String, Object> normalize(Map<String, Object> m); }### Answer:
@Test public void cannotOverrideNestedMap() { GatewayMap map = new GatewayMap(); map.put("a", 1); try { map.put("a.b", 2); fail("IllegalArgumentException not raised"); } catch (IllegalArgumentException e) { } catch (Exception e) { fail("Exception " + e + " thrown"); } } |
### Question:
ForkedFrameworkFactory { protected int getPort() { String configuredPort = System.getProperty(EXAM_FORKED_INVOKER_PORT); if (configuredPort != null) { return Integer.parseInt(configuredPort); } else { int lowerBound = Integer.parseInt(System.getProperty(EXAM_FORKED_INVOKER_PORT_RANGE_LOWERBOUND, "21000")); int upperBound = Integer.parseInt(System.getProperty(EXAM_FORKED_INVOKER_PORT_RANGE_UPPERBOUND, "21099")); return new FreePort(lowerBound, upperBound).getPort(); } } ForkedFrameworkFactory(FrameworkFactory frameworkFactory); FrameworkFactory getFrameworkFactory(); void setFrameworkFactory(FrameworkFactory frameworkFactory); RemoteFramework fork(List<String> vmArgs, Map<String, String> systemProperties,
Map<String, Object> frameworkProperties, List<String> beforeFrameworkClasspath,
List<String> afterFrameworkClasspath); RemoteFramework fork(List<String> vmArgs, Map<String, String> systemProperties,
Map<String, Object> frameworkProperties); void join(); }### Answer:
@Test() public void verifyPortConfiguration() throws Exception { ForkedFrameworkFactory frameworkFactory = new ForkedFrameworkFactory(null); new SystemPropertyRunnable(org.ops4j.pax.exam.Constants.EXAM_FORKED_INVOKER_PORT, "15000") { @Override protected void doRun() { Assert.assertThat(frameworkFactory.getPort(), CoreMatchers.equalTo(15000)); } }.run(); new SystemPropertyRunnable(org.ops4j.pax.exam.Constants.EXAM_FORKED_INVOKER_PORT_RANGE_LOWERBOUND, "15000") { @Override protected void doRun() { Assert.assertThat(frameworkFactory.getPort(), CoreMatchers.equalTo(15000)); } }.run(); } |
### Question:
JavaVersionUtil { public static int getMajorVersion() { return getMajorVersion(System.getProperty("java.specification.version")); } static int getMajorVersion(); }### Answer:
@Test public void testVersions() { assertEquals(8, JavaVersionUtil.getMajorVersion("1.8.0_171")); assertEquals(9, JavaVersionUtil.getMajorVersion("9")); assertEquals(10, JavaVersionUtil.getMajorVersion("10")); assertEquals(11, JavaVersionUtil.getMajorVersion("11")); } |
### Question:
KarafConfigFile extends KarafConfigurationFile { @Override public void store() throws IOException { final FileOutputStream fos = new FileOutputStream(file); ConfigurationHandler.write(fos, configuration); fos.close(); } KarafConfigFile(File karafHome, String location); @Override void store(); @SuppressWarnings("unchecked") @Override void load(); @Override void put(final String key, final Object value); @SuppressWarnings({ "unchecked", "rawtypes" }) @Override void extend(final String key, final Object value); @Override Object get(final String key); }### Answer:
@Test public void store() throws Exception { final int[] ints = {1, 2, 3, 4}; final Dictionary<String, Object> configuration = new Hashtable<>(); configuration.put("ints", ints); final FileOutputStream fos = new FileOutputStream("target/store.config"); ConfigurationHandler.write(fos, configuration); fos.close(); } |
### Question:
KarafConfigFile extends KarafConfigurationFile { @SuppressWarnings("unchecked") @Override public void load() throws IOException { if (!file.exists()) { return; } final FileInputStream fis = new FileInputStream(file); configuration = ConfigurationHandler.read(fis); fis.close(); } KarafConfigFile(File karafHome, String location); @Override void store(); @SuppressWarnings("unchecked") @Override void load(); @Override void put(final String key, final Object value); @SuppressWarnings({ "unchecked", "rawtypes" }) @Override void extend(final String key, final Object value); @Override Object get(final String key); }### Answer:
@Test public void load() throws Exception { final int[] expected = {1, 2, 3, 4}; final KarafConfigFile karafConfigFile = new KarafConfigFile(KARAF_ETC, "etc/ints_4.config"); karafConfigFile.load(); final int[] ints = (int[]) karafConfigFile.get("ints"); assertArrayEquals(expected, ints); } |
### Question:
KarafConfigFile extends KarafConfigurationFile { @Override public void put(final String key, final Object value) { configuration.put(key, value); } KarafConfigFile(File karafHome, String location); @Override void store(); @SuppressWarnings("unchecked") @Override void load(); @Override void put(final String key, final Object value); @SuppressWarnings({ "unchecked", "rawtypes" }) @Override void extend(final String key, final Object value); @Override Object get(final String key); }### Answer:
@Test public void put() throws Exception { final Double d = 2D; final KarafConfigFile karafConfigFile = new KarafConfigFile(KARAF_ETC, "etc/na.config"); karafConfigFile.put("Double", d); } |
### Question:
KarafConfigFile extends KarafConfigurationFile { @Override public Object get(final String key) { return configuration.get(key); } KarafConfigFile(File karafHome, String location); @Override void store(); @SuppressWarnings("unchecked") @Override void load(); @Override void put(final String key, final Object value); @SuppressWarnings({ "unchecked", "rawtypes" }) @Override void extend(final String key, final Object value); @Override Object get(final String key); }### Answer:
@Test public void get() throws Exception { final String in = "value"; final KarafConfigFile karafConfigFile = new KarafConfigFile(KARAF_ETC, "etc/na.config"); karafConfigFile.put("key", in); final Object out = karafConfigFile.get("key"); assertEquals(in, out); } |
### Question:
FileFinder { public static File findFile(File rootDir, final String fileName) { FilenameFilter filter = new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.equals(fileName); } }; return findFile(rootDir, filter); } private FileFinder(); static File findFile(File rootDir, final String fileName); static File findFile(File rootDir, FilenameFilter filter); }### Answer:
@Test public void findFileInTree() { File rootDir = new File("src/main/java"); File file = FileFinder.findFile(rootDir, "FileFinder.java"); assertFilePath(file, "src/main/java/org/ops4j/pax/exam/spi/war/FileFinder.java"); }
@Test public void findFileInRoot() { File rootDir = new File("src/main/java/org/ops4j/pax/exam/spi/war"); File file = FileFinder.findFile(rootDir, "FileFinder.java"); assertFilePath(file, "src/main/java/org/ops4j/pax/exam/spi/war/FileFinder.java"); }
@Test public void findFileWithFilter() { File rootDir = new File("src/main/java/"); FilenameFilter filter = new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.startsWith("Zip"); } }; File file = FileFinder.findFile(rootDir, filter); assertFilePath(file, "src/main/java/org/ops4j/pax/exam/spi/war/ZipBuilder.java"); }
@Test public void findDirectory() { File rootDir = new File("src"); File file = FileFinder.findFile(rootDir, "java"); assertFilePath(file, "src/main/java"); }
@Test public void findSubdirectory() { File rootDir = new File("src/test"); File file = FileFinder.findFile(rootDir, "java"); assertFilePath(file, "src/test/java"); } |
### Question:
WarBuilder { public URI buildWar() { if (option.getName() == null) { option.name(UUID.randomUUID().toString()); } processClassPath(); try { File webResourceDir = getWebResourceDir(); File probeWar = new File(tempDir, option.getName() + ".war"); ZipBuilder builder = new ZipBuilder(probeWar); for (String library : option.getLibraries()) { File file = toLocalFile(library); if (file.isDirectory()) { file = toJar(file); } LOG.debug("including library {} = {}", library, file); builder.addFile(file, "WEB-INF/lib/" + file.getName()); } builder.addDirectory(webResourceDir, ""); builder.close(); URI warUri = probeWar.toURI(); LOG.info("WAR probe = {}", warUri); return warUri; } catch (IOException exc) { throw new TestContainerException(exc); } } WarBuilder(File tempDir, WarProbeOption option); URI buildWar(); }### Answer:
@Test public void buildWar() throws MalformedURLException, IOException { war = localCopy(warProbe().library("target/classes")); assertThat(war.getEntry("WEB-INF/beans.xml"), is(notNullValue())); assertThat(war.getEntry("WEB-INF/lib/pax-exam-spi-" + Info.getPaxExamVersion() + ".jar"), is(notNullValue())); }
@Test public void buildWarWithName() throws MalformedURLException, IOException { WarBuilder warBuilder = new WarBuilder(DefaultExamSystem.createTempDir(), warProbe().library("target/classes").name("foo")); URI uri = warBuilder.buildWar(); assertThat(new File(uri).getName(), is("foo.war")); } |
### Question:
ConfigurationManager { public void loadSystemProperties(String configurationKey) { String propertyRef = getProperty(configurationKey); if (propertyRef == null) { return; } if (propertyRef.startsWith("env:")) { propertyRef = propertyRef.substring(4); propertyRef = System.getenv(propertyRef); } if (!propertyRef.startsWith("/")) { propertyRef = "/" + propertyRef; } try { URL url = getClass().getResource(propertyRef); if (url == null) { url = new URL(propertyRef); } Properties props = System.getProperties(); props.load(url.openStream()); System.setProperties(props); } catch (IOException exc) { throw new TestContainerException(exc); } } ConfigurationManager(); String getProperty(String key); String getProperty(String key, String defaultValue); void loadSystemProperties(String configurationKey); }### Answer:
@Test public void loadSystemProperties() { ConfigurationManager cm = new ConfigurationManager(); assertThat(System.getProperty("exam.test.key1"), is(nullValue())); assertThat(System.getProperty("exam.test.key2"), is(nullValue())); String cp = System.getProperty("java.class.path"); cm.loadSystemProperties("exam.test.props"); assertThat(System.getProperty("exam.test.key1"), is("value1")); assertThat(System.getProperty("exam.test.key2"), is("value2")); assertThat(System.getProperty("java.class.path"), is(cp)); } |
### Question:
AdminHandler { public Result showAdmin(Context context) { return Results.html(); } Result showAdmin(Context context); Result showUsers(Context context); Result showSummedTransactions(Context context); Result pagedMTX(Context context, @Param("p") int page); Result deleteMTXProcess(@PathParam("time") Integer time, Context context); Result activateUserProcess(@PathParam("id") Long userId, Context context); Result promoteUserProcess(@PathParam("id") Long userId, Context context); Result deleteUserProcess(@PathParam("id") Long deleteUserId, Context context); Result jsonUserSearch(Context context); @FilterWith(WhitelistFilter.class) Result showDomainWhitelist(Context context); @FilterWith(WhitelistFilter.class) Result callRemoveDomain(Context context, @Param("removeDomainsSelection") Long remDomainId); @FilterWith(WhitelistFilter.class) Result handleRemoveDomain(Context context, @Param("action") String action, @Param("domainId") long domainId); @FilterWith(WhitelistFilter.class) Result addDomain(Context context, @Param("domainName") String domainName); Result showEmailStatistics(Context context, @Param("dayPage") int dayPage, @Param("weekPage") int weekPage,
@Param("sortDailyList") String sortDailyList,
@Param("sortWeeklyList") String sortWeeklyList); Result getEmailSenderTablePage(Context context, @Param("scope") String scope, @Param("page") int page,
@Param("offset") int offset, @Param("limit") int limit,
@Param("sort") String sort, @Param("order") String order); }### Answer:
@Test public void testShowAdmin() { result = ninjaTestBrowser.makeRequest(ninjaTestServer.getBaseUrl() + "/admin"); assertTrue(!result.contains("<li class=\"active\">")); assertFalse(result.contains("FreeMarker template error")); assertFalse(result.contains("<title>404 - not found</title>")); } |
### Question:
MailboxApiController extends AbstractApiController { public Result getMailbox(@PathParam("mailboxAddress") @Email final String mailboxAddress, @Attribute("userId") @DbId final Long userId, final Context context) { return performAction(userId, mailboxAddress, context, mailbox -> { final MailboxData mailboxData = new MailboxData(mailbox); return ApiResults.ok().render(mailboxData); }); } Result listMailboxes(@Attribute("userId") @DbId final Long userId, final Context context); Result createMailbox(@JSR303Validation final MailboxData mailboxData, @Attribute("user") final User user,
final Context context); Result getMailbox(@PathParam("mailboxAddress") @Email final String mailboxAddress,
@Attribute("userId") @DbId final Long userId, final Context context); Result updateMailbox(@PathParam("mailboxAddress") @Email final String mailboxAddress,
@JSR303Validation final MailboxData mailboxData,
@Attribute("userId") @DbId final Long userId, final Context context); Result deleteMailbox(@PathParam("mailboxAddress") @Email final String mailboxAddress,
@Attribute("userId") @DbId final Long userId, final Context context); }### Answer:
@Test public void getMailbox() throws Exception { final MBox mailbox = TestDataUtils.createMailbox(user); final HttpResponse response = apiClient.getMailbox(mailbox.getFullAddress()); RestApiTestUtils.validateStatusCode(response, 200); final MailboxData mailboxData = RestApiTestUtils.getResponseBodyAs(response, MailboxData.class); RestApiTestUtils.validateMailboxData(mailboxData, mailbox); }
@Test public void getMailbox_invalidAddress() throws Exception { final HttpResponse response = apiClient.getMailbox(invalidAddress); RestApiTestUtils.validateStatusCode(response, 400); RestApiTestUtils.validateErrors(response, "mailboxAddress"); }
@Test public void getMailbox_unknownMailbox() throws Exception { final HttpResponse response = apiClient.getMailbox(unknownAddress); RestApiTestUtils.validateStatusCode(response, 404); } |
### Question:
MailboxApiController extends AbstractApiController { public Result updateMailbox(@PathParam("mailboxAddress") @Email final String mailboxAddress, @JSR303Validation final MailboxData mailboxData, @Attribute("userId") @DbId final Long userId, final Context context) { return performAction(userId, mailboxAddress, context, mailbox -> doUpdateMailbox(mailbox, mailboxData)); } Result listMailboxes(@Attribute("userId") @DbId final Long userId, final Context context); Result createMailbox(@JSR303Validation final MailboxData mailboxData, @Attribute("user") final User user,
final Context context); Result getMailbox(@PathParam("mailboxAddress") @Email final String mailboxAddress,
@Attribute("userId") @DbId final Long userId, final Context context); Result updateMailbox(@PathParam("mailboxAddress") @Email final String mailboxAddress,
@JSR303Validation final MailboxData mailboxData,
@Attribute("userId") @DbId final Long userId, final Context context); Result deleteMailbox(@PathParam("mailboxAddress") @Email final String mailboxAddress,
@Attribute("userId") @DbId final Long userId, final Context context); }### Answer:
@Test public void updateMailbox() throws Exception { MBox mailbox = TestDataUtils.createMailbox(user); final String mailboxAddress = "[email protected]"; final long expirationDate = System.currentTimeMillis(); final boolean forwardEnabled = true; final HttpResponse response = apiClient.updateMailbox(mailbox.getFullAddress(), mailboxAddress, expirationDate, forwardEnabled); RestApiTestUtils.validateStatusCode(response, 200); final MailboxData mailboxData = RestApiTestUtils.getResponseBodyAs(response, MailboxData.class); RestApiTestUtils.validateMailboxData(mailboxData, mailboxAddress, expirationDate, forwardEnabled); mailbox = MBox.getById(mailbox.getId()); RestApiTestUtils.validateMailbox(mailbox, mailboxData); } |
### Question:
MailboxApiController extends AbstractApiController { public Result deleteMailbox(@PathParam("mailboxAddress") @Email final String mailboxAddress, @Attribute("userId") @DbId final Long userId, final Context context) { return performAction(userId, mailboxAddress, context, mailbox -> { mailbox.delete(); return ApiResults.noContent(); }); } Result listMailboxes(@Attribute("userId") @DbId final Long userId, final Context context); Result createMailbox(@JSR303Validation final MailboxData mailboxData, @Attribute("user") final User user,
final Context context); Result getMailbox(@PathParam("mailboxAddress") @Email final String mailboxAddress,
@Attribute("userId") @DbId final Long userId, final Context context); Result updateMailbox(@PathParam("mailboxAddress") @Email final String mailboxAddress,
@JSR303Validation final MailboxData mailboxData,
@Attribute("userId") @DbId final Long userId, final Context context); Result deleteMailbox(@PathParam("mailboxAddress") @Email final String mailboxAddress,
@Attribute("userId") @DbId final Long userId, final Context context); }### Answer:
@Test public void deleteMailbox() throws Exception { final MBox mailbox = TestDataUtils.createMailbox(user); Assert.assertNotNull(MBox.getById(mailbox.getId())); final HttpResponse response = apiClient.deleteMailbox(mailbox.getFullAddress()); RestApiTestUtils.validateStatusCode(response, 204); Assert.assertNull(MBox.getById(mailbox.getId())); }
@Test public void deleteMailbox_invalidMailboxAddress() throws Exception { final HttpResponse response = apiClient.deleteMailbox(invalidAddress); RestApiTestUtils.validateStatusCode(response, 400); RestApiTestUtils.validateErrors(response, "mailboxAddress"); }
@Test public void deleteMailbox_unknownMailbox() throws Exception { final HttpResponse response = apiClient.deleteMailbox(unknownAddress); RestApiTestUtils.validateStatusCode(response, 404); } |
### Question:
MailApiController extends AbstractApiController { public Result getMail(@PathParam("mailId") @DbId final Long mailId, @Attribute("userId") @DbId final Long userId, final Context context) { return performAction(mailId, userId, context, mail -> { try { final MailData mailData = new MailData(mail); return ApiResults.ok().render(mailData); } catch (final Exception e) { log.error("Failed to parse MIME message", e); return ApiResults.internalServerError(); } }); } Result listMails(@Param("mailboxAddress") @Email final String mailboxAddress,
@Attribute("userId") @DbId final Long userId, final Context context); Result getMail(@PathParam("mailId") @DbId final Long mailId, @Attribute("userId") @DbId final Long userId,
final Context context); Result getMailAttachment(@PathParam("mailId") @DbId final Long mailId,
@PathParam("attachmentName") @NotBlank final String attachmentName,
@Attribute("userId") @DbId final Long userId, final Context context); Result deleteMail(@PathParam("mailId") @DbId final Long mailId, @Attribute("userId") @DbId final Long userId,
final Context context); }### Answer:
@Test public void getMail() throws Exception { final HttpResponse response = apiClient.getMail(mailId); RestApiTestUtils.validateStatusCode(response, 200); }
@Test public void getMail_someoneElsesMail() throws Exception { final HttpResponse response = apiClient.getMail(otherUsersMailId); RestApiTestUtils.validateStatusCode(response, 403); RestApiTestUtils.validateErrors(response, "mailId"); }
@Test public void getMail_invalidId() throws Exception { final HttpResponse response = apiClient.getMail(invalidId); RestApiTestUtils.validateStatusCode(response, 400); RestApiTestUtils.validateErrors(response, "mailId"); }
@Test public void getMail_unknownMail() throws Exception { final HttpResponse response = apiClient.getMail(unknownId); RestApiTestUtils.validateStatusCode(response, 404); } |
### Question:
MailApiController extends AbstractApiController { public Result getMailAttachment(@PathParam("mailId") @DbId final Long mailId, @PathParam("attachmentName") @NotBlank final String attachmentName, @Attribute("userId") @DbId final Long userId, final Context context) { return performAction(mailId, userId, context, mail -> { return serveMailAttachment(context, mail, attachmentName); }); } Result listMails(@Param("mailboxAddress") @Email final String mailboxAddress,
@Attribute("userId") @DbId final Long userId, final Context context); Result getMail(@PathParam("mailId") @DbId final Long mailId, @Attribute("userId") @DbId final Long userId,
final Context context); Result getMailAttachment(@PathParam("mailId") @DbId final Long mailId,
@PathParam("attachmentName") @NotBlank final String attachmentName,
@Attribute("userId") @DbId final Long userId, final Context context); Result deleteMail(@PathParam("mailId") @DbId final Long mailId, @Attribute("userId") @DbId final Long userId,
final Context context); }### Answer:
@Test public void getMailAttachment() throws Exception { HttpResponse response = apiClient.getMailAttachment(mailId, "test.pdf"); RestApiTestUtils.validateStatusCode(response, 200); RestApiTestUtils.validateResponseContent(response, "application/pdf", 89399); response = apiClient.getMailAttachment(mailId, "test.png"); RestApiTestUtils.validateStatusCode(response, 200); RestApiTestUtils.validateResponseContent(response, "image/png", 5799); }
@Test public void getMailAttachment_unknownName() throws Exception { final HttpResponse response = apiClient.getMailAttachment(mailId, "unknownAttachmentName"); RestApiTestUtils.validateStatusCode(response, 404); } |
### Question:
HelperUtils { public static Long parseTimeString(String input) { if (input.equals("0") || input.equals("unlimited")) { return 0L; } if (!hasCorrectFormat(input)) { return -1L; } input = input.trim(); DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm"); return formatter.parseDateTime(input).getMillis(); } private HelperUtils(); static Long parseTimeString(String input); static String parseStringTs(long ts_Active); static String addZero(int no); static boolean hasCorrectFormat(String input); static void parseEntryValue(Context context, Integer defaultNo); static List<String[]> getLanguageList(String[] availableLanguages, Context context, Result result,
Messages msg); static boolean checkEmailAddressValidness(String[] mailAddressParts, String[] domainList); static String[] splitMailAddress(String mailAddress); static String getHeaderText(final MimeMessage message); static byte[] readLimitedAmount(InputStream data, int maxSize); }### Answer:
@Test public void testParseTimeString() { long ts = HelperUtils.parseTimeString("2013-12-12 12:12"); DateTime dt = new DateTime(2013, 12, 12, 12, 12); assertEquals(dt.getMillis(), ts); ts = HelperUtils.parseTimeString(" 2013-12-12 12:12 "); assertEquals(dt.getMillis(), ts); ts = HelperUtils.parseTimeString("12:12:12 12:12"); assertEquals(-1L, ts); ts = HelperUtils.parseTimeString("2013-12-12 12:12"); assertEquals(-1L, ts); ts = HelperUtils.parseTimeString("2x, 2h"); assertEquals(-1L, ts); } |
### Question:
HelperUtils { public static String[] splitMailAddress(String mailAddress) { mailAddress = StringUtils.defaultString(mailAddress).trim(); if (mailAddress.length() > 0) { return mailAddress.split("@"); } return null; } private HelperUtils(); static Long parseTimeString(String input); static String parseStringTs(long ts_Active); static String addZero(int no); static boolean hasCorrectFormat(String input); static void parseEntryValue(Context context, Integer defaultNo); static List<String[]> getLanguageList(String[] availableLanguages, Context context, Result result,
Messages msg); static boolean checkEmailAddressValidness(String[] mailAddressParts, String[] domainList); static String[] splitMailAddress(String mailAddress); static String getHeaderText(final MimeMessage message); static byte[] readLimitedAmount(InputStream data, int maxSize); }### Answer:
@Test public void testSplitMailAddress() { assertNull(HelperUtils.splitMailAddress(null)); assertNull(HelperUtils.splitMailAddress("")); assertNull(HelperUtils.splitMailAddress(" ")); String[] parts = HelperUtils.splitMailAddress("foo"); assertNotNull(parts); assertEquals(1, parts.length); parts = HelperUtils.splitMailAddress("foo@bar"); assertNotNull(parts); assertEquals(2, parts.length); } |
### Question:
HelperUtils { public static boolean checkEmailAddressValidness(String[] mailAddressParts, String[] domainList) { if (mailAddressParts == null || domainList == null || mailAddressParts.length != 2) { return false; } boolean foundDomain = false; for (String domain : domainList) { if (domain.equalsIgnoreCase(mailAddressParts[1])) { foundDomain = true; break; } } return foundDomain; } private HelperUtils(); static Long parseTimeString(String input); static String parseStringTs(long ts_Active); static String addZero(int no); static boolean hasCorrectFormat(String input); static void parseEntryValue(Context context, Integer defaultNo); static List<String[]> getLanguageList(String[] availableLanguages, Context context, Result result,
Messages msg); static boolean checkEmailAddressValidness(String[] mailAddressParts, String[] domainList); static String[] splitMailAddress(String mailAddress); static String getHeaderText(final MimeMessage message); static byte[] readLimitedAmount(InputStream data, int maxSize); }### Answer:
@Test public void testCheckEmailAddressValidness() { assertFalse(HelperUtils.checkEmailAddressValidness(null, null)); assertFalse(HelperUtils.checkEmailAddressValidness(null, ArrayUtils.EMPTY_STRING_ARRAY)); assertFalse(HelperUtils.checkEmailAddressValidness(ArrayUtils.EMPTY_STRING_ARRAY, ArrayUtils.EMPTY_STRING_ARRAY)); String[] domainList = ArrayUtils.toArray("test.localhost"); String[] mailParts = ArrayUtils.toArray("foo"); assertFalse(HelperUtils.checkEmailAddressValidness(mailParts, domainList)); mailParts = ArrayUtils.add(mailParts, "bar"); assertFalse(HelperUtils.checkEmailAddressValidness(mailParts, domainList)); mailParts[1] = "test.localhost"; assertTrue(HelperUtils.checkEmailAddressValidness(mailParts, domainList)); mailParts[1] = "TesT.LOCALHosT"; assertTrue(HelperUtils.checkEmailAddressValidness(mailParts, domainList)); } |
### Question:
HelperUtils { public static byte[] readLimitedAmount(InputStream data, int maxSize) throws IOException { final ByteArrayOutputStream bos = new ByteArrayOutputStream(data.available()); final long count = IOUtils.copy(data, bos, 4096); if (count > maxSize) { throw new SizeLimitExceededException("Data stream exceeds size limit of " + maxSize + " bytes"); } return bos.toByteArray(); } private HelperUtils(); static Long parseTimeString(String input); static String parseStringTs(long ts_Active); static String addZero(int no); static boolean hasCorrectFormat(String input); static void parseEntryValue(Context context, Integer defaultNo); static List<String[]> getLanguageList(String[] availableLanguages, Context context, Result result,
Messages msg); static boolean checkEmailAddressValidness(String[] mailAddressParts, String[] domainList); static String[] splitMailAddress(String mailAddress); static String getHeaderText(final MimeMessage message); static byte[] readLimitedAmount(InputStream data, int maxSize); }### Answer:
@Test(expected = SizeLimitExceededException.class) public void testReadRawContent_LimitExceeded() throws Exception { final InputStream is = new ByteArrayInputStream(RandomUtils.nextBytes(30)); HelperUtils.readLimitedAmount(is, 25); } |
### Question:
MailboxApiController extends AbstractApiController { public Result listMailboxes(@Attribute("userId") @DbId final Long userId, final Context context) { final List<MBox> mailboxes = MBox.allUser(userId); final List<MailboxData> mailboxDatas = mailboxes.stream().map(mb -> new MailboxData(mb)) .collect(Collectors.toList()); return ApiResults.ok().render(mailboxDatas); } Result listMailboxes(@Attribute("userId") @DbId final Long userId, final Context context); Result createMailbox(@JSR303Validation final MailboxData mailboxData, @Attribute("user") final User user,
final Context context); Result getMailbox(@PathParam("mailboxAddress") @Email final String mailboxAddress,
@Attribute("userId") @DbId final Long userId, final Context context); Result updateMailbox(@PathParam("mailboxAddress") @Email final String mailboxAddress,
@JSR303Validation final MailboxData mailboxData,
@Attribute("userId") @DbId final Long userId, final Context context); Result deleteMailbox(@PathParam("mailboxAddress") @Email final String mailboxAddress,
@Attribute("userId") @DbId final Long userId, final Context context); }### Answer:
@Test public void listMailboxes_emptyList() throws Exception { final HttpResponse response = apiClient.listMailboxes(); RestApiTestUtils.validateStatusCode(response, 200); final MailboxData[] mailboxData = RestApiTestUtils.getResponseBodyAs(response, MailboxData[].class); Assert.assertEquals(0, mailboxData.length); } |
### Question:
UIController { @GetMapping( value = { "/", "/applications/**", "/clusters/**", "/commands/**", "/jobs/**", "/output/**" } ) public String getIndex() { return "index"; } @GetMapping( value = { "/", "/applications/**", "/clusters/**", "/commands/**", "/jobs/**", "/output/**" } ) String getIndex(); @GetMapping(value = "/file/{id}/**") String getFile(
@PathVariable("id") final String id,
final HttpServletRequest request
); }### Answer:
@Test void canGetIndex() { Assertions.assertThat(this.controller.getIndex()).isEqualTo("index"); } |
### Question:
ClusterModelAssembler implements RepresentationModelAssembler<Cluster, EntityModel<Cluster>> { @Override @Nonnull public EntityModel<Cluster> toModel(final Cluster cluster) { final String id = cluster.getId().orElseThrow(IllegalArgumentException::new); final EntityModel<Cluster> clusterModel = new EntityModel<>(cluster); try { clusterModel.add( WebMvcLinkBuilder.linkTo( WebMvcLinkBuilder .methodOn(ClusterRestController.class) .getCluster(id) ).withSelfRel() ); clusterModel.add( WebMvcLinkBuilder.linkTo( WebMvcLinkBuilder .methodOn(ClusterRestController.class) .getCommandsForCluster(id, null) ).withRel(COMMANDS_LINK) ); } catch (final NotFoundException ge) { throw new RuntimeException(ge); } return clusterModel; } @Override @Nonnull EntityModel<Cluster> toModel(final Cluster cluster); }### Answer:
@Test void canConvertToModel() { final EntityModel<Cluster> model = this.assembler.toModel(this.cluster); Assertions.assertThat(model.getLinks()).hasSize(2); Assertions.assertThat(model.getLink("self")).isPresent(); Assertions.assertThat(model.getLink("commands")).isPresent(); } |
### Question:
JobSearchResultModelAssembler implements RepresentationModelAssembler<JobSearchResult, EntityModel<JobSearchResult>> { @Override @Nonnull public EntityModel<JobSearchResult> toModel(final JobSearchResult job) { final EntityModel<JobSearchResult> jobSearchResultModel = new EntityModel<>(job); try { jobSearchResultModel.add( WebMvcLinkBuilder.linkTo( WebMvcLinkBuilder .methodOn(JobRestController.class) .getJob(job.getId()) ).withSelfRel() ); } catch (final GenieException ge) { throw new RuntimeException(ge); } return jobSearchResultModel; } @Override @Nonnull EntityModel<JobSearchResult> toModel(final JobSearchResult job); }### Answer:
@Test void canConvertToResource() { final EntityModel<JobSearchResult> model = this.assembler.toModel(this.jobSearchResult); Assertions.assertThat(model.getLinks()).hasSize(1); Assertions.assertThat(model.getLink("self")).isNotNull(); } |
### Question:
CommandModelAssembler implements RepresentationModelAssembler<Command, EntityModel<Command>> { @Override @Nonnull public EntityModel<Command> toModel(final Command command) { final String id = command.getId().orElseThrow(IllegalArgumentException::new); final EntityModel<Command> commandModel = new EntityModel<>(command); try { commandModel.add( WebMvcLinkBuilder.linkTo( WebMvcLinkBuilder .methodOn(CommandRestController.class) .getCommand(id) ).withSelfRel() ); commandModel.add( WebMvcLinkBuilder.linkTo( WebMvcLinkBuilder .methodOn(CommandRestController.class) .getApplicationsForCommand(id) ).withRel(APPLICATIONS_LINK) ); commandModel.add( WebMvcLinkBuilder.linkTo( WebMvcLinkBuilder .methodOn(CommandRestController.class) .getClustersForCommand(id, null) ).withRel(CLUSTERS_LINK) ); } catch (final GenieException | GenieCheckedException ge) { throw new RuntimeException(ge); } return commandModel; } @Override @Nonnull EntityModel<Command> toModel(final Command command); }### Answer:
@Test void canConvertToResource() { final EntityModel<Command> model = this.assembler.toModel(this.command); Assertions.assertThat(model.getLinks()).hasSize(3); Assertions.assertThat(model.getLink("self")).isPresent(); Assertions.assertThat(model.getLink("applications")).isPresent(); Assertions.assertThat(model.getLink("clusters")).isPresent(); } |
### Question:
PredicateUtils { public static String createTagSearchString(final Set<TagEntity> tags) { return TAG_DELIMITER + tags .stream() .map(TagEntity::getTag) .sorted(String.CASE_INSENSITIVE_ORDER) .reduce((one, two) -> one + TAG_DELIMITER + TAG_DELIMITER + two) .orElse("") + TAG_DELIMITER; } private PredicateUtils(); static String createTagSearchString(final Set<TagEntity> tags); }### Answer:
@Test void canCreateTagSearchString() { final String one = "oNe"; final String two = "TwO"; final String three = "3"; final Set<TagEntity> tags = Sets.newHashSet(); Assertions .assertThat(PredicateUtils.createTagSearchString(tags)) .isEqualTo( PredicateUtils.TAG_DELIMITER + PredicateUtils.TAG_DELIMITER ); final TagEntity oneTag = new TagEntity(); oneTag.setTag(one); final TagEntity twoTag = new TagEntity(); twoTag.setTag(two); final TagEntity threeTag = new TagEntity(); threeTag.setTag(three); tags.add(oneTag); Assertions .assertThat(PredicateUtils.createTagSearchString(tags)) .isEqualTo( PredicateUtils.TAG_DELIMITER + one + PredicateUtils.TAG_DELIMITER ); tags.add(twoTag); Assertions.assertThat(PredicateUtils.createTagSearchString(tags)) .isEqualTo( PredicateUtils.TAG_DELIMITER + one + PredicateUtils.TAG_DELIMITER + PredicateUtils.TAG_DELIMITER + two + PredicateUtils.TAG_DELIMITER ); tags.add(threeTag); Assertions.assertThat(PredicateUtils.createTagSearchString(tags)) .isEqualTo( PredicateUtils.TAG_DELIMITER + three + PredicateUtils.TAG_DELIMITER + PredicateUtils.TAG_DELIMITER + one + PredicateUtils.TAG_DELIMITER + PredicateUtils.TAG_DELIMITER + two + PredicateUtils.TAG_DELIMITER ); } |
### Question:
GenieExceptionMapper { @ExceptionHandler(ConstraintViolationException.class) public ResponseEntity<GeniePreconditionException> handleConstraintViolation( final ConstraintViolationException cve ) { this.countExceptionAndLog(cve); return new ResponseEntity<>( new GeniePreconditionException(cve.getMessage(), cve), HttpStatus.PRECONDITION_FAILED ); } @Autowired GenieExceptionMapper(final MeterRegistry registry); @ExceptionHandler(GenieException.class) ResponseEntity<GenieException> handleGenieException(final GenieException e); @ExceptionHandler(GenieRuntimeException.class) ResponseEntity<GenieRuntimeException> handleGenieRuntimeException(final GenieRuntimeException e); @ExceptionHandler(GenieCheckedException.class) ResponseEntity<GenieCheckedException> handleGenieCheckedException(final GenieCheckedException e); @ExceptionHandler(ConstraintViolationException.class) ResponseEntity<GeniePreconditionException> handleConstraintViolation(
final ConstraintViolationException cve
); @ExceptionHandler(MethodArgumentNotValidException.class) ResponseEntity<GeniePreconditionException> handleMethodArgumentNotValidException(
final MethodArgumentNotValidException e
); }### Answer:
@Test void canHandleConstraintViolationExceptions() { final ConstraintViolationException exception = new ConstraintViolationException("cve", null); final ResponseEntity<GeniePreconditionException> response = this.mapper.handleConstraintViolation(exception); Assertions.assertThat(response.getStatusCode()).isEqualByComparingTo(HttpStatus.PRECONDITION_FAILED); Mockito .verify(this.registry, Mockito.times(1)) .counter( GenieExceptionMapper.CONTROLLER_EXCEPTION_COUNTER_NAME, Sets.newHashSet( Tag.of(MetricsConstants.TagKeys.EXCEPTION_CLASS, exception.getClass().getCanonicalName()) ) ); Mockito .verify(this.counter, Mockito.times(1)) .increment(); } |
### Question:
ControllerUtils { static URL getRequestRoot( final HttpServletRequest request, @Nullable final String path ) throws MalformedURLException { return getRequestRoot(new URL(request.getRequestURL().toString()), path); } private ControllerUtils(); static String getRemainingPath(final HttpServletRequest request); }### Answer:
@Test void canGetRequestRoot() throws MalformedURLException { final HttpServletRequest request = Mockito.mock(HttpServletRequest.class); final URL requestURL = new URL("https: final StringBuffer buffer = new StringBuffer(requestURL.toString()); Mockito.when(request.getRequestURL()).thenReturn(buffer); Assertions .assertThat(ControllerUtils.getRequestRoot(request, "")) .isEqualTo(new URL("https: Assertions .assertThat(ControllerUtils.getRequestRoot(request, null)) .isEqualTo(new URL("https: Assertions .assertThat(ControllerUtils.getRequestRoot(request, UUID.randomUUID().toString())) .isEqualTo(new URL("https: Assertions .assertThat(ControllerUtils.getRequestRoot(request, ".done")) .isEqualTo(new URL("https: Assertions .assertThat(ControllerUtils.getRequestRoot(request, "genie/genie.done")) .isEqualTo(new URL("https: } |
### Question:
PredicateUtils { static Predicate getStringLikeOrEqualPredicate( @NotNull final CriteriaBuilder cb, @NotNull final Expression<String> expression, @NotNull final String value ) { if (StringUtils.contains(value, PERCENT)) { return cb.like(expression, value); } else { return cb.equal(expression, value); } } private PredicateUtils(); static String createTagSearchString(final Set<TagEntity> tags); }### Answer:
@SuppressWarnings("unchecked") @Test void canGetStringLikeOrEqualPredicate() { final CriteriaBuilder cb = Mockito.mock(CriteriaBuilder.class); final Expression<String> expression = (Expression<String>) Mockito.mock(Expression.class); final Predicate likePredicate = Mockito.mock(Predicate.class); final Predicate equalPredicate = Mockito.mock(Predicate.class); Mockito.when(cb.like(Mockito.eq(expression), Mockito.anyString())).thenReturn(likePredicate); Mockito.when(cb.equal(Mockito.eq(expression), Mockito.anyString())).thenReturn(equalPredicate); Assertions .assertThat(PredicateUtils.getStringLikeOrEqualPredicate(cb, expression, "equal")) .isEqualTo(equalPredicate); Assertions .assertThat(PredicateUtils.getStringLikeOrEqualPredicate(cb, expression, "lik%e")) .isEqualTo(likePredicate); } |
### Question:
SwaggerAutoConfiguration { @Bean @ConditionalOnMissingBean(name = "genieApi", value = Docket.class) public Docket genieApi() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo( new ApiInfo( "Genie REST API", "See our <a href=\"http: + "documentation.<br/>Post any issues found " + "<a href=\"https: "4.0.0", null, new Contact("Netflix, Inc.", "https: "Apache 2.0", "http: Lists.newArrayList() ) ) .select() .apis(RequestHandlerSelectors.basePackage("com.netflix.genie.web.apis.rest.v3.controllers")) .paths(PathSelectors.any()) .build() .pathMapping("/") .useDefaultResponseMessages(false); } @Bean @ConditionalOnMissingBean(name = "genieApi", value = Docket.class) Docket genieApi(); }### Answer:
@Test void canCreateDocket() { final SwaggerAutoConfiguration config = new SwaggerAutoConfiguration(); final Docket docket = config.genieApi(); Assertions.assertThat(docket.getDocumentationType()).isEqualTo(DocumentationType.SWAGGER_2); } |
### Question:
ApisAutoConfiguration { @Bean @ConditionalOnMissingBean(ResourceLoader.class) public ResourceLoader resourceLoader() { return new DefaultResourceLoader(); } @Bean @ConditionalOnMissingBean(ResourceLoader.class) ResourceLoader resourceLoader(); @Bean @ConditionalOnMissingBean(name = "genieRestTemplate") RestTemplate genieRestTemplate(
final HttpProperties httpProperties,
final RestTemplateBuilder restTemplateBuilder
); @Bean @ConditionalOnMissingBean(name = "genieRetryTemplate") RetryTemplate genieRetryTemplate(final RetryProperties retryProperties); @Bean @ConditionalOnMissingBean(DirectoryWriter.class) DefaultDirectoryWriter directoryWriter(); @Bean @ConditionalOnMissingBean(name = "jobsDir", value = Resource.class) Resource jobsDir(
final ResourceLoader resourceLoader,
final JobsProperties jobsProperties
); @Bean CharacterEncodingFilter characterEncodingFilter(); @Bean Jackson2ObjectMapperBuilderCustomizer apisObjectMapperCustomizer(); }### Answer:
@Test void canGetResourceLoader() { Assertions.assertThat(this.apisAutoConfiguration.resourceLoader()).isInstanceOf(DefaultResourceLoader.class); } |
### Question:
ApisAutoConfiguration { @Bean @ConditionalOnMissingBean(name = "genieRestTemplate") public RestTemplate genieRestTemplate( final HttpProperties httpProperties, final RestTemplateBuilder restTemplateBuilder ) { return restTemplateBuilder .setConnectTimeout(Duration.of(httpProperties.getConnect().getTimeout(), ChronoUnit.MILLIS)) .setReadTimeout(Duration.of(httpProperties.getRead().getTimeout(), ChronoUnit.MILLIS)) .build(); } @Bean @ConditionalOnMissingBean(ResourceLoader.class) ResourceLoader resourceLoader(); @Bean @ConditionalOnMissingBean(name = "genieRestTemplate") RestTemplate genieRestTemplate(
final HttpProperties httpProperties,
final RestTemplateBuilder restTemplateBuilder
); @Bean @ConditionalOnMissingBean(name = "genieRetryTemplate") RetryTemplate genieRetryTemplate(final RetryProperties retryProperties); @Bean @ConditionalOnMissingBean(DirectoryWriter.class) DefaultDirectoryWriter directoryWriter(); @Bean @ConditionalOnMissingBean(name = "jobsDir", value = Resource.class) Resource jobsDir(
final ResourceLoader resourceLoader,
final JobsProperties jobsProperties
); @Bean CharacterEncodingFilter characterEncodingFilter(); @Bean Jackson2ObjectMapperBuilderCustomizer apisObjectMapperCustomizer(); }### Answer:
@Test void canGetRestTemplate() { Assertions .assertThat(this.apisAutoConfiguration.genieRestTemplate(new HttpProperties(), new RestTemplateBuilder())) .isNotNull(); } |
### Question:
ApisAutoConfiguration { @Bean @ConditionalOnMissingBean(DirectoryWriter.class) public DefaultDirectoryWriter directoryWriter() { return new DefaultDirectoryWriter(); } @Bean @ConditionalOnMissingBean(ResourceLoader.class) ResourceLoader resourceLoader(); @Bean @ConditionalOnMissingBean(name = "genieRestTemplate") RestTemplate genieRestTemplate(
final HttpProperties httpProperties,
final RestTemplateBuilder restTemplateBuilder
); @Bean @ConditionalOnMissingBean(name = "genieRetryTemplate") RetryTemplate genieRetryTemplate(final RetryProperties retryProperties); @Bean @ConditionalOnMissingBean(DirectoryWriter.class) DefaultDirectoryWriter directoryWriter(); @Bean @ConditionalOnMissingBean(name = "jobsDir", value = Resource.class) Resource jobsDir(
final ResourceLoader resourceLoader,
final JobsProperties jobsProperties
); @Bean CharacterEncodingFilter characterEncodingFilter(); @Bean Jackson2ObjectMapperBuilderCustomizer apisObjectMapperCustomizer(); }### Answer:
@Test void canGetDirectoryWriter() { Assertions.assertThat(this.apisAutoConfiguration.directoryWriter()).isNotNull(); } |
### Question:
FileLockFactory { public CloseableLock getLock(final File file) throws LockException { return new FileLock(file); } CloseableLock getLock(final File file); }### Answer:
@Test void canGetTaskExecutor(@TempDir final Path tmpDir) throws IOException, LockException { Assertions .assertThat( this.fileLockFactory.getLock(Files.createFile(tmpDir.resolve(UUID.randomUUID().toString())).toFile()) ) .isInstanceOf(FileLock.class); } |
### Question:
GenieDefaultPropertiesPostProcessor implements EnvironmentPostProcessor { @Override public void postProcessEnvironment(final ConfigurableEnvironment environment, final SpringApplication application) { final Resource defaultProperties = new ClassPathResource(DEFAULT_PROPERTIES_FILE); final PropertySource<?> defaultSource = PropertySourceUtils.loadYamlPropertySource(DEFAULT_PROPERTY_SOURCE_NAME, defaultProperties); environment.getPropertySources().addLast(defaultSource); } @Override void postProcessEnvironment(final ConfigurableEnvironment environment, final SpringApplication application); }### Answer:
@Test void testSmokeProperty() { this.contextRunner .run( context -> { final SpringApplication application = Mockito.mock(SpringApplication.class); final ConfigurableEnvironment environment = context.getEnvironment(); Assertions.assertThat( environment .getPropertySources() .contains(GenieDefaultPropertiesPostProcessor.DEFAULT_PROPERTY_SOURCE_NAME) ).isFalse(); Assertions.assertThat(environment.getProperty("genie.smoke")).isBlank(); this.processor.postProcessEnvironment(environment, application); Assertions .assertThat( environment .getPropertySources() .contains(GenieDefaultPropertiesPostProcessor.DEFAULT_PROPERTY_SOURCE_NAME) ) .isTrue(); Assertions .assertThat(environment.getProperty("genie.smoke", Boolean.class, false)) .isTrue(); } ); } |
### Question:
AgentAutoConfiguration { @Bean TaskExecutorCustomizer taskExecutorCustomizer(final AgentProperties agentProperties) { return taskExecutor -> { taskExecutor.setWaitForTasksToCompleteOnShutdown(true); taskExecutor.setAwaitTerminationSeconds( (int) agentProperties.getShutdown().getSystemExecutorLeeway().getSeconds() ); }; } @Bean @ConditionalOnMissingBean(GenieHostInfo.class) GenieHostInfo genieAgentHostInfo(); @Bean @Lazy @ConditionalOnMissingBean(AgentMetadata.class) AgentMetadataImpl agentMetadata(final GenieHostInfo genieHostInfo); @Bean @Lazy FileLockFactory fileLockFactory(); @Bean @Lazy @ConditionalOnMissingBean(name = "sharedAgentTaskExecutor", value = AsyncTaskExecutor.class) AsyncTaskExecutor sharedAgentTaskExecutor(final AgentProperties agentProperties); @Bean @Lazy @ConditionalOnMissingBean(name = "sharedAgentTaskScheduler") TaskScheduler sharedAgentTaskScheduler(final AgentProperties agentProperties); @Bean @Lazy @ConditionalOnMissingBean(name = "heartBeatServiceTaskScheduler") TaskScheduler heartBeatServiceTaskScheduler(final AgentProperties agentProperties); }### Answer:
@Test void testTaskExecutorCustomizer() { final AgentProperties properties = new AgentProperties(); final TaskExecutorCustomizer customizer = new AgentAutoConfiguration().taskExecutorCustomizer(properties); final ThreadPoolTaskExecutor taskExecutor = Mockito.mock(ThreadPoolTaskExecutor.class); customizer.customize(taskExecutor); Mockito.verify(taskExecutor).setWaitForTasksToCompleteOnShutdown(true); Mockito.verify(taskExecutor).setAwaitTerminationSeconds(60); } |
### Question:
PredicateUtils { static String getTagLikeString(@NotNull final Set<String> tags) { final StringBuilder builder = new StringBuilder(); tags.stream() .filter(StringUtils::isNotBlank) .sorted(String.CASE_INSENSITIVE_ORDER) .forEach( tag -> builder .append(PERCENT) .append(TAG_DELIMITER) .append(tag) .append(TAG_DELIMITER) ); return builder.append(PERCENT).toString(); } private PredicateUtils(); static String createTagSearchString(final Set<TagEntity> tags); }### Answer:
@Test void canGetTagLikeString() { Assertions .assertThat(PredicateUtils.getTagLikeString(Sets.newHashSet())) .isEqualTo( PredicateUtils.PERCENT ); Assertions .assertThat(PredicateUtils.getTagLikeString(Sets.newHashSet("tag"))) .isEqualTo( PredicateUtils.PERCENT + PredicateUtils.TAG_DELIMITER + "tag" + PredicateUtils.TAG_DELIMITER + PredicateUtils.PERCENT ); Assertions .assertThat(PredicateUtils.getTagLikeString(Sets.newHashSet("tag", "Stag", "rag"))) .isEqualTo( PredicateUtils.PERCENT + PredicateUtils.TAG_DELIMITER + "rag" + PredicateUtils.TAG_DELIMITER + "%" + PredicateUtils.TAG_DELIMITER + "Stag" + PredicateUtils.TAG_DELIMITER + "%" + PredicateUtils.TAG_DELIMITER + "tag" + PredicateUtils.TAG_DELIMITER + PredicateUtils.PERCENT ); } |
### Question:
AgentAutoConfiguration { @Bean TaskSchedulerCustomizer taskSchedulerCustomizer(final AgentProperties agentProperties) { return taskScheduler -> { taskScheduler.setWaitForTasksToCompleteOnShutdown(true); taskScheduler.setAwaitTerminationSeconds( (int) agentProperties.getShutdown().getSystemSchedulerLeeway().getSeconds() ); }; } @Bean @ConditionalOnMissingBean(GenieHostInfo.class) GenieHostInfo genieAgentHostInfo(); @Bean @Lazy @ConditionalOnMissingBean(AgentMetadata.class) AgentMetadataImpl agentMetadata(final GenieHostInfo genieHostInfo); @Bean @Lazy FileLockFactory fileLockFactory(); @Bean @Lazy @ConditionalOnMissingBean(name = "sharedAgentTaskExecutor", value = AsyncTaskExecutor.class) AsyncTaskExecutor sharedAgentTaskExecutor(final AgentProperties agentProperties); @Bean @Lazy @ConditionalOnMissingBean(name = "sharedAgentTaskScheduler") TaskScheduler sharedAgentTaskScheduler(final AgentProperties agentProperties); @Bean @Lazy @ConditionalOnMissingBean(name = "heartBeatServiceTaskScheduler") TaskScheduler heartBeatServiceTaskScheduler(final AgentProperties agentProperties); }### Answer:
@Test void testTaskSchedulerCustomizer() { final AgentProperties properties = new AgentProperties(); final TaskSchedulerCustomizer customizer = new AgentAutoConfiguration().taskSchedulerCustomizer(properties); final ThreadPoolTaskScheduler taskScheduler = Mockito.mock(ThreadPoolTaskScheduler.class); customizer.customize(taskScheduler); Mockito.verify(taskScheduler).setWaitForTasksToCompleteOnShutdown(true); Mockito.verify(taskScheduler).setAwaitTerminationSeconds(60); } |
### Question:
ExecutionAutoConfiguration { @Bean @Lazy @ConditionalOnMissingBean ExecutionContext executionContext(final AgentProperties agentProperties) { return new ExecutionContext(agentProperties); } @Bean @Lazy @ConditionalOnMissingBean(LoggingListener.class) LoggingListener loggingListener(); @Bean @Lazy @ConditionalOnMissingBean(ConsoleLogListener.class) ConsoleLogListener consoleLogLoggingListener(); }### Answer:
@Test void executionContext() { contextRunner.run( context -> { Assertions.assertThat(context).hasSingleBean(LoggingListener.class); Assertions.assertThat(context).hasSingleBean(ConsoleLogListener.class); Assertions.assertThat(context).hasSingleBean(ExecutionContext.class); Assertions.assertThat(context).hasSingleBean(JobExecutionStateMachine.class); Assertions.assertThat(context).hasSingleBean(AgentProperties.class); uniqueExecutionStages.forEach( stageClass -> Assertions.assertThat(context).hasSingleBean(stageClass) ); repeatedExecutionStages.forEach( (clazz, count) -> Assertions.assertThat(context).getBeans(clazz).hasSize(count) ); } ); } |
### Question:
Job extends CommonDTO { public Optional<String> getCommandArgs() { return Optional.ofNullable(this.commandArgs); } protected Job(@Valid final Builder builder); Optional<String> getCommandArgs(); Optional<String> getStatusMsg(); Optional<String> getArchiveLocation(); Optional<String> getClusterName(); Optional<String> getCommandName(); Optional<String> getGrouping(); Optional<String> getGroupingInstance(); Optional<Instant> getStarted(); Optional<Instant> getFinished(); }### Answer:
@Test void testCommandArgsEdgeCases() { final Job.Builder builder = new Job.Builder(NAME, USER, VERSION); String commandArgs = " blah "; builder.withCommandArgs(commandArgs); Assertions .assertThat(builder.build().getCommandArgs().orElseThrow(IllegalArgumentException::new)) .isEqualTo(" blah "); commandArgs = " blah "; builder.withCommandArgs(commandArgs); Assertions .assertThat(builder.build().getCommandArgs().orElseThrow(IllegalArgumentException::new)) .isEqualTo(" blah "); commandArgs = " blah blah blah\nblah\tblah \"blah\" blah "; builder.withCommandArgs(commandArgs); Assertions .assertThat(builder.build().getCommandArgs().orElseThrow(IllegalArgumentException::new)) .isEqualTo(" blah blah blah\nblah\tblah \"blah\" blah "); builder.withCommandArgs(Lists.newArrayList("blah", "blah", " blah", "\nblah", "\"blah\"")); Assertions .assertThat(builder.build().getCommandArgs().orElseThrow(IllegalArgumentException::new)) .isEqualTo("blah blah blah \nblah \"blah\""); } |
### Question:
BaseEntity extends UniqueIdEntity implements BaseProjection, SetupFileProjection { public void setDescription(@Nullable final String description) { this.description = description; } BaseEntity(); @Override Optional<String> getDescription(); void setDescription(@Nullable final String description); @Override Optional<JsonNode> getMetadata(); void setMetadata(@Nullable final JsonNode metadata); @Override Optional<FileEntity> getSetupFile(); void setSetupFile(@Nullable final FileEntity setupFile); @Override boolean equals(final Object o); @Override int hashCode(); }### Answer:
@Test void testSetDescription() { Assertions.assertThat(this.b.getDescription()).isNotPresent(); final String description = "Test description"; this.b.setDescription(description); Assertions.assertThat(this.b.getDescription()).isPresent().contains(description); } |
### Question:
BaseDTO implements Serializable { @Override public String toString() { try { return GenieObjectMapper.getMapper().writeValueAsString(this); } catch (final JsonProcessingException ioe) { return ioe.getLocalizedMessage(); } } BaseDTO(final Builder builder); Optional<String> getId(); Optional<Instant> getCreated(); Optional<Instant> getUpdated(); @Override String toString(); }### Answer:
@Test void canCreateValidJsonString() { final Application application = new Application.Builder( UUID.randomUUID().toString(), UUID.randomUUID().toString(), UUID.randomUUID().toString(), ApplicationStatus.ACTIVE ).build(); final String json = application.toString(); Assertions.assertThatCode(() -> GenieObjectMapper.getMapper().readTree(json)).doesNotThrowAnyException(); } |
### Question:
JobRequest extends ExecutionEnvironmentDTO { public Optional<String> getCommandArgs() { return Optional.ofNullable(this.commandArgs); } JobRequest(@Valid final Builder builder); Optional<String> getCommandArgs(); Optional<String> getGroup(); Optional<String> getEmail(); Optional<Integer> getCpu(); Optional<Integer> getMemory(); Optional<Integer> getTimeout(); Optional<String> getGrouping(); Optional<String> getGroupingInstance(); static final int DEFAULT_TIMEOUT_DURATION; }### Answer:
@Test void testCommandArgsEdgeCases() { final JobRequest.Builder builder = new JobRequest.Builder(NAME, USER, VERSION, Lists.newArrayList(), Sets.newHashSet()); String commandArgs = " blah "; builder.withCommandArgs(commandArgs); Assertions .assertThat(builder.build().getCommandArgs().orElseThrow(IllegalArgumentException::new)) .isEqualTo(" blah "); commandArgs = " blah "; builder.withCommandArgs(commandArgs); Assertions .assertThat(builder.build().getCommandArgs().orElseThrow(IllegalArgumentException::new)) .isEqualTo(" blah "); commandArgs = " blah blah blah\nblah\tblah \"blah\" blah "; builder.withCommandArgs(commandArgs); Assertions .assertThat(builder.build().getCommandArgs().orElseThrow(IllegalArgumentException::new)) .isEqualTo(" blah blah blah\nblah\tblah \"blah\" blah "); builder.withCommandArgs(Lists.newArrayList("blah", "blah", " blah", "\nblah", "\"blah\"")); Assertions .assertThat(builder.build().getCommandArgs().orElseThrow(IllegalArgumentException::new)) .isEqualTo("blah blah blah \nblah \"blah\""); } |
### Question:
TimeUtils { public static Duration getDuration(@Nullable final Instant started, @Nullable final Instant finished) { if (started == null || started.toEpochMilli() == 0L) { return Duration.ZERO; } else if (finished == null || finished.toEpochMilli() == 0L) { return Duration.ofMillis(Instant.now().toEpochMilli() - started.toEpochMilli()); } else { return Duration.ofMillis(finished.toEpochMilli() - started.toEpochMilli()); } } private TimeUtils(); static Duration getDuration(@Nullable final Instant started, @Nullable final Instant finished); }### Answer:
@Test void canGetDuration() { final long durationMillis = 50823L; final Duration duration = Duration.ofMillis(durationMillis); final Instant started = Instant.now(); final Instant finished = started.plusMillis(durationMillis); Assertions.assertThat(TimeUtils.getDuration(null, finished)).isEqualByComparingTo(Duration.ZERO); Assertions.assertThat(TimeUtils.getDuration(Instant.EPOCH, finished)).isEqualByComparingTo(Duration.ZERO); Assertions.assertThat(TimeUtils.getDuration(started, null)).isNotNull(); Assertions.assertThat(TimeUtils.getDuration(started, Instant.EPOCH)).isNotNull(); Assertions.assertThat(TimeUtils.getDuration(started, finished)).isEqualByComparingTo(duration); } |
### Question:
JsonUtils { public static String marshall(final Object value) throws GenieException { try { return GenieObjectMapper.getMapper().writeValueAsString(value); } catch (final JsonProcessingException jpe) { throw new GenieServerException("Failed to marshall object", jpe); } } protected JsonUtils(); static String marshall(final Object value); static T unmarshall(
final String source,
final TypeReference<T> typeReference
); @Nonnull static List<String> splitArguments(final String commandArgs); @Nullable static String joinArguments(final List<String> commandArgs); }### Answer:
@Test void canMarshall() throws GenieException { final List<String> strings = Lists.newArrayList("one", "two", "three"); Assertions.assertThat(JsonUtils.marshall(strings)).isEqualTo("[\"one\",\"two\",\"three\"]"); } |
### Question:
JsonUtils { public static <T extends Collection> T unmarshall( final String source, final TypeReference<T> typeReference ) throws GenieException { try { if (StringUtils.isNotBlank(source)) { return GenieObjectMapper.getMapper().readValue(source, typeReference); } else { return GenieObjectMapper.getMapper().readValue("[]", typeReference); } } catch (final IOException ioe) { throw new GenieServerException("Failed to read JSON value", ioe); } } protected JsonUtils(); static String marshall(final Object value); static T unmarshall(
final String source,
final TypeReference<T> typeReference
); @Nonnull static List<String> splitArguments(final String commandArgs); @Nullable static String joinArguments(final List<String> commandArgs); }### Answer:
@Test void canUnmarshall() throws GenieException { final String source = "[\"one\",\"two\",\"three\"]"; final TypeReference<List<String>> list = new TypeReference<List<String>>() { }; Assertions .assertThat(JsonUtils.unmarshall(source, list)) .isEqualTo(Lists.newArrayList("one", "two", "three")); Assertions.assertThat(JsonUtils.unmarshall(null, list)).isEqualTo(Lists.newArrayList()); } |
### Question:
GenieException extends Exception { public int getErrorCode() { return errorCode; } GenieException(final int errorCode, final String msg, final Throwable cause); GenieException(final int errorCode, final String msg); int getErrorCode(); }### Answer:
@Test void testThreeArgConstructor() { Assertions .assertThatExceptionOfType(GenieException.class) .isThrownBy( () -> { throw new GenieException(ERROR_CODE, ERROR_MESSAGE, IOE); } ) .withCause(IOE) .withMessage(ERROR_MESSAGE) .satisfies(e -> Assertions.assertThat(e.getErrorCode()).isEqualTo(HttpURLConnection.HTTP_NOT_FOUND)); }
@Test void testTwoArgConstructorWithMessage() { Assertions .assertThatExceptionOfType(GenieException.class) .isThrownBy( () -> { throw new GenieException(ERROR_CODE, ERROR_MESSAGE); } ) .withNoCause() .withMessage(ERROR_MESSAGE) .satisfies(e -> Assertions.assertThat(e.getErrorCode()).isEqualTo(HttpURLConnection.HTTP_NOT_FOUND)); } |
### Question:
BaseEntity extends UniqueIdEntity implements BaseProjection, SetupFileProjection { public void setSetupFile(@Nullable final FileEntity setupFile) { this.setupFile = setupFile; } BaseEntity(); @Override Optional<String> getDescription(); void setDescription(@Nullable final String description); @Override Optional<JsonNode> getMetadata(); void setMetadata(@Nullable final JsonNode metadata); @Override Optional<FileEntity> getSetupFile(); void setSetupFile(@Nullable final FileEntity setupFile); @Override boolean equals(final Object o); @Override int hashCode(); }### Answer:
@Test void testSetSetupFile() { Assertions.assertThat(this.b.getSetupFile()).isNotPresent(); final FileEntity setupFile = new FileEntity(UUID.randomUUID().toString()); this.b.setSetupFile(setupFile); Assertions.assertThat(this.b.getSetupFile()).isPresent().contains(setupFile); this.b.setSetupFile(null); Assertions.assertThat(this.b.getSetupFile()).isNotPresent(); } |
### Question:
CommonServicesAutoConfiguration { @Bean(name = "jobDirectoryManifestCache") @ConditionalOnMissingBean(name = "jobDirectoryManifestCache") public Cache<Path, DirectoryManifest> jobDirectoryManifestCache() { return Caffeine.newBuilder() .maximumSize(100) .expireAfterWrite(30, TimeUnit.SECONDS) .build(); } @Bean @Order(FILE_SYSTEM_JOB_ARCHIVER_PRECEDENCE) FileSystemJobArchiverImpl fileSystemJobArchiver(); @Bean @ConditionalOnMissingBean(JobArchiveService.class) JobArchiveService jobArchiveService(
final List<JobArchiver> jobArchivers,
final DirectoryManifest.Factory directoryManifestFactory
); @Bean @ConditionalOnMissingBean(JobDirectoryManifestCreatorService.class) JobDirectoryManifestCreatorServiceImpl jobDirectoryManifestCreatorService(
final DirectoryManifest.Factory directoryManifestFactory,
@Qualifier("jobDirectoryManifestCache") final Cache<Path, DirectoryManifest> cache
); @Bean(name = "jobDirectoryManifestCache") @ConditionalOnMissingBean(name = "jobDirectoryManifestCache") Cache<Path, DirectoryManifest> jobDirectoryManifestCache(); @Bean @ConditionalOnMissingBean(DirectoryManifest.Factory.class) DirectoryManifest.Factory directoryManifestFactory(
final DirectoryManifest.Filter directoryManifestFilter
); @Bean @ConditionalOnMissingBean(DirectoryManifest.Filter.class) DirectoryManifest.Filter directoryManifestFilter(final RegexDirectoryManifestProperties properties); static final int FILE_SYSTEM_JOB_ARCHIVER_PRECEDENCE; }### Answer:
@Test void testJobDirectoryManifestCache() { this.contextRunner.run( context -> Assertions.assertThat(context).getBean("jobDirectoryManifestCache").isNotNull() ); } |
### Question:
CommonServicesAutoConfiguration { @Bean @ConditionalOnMissingBean(DirectoryManifest.Factory.class) public DirectoryManifest.Factory directoryManifestFactory( final DirectoryManifest.Filter directoryManifestFilter ) { return new DirectoryManifest.Factory(directoryManifestFilter); } @Bean @Order(FILE_SYSTEM_JOB_ARCHIVER_PRECEDENCE) FileSystemJobArchiverImpl fileSystemJobArchiver(); @Bean @ConditionalOnMissingBean(JobArchiveService.class) JobArchiveService jobArchiveService(
final List<JobArchiver> jobArchivers,
final DirectoryManifest.Factory directoryManifestFactory
); @Bean @ConditionalOnMissingBean(JobDirectoryManifestCreatorService.class) JobDirectoryManifestCreatorServiceImpl jobDirectoryManifestCreatorService(
final DirectoryManifest.Factory directoryManifestFactory,
@Qualifier("jobDirectoryManifestCache") final Cache<Path, DirectoryManifest> cache
); @Bean(name = "jobDirectoryManifestCache") @ConditionalOnMissingBean(name = "jobDirectoryManifestCache") Cache<Path, DirectoryManifest> jobDirectoryManifestCache(); @Bean @ConditionalOnMissingBean(DirectoryManifest.Factory.class) DirectoryManifest.Factory directoryManifestFactory(
final DirectoryManifest.Filter directoryManifestFilter
); @Bean @ConditionalOnMissingBean(DirectoryManifest.Filter.class) DirectoryManifest.Filter directoryManifestFilter(final RegexDirectoryManifestProperties properties); static final int FILE_SYSTEM_JOB_ARCHIVER_PRECEDENCE; }### Answer:
@Test void testDirectoryManifestFactory() { this.contextRunner.run( context -> Assertions.assertThat(context).hasSingleBean(DirectoryManifest.Factory.class) ); } |
### Question:
CommonServicesAutoConfiguration { @Bean @ConditionalOnMissingBean(DirectoryManifest.Filter.class) public DirectoryManifest.Filter directoryManifestFilter(final RegexDirectoryManifestProperties properties) { return new RegexDirectoryManifestFilter(properties); } @Bean @Order(FILE_SYSTEM_JOB_ARCHIVER_PRECEDENCE) FileSystemJobArchiverImpl fileSystemJobArchiver(); @Bean @ConditionalOnMissingBean(JobArchiveService.class) JobArchiveService jobArchiveService(
final List<JobArchiver> jobArchivers,
final DirectoryManifest.Factory directoryManifestFactory
); @Bean @ConditionalOnMissingBean(JobDirectoryManifestCreatorService.class) JobDirectoryManifestCreatorServiceImpl jobDirectoryManifestCreatorService(
final DirectoryManifest.Factory directoryManifestFactory,
@Qualifier("jobDirectoryManifestCache") final Cache<Path, DirectoryManifest> cache
); @Bean(name = "jobDirectoryManifestCache") @ConditionalOnMissingBean(name = "jobDirectoryManifestCache") Cache<Path, DirectoryManifest> jobDirectoryManifestCache(); @Bean @ConditionalOnMissingBean(DirectoryManifest.Factory.class) DirectoryManifest.Factory directoryManifestFactory(
final DirectoryManifest.Filter directoryManifestFilter
); @Bean @ConditionalOnMissingBean(DirectoryManifest.Filter.class) DirectoryManifest.Filter directoryManifestFilter(final RegexDirectoryManifestProperties properties); static final int FILE_SYSTEM_JOB_ARCHIVER_PRECEDENCE; }### Answer:
@Test void testDirectoryManifestFilter() { this.contextRunner.run( context -> Assertions.assertThat(context).hasSingleBean(DirectoryManifest.Filter.class) ); } |
### Question:
BaseEntity extends UniqueIdEntity implements BaseProjection, SetupFileProjection { public void setMetadata(@Nullable final JsonNode metadata) { this.metadata = metadata; } BaseEntity(); @Override Optional<String> getDescription(); void setDescription(@Nullable final String description); @Override Optional<JsonNode> getMetadata(); void setMetadata(@Nullable final JsonNode metadata); @Override Optional<FileEntity> getSetupFile(); void setSetupFile(@Nullable final FileEntity setupFile); @Override boolean equals(final Object o); @Override int hashCode(); }### Answer:
@Test void testSetMetadata() { Assertions.assertThat(this.b.getMetadata()).isNotPresent(); this.b.setMetadata(METADATA); Assertions.assertThat(this.b.getMetadata()).isPresent().contains(METADATA); this.b.setMetadata(null); Assertions.assertThat(this.b.getMetadata()).isNotPresent(); } |
### Question:
BaseEntity extends UniqueIdEntity implements BaseProjection, SetupFileProjection { @Override public int hashCode() { return super.hashCode(); } BaseEntity(); @Override Optional<String> getDescription(); void setDescription(@Nullable final String description); @Override Optional<JsonNode> getMetadata(); void setMetadata(@Nullable final JsonNode metadata); @Override Optional<FileEntity> getSetupFile(); void setSetupFile(@Nullable final FileEntity setupFile); @Override boolean equals(final Object o); @Override int hashCode(); }### Answer:
@Test void testEqualsAndHashCode() { final String id = UUID.randomUUID().toString(); final String name = UUID.randomUUID().toString(); final BaseEntity one = new BaseEntity(); one.setUniqueId(id); one.setName(UUID.randomUUID().toString()); final BaseEntity two = new BaseEntity(); two.setUniqueId(id); two.setName(name); final BaseEntity three = new BaseEntity(); three.setUniqueId(UUID.randomUUID().toString()); three.setName(name); Assertions.assertThat(one).isEqualTo(two); Assertions.assertThat(one).isNotEqualTo(three); Assertions.assertThat(two).isNotEqualTo(three); Assertions.assertThat(one.hashCode()).isEqualTo(two.hashCode()); Assertions.assertThat(one.hashCode()).isNotEqualTo(three.hashCode()); Assertions.assertThat(two.hashCode()).isNotEqualTo(three.hashCode()); } |
### Question:
UIController { @GetMapping(value = "/file/{id}/**") public String getFile( @PathVariable("id") final String id, final HttpServletRequest request ) throws UnsupportedEncodingException { final String encodedId = URLEncoder.encode(id, "UTF-8"); final String path = "/api/v3/jobs/" + encodedId + "/" + ControllerUtils.getRemainingPath(request); return "forward:" + path; } @GetMapping( value = { "/", "/applications/**", "/clusters/**", "/commands/**", "/jobs/**", "/output/**" } ) String getIndex(); @GetMapping(value = "/file/{id}/**") String getFile(
@PathVariable("id") final String id,
final HttpServletRequest request
); }### Answer:
@Test void canGetFile() throws Exception { final String id = UUID.randomUUID().toString(); final HttpServletRequest request = Mockito.mock(HttpServletRequest.class); Mockito .when(request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE)) .thenReturn("/file/" + id + "/output/genie/log.out"); Mockito .when(request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE)) .thenReturn("/file/{id}/**"); final String encodedId = URLEncoder.encode(id, "UTF-8"); final String expectedPath = "/api/v3/jobs/" + encodedId + "/output/genie/log.out"; Assertions.assertThat(this.controller.getFile(id, request)).isEqualTo("forward:" + expectedPath); } |
### Question:
TokenFetcher { public AccessToken getToken() throws GenieClientException { try { if (Instant.now().isAfter(this.expirationTime)) { final Response<AccessToken> response = tokenService.getToken(oauthUrl, credentialParams).execute(); if (response.isSuccessful()) { this.accessToken = response.body(); this.expirationTime = Instant .now() .plus(this.accessToken.getExpiresIn() - 300, ChronoUnit.SECONDS); return this.accessToken; } else { throw new GenieClientException(response.code(), "Could not fetch Token"); } } else { return this.accessToken; } } catch (final Exception e) { throw new GenieClientException("Could not get access tokens" + e); } } TokenFetcher(
final String oauthUrl,
final String clientId,
final String clientSecret,
final String grantType,
final String scope
); AccessToken getToken(); }### Answer:
@Test @Disabled("Fails from time to time non-deterministically") void testGetTokenFailure() { Assertions .assertThatExceptionOfType(GenieClientException.class) .isThrownBy( () -> { final TokenFetcher tokenFetcher = new TokenFetcher(URL, CLIENT_ID, CLIENT_SECRET, GRANT_TYPE, SCOPE); tokenFetcher.getToken(); } ) .satisfies(e -> Assertions.assertThat(e.getErrorCode()).isEqualTo(-1)); } |
### Question:
OAuth2SecurityInterceptor implements SecurityInterceptor { @Override public Response intercept( final Chain chain ) throws IOException { final AccessToken accessToken = this.tokenFetcher.getToken(); final Request newRequest = chain .request() .newBuilder() .addHeader(HttpHeaders.AUTHORIZATION, accessToken.getTokenType() + " " + accessToken.getAccessToken()) .build(); log.debug("Sending request {} on {} {}", newRequest.url(), chain.connection(), newRequest.headers()); return chain.proceed(newRequest); } OAuth2SecurityInterceptor(
final String url,
final String clientId,
final String clientSecret,
final String grantType,
final String scope
); @Override Response intercept(
final Chain chain
); }### Answer:
@Disabled("fails randomly") @Test void testTokenFetchFailure() throws Exception { final Interceptor.Chain chain = Mockito.mock(Interceptor.Chain.class); final OAuth2SecurityInterceptor oAuth2SecurityInterceptor = new OAuth2SecurityInterceptor( URL, CLIENT_ID, CLIENT_SECRET, GRANT_TYPE, SCOPE ); Assertions.assertThatIOException().isThrownBy(() -> oAuth2SecurityInterceptor.intercept(chain)); } |
### Question:
ClusterEntity extends BaseEntity { public void setTags(@Nullable final Set<TagEntity> tags) { this.tags.clear(); if (tags != null) { this.tags.addAll(tags); } } ClusterEntity(); void setConfigs(@Nullable final Set<FileEntity> configs); void setDependencies(@Nullable final Set<FileEntity> dependencies); void setTags(@Nullable final Set<TagEntity> tags); @Override boolean equals(final Object o); @Override int hashCode(); static final String DTO_ENTITY_GRAPH; }### Answer:
@Test void testSetTags() { Assertions.assertThat(this.c.getTags()).isEmpty(); final TagEntity prodTag = new TagEntity(); prodTag.setTag("prod"); final TagEntity slaTag = new TagEntity(); slaTag.setTag("sla"); final Set<TagEntity> tags = Sets.newHashSet(prodTag, slaTag); this.c.setTags(tags); Assertions.assertThat(this.c.getTags()).isEqualTo(tags); this.c.setTags(null); Assertions.assertThat(this.c.getTags()).isEmpty(); }
@Test void canSetClusterTags() { final TagEntity oneTag = new TagEntity(); oneTag.setTag("one"); final TagEntity twoTag = new TagEntity(); twoTag.setTag("tow"); final TagEntity preTag = new TagEntity(); preTag.setTag("Pre"); final Set<TagEntity> tags = Sets.newHashSet(oneTag, twoTag, preTag); this.c.setTags(tags); Assertions.assertThat(this.c.getTags()).isEqualTo(tags); this.c.setTags(Sets.newHashSet()); Assertions.assertThat(this.c.getTags()).isEmpty(); this.c.setTags(null); Assertions.assertThat(this.c.getTags()).isEmpty(); } |
### Question:
ClusterEntity extends BaseEntity { public void setConfigs(@Nullable final Set<FileEntity> configs) { this.configs.clear(); if (configs != null) { this.configs.addAll(configs); } } ClusterEntity(); void setConfigs(@Nullable final Set<FileEntity> configs); void setDependencies(@Nullable final Set<FileEntity> dependencies); void setTags(@Nullable final Set<TagEntity> tags); @Override boolean equals(final Object o); @Override int hashCode(); static final String DTO_ENTITY_GRAPH; }### Answer:
@Test void testSetConfigs() { Assertions.assertThat(this.c.getConfigs()).isEmpty(); this.c.setConfigs(this.configs); Assertions.assertThat(this.c.getConfigs()).isEqualTo(this.configs); this.c.setConfigs(null); Assertions.assertThat(c.getConfigs()).isEmpty(); } |
### Question:
ClusterEntity extends BaseEntity { public void setDependencies(@Nullable final Set<FileEntity> dependencies) { this.dependencies.clear(); if (dependencies != null) { this.dependencies.addAll(dependencies); } } ClusterEntity(); void setConfigs(@Nullable final Set<FileEntity> configs); void setDependencies(@Nullable final Set<FileEntity> dependencies); void setTags(@Nullable final Set<TagEntity> tags); @Override boolean equals(final Object o); @Override int hashCode(); static final String DTO_ENTITY_GRAPH; }### Answer:
@Test void testSetDependencies() { Assertions.assertThat(this.c.getDependencies()).isEmpty(); final FileEntity dependency = new FileEntity(); dependency.setFile("s3: final Set<FileEntity> dependencies = Sets.newHashSet(dependency); this.c.setDependencies(dependencies); Assertions.assertThat(this.c.getDependencies()).isEqualTo(dependencies); this.c.setDependencies(null); Assertions.assertThat(this.c.getDependencies()).isEmpty(); } |
### Question:
ApplicationEntity extends BaseEntity { public void setConfigs(@Nullable final Set<FileEntity> configs) { this.configs.clear(); if (configs != null) { this.configs.addAll(configs); } } ApplicationEntity(); Optional<String> getType(); void setConfigs(@Nullable final Set<FileEntity> configs); void setDependencies(@Nullable final Set<FileEntity> dependencies); void setTags(@Nullable final Set<TagEntity> tags); @Override boolean equals(final Object o); @Override int hashCode(); static final String COMMANDS_ENTITY_GRAPH; static final String COMMANDS_DTO_ENTITY_GRAPH; static final String DTO_ENTITY_GRAPH; }### Answer:
@Test void testSetConfigs() { final Set<FileEntity> configs = Sets.newHashSet(new FileEntity("s3: this.a.setConfigs(configs); Assertions.assertThat(this.a.getConfigs()).isEqualTo(configs); this.a.setConfigs(null); Assertions.assertThat(this.a.getConfigs()).isEmpty(); } |
### Question:
ApplicationEntity extends BaseEntity { public void setDependencies(@Nullable final Set<FileEntity> dependencies) { this.dependencies.clear(); if (dependencies != null) { this.dependencies.addAll(dependencies); } } ApplicationEntity(); Optional<String> getType(); void setConfigs(@Nullable final Set<FileEntity> configs); void setDependencies(@Nullable final Set<FileEntity> dependencies); void setTags(@Nullable final Set<TagEntity> tags); @Override boolean equals(final Object o); @Override int hashCode(); static final String COMMANDS_ENTITY_GRAPH; static final String COMMANDS_DTO_ENTITY_GRAPH; static final String DTO_ENTITY_GRAPH; }### Answer:
@Test void testSetDependencies() { final Set<FileEntity> dependencies = Sets.newHashSet(new FileEntity("s3: this.a.setDependencies(dependencies); Assertions.assertThat(this.a.getDependencies()).isEqualTo(dependencies); this.a.setDependencies(null); Assertions.assertThat(this.a.getDependencies()).isEmpty(); } |
### Question:
ApplicationEntity extends BaseEntity { public void setTags(@Nullable final Set<TagEntity> tags) { this.tags.clear(); if (tags != null) { this.tags.addAll(tags); } } ApplicationEntity(); Optional<String> getType(); void setConfigs(@Nullable final Set<FileEntity> configs); void setDependencies(@Nullable final Set<FileEntity> dependencies); void setTags(@Nullable final Set<TagEntity> tags); @Override boolean equals(final Object o); @Override int hashCode(); static final String COMMANDS_ENTITY_GRAPH; static final String COMMANDS_DTO_ENTITY_GRAPH; static final String DTO_ENTITY_GRAPH; }### Answer:
@Test void testSetTags() { final TagEntity tag1 = new TagEntity("tag1"); final TagEntity tag2 = new TagEntity("tag2"); final Set<TagEntity> tags = Sets.newHashSet(tag1, tag2); this.a.setTags(tags); Assertions.assertThat(this.a.getTags()).isEqualTo(tags); this.a.setTags(null); Assertions.assertThat(this.a.getTags()).isEmpty(); } |
### Question:
ApplicationEntity extends BaseEntity { void setCommands(@Nullable final Set<CommandEntity> commands) { this.commands.clear(); if (commands != null) { this.commands.addAll(commands); } } ApplicationEntity(); Optional<String> getType(); void setConfigs(@Nullable final Set<FileEntity> configs); void setDependencies(@Nullable final Set<FileEntity> dependencies); void setTags(@Nullable final Set<TagEntity> tags); @Override boolean equals(final Object o); @Override int hashCode(); static final String COMMANDS_ENTITY_GRAPH; static final String COMMANDS_DTO_ENTITY_GRAPH; static final String DTO_ENTITY_GRAPH; }### Answer:
@Test void testSetCommands() { final Set<CommandEntity> commandEntities = Sets.newHashSet(new CommandEntity()); this.a.setCommands(commandEntities); Assertions.assertThat(this.a.getCommands()).isEqualTo(commandEntities); this.a.setCommands(null); Assertions.assertThat(this.a.getCommands()).isEmpty(); } |
### Question:
CriterionEntity extends IdEntity { public void setTags(@Nullable final Set<TagEntity> tags) { this.tags.clear(); if (tags != null) { this.tags.addAll(tags); } } CriterionEntity(
@Nullable final String uniqueId,
@Nullable final String name,
@Nullable final String version,
@Nullable final String status,
@Nullable final Set<TagEntity> tags
); Optional<String> getUniqueId(); void setUniqueId(@Nullable final String uniqueId); Optional<String> getName(); void setName(@Nullable final String name); Optional<String> getVersion(); void setVersion(@Nullable final String version); Optional<String> getStatus(); void setStatus(@Nullable final String status); void setTags(@Nullable final Set<TagEntity> tags); @Override boolean equals(final Object o); @Override int hashCode(); }### Answer:
@Test void canSetTags() { final CriterionEntity entity = new CriterionEntity(); Assertions.assertThat(entity.getTags()).isEmpty(); entity.setTags(null); Assertions.assertThat(entity.getTags()).isEmpty(); final Set<TagEntity> tags = Sets.newHashSet(); entity.setTags(tags); Assertions.assertThat(entity.getTags()).isEmpty(); tags.add(new TagEntity(UUID.randomUUID().toString())); entity.setTags(tags); Assertions.assertThat(entity.getTags()).isEqualTo(tags); } |
### Question:
CriterionEntity extends IdEntity { @Override public int hashCode() { return super.hashCode(); } CriterionEntity(
@Nullable final String uniqueId,
@Nullable final String name,
@Nullable final String version,
@Nullable final String status,
@Nullable final Set<TagEntity> tags
); Optional<String> getUniqueId(); void setUniqueId(@Nullable final String uniqueId); Optional<String> getName(); void setName(@Nullable final String name); Optional<String> getVersion(); void setVersion(@Nullable final String version); Optional<String> getStatus(); void setStatus(@Nullable final String status); void setTags(@Nullable final Set<TagEntity> tags); @Override boolean equals(final Object o); @Override int hashCode(); }### Answer:
@Test void testEqualsAndHashCode() { final Set<TagEntity> tags = Sets.newHashSet( new TagEntity(UUID.randomUUID().toString()), new TagEntity(UUID.randomUUID().toString()) ); final CriterionEntity one = new CriterionEntity(null, null, null, null, tags); final CriterionEntity two = new CriterionEntity(null, null, null, null, tags); final CriterionEntity three = new CriterionEntity(); Assertions.assertThat(one).isEqualTo(two); Assertions.assertThat(one).isEqualTo(three); Assertions.assertThat(two).isEqualTo(three); Assertions.assertThat(one.hashCode()).isEqualTo(two.hashCode()); Assertions.assertThat(one.hashCode()).isEqualTo(three.hashCode()); Assertions.assertThat(two.hashCode()).isEqualTo(three.hashCode()); } |
### Question:
CommandEntity extends BaseEntity { public Optional<Integer> getMemory() { return Optional.ofNullable(this.memory); } CommandEntity(); void setExecutable(@NotEmpty final List<@NotBlank @Size(max = 1024) String> executable); void setConfigs(@Nullable final Set<FileEntity> configs); void setDependencies(@Nullable final Set<FileEntity> dependencies); void setTags(@Nullable final Set<TagEntity> tags); Optional<Integer> getMemory(); Optional<JsonNode> getLauncherExt(); void setLauncherExt(@Nullable final JsonNode launcherExt); void setApplications(
@Nullable final List<ApplicationEntity> applications
); void addApplication(@NotNull final ApplicationEntity application); void removeApplication(@NotNull final ApplicationEntity application); void setClusterCriteria(@Nullable final List<CriterionEntity> clusterCriteria); void addClusterCriterion(final CriterionEntity criterion); void addClusterCriterion(final CriterionEntity criterion, final int priority); CriterionEntity removeClusterCriterion(final int priority); @Override boolean equals(final Object o); @Override int hashCode(); static final String APPLICATIONS_ENTITY_GRAPH; static final String APPLICATIONS_DTO_ENTITY_GRAPH; static final String CLUSTER_CRITERIA_ENTITY_GRAPH; static final String DTO_ENTITY_GRAPH; }### Answer:
@Test void testSetMemory() { Assertions.assertThat(this.c.getMemory()).isPresent().contains(MEMORY); final int newMemory = MEMORY + 1; this.c.setMemory(newMemory); Assertions.assertThat(this.c.getMemory()).isPresent().contains(newMemory); } |
### Question:
CommandEntity extends BaseEntity { public void setConfigs(@Nullable final Set<FileEntity> configs) { this.configs.clear(); if (configs != null) { this.configs.addAll(configs); } } CommandEntity(); void setExecutable(@NotEmpty final List<@NotBlank @Size(max = 1024) String> executable); void setConfigs(@Nullable final Set<FileEntity> configs); void setDependencies(@Nullable final Set<FileEntity> dependencies); void setTags(@Nullable final Set<TagEntity> tags); Optional<Integer> getMemory(); Optional<JsonNode> getLauncherExt(); void setLauncherExt(@Nullable final JsonNode launcherExt); void setApplications(
@Nullable final List<ApplicationEntity> applications
); void addApplication(@NotNull final ApplicationEntity application); void removeApplication(@NotNull final ApplicationEntity application); void setClusterCriteria(@Nullable final List<CriterionEntity> clusterCriteria); void addClusterCriterion(final CriterionEntity criterion); void addClusterCriterion(final CriterionEntity criterion, final int priority); CriterionEntity removeClusterCriterion(final int priority); @Override boolean equals(final Object o); @Override int hashCode(); static final String APPLICATIONS_ENTITY_GRAPH; static final String APPLICATIONS_DTO_ENTITY_GRAPH; static final String CLUSTER_CRITERIA_ENTITY_GRAPH; static final String DTO_ENTITY_GRAPH; }### Answer:
@Test void testSetConfigs() { Assertions.assertThat(this.c.getConfigs()).isEmpty(); final Set<FileEntity> configs = Sets.newHashSet(new FileEntity("s3: this.c.setConfigs(configs); Assertions.assertThat(this.c.getConfigs()).isEqualTo(configs); this.c.setConfigs(null); Assertions.assertThat(this.c.getConfigs()).isEmpty(); } |
### Question:
CommandEntity extends BaseEntity { public void setDependencies(@Nullable final Set<FileEntity> dependencies) { this.dependencies.clear(); if (dependencies != null) { this.dependencies.addAll(dependencies); } } CommandEntity(); void setExecutable(@NotEmpty final List<@NotBlank @Size(max = 1024) String> executable); void setConfigs(@Nullable final Set<FileEntity> configs); void setDependencies(@Nullable final Set<FileEntity> dependencies); void setTags(@Nullable final Set<TagEntity> tags); Optional<Integer> getMemory(); Optional<JsonNode> getLauncherExt(); void setLauncherExt(@Nullable final JsonNode launcherExt); void setApplications(
@Nullable final List<ApplicationEntity> applications
); void addApplication(@NotNull final ApplicationEntity application); void removeApplication(@NotNull final ApplicationEntity application); void setClusterCriteria(@Nullable final List<CriterionEntity> clusterCriteria); void addClusterCriterion(final CriterionEntity criterion); void addClusterCriterion(final CriterionEntity criterion, final int priority); CriterionEntity removeClusterCriterion(final int priority); @Override boolean equals(final Object o); @Override int hashCode(); static final String APPLICATIONS_ENTITY_GRAPH; static final String APPLICATIONS_DTO_ENTITY_GRAPH; static final String CLUSTER_CRITERIA_ENTITY_GRAPH; static final String DTO_ENTITY_GRAPH; }### Answer:
@Test void testSetDependencies() { Assertions.assertThat(this.c.getDependencies()).isEmpty(); final Set<FileEntity> dependencies = Sets.newHashSet(new FileEntity("dep1")); this.c.setDependencies(dependencies); Assertions.assertThat(this.c.getDependencies()).isEqualTo(dependencies); this.c.setDependencies(null); Assertions.assertThat(this.c.getDependencies()).isEmpty(); } |
### Question:
CommandEntity extends BaseEntity { public void setTags(@Nullable final Set<TagEntity> tags) { this.tags.clear(); if (tags != null) { this.tags.addAll(tags); } } CommandEntity(); void setExecutable(@NotEmpty final List<@NotBlank @Size(max = 1024) String> executable); void setConfigs(@Nullable final Set<FileEntity> configs); void setDependencies(@Nullable final Set<FileEntity> dependencies); void setTags(@Nullable final Set<TagEntity> tags); Optional<Integer> getMemory(); Optional<JsonNode> getLauncherExt(); void setLauncherExt(@Nullable final JsonNode launcherExt); void setApplications(
@Nullable final List<ApplicationEntity> applications
); void addApplication(@NotNull final ApplicationEntity application); void removeApplication(@NotNull final ApplicationEntity application); void setClusterCriteria(@Nullable final List<CriterionEntity> clusterCriteria); void addClusterCriterion(final CriterionEntity criterion); void addClusterCriterion(final CriterionEntity criterion, final int priority); CriterionEntity removeClusterCriterion(final int priority); @Override boolean equals(final Object o); @Override int hashCode(); static final String APPLICATIONS_ENTITY_GRAPH; static final String APPLICATIONS_DTO_ENTITY_GRAPH; static final String CLUSTER_CRITERIA_ENTITY_GRAPH; static final String DTO_ENTITY_GRAPH; }### Answer:
@Test void testSetTags() { Assertions.assertThat(this.c.getTags()).isEmpty(); final TagEntity one = new TagEntity("tag1"); final TagEntity two = new TagEntity("tag2"); final Set<TagEntity> tags = Sets.newHashSet(one, two); this.c.setTags(tags); Assertions.assertThat(this.c.getTags()).isEqualTo(tags); this.c.setTags(null); Assertions.assertThat(this.c.getTags()).isEmpty(); } |
### Question:
UNIXUtils { public static void changeOwnershipOfDirectory( final String dir, final String user, final Executor executor ) throws IOException { final CommandLine commandLine = new CommandLine(SUDO) .addArgument("chown") .addArgument("-R") .addArgument(user) .addArgument(dir); executor.execute(commandLine); } private UNIXUtils(); static synchronized void createUser(
final String user,
@Nullable final String group,
final Executor executor
); static void changeOwnershipOfDirectory(
final String dir,
final String user,
final Executor executor
); }### Answer:
@Test void testChangeOwnershipOfDirectoryMethodSuccess() throws IOException { final String user = "user"; final String dir = "dir"; final ArgumentCaptor<CommandLine> argumentCaptor = ArgumentCaptor.forClass(CommandLine.class); final List<String> command = Arrays.asList("sudo", "chown", "-R", user, dir); UNIXUtils.changeOwnershipOfDirectory(dir, user, executor); Mockito.verify(this.executor).execute(argumentCaptor.capture()); Assertions.assertThat(argumentCaptor.getValue().toStrings()).containsExactlyElementsOf(command); }
@Test void testChangeOwnershipOfDirectoryMethodFailure() throws IOException { final String user = "user"; final String dir = "dir"; Mockito.when(this.executor.execute(Mockito.any(CommandLine.class))).thenThrow(new IOException()); Assertions.assertThatIOException().isThrownBy(() -> UNIXUtils.changeOwnershipOfDirectory(dir, user, executor)); } |
### Question:
JobsActiveLimitProperties implements EnvironmentAware { public int getUserLimit(final String user) { final Environment env = this.environment.get(); if (env != null) { return env.getProperty( USER_LIMIT_OVERRIDE_PROPERTY_PREFIX + user, Integer.class, this.count ); } return this.count; } int getUserLimit(final String user); @Override void setEnvironment(final Environment environment); static final String PROPERTY_PREFIX; static final String ENABLED_PROPERTY; static final String USER_LIMIT_OVERRIDE_PROPERTY_PREFIX; static final boolean DEFAULT_ENABLED; static final int DEFAULT_COUNT; }### Answer:
@Test void canConstruct() { Assertions.assertThat(this.properties.isEnabled()).isEqualTo(JobsActiveLimitProperties.DEFAULT_ENABLED); Assertions.assertThat(this.properties.getCount()).isEqualTo(JobsActiveLimitProperties.DEFAULT_COUNT); Assertions .assertThat(this.properties.getUserLimit("SomeUser")) .isEqualTo(JobsActiveLimitProperties.DEFAULT_COUNT); } |
### Question:
TaskUtils { public static Instant getMidnightUTC() { return ZonedDateTime.now(ZoneId.of("UTC")).withHour(0).withMinute(0).withSecond(0).withNano(0).toInstant(); } protected TaskUtils(); static Instant getMidnightUTC(); }### Answer:
@Test void canGetMidnightUtc() { final Instant midnightUTC = TaskUtils.getMidnightUTC(); final ZonedDateTime cal = ZonedDateTime.ofInstant(midnightUTC, ZoneId.of("UTC")); Assertions.assertThat(cal.getNano()).isEqualTo(0); Assertions.assertThat(cal.getSecond()).isEqualTo(0); Assertions.assertThat(cal.getMinute()).isEqualTo(0); Assertions.assertThat(cal.getHour()).isEqualTo(0); } |
### Question:
DatabaseCleanupTask extends LeaderTask { @Override public GenieTaskScheduleType getScheduleType() { return GenieTaskScheduleType.TRIGGER; } DatabaseCleanupTask(
@NotNull final DatabaseCleanupProperties cleanupProperties,
@NotNull final Environment environment,
@NotNull final DataServices dataServices,
@NotNull final MeterRegistry registry
); @Override GenieTaskScheduleType getScheduleType(); @Override Trigger getTrigger(); @Override void run(); @Override void cleanup(); }### Answer:
@Test void canGetScheduleType() { Assertions.assertThat(this.task.getScheduleType()).isEqualTo(GenieTaskScheduleType.TRIGGER); } |
### Question:
DatabaseCleanupTask extends LeaderTask { @Override public Trigger getTrigger() { final String expression = this.environment.getProperty( DatabaseCleanupProperties.EXPRESSION_PROPERTY, String.class, this.cleanupProperties.getExpression() ); return new CronTrigger(expression, JobConstants.UTC); } DatabaseCleanupTask(
@NotNull final DatabaseCleanupProperties cleanupProperties,
@NotNull final Environment environment,
@NotNull final DataServices dataServices,
@NotNull final MeterRegistry registry
); @Override GenieTaskScheduleType getScheduleType(); @Override Trigger getTrigger(); @Override void run(); @Override void cleanup(); }### Answer:
@Test void canGetTrigger() { final String expression = "0 0 1 * * *"; this.environment.setProperty(DatabaseCleanupProperties.EXPRESSION_PROPERTY, expression); Mockito.when(this.cleanupProperties.getExpression()).thenReturn("0 0 0 * * *"); final Trigger trigger = this.task.getTrigger(); if (trigger instanceof CronTrigger) { final CronTrigger cronTrigger = (CronTrigger) trigger; Assertions.assertThat(cronTrigger.getExpression()).isEqualTo(expression); } else { Assertions.fail("Trigger was not of expected type: " + CronTrigger.class.getName()); } } |
### Question:
DefaultDirectoryWriter implements DirectoryWriter { @Override public String toHtml( @NotNull final File directory, @URL final String requestURL, final boolean includeParent ) throws IOException { final Directory dir = this.getDirectory(directory, requestURL, includeParent); return directoryToHTML(directory.getName(), dir); } static String directoryToHTML(final String directoryName, final Directory directory); @Override String toHtml(
@NotNull final File directory,
@URL final String requestURL,
final boolean includeParent
); @Override String toJson(
@NotNull final File directory,
@URL final String requestURL,
final boolean includeParent
); }### Answer:
@Test void canConvertToHtml() throws Exception { this.setupWithParent(); final String html = this.writer.toHtml(this.directory, REQUEST_URL_WITH_PARENT, true); Assertions.assertThat(html).isNotNull(); final Tidy tidy = new Tidy(); final Writer stringWriter = new StringWriter(); tidy.parse(new ByteArrayInputStream(html.getBytes(StandardCharsets.UTF_8)), stringWriter); Assertions.assertThat(tidy.getParseErrors()).isEqualTo(0); Assertions.assertThat(tidy.getParseWarnings()).isEqualTo(0); } |
### Question:
TasksCleanup { @EventListener public void onShutdown(final ContextClosedEvent event) { log.info("Shutting down the scheduler due to {}", event); this.scheduler.shutdown(); } @Autowired TasksCleanup(@Qualifier("genieTaskScheduler") @NotNull final ThreadPoolTaskScheduler scheduler); @EventListener void onShutdown(final ContextClosedEvent event); }### Answer:
@Test void canShutdown() { final ContextClosedEvent event = Mockito.mock(ContextClosedEvent.class); final TasksCleanup cleanup = new TasksCleanup(this.scheduler); cleanup.onShutdown(event); Mockito.verify(this.scheduler, Mockito.times(1)).shutdown(); } |
### Question:
ApplicationModelAssembler implements RepresentationModelAssembler<Application, EntityModel<Application>> { @Override @Nonnull public EntityModel<Application> toModel(final Application application) { final String id = application.getId().orElseThrow(IllegalArgumentException::new); final EntityModel<Application> applicationModel = new EntityModel<>(application); try { applicationModel.add( WebMvcLinkBuilder.linkTo( WebMvcLinkBuilder .methodOn(ApplicationRestController.class) .getApplication(id) ).withSelfRel() ); applicationModel.add( WebMvcLinkBuilder.linkTo( WebMvcLinkBuilder .methodOn(ApplicationRestController.class) .getCommandsForApplication(id, null) ).withRel(COMMANDS_LINK) ); } catch (final GenieException | NotFoundException ge) { throw new RuntimeException(ge); } return applicationModel; } @Override @Nonnull EntityModel<Application> toModel(final Application application); }### Answer:
@Test void canConvertToModel() { final EntityModel<Application> model = this.assembler.toModel(this.application); Assertions.assertThat(model.getLinks()).hasSize(2); Assertions.assertThat(model.getLink("self")).isPresent(); Assertions.assertThat(model.getLink("commands")).isPresent(); } |
### Question:
DefaultDirectoryWriter implements DirectoryWriter { @Override public String toJson( @NotNull final File directory, @URL final String requestURL, final boolean includeParent ) throws Exception { final Directory dir = this.getDirectory(directory, requestURL, includeParent); return GenieObjectMapper.getMapper().writeValueAsString(dir); } static String directoryToHTML(final String directoryName, final Directory directory); @Override String toHtml(
@NotNull final File directory,
@URL final String requestURL,
final boolean includeParent
); @Override String toJson(
@NotNull final File directory,
@URL final String requestURL,
final boolean includeParent
); }### Answer:
@Test void canConvertToJson() throws Exception { this.setupWithParent(); final String json = this.writer.toJson(this.directory, REQUEST_URL_WITH_PARENT, true); Assertions.assertThat(json).isNotNull(); final DefaultDirectoryWriter.Directory dir = GenieObjectMapper.getMapper().readValue(json, DefaultDirectoryWriter.Directory.class); Assertions.assertThat(dir.getParent()).isNotNull(); Assertions.assertThat(dir.getParent().getName()).isEqualTo(PARENT_NAME); Assertions.assertThat(dir.getParent().getUrl()).isEqualTo(PARENT_URL); Assertions.assertThat(dir.getParent().getSize()).isEqualTo(PARENT_SIZE); Assertions.assertThat(dir.getParent().getLastModified()).isEqualTo(PARENT_LAST_MODIFIED); Assertions.assertThat(dir.getDirectories()).isNotNull(); Assertions .assertThat(dir.getDirectories()) .containsExactlyInAnyOrder(this.directoryEntry1, this.directoryEntry2); Assertions.assertThat(dir.getFiles()).isNotNull(); Assertions .assertThat(dir.getFiles()) .containsExactlyInAnyOrder(this.fileEntry1, this.fileEntry2); } |
### Question:
Entity_Feature { public String getAddress() { return address; } Entity_Feature(tracerengine Trac, Activity activity, String device_feature_model_id, int id, int devId, String device_usage_id, String address, String device_type_id, String description, String name, String state_key, String parameters, String value_type); int getId(); void setId(int id); JSONObject getDevice(); String getDescription(); void setDescription(String description); String getDevice_usage_id(); void setDevice_usage_id(String device_usage_id); String getAddress(); void setAddress(String address); int getDevId(); void setDevId(int devId); String getName(); void setName(String name); String getDevice_feature_model_id(); void setDevice_feature_model_id(String device_feature_model_id); String getState_key(); void setState_key(String state_key); String getParameters(); void setParameters(String parameters); String getValue_type(); void setValue_type(String value_type); int getRessources(); void setState(int state); String getDevice_type(); String getDevice_type_id(); void setDevice_type_id(String device_type_id); String getIcon_name(); }### Answer:
@Test public void testGetAddress() throws Exception { String address = client.getAddress(); Assert.assertEquals(null, address); client.setAddress("Address"); address = client.getAddress(); Assert.assertEquals("Address", address); } |
### Question:
Entity_Feature_Association { public String getPlace_type() { return place_type; } Entity_Feature_Association(int place_id, String place_type, int device_feature_id, int id, String device_feature); int getPlace_id(); void setPlace_id(int placeId); String getPlace_type(); void setPlace_type(String placeType); int getDevice_feature_id(); void setDevice_feature_id(int deviceFeatureId); int getId(); void setId(int id); JSONObject getDevice_feature(); void setDevice_feature(JSONObject json_deviceFeature); String getFeat_model_id(); int getFeat_id(); int getFeat_device_id(); }### Answer:
@Test public void testGetPlace_type() throws Exception { Entity_Feature_Association feature_association = new Entity_Feature_Association(0, null, 0, 0, null); } |
### Question:
Entity_Feature_Association { public int getDevice_feature_id() { return device_feature_id; } Entity_Feature_Association(int place_id, String place_type, int device_feature_id, int id, String device_feature); int getPlace_id(); void setPlace_id(int placeId); String getPlace_type(); void setPlace_type(String placeType); int getDevice_feature_id(); void setDevice_feature_id(int deviceFeatureId); int getId(); void setId(int id); JSONObject getDevice_feature(); void setDevice_feature(JSONObject json_deviceFeature); String getFeat_model_id(); int getFeat_id(); int getFeat_device_id(); }### Answer:
@Test public void testGetDevice_feature_id() throws Exception { Entity_Feature_Association feature_association = new Entity_Feature_Association(0, null, 0, 0, null); int Device_feature_id = feature_association.getDevice_feature_id(); Assert.assertEquals(0, Device_feature_id); feature_association.setDevice_feature_id(125); Device_feature_id = feature_association.getDevice_feature_id(); Assert.assertEquals(125, Device_feature_id); } |
### Question:
Entity_Feature_Association { public int getId() { return id; } Entity_Feature_Association(int place_id, String place_type, int device_feature_id, int id, String device_feature); int getPlace_id(); void setPlace_id(int placeId); String getPlace_type(); void setPlace_type(String placeType); int getDevice_feature_id(); void setDevice_feature_id(int deviceFeatureId); int getId(); void setId(int id); JSONObject getDevice_feature(); void setDevice_feature(JSONObject json_deviceFeature); String getFeat_model_id(); int getFeat_id(); int getFeat_device_id(); }### Answer:
@Test public void testGetId() throws Exception { Entity_Feature_Association feature_association = new Entity_Feature_Association(0, null, 0, 0, null); int id = feature_association.getId(); Assert.assertEquals(0, id); feature_association.setId(125); id = feature_association.getId(); Assert.assertEquals(125, id); } |
### Question:
Entity_Feature_Association { public JSONObject getDevice_feature() { return json_device_feature; } Entity_Feature_Association(int place_id, String place_type, int device_feature_id, int id, String device_feature); int getPlace_id(); void setPlace_id(int placeId); String getPlace_type(); void setPlace_type(String placeType); int getDevice_feature_id(); void setDevice_feature_id(int deviceFeatureId); int getId(); void setId(int id); JSONObject getDevice_feature(); void setDevice_feature(JSONObject json_deviceFeature); String getFeat_model_id(); int getFeat_id(); int getFeat_device_id(); }### Answer:
@Test public void testGetDevice_feature() throws Exception { Entity_Feature_Association feature_association = new Entity_Feature_Association(0, null, 0, 0, null); JSONObject device_feature = feature_association.getDevice_feature(); feature_association.setDevice_feature(new JSONObject("")); device_feature = feature_association.getDevice_feature(); } |
### Question:
Entity_Feature_Association { public String getFeat_model_id() { return feat_model_id; } Entity_Feature_Association(int place_id, String place_type, int device_feature_id, int id, String device_feature); int getPlace_id(); void setPlace_id(int placeId); String getPlace_type(); void setPlace_type(String placeType); int getDevice_feature_id(); void setDevice_feature_id(int deviceFeatureId); int getId(); void setId(int id); JSONObject getDevice_feature(); void setDevice_feature(JSONObject json_deviceFeature); String getFeat_model_id(); int getFeat_id(); int getFeat_device_id(); }### Answer:
@Test public void testGetFeat_model_id() throws Exception { Entity_Feature_Association feature_association = new Entity_Feature_Association(0, null, 0, 0, null); String feature_model_id = feature_association.getFeat_model_id(); Assert.assertEquals(null, feature_model_id); JSONObject device_feature_model_id = new JSONObject(); device_feature_model_id.put("device_feature_model_id", "125"); feature_association.setDevice_feature(device_feature_model_id); feature_model_id = feature_association.getFeat_model_id(); } |
### Question:
Entity_Feature_Association { public int getFeat_id() { return feat_id; } Entity_Feature_Association(int place_id, String place_type, int device_feature_id, int id, String device_feature); int getPlace_id(); void setPlace_id(int placeId); String getPlace_type(); void setPlace_type(String placeType); int getDevice_feature_id(); void setDevice_feature_id(int deviceFeatureId); int getId(); void setId(int id); JSONObject getDevice_feature(); void setDevice_feature(JSONObject json_deviceFeature); String getFeat_model_id(); int getFeat_id(); int getFeat_device_id(); }### Answer:
@Test public void testGetFeat_id() throws Exception { Entity_Feature_Association feature_association = new Entity_Feature_Association(0, null, 0, 0, null); int feature_id = feature_association.getFeat_id(); Assert.assertEquals(0, feature_id); JSONObject device_feature_model_id = new JSONObject(); device_feature_model_id.put("id", "125"); feature_association.setDevice_feature(device_feature_model_id); feature_id = feature_association.getFeat_id(); } |
### Question:
Entity_Feature_Association { public int getFeat_device_id() { return feat_device_id; } Entity_Feature_Association(int place_id, String place_type, int device_feature_id, int id, String device_feature); int getPlace_id(); void setPlace_id(int placeId); String getPlace_type(); void setPlace_type(String placeType); int getDevice_feature_id(); void setDevice_feature_id(int deviceFeatureId); int getId(); void setId(int id); JSONObject getDevice_feature(); void setDevice_feature(JSONObject json_deviceFeature); String getFeat_model_id(); int getFeat_id(); int getFeat_device_id(); }### Answer:
@Test public void testGetFeat_device_id() throws Exception { Entity_Feature_Association feature_association = new Entity_Feature_Association(0, null, 0, 0, null); int feature_device_id = feature_association.getFeat_device_id(); Assert.assertEquals(0, feature_device_id); JSONObject device_feature_model_id = new JSONObject(); device_feature_model_id.put("device_id", "125"); feature_device_id = feature_association.getFeat_device_id(); } |
### Question:
Entity_client { public int getClientType() { return client_type; } Entity_client(int devId, String skey, String Name, int session_type); void setClientType(int type); void setClientId(int id); void setcacheId(int Id); void setDevId(int devId); void setskey(String skey); void setValue(String Value); void setName(String Name); void setTimestamp(String Timestamp); void setType(Boolean type); int getClientType(); int getClientId(); int getcacheId(); int getDevId(); String getskey(); String getValue(); String getName(); String getTimestamp(); Boolean is_Miniwidget(); void client_value_update(String val, String valtimestamp); }### Answer:
@Test public void testGetClientType() throws Exception { int type = client.getClientType(); Assert.assertEquals(0, type); client.setClientType(125); type = client.getClientType(); Assert.assertEquals(125, type); } |
### Question:
Entity_client { public int getClientId() { return client_id; } Entity_client(int devId, String skey, String Name, int session_type); void setClientType(int type); void setClientId(int id); void setcacheId(int Id); void setDevId(int devId); void setskey(String skey); void setValue(String Value); void setName(String Name); void setTimestamp(String Timestamp); void setType(Boolean type); int getClientType(); int getClientId(); int getcacheId(); int getDevId(); String getskey(); String getValue(); String getName(); String getTimestamp(); Boolean is_Miniwidget(); void client_value_update(String val, String valtimestamp); }### Answer:
@Test public void testGetClientId() throws Exception { int id = client.getClientId(); Assert.assertEquals(-1, id); client.setClientId(125); id = client.getClientId(); Assert.assertEquals(125, id); } |
### Question:
Entity_client { public int getcacheId() { return cache_id; } Entity_client(int devId, String skey, String Name, int session_type); void setClientType(int type); void setClientId(int id); void setcacheId(int Id); void setDevId(int devId); void setskey(String skey); void setValue(String Value); void setName(String Name); void setTimestamp(String Timestamp); void setType(Boolean type); int getClientType(); int getClientId(); int getcacheId(); int getDevId(); String getskey(); String getValue(); String getName(); String getTimestamp(); Boolean is_Miniwidget(); void client_value_update(String val, String valtimestamp); }### Answer:
@Test public void testGetcacheId() throws Exception { int cacheid = client.getcacheId(); Assert.assertEquals(0, cacheid); client.setcacheId(125); cacheid = client.getcacheId(); Assert.assertEquals(125, cacheid); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.