method2testcases
stringlengths
118
3.08k
### Question: SyncopeLoginModule extends AbstractKarafLoginModule { protected List<String> extractingRolesSyncope1(String response) throws Exception { List<String> roles = new ArrayList<>(); if (response != null && !response.isEmpty()) { int index = response.indexOf("<memberships>"); if (index != -1) { response = response.substring(index + "<memberships>".length()); index = response.indexOf("</memberships>"); response = response.substring(0, index); index = response.indexOf("<roleName>"); while (index != -1) { response = response.substring(index + "<roleName>".length()); int end = response.indexOf("</roleName>"); if (end == -1) { index = -1; } String role = response.substring(0, end); roles.add(role); response = response.substring(end + "</roleName>".length()); index = response.indexOf("<roleName>"); } } } return roles; } void initialize(Subject subject, CallbackHandler callbackHandler, Map<String, ?> sharedState, Map<String, ?> options); boolean login(); final static String ADDRESS; final static String VERSION; final static String USE_ROLES_FOR_SYNCOPE2; final static String ADMIN_USER; final static String ADMIN_PASSWORD; }### Answer: @Test public void testRolesExtractionSyncope1() throws Exception { String syncopeResponse = read("syncope1Response.xml"); SyncopeLoginModule syncopeLoginModule = new SyncopeLoginModule(); List<String> roles = syncopeLoginModule.extractingRolesSyncope1(syncopeResponse); assertThat(roles, contains("admin", "another")); }
### Question: SyncopeLoginModule extends AbstractKarafLoginModule { @SuppressWarnings("unchecked") protected List<String> extractingRolesSyncope2(String response) throws Exception { List<String> roles = new ArrayList<>(); if (response != null && !response.isEmpty()) { JSONParser parser = new JSONParser(response); if (useRolesForSyncope2) { return (List<String>) parser.getParsed().get("roles"); } else { List<Map<String, String>> memberships = (List<Map<String, String>>) parser.getParsed().get("memberships"); if (memberships != null) { for (Map<String, String> membership : memberships) { if (membership.containsKey("groupName")) { roles.add(membership.get("groupName")); } } } } } return roles; } void initialize(Subject subject, CallbackHandler callbackHandler, Map<String, ?> sharedState, Map<String, ?> options); boolean login(); final static String ADDRESS; final static String VERSION; final static String USE_ROLES_FOR_SYNCOPE2; final static String ADMIN_USER; final static String ADMIN_PASSWORD; }### Answer: @Test public void testGroupsExtractionSyncope2() throws Exception { String syncopeResponse = read("syncope2Response.json"); SyncopeLoginModule syncopeLoginModule = new SyncopeLoginModule(); List<String> roles = syncopeLoginModule.extractingRolesSyncope2(syncopeResponse); assertThat(roles, contains("manager")); }
### Question: AbstractAuditLoginModule implements LoginModule { protected String getPrincipalInfo() { String principalInfo; List<String> principalInfos = subject.getPrincipals(ClientPrincipal.class).stream().map(ClientPrincipal::getName).collect(toList()); if (principalInfos.size() > 0) { principalInfo = String.join(", ", principalInfos); } else { principalInfo = "no client principals found"; } return principalInfo; } void initialize(Subject subject, CallbackHandler callbackHandler, Map<String, ?> sharedState, Map<String, ?> options); boolean login(); boolean commit(); boolean abort(); boolean logout(); }### Answer: @Test public void getPrincipalInfo() { LogAuditLoginModule module = new LogAuditLoginModule(); Map<String, String> options = new HashMap<>(); options.put("logger", "test"); Subject subject = new Subject(); subject.getPrincipals().add(new ClientPrincipal("ssh", "/127.0.0.1")); subject.getPrincipals().add(new ClientPrincipal("ssh", "/127.0.0.2")); subject.getPrincipals().add((UserPrincipal) () -> "noexist"); module.initialize(subject, new NamePasswordCallbackHandler("myuser", "mypassword"), null, options); Assert.assertEquals("ssh(/127.0.0.1), ssh(/127.0.0.2)", module.getPrincipalInfo()); }
### Question: ObjectClassMatcher { static String getShortName(String name) { int idx = name.lastIndexOf("."); if (idx + 1 > name.length()) { idx = 0; } return name.substring(idx + 1); } private ObjectClassMatcher(); }### Answer: @Test public void testGetShortName() { Assert.assertEquals("TestClass", ObjectClassMatcher.getShortName("org.apache.TestClass")); Assert.assertEquals("", ObjectClassMatcher.getShortName("test.")); Assert.assertEquals("TestClass", ObjectClassMatcher.getShortName("TestClass")); }
### Question: ObjectClassMatcher { static boolean matchesName(String name, String pattern) { return name.equals(pattern) || getShortName(name).equals(pattern); } private ObjectClassMatcher(); }### Answer: @Test public void testMatchesName() { Assert.assertTrue(ObjectClassMatcher.matchesName("org.apache.TestClass", "TestClass")); Assert.assertTrue(ObjectClassMatcher.matchesName("TestClass", "TestClass")); }
### Question: ObjectClassMatcher { static boolean matchesAtLeastOneName(String[] names, String pattern) { for (String objectClass : names) { if (matchesName(objectClass, pattern)) { return true; } } return false; } private ObjectClassMatcher(); }### Answer: @Test public void testMatchesAtLeastOneName() { Assert.assertTrue(ObjectClassMatcher.matchesAtLeastOneName(new String[]{"other", "org.apache.TestClass"}, "TestClass")); Assert.assertFalse(ObjectClassMatcher.matchesAtLeastOneName(new String[]{"TestClass2"}, "TestClass")); }
### Question: ACLConfigurationParser { public static List<String> parseRoles(String roleStr) { int hashIdx = roleStr.indexOf('#'); if (hashIdx >= 0) { roleStr = roleStr.substring(0, hashIdx); } List<String> roles = new ArrayList<>(); for (String role : roleStr.split("[,]")) { String trimmed = role.trim(); if (trimmed.length() > 0) { roles.add(trimmed); } } return roles; } static Specificity getRolesForInvocation(String methodName, Object[] params, String[] signature, Dictionary<String, Object> config, List<String> addToRoles); static Specificity getRolesForInvocationForAlias(String methodName, Object[] params, String[] signature, Dictionary<String, Object> config, List<String> addToRoles); static void getCompulsoryRoles(List<String> roles); static List<String> parseRoles(String roleStr); }### Answer: @Test public void testParseRoles() { assertEquals(Collections.singletonList("some_role"), ACLConfigurationParser.parseRoles(" some_role ")); assertEquals(Arrays.asList("a","b","C"), ACLConfigurationParser.parseRoles("a,b,C")); assertEquals(Collections.emptyList(), ACLConfigurationParser.parseRoles("# test comment")); }
### Question: Activator implements BundleActivator { @Override public void stop(BundleContext bundleContext) throws Exception { if (guardProxyCatalog != null) { guardProxyCatalog.close(); } } @Override void start(BundleContext bundleContext); @Override void stop(BundleContext bundleContext); }### Answer: @Test public void testStopActivator() throws Exception { Activator a = new Activator(); a.guardProxyCatalog = EasyMock.createMock(GuardProxyCatalog.class); a.guardProxyCatalog.close(); EasyMock.expectLastCall().once(); EasyMock.replay(a.guardProxyCatalog); a.stop(EasyMock.createMock(BundleContext.class)); EasyMock.verify(a.guardProxyCatalog); }
### Question: GuardProxyCatalog implements ServiceListener { boolean isProxy(ServiceReference<?> sr) { return sr.getProperty(PROXY_SERVICE_KEY) != null; } GuardProxyCatalog(BundleContext bc); @Override void serviceChanged(ServiceEvent event); static final String KARAF_SECURED_SERVICES_SYSPROP; static final String SERVICE_GUARD_ROLES_PROPERTY; static final String KARAF_SECURED_COMMAND_COMPULSORY_ROLES_PROPERTY; }### Answer: @Test public void testIsProxy() throws Exception { BundleContext bc = mockBundleContext(); GuardProxyCatalog gpc = new GuardProxyCatalog(bc); Dictionary<String, Object> props = new Hashtable<>(); props.put(GuardProxyCatalog.PROXY_SERVICE_KEY, Boolean.TRUE); assertTrue(gpc.isProxy(mockServiceReference(props))); assertFalse(gpc.isProxy(mockServiceReference(new Hashtable<>()))); }
### Question: GuardProxyCatalog implements ServiceListener { boolean handleProxificationForHook(ServiceReference<?> sr) { if (isProxy(sr)) { return false; } proxyIfNotAlreadyProxied(sr); return true; } GuardProxyCatalog(BundleContext bc); @Override void serviceChanged(ServiceEvent event); static final String KARAF_SECURED_SERVICES_SYSPROP; static final String SERVICE_GUARD_ROLES_PROPERTY; static final String KARAF_SECURED_COMMAND_COMPULSORY_ROLES_PROPERTY; }### Answer: @SuppressWarnings("unchecked") @Test public void testHandleProxificationForHook() throws Exception { Dictionary<String, Object> config = new Hashtable<>(); config.put(Constants.SERVICE_PID, GuardProxyCatalog.SERVICE_ACL_PREFIX + "foo"); config.put(GuardProxyCatalog.SERVICE_GUARD_KEY, "(a>=5)"); BundleContext bc = mockConfigAdminBundleContext(config); GuardProxyCatalog gpc = new GuardProxyCatalog(bc); Dictionary<String, Object> props = new Hashtable<>(); props.put(Constants.SERVICE_ID, 13L); props.put("a", "6"); props.put(GuardProxyCatalog.PROXY_SERVICE_KEY, Boolean.TRUE); ServiceReference<?> sref2 = mockServiceReference(props); assertFalse("Should not hide an existing proxy for this client", gpc.handleProxificationForHook(sref2)); assertEquals("No proxy should have been created", 0, gpc.proxyMap.size()); Dictionary<String, Object> props4 = new Hashtable<>(); props4.put(Constants.SERVICE_ID, 15L); props4.put("a", "7"); ServiceReference<?> sref4 = mockServiceReference(props4); assertTrue("Should hide a service that needs to be proxied", gpc.handleProxificationForHook(sref4)); assertEquals("Should trigger proxy creation", 1, gpc.proxyMap.size()); }
### Question: KarArtifactInstaller implements ArtifactInstaller { public boolean canHandle(File file) { if (file.getName().endsWith(KAR_SUFFIX)) { LOGGER.info("Found a .kar file to deploy."); return true; } else if (file.isFile() && file.getName().endsWith(ZIP_SUFFIX)) { LOGGER.debug("Found a .zip file to deploy; checking contents to see if it's a Karaf archive."); ZipFile zipFile = null; try { zipFile = new ZipFile(file); if (zipFile.getEntry("META-INF/KARAF.MF") != null) { LOGGER.info("Found a Karaf archive with .zip prefix; will deploy."); return true; } } catch (Exception e) { LOGGER.warn("Problem extracting zip file '{}'; ignoring.", file.getName(), e); } finally { try { if (zipFile != null) { zipFile.close(); } } catch (IOException e) { LOGGER.warn("Problem closing zip file '{}'; ignoring.", file.getName(), e); } } } return false; } void install(File file); void uninstall(File file); void update(File file); boolean canHandle(File file); KarService getKarService(); void setKarService(KarService karService); static final String FEATURE_CLASSIFIER; }### Answer: @Test public void shouldHandleKarFile() throws Exception { assertTrue(karArtifactInstaller.canHandle(new File(goodKarFile))); } @Test public void shouldHandleZipFileWithKarafManifest() throws Exception { assertTrue(karArtifactInstaller.canHandle(new File(zipFileWithKarafManifest))); } @Test public void shouldIgnoreZipFileWithoutKarafManifest() throws Exception { assertFalse(karArtifactInstaller.canHandle(new File(zipFileWithoutKarafManifest))); } @Test public void shouldIgnoreBadZipFile() throws Exception { assertFalse(karArtifactInstaller.canHandle(new File(badZipFile))); }
### Question: SystemServiceImpl implements SystemService { @Override public void setName(String name) { try { String karafEtc = bundleContext.getProperty("karaf.etc"); File etcDir = new File(karafEtc); File syspropsFile = new File(etcDir, "system.properties"); FileInputStream fis = new FileInputStream(syspropsFile); Properties props = new Properties(); props.load(fis); fis.close(); props.setProperty("karaf.name", name); FileOutputStream fos = new FileOutputStream(syspropsFile); props.store(fos, ""); fos.close(); } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } } void setBundleContext(BundleContext bundleContext); BundleContext getBundleContext(); void halt(); void halt(String time); void reboot(); void reboot(String time, Swipe cleanup); void setStartLevel(int startLevel); int getStartLevel(); @Override String getVersion(); @Override String getName(); @Override void setName(String name); FrameworkType getFramework(); void setFramework(FrameworkType framework); void setFrameworkDebug(boolean debug); @Override String setSystemProperty(String key, String value, boolean persist); }### Answer: @Test public void testSetName() throws URISyntaxException, IOException { SystemServiceImpl system = new SystemServiceImpl(); BundleContext bundleContext = EasyMock.createMock(BundleContext.class); URL propUrl = this.getClass().getClassLoader().getResource("etc/system.properties"); File propfile = new File(propUrl.toURI()); EasyMock.expect(bundleContext.getProperty("karaf.etc")).andReturn(propfile.getParentFile().getParent() + "/etc"); EasyMock.replay(bundleContext); system.setBundleContext(bundleContext); system.setName(NEW_NAME); EasyMock.verify(bundleContext); Properties props = new Properties(propfile); String nameAfter = props.getProperty("karaf.name"); Assert.assertEquals(NEW_NAME, nameAfter); }
### Question: InstanceServiceImpl implements InstanceService { void addFeaturesFromSettings(File featuresCfg, final InstanceSettings settings) throws IOException { FileLockUtils.execute(featuresCfg, properties -> { appendToPropList(properties, "featuresBoot", settings.getFeatures()); appendToPropList(properties, "featuresRepositories", settings.getFeatureURLs()); }, true); } InstanceServiceImpl(); File getStorageLocation(); void setStorageLocation(File storage); long getStopTimeout(); void setStopTimeout(long stopTimeout); synchronized Instance createInstance(final String name, final InstanceSettings settings, final boolean printOutput); Instance[] getInstances(); Instance getInstance(final String name); void startInstance(final String name, final String javaOpts); void restartInstance(final String name, final String javaOpts); void stopInstance(final String name); void destroyInstance(final String name); void renameInstance(final String oldName, final String newName, final boolean printOutput); synchronized Instance cloneInstance(final String name, final String cloneName, final InstanceSettings settings, final boolean printOutput); void changeInstanceSshHost(String name, String host); static final String STORAGE_FILE; static final String BACKUP_EXTENSION; static final String DEFAULT_JAVA_OPTS; }### Answer: @Test public void testHandleFeatures() throws Exception { InstanceServiceImpl as = new InstanceServiceImpl(); File f = tempFolder.newFile(getName() + ".test"); Properties p = new Properties(); p.put("featuresBoot", "abc,def "); p.put("featuresRepositories", "somescheme: try (OutputStream os = new FileOutputStream(f)) { p.store(os, "Test comment"); } InstanceSettings s = new InstanceSettings(8122, 1122, 44444, null, null, null, Collections.singletonList("test")); as.addFeaturesFromSettings(f, s); Properties p2 = new Properties(); try (InputStream is = new FileInputStream(f)) { p2.load(is); } assertEquals(2, p2.size()); assertEquals("abc,def,test", p2.get("featuresBoot")); assertEquals("somescheme: }
### Question: DockerClient { public List<ImageSearch> search(String term) throws Exception { URL dockerUrl = new URL(this.url + "/images/search?term=" + term); HttpURLConnection connection = (HttpURLConnection) dockerUrl.openConnection(); connection.setRequestMethod("GET"); List<ImageSearch> images = mapper.readValue(connection.getInputStream(), new TypeReference<List<ImageSearch>>(){}); return images; } DockerClient(String url); Info info(); Version version(); List<Container> ps(boolean showAll); Container inspect(String id); Top top(String id); void create(ContainerConfig config, String name); void rm(String id, boolean removeVolumes, boolean force); void start(String id); void stop(String id, int timeToWait); void restart(String id, int timeToWait); void kill(String id, String signal); void rename(String id, String name); void pause(String id); void unpause(String id); String logs(String id, boolean stdout, boolean stderr, boolean timestamps, boolean details); void commit(String container, ContainerConfig config, String message, String repo, String tag); List<Image> images(boolean showAll); void pull(String name, String tag, boolean verbose); void push(String name, String tag, boolean verbose); void tag(String name, String repo, String tag); void rmi(String name, boolean force, boolean noprune); List<ImageSearch> search(String term); Image getImage(String name); List<ImageHistory> history(String name); static final String DEFAULT_URL; }### Answer: @Test @Ignore("Need a running Docker daemon") public void testSearchImages() throws Exception { List<ImageSearch> images = dockerClient.search("karaf"); for (ImageSearch image : images) { System.out.println("----"); System.out.println("Image Name: " + image.getName()); System.out.println("Image Star Count: " + image.getStarCount()); System.out.println("Image Automated: " + image.isAutomated()); System.out.println("Image Official: " + image.isOfficial()); System.out.println("Image Description: " + image.getDescription()); } }
### Question: DockerClient { public void pull(String name, String tag, boolean verbose) throws Exception { URL dockerUrl = new URL(this.url + "/images/create?fromImage=" + name + "&tag=" + tag); HttpURLConnection connection = (HttpURLConnection) dockerUrl.openConnection(); connection.setRequestMethod("POST"); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; while ((line = reader.readLine()) != null) { LOGGER.debug(line); if (verbose) { System.out.println(line); } } if (connection.getResponseCode() != 200) { throw new IllegalStateException("Can't pull image " + name + ": " + connection.getResponseMessage()); } } DockerClient(String url); Info info(); Version version(); List<Container> ps(boolean showAll); Container inspect(String id); Top top(String id); void create(ContainerConfig config, String name); void rm(String id, boolean removeVolumes, boolean force); void start(String id); void stop(String id, int timeToWait); void restart(String id, int timeToWait); void kill(String id, String signal); void rename(String id, String name); void pause(String id); void unpause(String id); String logs(String id, boolean stdout, boolean stderr, boolean timestamps, boolean details); void commit(String container, ContainerConfig config, String message, String repo, String tag); List<Image> images(boolean showAll); void pull(String name, String tag, boolean verbose); void push(String name, String tag, boolean verbose); void tag(String name, String repo, String tag); void rmi(String name, boolean force, boolean noprune); List<ImageSearch> search(String term); Image getImage(String name); List<ImageHistory> history(String name); static final String DEFAULT_URL; }### Answer: @Test @Ignore("Need a running Docker daemon") public void testPullImage() throws Exception { dockerClient.pull("mkroli/karaf", "latest", true); }
### Question: DockerClient { public void rmi(String name, boolean force, boolean noprune) throws Exception { URL dockerUrl = new URL(this.url + "/images/" + name + "?force=" + force + "&noprune=" + noprune); HttpURLConnection connection = (HttpURLConnection) dockerUrl.openConnection(); connection.setRequestMethod("DELETE"); if (connection.getResponseCode() != 200) { throw new IllegalStateException("Can't remove image " + name + ": " + connection.getResponseMessage()); } } DockerClient(String url); Info info(); Version version(); List<Container> ps(boolean showAll); Container inspect(String id); Top top(String id); void create(ContainerConfig config, String name); void rm(String id, boolean removeVolumes, boolean force); void start(String id); void stop(String id, int timeToWait); void restart(String id, int timeToWait); void kill(String id, String signal); void rename(String id, String name); void pause(String id); void unpause(String id); String logs(String id, boolean stdout, boolean stderr, boolean timestamps, boolean details); void commit(String container, ContainerConfig config, String message, String repo, String tag); List<Image> images(boolean showAll); void pull(String name, String tag, boolean verbose); void push(String name, String tag, boolean verbose); void tag(String name, String repo, String tag); void rmi(String name, boolean force, boolean noprune); List<ImageSearch> search(String term); Image getImage(String name); List<ImageHistory> history(String name); static final String DEFAULT_URL; }### Answer: @Test @Ignore("Need a running Docker daemon") public void testRemoveImage() throws Exception { dockerClient.rmi("sha256:f3ea90d50ffd7851cb984764409326b82593c612fe6e6dc7933d9568f735084b", true, false); }
### Question: DockerClient { public void start(String id) throws Exception { URL dockerUrl = new URL(this.url + "/containers/" + id + "/start"); HttpURLConnection connection = (HttpURLConnection) dockerUrl.openConnection(); connection.setRequestMethod("POST"); if (connection.getResponseCode() != 204) { throw new IllegalStateException("Can't start Docker container " + id + ": " + connection.getResponseMessage()); } } DockerClient(String url); Info info(); Version version(); List<Container> ps(boolean showAll); Container inspect(String id); Top top(String id); void create(ContainerConfig config, String name); void rm(String id, boolean removeVolumes, boolean force); void start(String id); void stop(String id, int timeToWait); void restart(String id, int timeToWait); void kill(String id, String signal); void rename(String id, String name); void pause(String id); void unpause(String id); String logs(String id, boolean stdout, boolean stderr, boolean timestamps, boolean details); void commit(String container, ContainerConfig config, String message, String repo, String tag); List<Image> images(boolean showAll); void pull(String name, String tag, boolean verbose); void push(String name, String tag, boolean verbose); void tag(String name, String repo, String tag); void rmi(String name, boolean force, boolean noprune); List<ImageSearch> search(String term); Image getImage(String name); List<ImageHistory> history(String name); static final String DEFAULT_URL; }### Answer: @Test @Ignore("Need a running Docker daemon") public void testStartContainer() throws Exception { dockerClient.start("test"); }
### Question: DockerClient { public void stop(String id, int timeToWait) throws Exception { URL dockerUrl = new URL(this.url + "/containers/" + id + "/stop?t=" + timeToWait); HttpURLConnection connection = (HttpURLConnection) dockerUrl.openConnection(); connection.setRequestMethod("POST"); if (connection.getResponseCode() != 204) { throw new IllegalStateException("Can't stop Docker container " + id + ": " + connection.getResponseMessage()); } } DockerClient(String url); Info info(); Version version(); List<Container> ps(boolean showAll); Container inspect(String id); Top top(String id); void create(ContainerConfig config, String name); void rm(String id, boolean removeVolumes, boolean force); void start(String id); void stop(String id, int timeToWait); void restart(String id, int timeToWait); void kill(String id, String signal); void rename(String id, String name); void pause(String id); void unpause(String id); String logs(String id, boolean stdout, boolean stderr, boolean timestamps, boolean details); void commit(String container, ContainerConfig config, String message, String repo, String tag); List<Image> images(boolean showAll); void pull(String name, String tag, boolean verbose); void push(String name, String tag, boolean verbose); void tag(String name, String repo, String tag); void rmi(String name, boolean force, boolean noprune); List<ImageSearch> search(String term); Image getImage(String name); List<ImageHistory> history(String name); static final String DEFAULT_URL; }### Answer: @Test @Ignore("Need a running Docker daemon") public void testStopContainer() throws Exception { dockerClient.stop("test", 30); }
### Question: DockerClient { public void restart(String id, int timeToWait) throws Exception { URL dockerUrl = new URL(this.url + "/containers/" + id + "/restart?t=" + timeToWait); HttpURLConnection connection = (HttpURLConnection) dockerUrl.openConnection(); connection.setRequestMethod("POST"); if (connection.getResponseCode() != 204) { throw new IllegalStateException("Can't restart Docker container " + id + ": " + connection.getResponseMessage()); } } DockerClient(String url); Info info(); Version version(); List<Container> ps(boolean showAll); Container inspect(String id); Top top(String id); void create(ContainerConfig config, String name); void rm(String id, boolean removeVolumes, boolean force); void start(String id); void stop(String id, int timeToWait); void restart(String id, int timeToWait); void kill(String id, String signal); void rename(String id, String name); void pause(String id); void unpause(String id); String logs(String id, boolean stdout, boolean stderr, boolean timestamps, boolean details); void commit(String container, ContainerConfig config, String message, String repo, String tag); List<Image> images(boolean showAll); void pull(String name, String tag, boolean verbose); void push(String name, String tag, boolean verbose); void tag(String name, String repo, String tag); void rmi(String name, boolean force, boolean noprune); List<ImageSearch> search(String term); Image getImage(String name); List<ImageHistory> history(String name); static final String DEFAULT_URL; }### Answer: @Test @Ignore("Need a running Docker daemon") public void testRestartContainer() throws Exception { dockerClient.restart("test", 30); }
### Question: DockerClient { public void kill(String id, String signal) throws Exception { URL dockerUrl = new URL(this.url + "/containers/" + id + "/kill?signal=" + signal); HttpURLConnection connection = (HttpURLConnection) dockerUrl.openConnection(); connection.setRequestMethod("POST"); if (connection.getResponseCode() != 204) { throw new IllegalStateException("Can't kill Docker container " + id + ": " + connection.getResponseMessage()); } } DockerClient(String url); Info info(); Version version(); List<Container> ps(boolean showAll); Container inspect(String id); Top top(String id); void create(ContainerConfig config, String name); void rm(String id, boolean removeVolumes, boolean force); void start(String id); void stop(String id, int timeToWait); void restart(String id, int timeToWait); void kill(String id, String signal); void rename(String id, String name); void pause(String id); void unpause(String id); String logs(String id, boolean stdout, boolean stderr, boolean timestamps, boolean details); void commit(String container, ContainerConfig config, String message, String repo, String tag); List<Image> images(boolean showAll); void pull(String name, String tag, boolean verbose); void push(String name, String tag, boolean verbose); void tag(String name, String repo, String tag); void rmi(String name, boolean force, boolean noprune); List<ImageSearch> search(String term); Image getImage(String name); List<ImageHistory> history(String name); static final String DEFAULT_URL; }### Answer: @Test @Ignore("Need a running Docker daemon") public void testKillContainer() throws Exception { dockerClient.kill("test", "SIGKILL"); }
### Question: DockerClient { public void rm(String id, boolean removeVolumes, boolean force) throws Exception { URL dockerUrl = new URL(this.url + "/containers/" + id + "?v=" + removeVolumes + "&force=" + force); HttpURLConnection connection = (HttpURLConnection) dockerUrl.openConnection(); connection.setRequestMethod("DELETE"); if (connection.getResponseCode() != 204) { throw new IllegalStateException("Can't remove Docker container " + id + ": " + connection.getResponseMessage()); } } DockerClient(String url); Info info(); Version version(); List<Container> ps(boolean showAll); Container inspect(String id); Top top(String id); void create(ContainerConfig config, String name); void rm(String id, boolean removeVolumes, boolean force); void start(String id); void stop(String id, int timeToWait); void restart(String id, int timeToWait); void kill(String id, String signal); void rename(String id, String name); void pause(String id); void unpause(String id); String logs(String id, boolean stdout, boolean stderr, boolean timestamps, boolean details); void commit(String container, ContainerConfig config, String message, String repo, String tag); List<Image> images(boolean showAll); void pull(String name, String tag, boolean verbose); void push(String name, String tag, boolean verbose); void tag(String name, String repo, String tag); void rmi(String name, boolean force, boolean noprune); List<ImageSearch> search(String term); Image getImage(String name); List<ImageHistory> history(String name); static final String DEFAULT_URL; }### Answer: @Test @Ignore("Need a running Docker daemon") public void testRemoveContainer() throws Exception { dockerClient.rm("test", true, true); }
### Question: DockerClient { public void rename(String id, String name) throws Exception { URL dockerUrl = new URL(this.url + "/containers/" + id + "/rename?name=" + name); HttpURLConnection connection = (HttpURLConnection) dockerUrl.openConnection(); connection.setRequestMethod("POST"); if (connection.getResponseCode() != 204) { throw new IllegalStateException("Can't rename Docker container " + id + ": " + connection.getResponseMessage()); } } DockerClient(String url); Info info(); Version version(); List<Container> ps(boolean showAll); Container inspect(String id); Top top(String id); void create(ContainerConfig config, String name); void rm(String id, boolean removeVolumes, boolean force); void start(String id); void stop(String id, int timeToWait); void restart(String id, int timeToWait); void kill(String id, String signal); void rename(String id, String name); void pause(String id); void unpause(String id); String logs(String id, boolean stdout, boolean stderr, boolean timestamps, boolean details); void commit(String container, ContainerConfig config, String message, String repo, String tag); List<Image> images(boolean showAll); void pull(String name, String tag, boolean verbose); void push(String name, String tag, boolean verbose); void tag(String name, String repo, String tag); void rmi(String name, boolean force, boolean noprune); List<ImageSearch> search(String term); Image getImage(String name); List<ImageHistory> history(String name); static final String DEFAULT_URL; }### Answer: @Test @Ignore("Need a running Docker daemon") public void testRenameContainer() throws Exception { dockerClient.rename("test", "karaf-test"); }
### Question: DockerClient { public void pause(String id) throws Exception { URL dockerUrl = new URL(this.url + "/containers/" + id + "/pause"); HttpURLConnection connection = (HttpURLConnection) dockerUrl.openConnection(); connection.setRequestMethod("POST"); if (connection.getResponseCode() != 204) { throw new IllegalStateException("Can't pause Docker container " + id + ": " + connection.getResponseMessage()); } } DockerClient(String url); Info info(); Version version(); List<Container> ps(boolean showAll); Container inspect(String id); Top top(String id); void create(ContainerConfig config, String name); void rm(String id, boolean removeVolumes, boolean force); void start(String id); void stop(String id, int timeToWait); void restart(String id, int timeToWait); void kill(String id, String signal); void rename(String id, String name); void pause(String id); void unpause(String id); String logs(String id, boolean stdout, boolean stderr, boolean timestamps, boolean details); void commit(String container, ContainerConfig config, String message, String repo, String tag); List<Image> images(boolean showAll); void pull(String name, String tag, boolean verbose); void push(String name, String tag, boolean verbose); void tag(String name, String repo, String tag); void rmi(String name, boolean force, boolean noprune); List<ImageSearch> search(String term); Image getImage(String name); List<ImageHistory> history(String name); static final String DEFAULT_URL; }### Answer: @Test @Ignore("Need a running Docker daemon") public void testPauseContainer() throws Exception { dockerClient.pause("test"); }
### Question: DockerClient { public void unpause(String id) throws Exception { URL dockerUrl = new URL(this.url + "/containers/" + id + "/unpause"); HttpURLConnection connection = (HttpURLConnection) dockerUrl.openConnection(); connection.setRequestMethod("POST"); if (connection.getResponseCode() != 204) { throw new IllegalStateException("Can't unpause Docker container " + id + ": " + connection.getResponseMessage()); } } DockerClient(String url); Info info(); Version version(); List<Container> ps(boolean showAll); Container inspect(String id); Top top(String id); void create(ContainerConfig config, String name); void rm(String id, boolean removeVolumes, boolean force); void start(String id); void stop(String id, int timeToWait); void restart(String id, int timeToWait); void kill(String id, String signal); void rename(String id, String name); void pause(String id); void unpause(String id); String logs(String id, boolean stdout, boolean stderr, boolean timestamps, boolean details); void commit(String container, ContainerConfig config, String message, String repo, String tag); List<Image> images(boolean showAll); void pull(String name, String tag, boolean verbose); void push(String name, String tag, boolean verbose); void tag(String name, String repo, String tag); void rmi(String name, boolean force, boolean noprune); List<ImageSearch> search(String term); Image getImage(String name); List<ImageHistory> history(String name); static final String DEFAULT_URL; }### Answer: @Test @Ignore("Need a running Docker daemon") public void testUnpauseContainer() throws Exception { dockerClient.unpause("test"); }
### Question: DockerClient { public String logs(String id, boolean stdout, boolean stderr, boolean timestamps, boolean details) throws Exception { URL dockerUrl = new URL(this.url + "/containers/" + id + "/logs?stdout=" + stdout + "&stderr=" + stderr + "&timestamps=" + timestamps + "&details=" + details); HttpURLConnection connection = (HttpURLConnection) dockerUrl.openConnection(); connection.setRequestMethod("GET"); StringBuilder buffer = new StringBuilder(); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; while ((line = reader.readLine()) != null) { buffer.append(line).append("\n"); } return buffer.toString(); } DockerClient(String url); Info info(); Version version(); List<Container> ps(boolean showAll); Container inspect(String id); Top top(String id); void create(ContainerConfig config, String name); void rm(String id, boolean removeVolumes, boolean force); void start(String id); void stop(String id, int timeToWait); void restart(String id, int timeToWait); void kill(String id, String signal); void rename(String id, String name); void pause(String id); void unpause(String id); String logs(String id, boolean stdout, boolean stderr, boolean timestamps, boolean details); void commit(String container, ContainerConfig config, String message, String repo, String tag); List<Image> images(boolean showAll); void pull(String name, String tag, boolean verbose); void push(String name, String tag, boolean verbose); void tag(String name, String repo, String tag); void rmi(String name, boolean force, boolean noprune); List<ImageSearch> search(String term); Image getImage(String name); List<ImageHistory> history(String name); static final String DEFAULT_URL; }### Answer: @Test @Ignore("Need a running Docker daemon") public void testContainerLog() throws Exception { System.out.println(dockerClient.logs("test", true, true, true, true)); }
### Question: DockerClient { public Top top(String id) throws Exception { URL dockerUrl = new URL(this.url + "/containers/" + id + "/top?ps_args=aux"); HttpURLConnection connection = (HttpURLConnection) dockerUrl.openConnection(); connection.setRequestMethod("GET"); Top top = mapper.readValue(connection.getInputStream(), Top.class); return top; } DockerClient(String url); Info info(); Version version(); List<Container> ps(boolean showAll); Container inspect(String id); Top top(String id); void create(ContainerConfig config, String name); void rm(String id, boolean removeVolumes, boolean force); void start(String id); void stop(String id, int timeToWait); void restart(String id, int timeToWait); void kill(String id, String signal); void rename(String id, String name); void pause(String id); void unpause(String id); String logs(String id, boolean stdout, boolean stderr, boolean timestamps, boolean details); void commit(String container, ContainerConfig config, String message, String repo, String tag); List<Image> images(boolean showAll); void pull(String name, String tag, boolean verbose); void push(String name, String tag, boolean verbose); void tag(String name, String repo, String tag); void rmi(String name, boolean force, boolean noprune); List<ImageSearch> search(String term); Image getImage(String name); List<ImageHistory> history(String name); static final String DEFAULT_URL; }### Answer: @Test @Ignore("Need a running Docker daemon") public void testContainerTop() throws Exception { Top top = dockerClient.top("test"); for (String title : top.getTitles()) { System.out.print(title); System.out.print("\t"); } System.out.println(); for (List<String> process : top.getProcesses()) { for (String p : process) { System.out.print(p); System.out.print("\t"); } System.out.println(); } }
### Question: AnsiSplitter { public static AnsiBufferedReader window(InputStream is, int begin, int end, int tabs) throws IOException { AnsiBufferedReader reader = new AnsiBufferedReader(is, begin, end, Integer.MAX_VALUE); reader.setTabs(tabs); return reader; } static List<String> splitLines(String text, int maxLength, int tabs); static String substring(String text, int begin, int end, int tabs); static int length(String text, int tabs); static String cut(String text, int maxLength, int tabs); static AnsiBufferedReader window(InputStream is, int begin, int end, int tabs); static AnsiBufferedReader splitter(InputStream is, int maxLength, int tabs); }### Answer: @Test public void testWindow() throws IOException { String text = "\u001B[1mThis is bold.\u001B[22m"; assertEquals("\u001B[1mis\u001B[0m", AnsiSplitter.substring(text, 5, 7, 4)); assertEquals(13, AnsiSplitter.length(text, 4)); }
### Question: VerifyMojo extends MojoSupport { static Pattern getPattern(List<String> features) { StringBuilder sb = new StringBuilder(); boolean prevIsNeg = false; for (String feature : features) { if (sb.length() > 0 && !prevIsNeg) { sb.append("|"); } sb.append("("); feature = feature.trim(); boolean negative = feature.startsWith("!"); if (negative) { feature = feature.substring("!".length()); sb.append("(?!"); } String p = feature.replaceAll("\\.", "\\\\.").replaceAll("\\*", ".*"); sb.append(p); if (!feature.contains("/")) { sb.append("/.*"); } if (negative) { sb.append(")"); } prevIsNeg = negative; } for (String feature : features) { sb.append(")"); } return Pattern.compile(sb.toString()); } @Override void execute(); Map<String, Features> loadRepositories(DownloadManager manager, Set<String> uris); static Set<String> getPrefixedProperties(Map<String, String> properties, String prefix); static Map<String, Map<VersionRange, Map<String, String>>> getMetadata(Map<String, String> properties, String prefix); }### Answer: @Test public void testFeaturePattern() { Pattern pattern = VerifyMojo.getPattern(Arrays.asList("foobiz", "!foo*", "bar", "!ba*", "*")); assertTrue(pattern.matcher("foobiz/1.0").matches()); assertFalse(pattern.matcher("foobaz/1.0").matches()); assertTrue(pattern.matcher("bar/1.0").matches()); assertFalse(pattern.matcher("baz/1.0").matches()); assertTrue(pattern.matcher("biz/1.0").matches()); pattern = VerifyMojo.getPattern(Arrays.asList("!hibernate", " *")); assertTrue(pattern.matcher("framework/4.2.0.SNAPSHOT").matches()); }
### Question: Manifest { public String toString() { StringBuilder resource = new StringBuilder(); for (String s : toStringList()) { if (resource.length() > 0) resource.append("\n"); resource.append(s); } return resource.toString(); } Manifest(String module); Manifest(String module, String className); String toString(); String getName(); String getHiera(); final String module; final String className; final Map<String, String> attribs; }### Answer: @Test public void testPuppetConversion() { Manifest nginx = new Manifest("nginx", null); assertEquals("Puppet representation is incorrect.", NGINX_PUPPET, nginx.toString()); } @Test public void testPuppetConversionWithSpecificClass() { Manifest postgresql = new Manifest("postgresql", "server"); assertEquals("PUPPET representation is incorrect.", POSTGRES_PUPPET, postgresql.toString()); } @Test public void testPuppetConversionWithAttribs() { Manifest ntp = new Manifest("ntp"); ntp.attribs.put("servers", "\"10.0.0.1\""); assertEquals("Puppet representation is incorrect.", NTP_PUPPET, ntp.toString()); }
### Question: StatementToInstallModule implements Function<Map<String, String>, Statement> { @Override public Statement apply(Map<String, String> props) { try { return installModuleFromRemoteFileOrGit(find(props.keySet(), contains(MODULE_KEY_PATTERN)), props); } catch (NoSuchElementException e) { throw new IllegalArgumentException(format("couldn't find pattern: %s in properties %s", MODULE_KEY_PATTERN, props)); } } StatementToInstallModule(ClusterActionEvent event); StatementToInstallModule(PrepareRemoteFileUrl prepareRemoteFileUrl); @Override Statement apply(Map<String, String> props); }### Answer: @Test public void testWhenGit() { assertEquals("git clone git: getStatement.apply(ImmutableMap.of("puppet.nginx.module", "git: } @Test public void testWhenGitAndBranch() { assertEquals("git clone -b notmaster git: getStatement.apply(ImmutableMap.of("puppet.nginx.module.branch", "notmaster", "puppet.nginx.module", "git: } @Test public void testWhenRemote() { assertEquals("install_tarball remote: ImmutableMap.of("puppet.nginx.module", "remote: .render(OsFamily.UNIX)); } @Test public void testWhenFile() { assertEquals("install_tarball file: ImmutableMap.of("puppet.nginx.module", "file: .render(OsFamily.UNIX)); }
### Question: InstallAllModulesStatementFromProperties implements Function<Map<String, String>, Statement> { @Override public Statement apply(Map<String, String> moduleProps) { Set<String> allModules = ImmutableSet.copyOf(transform( filter(moduleProps.keySet(), contains(MODULE_KEY_PATTERN)), KeyToModuleNameOrNull.INSTANCE)); Builder<Statement> statements = ImmutableSet.<Statement> builder(); for (String module : allModules) { statements.add(statementMaker.apply(filterKeys(moduleProps, isModuleSubKey(module)))); } StatementList installModules = new StatementList(statements.build()); return installModules; } InstallAllModulesStatementFromProperties(StatementToInstallModule statementMaker); @Override Statement apply(Map<String, String> moduleProps); }### Answer: @Test public void testWhenMultiple() { assertEquals("git clone git: + "git clone git: .apply( ImmutableMap.of("puppet.nginx.module", "git: "puppet.http.module", "git: OsFamily.UNIX)); }
### Question: PuppetClusterActionHandlerFactory extends ClusterActionHandlerFactory { @Override public ClusterActionHandler create(String roleName) { return new PuppetClusterActionHandler(checkNotNull(roleName, "roleName")); } @Override String getRolePrefix(); @Override ClusterActionHandler create(String roleName); }### Answer: @Test public void testPuppetFactoryIsRegisteredAndWorksWithModules() { assertEquals(new HandlerMapFactory().create().getUnchecked("puppet:nginx"), new PuppetClusterActionHandler("nginx")); } @Test public void testPuppetFactoryIsRegisteredAndWorksWithManifests() { assertEquals(new HandlerMapFactory().create().getUnchecked("puppet:postgresql::server"), new PuppetClusterActionHandler( "postgresql::server")); }
### Question: ElasticSearchConfigurationBuilder { @VisibleForTesting public static List<String> asYamlLines(Configuration config) { return asYamlLines(config, 0); } static Statement build(String path, Configuration config); static Statement build(String path, ClusterSpec spec, Cluster cluster); static Configuration buildConfig(ClusterSpec spec, Cluster cluster); @VisibleForTesting static List<String> asYamlLines(Configuration config); static final String ES_PREFIX; }### Answer: @Test public void testGenerateYamlConfig() { Configuration defaults = new PropertiesConfiguration(); defaults.addProperty("cloud.aws.id", "a"); defaults.addProperty("cloud.aws.key", "b"); defaults.addProperty("index.store.type", "memory"); String content = StringUtils.join( ElasticSearchConfigurationBuilder.asYamlLines(defaults), "\n"); assertThat(content, is("cloud:\n" + " aws:\n" + " id: a\n" + " key: b\n" + "index:\n" + " store:\n" + " type: memory")); }
### Question: CassandraClusterActionHandler extends ClusterActionHandlerSupport { protected List<Instance> getSeeds(Set<Instance> instances) { List<Instance> nodes = Lists.newArrayList(instances); int seeds = (int) Math.ceil(Math.max(1, instances.size() * 0.2)); List<Instance> rv = Lists.newArrayList(); for (int i = 0; i < seeds; i++) { rv.add(nodes.get(i)); } return rv; } @Override String getRole(); static final String CASSANDRA_ROLE; static final int CLIENT_PORT; static final int JMX_PORT; static final String BIN_TARBALL; static final String MAJOR_VERSION; }### Answer: @Test() public void testGetSeeds() throws UnknownHostException { Instance one = getInstance("1"); Instance two = getInstance("2"); Set<Instance> instances = Sets.newLinkedHashSet(); instances.add(one); CassandraClusterActionHandler handler = new CassandraClusterActionHandler(); List<Instance> seeds1 = handler.getSeeds(instances); assertEquals(1, seeds1.size()); assertEquals(one, seeds1.get(0)); instances.add(two); for (int i = 3; i < 10; i++) { instances.add(getInstance(Integer.toString(i))); } List<Instance> seeds2 = handler.getSeeds(instances); assertEquals(2, seeds2.size()); assertEquals(one, seeds2.get(0)); assertEquals(two, seeds2.get(1)); }
### Question: CassandraClusterActionHandler extends ClusterActionHandlerSupport { protected List<String> computeInitialTokens(int numberOfNodes) { List<String> tokens = Lists.newArrayList(); BigInteger step = new BigInteger("2") .pow(127).divide(BigInteger.valueOf(numberOfNodes)); for (int i = 0; i < numberOfNodes; i++) { tokens.add(step.multiply(BigInteger.valueOf(i)).toString()); } return tokens; } @Override String getRole(); static final String CASSANDRA_ROLE; static final int CLIENT_PORT; static final int JMX_PORT; static final String BIN_TARBALL; static final String MAJOR_VERSION; }### Answer: @Test public void testComputeInitialTokens() { List<String> result = new CassandraClusterActionHandler().computeInitialTokens(5); assertEquals(result, ImmutableList.of( "0", "34028236692093846346337460743176821145", "68056473384187692692674921486353642290", "102084710076281539039012382229530463435", "136112946768375385385349842972707284580" )); }
### Question: HadoopConfigurationBuilder { @VisibleForTesting static Configuration buildHdfsConfiguration(ClusterSpec clusterSpec, Cluster cluster, Configuration defaults, Set<String> dataDirectories) throws ConfigurationException { Configuration config = build(clusterSpec, cluster, defaults, "hadoop-hdfs"); setIfAbsent(config, "dfs.data.dir", appendToDataDirectories(dataDirectories, "/hadoop/hdfs/data")); setIfAbsent(config, "dfs.name.dir", appendToDataDirectories(dataDirectories, "/hadoop/hdfs/name")); setIfAbsent(config, "fs.checkpoint.dir", appendToDataDirectories(dataDirectories, "/hadoop/hdfs/secondary")); return config; } static Statement buildCommon(String path, ClusterSpec clusterSpec, Cluster cluster); static Statement buildHdfs(String path, ClusterSpec clusterSpec, Cluster cluster, Set<String> dataDirectories); static Statement buildMapReduce(String path, ClusterSpec clusterSpec, Cluster cluster, Set<String> dataDirectories); static Statement buildHadoopEnv(String path, ClusterSpec clusterSpec, Cluster cluster); }### Answer: @Test public void testHdfs() throws Exception { Configuration conf = HadoopConfigurationBuilder.buildHdfsConfiguration( clusterSpec, cluster, defaults, Sets.newLinkedHashSet(Lists.newArrayList("/data0", "/data1"))); assertThat(Iterators.size(conf.getKeys()), is(4)); assertThat(conf.getString("p1"), is("hdfs1")); assertThat(conf.getString("dfs.data.dir"), is("/data0/hadoop/hdfs/data,/data1/hadoop/hdfs/data")); }
### Question: Recipe implements Statement { public String toJSON() { Gson gson = new Gson(); JsonObject recipeAsJSON = new JsonObject(); if (!attribs.isEmpty()) { JsonObject jsonAttribs = new JsonObject(); for (Map.Entry<String, Object> entry : attribs.entrySet()) { jsonAttribs.add(entry.getKey(), gson.toJsonTree(entry.getValue())); } recipeAsJSON.add(cookbook, jsonAttribs); } recipeAsJSON.add( "run_list", gson.toJsonTree(new String[] { "recipe[" + cookbook + (recipe != null ? ("::" + recipe) : "") + "]" })); return gson.toJson(recipeAsJSON); } Recipe(String cookbook); Recipe(String cookbook, String recipe); Recipe(String cookbook, String recipe, String url); Recipe(String cookbook, String recipe, Configuration config); String toJSON(); @Override Iterable<String> functionDependencies(OsFamily family); @Override String render(OsFamily family); static RunScriptOptions recipeScriptOptions(RunScriptOptions options); final String cookbook; final String recipe; public String url; final Map<String, Object> attribs; }### Answer: @Test public void testJSONConversion() { Recipe nginx = new Recipe("nginx"); assertEquals("JSON representation is incorrect.", NGINX_JSON, nginx.toJSON()); } @Test public void testJSONConversionWithSpecificRecipe() { Recipe postgresql = new Recipe("postgresql", "server"); assertEquals("JSON representation is incorrect.", POSTGRES_JSON, postgresql.toJSON()); } @Test public void testJSONConversionWithAttribs() { Recipe resolver = new Recipe("resolver"); resolver.attribs.put("nameservers", new String[] { "10.0.0.1" }); resolver.attribs.put("search", "int.example.com"); assertEquals("JSON representation is incorrect.", RESOLVER_JSON, resolver.toJSON()); }
### Question: Recipe implements Statement { @Override public String render(OsFamily family) { if (family.equals(OsFamily.UNIX)) { String fileName = "/tmp/" + this.fileName + ".json"; Statement storeJSonFile = Statements.createOrOverwriteFile(fileName, Collections.singleton(toJSON())); Statement runRecipe = null; runRecipe = Statements.exec("sudo -i chef-solo -j " + fileName + (url != null ? " -r " + url : "")); return Statements.newStatementList(storeJSonFile, runRecipe).render( family); } else { throw new UnsupportedOperationException(); } } Recipe(String cookbook); Recipe(String cookbook, String recipe); Recipe(String cookbook, String recipe, String url); Recipe(String cookbook, String recipe, Configuration config); String toJSON(); @Override Iterable<String> functionDependencies(OsFamily family); @Override String render(OsFamily family); static RunScriptOptions recipeScriptOptions(RunScriptOptions options); final String cookbook; final String recipe; public String url; final Map<String, Object> attribs; }### Answer: @Test public void testStatementGeneration() { Recipe recipe = new Recipe("nginx", null, "http: recipe.attribs.put("webport", "90"); recipe.fileName = "test"; assertEquals("Statement representation incorrect", CHEF_COMMAND, recipe.render(OsFamily.UNIX)); }
### Question: KeyPair { public static Map<String, String> generate() throws JSchException { return generate(null); } static Map<String, String> generate(); static Map<String,String> generate(String passPhrase); static Map<String, File> generateTemporaryFiles(); static Map<String, File> generateTemporaryFiles(String passPhrase); static void setPermissionsTo600(File f); static boolean sameKeyPair(File privateKeyFile, File publicKeyFile); }### Answer: @Test public void testGenerate() throws JSchException { Map<String, String> pair = generate(); assertThat(pair.get("public"), containsString("ssh-rsa ")); assertThat(pair.get("private"), containsString("-----BEGIN RSA PRIVATE KEY-----\n")); }
### Question: Manifest { public String getHiera() { String name = getName(); StringBuilder result = new StringBuilder(); for (Map.Entry<String, String> entry : attribs.entrySet()) { result.append("\n" + name + "::" + entry.getKey() + ": " + entry.getValue()); } return result.toString(); } Manifest(String module); Manifest(String module, String className); String toString(); String getName(); String getHiera(); final String module; final String className; final Map<String, String> attribs; }### Answer: @Test public void testPuppetConversionWithAttribsHiera() { Manifest ntp = new Manifest("ntp"); ntp.attribs.put("servers", "\"10.0.0.1\""); assertEquals("Puppet/Hiera representation is incorrect.", NTP_PUPPET_HIERA, ntp.getHiera()); }
### Question: RunUrlStatement implements Statement { @Override public String render(OsFamily family) { StringBuilder command = new StringBuilder("runurl "); command.append(runUrl); if (!args.isEmpty()) { command.append(' '); command.append(Joiner.on(' ').join(args)); } return Statements.exec(command.toString()).render(family); } RunUrlStatement(String runUrlBase, String url, String... args); RunUrlStatement(boolean checkUrlExists, String runUrlBase, String url, String... args); @Override Iterable<String> functionDependencies(OsFamily family); @Override String render(OsFamily family); @Override boolean equals(Object o); @Override int hashCode(); static void checkUrlExists(URL url, String errorMessageTemplate, Object... errorMessageArgs); }### Answer: @Test public void testBaseWithTrailingSlash() throws IOException { assertThat( new RunUrlStatement(false, "http: is("runurl http: } @Test public void testWithArgs() throws IOException { assertThat( new RunUrlStatement(false, "http: is("runurl http: } @Test public void testBaseWithoutTrailingSlash() throws IOException { assertThat( new RunUrlStatement(false, "http: is("runurl http: } @Test public void testAbsolutePath() throws IOException { assertThat( new RunUrlStatement(false, "http: .render(OsFamily.UNIX), is("runurl http: }
### Question: RunUrlStatement implements Statement { public static void checkUrlExists(URL url, String errorMessageTemplate, Object... errorMessageArgs) throws IOException { if (!urlExists(url)) { throw new IllegalArgumentException( String.format(errorMessageTemplate, errorMessageArgs)); } } RunUrlStatement(String runUrlBase, String url, String... args); RunUrlStatement(boolean checkUrlExists, String runUrlBase, String url, String... args); @Override Iterable<String> functionDependencies(OsFamily family); @Override String render(OsFamily family); @Override boolean equals(Object o); @Override int hashCode(); static void checkUrlExists(URL url, String errorMessageTemplate, Object... errorMessageArgs); }### Answer: @Test public void testCheckUrlExists() throws IOException { RunUrlStatement.checkUrlExists(new URL("http: "Exists"); } @Test(expected = IllegalArgumentException.class) public void testCheckUrlDoesNotExist() throws IOException { RunUrlStatement.checkUrlExists( new URL("http: }
### Question: Manifest { public String getName() { return module + (className != null ? "::" + className : ""); } Manifest(String module); Manifest(String module, String className); String toString(); String getName(); String getHiera(); final String module; final String className; final Map<String, String> attribs; }### Answer: @Test public void testPuppetConversionHiera() { Manifest postgress = new Manifest("postgresql", "server"); assertEquals("Puppet/Name representation is incorrect.", POSTGRES_PUPPET_NAME, postgress.getName()); }
### Question: AbstractClusterCommand extends Command { protected ClusterController createClusterController(String serviceName) { ClusterController controller = factory.create(serviceName); if (controller == null) { LOG.warn("Unable to find service {}, using default.", serviceName); controller = factory.create(null); } return controller; } AbstractClusterCommand(String name, String description, ClusterControllerFactory factory); AbstractClusterCommand(String name, String description, ClusterControllerFactory factory, ClusterStateStoreFactory stateStoreFactory); @Override void printUsage(PrintStream stream); }### Answer: @Test public void testCreateServerWithInvalidClusterControllerName() throws Exception { AbstractClusterCommand clusterCommand = new AbstractClusterCommand("name", "description", new ClusterControllerFactory()) { @Override public int run(InputStream in, PrintStream out, PrintStream err, List<String> args) throws Exception { return 0; } }; clusterCommand.createClusterController("bar"); }
### Question: Cluster { public Instance getInstanceMatching(Predicate<Instance> predicate) { return Iterables.getOnlyElement(Sets.filter(instances, predicate)); } Cluster(Set<Instance> instances); Cluster(Set<Instance> instances, Properties configuration); static Cluster empty(); Set<Instance> getInstances(); Properties getConfiguration(); Instance getInstanceMatching(Predicate<Instance> predicate); Set<Instance> getInstancesMatching(Predicate<Instance> predicate); void removeInstancesMatching(Predicate<Instance> predicate); String toString(); }### Answer: @Test public void getInstanceById() { Cluster.Instance instance = cluster.getInstanceMatching(withIds("id-0")); assertThat(instance.getRoles().contains("role-0"), is(true)); } @Test public void getInstanceByRole() { Cluster.Instance instance = cluster.getInstanceMatching(role("role-0")); assertThat(instance.getId(), is("id-0")); }
### Question: ClusterControllerFactory { public ClusterController create(String serviceName) { if (serviceName == null) { return new ClusterController(); } for (ClusterController controller : serviceLoader) { if (controller.getName().equals(serviceName)) { return controller; } } return null; } ClusterController create(String serviceName); Set<String> availableServices(); }### Answer: @Test public void testServiceFactoryIsCreatedFromWhirrProperties() throws IOException { ClusterControllerFactory factory = new ClusterControllerFactory(); ClusterController controller = factory.create("test-service"); assertThat(controller, instanceOf(TestClusterController.class)); } @Test public void testServiceFactoryWithNullServiceName() throws IOException { ClusterControllerFactory factory = new ClusterControllerFactory(); ClusterController controller = factory.create(null); assertThat(controller, instanceOf(ClusterController.class)); }
### Question: TemplateUtils { public static String processTemplate(VelocityEngine engine, String templateName, ClusterSpec clusterSpec, Cluster cluster) { VelocityContext context = new VelocityContext(); context.put("clusterSpec", clusterSpec); context.put("cluster", cluster); context.put("RolePredicates", RolePredicates.class); Template template = engine.getTemplate(templateName); StringWriter writer = new StringWriter(); template.merge(context, writer); return writer.toString(); } static Statement createFileFromTemplate(String path, VelocityEngine engine, String templateName, ClusterSpec clusterSpec, Cluster cluster); static String processTemplate(VelocityEngine engine, String templateName, ClusterSpec clusterSpec, Cluster cluster); static VelocityEngine newVelocityEngine(); static VelocityEngine newVelocityEngine(Properties properties); }### Answer: @Test public void testProcessTemplate() throws Exception { Credentials credentials = new Credentials("dummy", "dummy"); Cluster.Instance instance = new Cluster.Instance(credentials, Sets.newHashSet("foo"), "127.0.0.1", "127.0.0.1", "id-0", null); ClusterSpec clusterSpec = ClusterSpec.withTemporaryKeys(new PropertiesConfiguration("whirr-core-test.properties")); Cluster cluster = new Cluster(Sets.newHashSet(instance)); VelocityEngine ve = TemplateUtils.newVelocityEngine(); String result = TemplateUtils.processTemplate(ve, "template-test.txt.vm", clusterSpec, cluster); Assert.assertEquals("instance ip: 127.0.0.1", result); }
### Question: InstallModuleFromGit implements Statement { @Override public String render(OsFamily arg0) { return exec( "git clone " + (vcsBranch != null ? "-b " + vcsBranch + " " : "") + url + " " + MODULES_DIR + module).render(arg0); } InstallModuleFromGit(String module, URI url); InstallModuleFromGit(String module, URI url, @Nullable String vcsBranch); @Override Iterable<String> functionDependencies(OsFamily arg0); @Override String render(OsFamily arg0); }### Answer: @Test public void testWhenModuleAndURIValid() { InstallModuleFromGit nginx = new InstallModuleFromGit("nginx", URI .create("git: assertEquals("git clone git: .render(OsFamily.UNIX)); } @Test public void testWhenModuleAndURIAndBranchValid() { InstallModuleFromGit nginx = new InstallModuleFromGit("nginx", URI .create("git: assertEquals("git clone -b WHIRR-385 git: .render(OsFamily.UNIX)); }
### Question: VersionCommand extends Command { @Override public int run(InputStream in, PrintStream out, PrintStream err, List<String> args) throws Exception { InputStream input = getClass().getResourceAsStream("/version-banner.txt"); if (input == null) { err.printf("Cannot determine version number\n"); return -1; } out.write(IOUtils.toByteArray(input)); out.println("jclouds " + JcloudsVersion.get().toString()); return 0; } VersionCommand(); @Override int run(InputStream in, PrintStream out, PrintStream err, List<String> args); @Override void printUsage(PrintStream stream); }### Answer: @Test public void testOverrides() throws Exception { VersionCommand command = new VersionCommand(); int rc = command.run(null, out, null, Collections.<String>emptyList()); assertThat(rc, is(0)); assertThat(outBytes.toString(), startsWith("Apache Whirr ")); assertThat(outBytes.toString(), containsString("jclouds")); }
### Question: Main { int run(InputStream in, PrintStream out, PrintStream err, List<String> list) throws Exception { if (list.isEmpty()) { printUsage(out); return -1; } Command command = commandMap.get(list.get(0)); if (command == null) { err.printf("Unrecognized command '%s'\n", list.get(0)); err.println(); printUsage(err); return -1; } return command.run(in, out, err, list.subList(1, list.size())); } Main(Command... commands); Main(Iterable<Command> commands); static void main(String... args); }### Answer: @Test public void testNoArgs() throws Exception { Main main = new Main(new TestCommand()); ByteArrayOutputStream bytes = new ByteArrayOutputStream(); PrintStream out = new PrintStream(bytes); int rc = main.run(null, out, null, Collections.<String>emptyList()); assertThat(rc, is(-1)); assertThat(bytes.toString(), containsString("Usage: whirr COMMAND")); assertThat(bytes.toString(), containsString("test-command test description")); } @Test public void testUnrecognizedCommand() throws Exception { Main main = new Main(new TestCommand()); ByteArrayOutputStream bytes = new ByteArrayOutputStream(); PrintStream err = new PrintStream(bytes); int rc = main.run(null, null, err, Lists.newArrayList("bogus-command")); assertThat(rc, is(-1)); assertThat(bytes.toString(), containsString("Unrecognized command 'bogus-command'")); } @Test public void testCommand() throws Exception { Command command = mock(Command.class); when(command.getName()).thenReturn("mock-command"); Main main = new Main(command); main.run(null, null, null, Lists.newArrayList("mock-command", "arg1", "arg2")); verify(command).run(null, null, null, Lists.newArrayList("arg1", "arg2")); }
### Question: DirectoryScanner { public DefaultScanResult scan() { FileScanner scanner = new FileScanner( basedir, "class" ); List<String> result = new ArrayList<>(); scanner.scanTo( result, filter ); return new DefaultScanResult( result ); } DirectoryScanner( File basedir, TestListResolver filter ); DefaultScanResult scan(); }### Answer: @Test public void locateTestClasses() throws Exception { File baseDir = new File( new File( "target/test-classes" ).getCanonicalPath() ); TestListResolver resolver = new TestListResolver( filter ); DirectoryScanner surefireDirectoryScanner = new DirectoryScanner( baseDir, resolver ); ScanResult classNames = surefireDirectoryScanner.scan(); assertThat( classNames, is( notNullValue() ) ); assertThat( classNames.size(), is( expectedClassesCount ) ); Map<String, String> props = new HashMap<>(); classNames.writeTo( props ); assertThat( props.values(), hasSize( expectedClassesCount ) ); }
### Question: RunListenerAdapter implements TestExecutionListener { @Override public void executionStarted( TestIdentifier testIdentifier ) { if ( testIdentifier.isContainer() && testIdentifier.getSource().filter( ClassSource.class::isInstance ).isPresent() ) { testStartTime.put( testIdentifier, System.currentTimeMillis() ); runListener.testSetStarting( createReportEntry( testIdentifier ) ); } else if ( testIdentifier.isTest() ) { testStartTime.put( testIdentifier, System.currentTimeMillis() ); runListener.testStarting( createReportEntry( testIdentifier ) ); } } RunListenerAdapter( RunListener runListener ); @Override void testPlanExecutionStarted( TestPlan testPlan ); @Override void testPlanExecutionFinished( TestPlan testPlan ); @Override void executionStarted( TestIdentifier testIdentifier ); @Override void executionFinished( TestIdentifier testIdentifier, TestExecutionResult testExecutionResult ); @Override void executionSkipped( TestIdentifier testIdentifier, String reason ); }### Answer: @Test public void notNotifiedWhenEngineExecutionStarted() { adapter.executionStarted( newEngineIdentifier() ); verify( listener, never() ).testStarting( any() ); }
### Question: RunListenerAdapter implements TestExecutionListener { @Override public void executionSkipped( TestIdentifier testIdentifier, String reason ) { testStartTime.remove( testIdentifier ); runListener.testSkipped( createReportEntry( testIdentifier, null, emptyMap(), reason, null ) ); } RunListenerAdapter( RunListener runListener ); @Override void testPlanExecutionStarted( TestPlan testPlan ); @Override void testPlanExecutionFinished( TestPlan testPlan ); @Override void executionStarted( TestIdentifier testIdentifier ); @Override void executionFinished( TestIdentifier testIdentifier, TestExecutionResult testExecutionResult ); @Override void executionSkipped( TestIdentifier testIdentifier, String reason ); }### Answer: @Test public void notifiedWhenMethodExecutionSkipped() throws Exception { adapter.executionSkipped( newMethodIdentifier(), "test" ); verify( listener ).testSkipped( any() ); } @Test public void notifiedWhenEngineExecutionSkipped() { adapter.executionSkipped( newEngineIdentifier(), "test" ); verify( listener ).testSkipped( any() ); } @Test public void displayNamesIgnoredInReport() throws NoSuchMethodException { TestMethodTestDescriptorWithDisplayName descriptor = new TestMethodTestDescriptorWithDisplayName( newId(), MyTestClass.class, MyTestClass.class.getDeclaredMethod( "myNamedTestMethod" ), "some display name" ); TestIdentifier factoryIdentifier = TestIdentifier.from( descriptor ); ArgumentCaptor<ReportEntry> entryCaptor = ArgumentCaptor.forClass( ReportEntry.class ); adapter.executionSkipped( factoryIdentifier, "" ); verify( listener ).testSkipped( entryCaptor.capture() ); ReportEntry value = entryCaptor.getValue(); assertEquals( MyTestClass.class.getName(), value.getSourceName() ); assertNull( value.getSourceText() ); assertEquals( "myNamedTestMethod", value.getName() ); assertEquals( "some display name", value.getNameText() ); }
### Question: JUnitPlatformProvider extends AbstractProvider { @Override public Iterable<Class<?>> getSuites() { return scanClasspath(); } JUnitPlatformProvider( ProviderParameters parameters ); JUnitPlatformProvider( ProviderParameters parameters, Launcher launcher ); @Override Iterable<Class<?>> getSuites(); @Override RunResult invoke( Object forkTestSet ); }### Answer: @Test public void getSuitesReturnsScannedClasses() { ProviderParameters providerParameters = providerParametersMock( TestClass1.class, TestClass2.class ); JUnitPlatformProvider provider = new JUnitPlatformProvider( providerParameters ); assertThat( provider.getSuites() ) .containsOnly( TestClass1.class, TestClass2.class ); }
### Question: JUnitPlatformProvider extends AbstractProvider { Map<String, String> getConfigurationParameters() { return configurationParameters; } JUnitPlatformProvider( ProviderParameters parameters ); JUnitPlatformProvider( ProviderParameters parameters, Launcher launcher ); @Override Iterable<Class<?>> getSuites(); @Override RunResult invoke( Object forkTestSet ); }### Answer: @Test public void defaultConfigurationParametersAreEmpty() { ProviderParameters providerParameters = providerParametersMock( TestClass1.class ); when( providerParameters.getProviderProperties() ).thenReturn( emptyMap() ); JUnitPlatformProvider provider = new JUnitPlatformProvider( providerParameters ); assertTrue( provider.getConfigurationParameters().isEmpty() ); } @Test public void parsesConfigurationParameters() { ProviderParameters providerParameters = providerParametersMock( TestClass1.class ); when( providerParameters.getProviderProperties() ) .thenReturn( singletonMap( JUnitPlatformProvider.CONFIGURATION_PARAMETERS, "foo = true\nbar 42\rbaz: *\r\nqux: EOF" ) ); JUnitPlatformProvider provider = new JUnitPlatformProvider( providerParameters ); assertEquals( 4, provider.getConfigurationParameters().size() ); assertEquals( "true", provider.getConfigurationParameters().get( "foo" ) ); assertEquals( "42", provider.getConfigurationParameters().get( "bar" ) ); assertEquals( "*", provider.getConfigurationParameters().get( "baz" ) ); assertEquals( "EOF", provider.getConfigurationParameters().get( "qux" ) ); }
### Question: SchedulingStrategies { public static SchedulingStrategy createInvokerStrategy( ConsoleStream logger ) { return new InvokerStrategy( logger ); } static SchedulingStrategy createInvokerStrategy( ConsoleStream logger ); static SchedulingStrategy createParallelStrategy( ConsoleStream logger, int nThreads ); static SchedulingStrategy createParallelStrategyUnbounded( ConsoleStream logger ); static SchedulingStrategy createParallelSharedStrategy( ConsoleStream logger, ExecutorService threadPool ); }### Answer: @Test public void invokerStrategy() throws InterruptedException { SchedulingStrategy strategy = SchedulingStrategies.createInvokerStrategy( logger ); assertFalse( strategy.hasSharedThreadPool() ); assertTrue( strategy.canSchedule() ); Task task = new Task(); strategy.schedule( task ); assertTrue( strategy.canSchedule() ); assertTrue( task.result ); assertTrue( strategy.finished() ); assertFalse( strategy.canSchedule() ); }
### Question: SchedulingStrategies { public static SchedulingStrategy createParallelStrategy( ConsoleStream logger, int nThreads ) { return new NonSharedThreadPoolStrategy( logger, Executors.newFixedThreadPool( nThreads, DAEMON_THREAD_FACTORY ) ); } static SchedulingStrategy createInvokerStrategy( ConsoleStream logger ); static SchedulingStrategy createParallelStrategy( ConsoleStream logger, int nThreads ); static SchedulingStrategy createParallelStrategyUnbounded( ConsoleStream logger ); static SchedulingStrategy createParallelSharedStrategy( ConsoleStream logger, ExecutorService threadPool ); }### Answer: @Test public void nonSharedPoolStrategy() throws InterruptedException { SchedulingStrategy strategy = SchedulingStrategies.createParallelStrategy( logger, 2 ); assertFalse( strategy.hasSharedThreadPool() ); assertTrue( strategy.canSchedule() ); Task task1 = new Task(); Task task2 = new Task(); strategy.schedule( task1 ); strategy.schedule( task2 ); assertTrue( strategy.canSchedule() ); assertTrue( strategy.finished() ); assertFalse( strategy.canSchedule() ); assertTrue( task1.result ); assertTrue( task2.result ); }
### Question: SchedulingStrategies { public static SchedulingStrategy createParallelSharedStrategy( ConsoleStream logger, ExecutorService threadPool ) { if ( threadPool == null ) { throw new NullPointerException( "null threadPool in #createParallelSharedStrategy" ); } return new SharedThreadPoolStrategy( logger, threadPool ); } static SchedulingStrategy createInvokerStrategy( ConsoleStream logger ); static SchedulingStrategy createParallelStrategy( ConsoleStream logger, int nThreads ); static SchedulingStrategy createParallelStrategyUnbounded( ConsoleStream logger ); static SchedulingStrategy createParallelSharedStrategy( ConsoleStream logger, ExecutorService threadPool ); }### Answer: @Test( expected = NullPointerException.class ) public void sharedPoolStrategyNullPool() { SchedulingStrategies.createParallelSharedStrategy( logger, null ); } @Test public void sharedPoolStrategy() throws InterruptedException { ExecutorService sharedPool = Executors.newCachedThreadPool( DAEMON_THREAD_FACTORY ); SchedulingStrategy strategy1 = SchedulingStrategies.createParallelSharedStrategy( logger, sharedPool ); assertTrue( strategy1.hasSharedThreadPool() ); assertTrue( strategy1.canSchedule() ); SchedulingStrategy strategy2 = SchedulingStrategies.createParallelSharedStrategy( logger, sharedPool ); assertTrue( strategy2.hasSharedThreadPool() ); assertTrue( strategy2.canSchedule() ); Task task1 = new Task(); Task task2 = new Task(); Task task3 = new Task(); Task task4 = new Task(); strategy1.schedule( task1 ); strategy2.schedule( task2 ); strategy1.schedule( task3 ); strategy2.schedule( task4 ); assertTrue( strategy1.canSchedule() ); assertTrue( strategy2.canSchedule() ); assertTrue( strategy1.finished() ); assertFalse( strategy1.canSchedule() ); assertTrue( strategy2.finished() ); assertFalse( strategy2.canSchedule() ); assertTrue( task1.result ); assertTrue( task2.result ); assertTrue( task3.result ); assertTrue( task4.result ); }
### Question: SchedulingStrategies { public static SchedulingStrategy createParallelStrategyUnbounded( ConsoleStream logger ) { return new NonSharedThreadPoolStrategy( logger, Executors.newCachedThreadPool( DAEMON_THREAD_FACTORY ) ); } static SchedulingStrategy createInvokerStrategy( ConsoleStream logger ); static SchedulingStrategy createParallelStrategy( ConsoleStream logger, int nThreads ); static SchedulingStrategy createParallelStrategyUnbounded( ConsoleStream logger ); static SchedulingStrategy createParallelSharedStrategy( ConsoleStream logger, ExecutorService threadPool ); }### Answer: @Test public void infinitePoolStrategy() throws InterruptedException { SchedulingStrategy strategy = SchedulingStrategies.createParallelStrategyUnbounded( logger ); assertFalse( strategy.hasSharedThreadPool() ); assertTrue( strategy.canSchedule() ); Task task1 = new Task(); Task task2 = new Task(); strategy.schedule( task1 ); strategy.schedule( task2 ); assertTrue( strategy.canSchedule() ); assertTrue( strategy.finished() ); assertFalse( strategy.canSchedule() ); assertTrue( task1.result ); assertTrue( task2.result ); }
### Question: ParallelComputerBuilder { public ParallelComputer buildComputer() { return new PC(); } ParallelComputerBuilder( ConsoleStream logger ); ParallelComputerBuilder( ConsoleStream logger, JUnitCoreParameters parameters ); ParallelComputer buildComputer(); }### Answer: @Test public void testsWithoutChildrenShouldAlsoBeRun() { ParallelComputerBuilder parallelComputerBuilder = new ParallelComputerBuilder( LOGGER ); ParallelComputerBuilder.PC computer = (ParallelComputerBuilder.PC) parallelComputerBuilder.buildComputer(); Result result = new JUnitCore().run( computer, TestWithoutPrecalculatedChildren.class ); assertThat( result.getRunCount(), is( 1 ) ); }
### Question: ConfigurableParallelComputer extends Computer { @SuppressWarnings( { "UnusedDeclaration" } ) public void close() throws ExecutionException { for ( AsynchronousRunner nonBlocker : nonBlockers ) { nonBlocker.waitForCompletion(); } fService.shutdown(); try { if ( !fService.awaitTermination( 10, java.util.concurrent.TimeUnit.SECONDS ) ) { throw new RuntimeException( "Executor did not shut down within timeout" ); } } catch ( InterruptedException e ) { throw new RuntimeException( e ); } } ConfigurableParallelComputer(); ConfigurableParallelComputer( boolean fClasses, boolean fMethods ); ConfigurableParallelComputer( boolean fClasses, boolean fMethods, Integer numberOfThreads, boolean perCore ); private ConfigurableParallelComputer( boolean fClasses, boolean fMethods, ExecutorService executorService, boolean fixedPool ); @SuppressWarnings( { "UnusedDeclaration" } ) void close(); @Override Runner getSuite( RunnerBuilder builder, java.lang.Class<?>[] classes ); @Override String toString(); }### Answer: @Test public void testAnythingYouWantToPlayWith() throws Exception { Result result = new Result(); Class<?>[] realClasses = new Class[]{ Dummy.class, Dummy2.class }; DiagnosticRunListener diagnosticRunListener = new DiagnosticRunListener( false, result.createListener() ); JUnitCore jUnitCore = getJunitCore( diagnosticRunListener ); ConfigurableParallelComputer computer = new ConfigurableParallelComputer( true, false ); jUnitCore.run( computer, realClasses ); computer.close(); assertEquals( "All tests should succeed, right ?", 5, result.getRunCount() ); } @Test public void testOneMethod() throws ExecutionException { JUnitCore jUnitCore = new JUnitCore(); ConfigurableParallelComputer computer = new ConfigurableParallelComputer( false, true ); jUnitCore.run( computer, new Class[]{ Dummy.class, Dummy.class, Dummy.class } ); computer.close(); }
### Question: JUnitCoreParameters { public boolean isParallelOptimization() { return parallelOptimization; } JUnitCoreParameters( Map<String, String> properties ); boolean isParallelMethods(); boolean isParallelClasses(); boolean isParallelSuites(); @Deprecated @SuppressWarnings( "unused" ) boolean isParallelBoth(); boolean isPerCoreThreadCount(); int getThreadCount(); int getThreadCountMethods(); int getThreadCountClasses(); int getThreadCountSuites(); boolean isUseUnlimitedThreads(); double getParallelTestsTimeoutInSeconds(); double getParallelTestsTimeoutForcedInSeconds(); boolean isNoThreading(); boolean isParallelismSelected(); boolean isParallelOptimization(); @Override String toString(); static final String PARALLEL_KEY; static final String PERCORETHREADCOUNT_KEY; static final String THREADCOUNT_KEY; static final String THREADCOUNTSUITES_KEY; static final String THREADCOUNTCLASSES_KEY; static final String THREADCOUNTMETHODS_KEY; static final String USEUNLIMITEDTHREADS_KEY; static final String PARALLEL_TIMEOUT_KEY; static final String PARALLEL_TIMEOUTFORCED_KEY; static final String PARALLEL_OPTIMIZE_KEY; }### Answer: @Test public void optimizationParameter() { assertFalse( newTestSetOptimization( false ).isParallelOptimization() ); }
### Question: JUnitCoreParameters { public boolean isParallelMethods() { return isAllParallel() || lowerCase( "both", "methods", "suitesAndMethods", "classesAndMethods" ).contains( parallel ); } JUnitCoreParameters( Map<String, String> properties ); boolean isParallelMethods(); boolean isParallelClasses(); boolean isParallelSuites(); @Deprecated @SuppressWarnings( "unused" ) boolean isParallelBoth(); boolean isPerCoreThreadCount(); int getThreadCount(); int getThreadCountMethods(); int getThreadCountClasses(); int getThreadCountSuites(); boolean isUseUnlimitedThreads(); double getParallelTestsTimeoutInSeconds(); double getParallelTestsTimeoutForcedInSeconds(); boolean isNoThreading(); boolean isParallelismSelected(); boolean isParallelOptimization(); @Override String toString(); static final String PARALLEL_KEY; static final String PERCORETHREADCOUNT_KEY; static final String THREADCOUNT_KEY; static final String THREADCOUNTSUITES_KEY; static final String THREADCOUNTCLASSES_KEY; static final String THREADCOUNTMETHODS_KEY; static final String USEUNLIMITEDTHREADS_KEY; static final String PARALLEL_TIMEOUT_KEY; static final String PARALLEL_TIMEOUTFORCED_KEY; static final String PARALLEL_OPTIMIZE_KEY; }### Answer: @Test public void isParallelMethod() { assertFalse( newTestSetClasses().isParallelMethods() ); assertTrue( newTestSetMethods().isParallelMethods() ); assertTrue( newTestSetBoth().isParallelMethods() ); }
### Question: JUnitCoreParameters { public boolean isParallelClasses() { return isAllParallel() || lowerCase( "both", "classes", "suitesAndClasses", "classesAndMethods" ).contains( parallel ); } JUnitCoreParameters( Map<String, String> properties ); boolean isParallelMethods(); boolean isParallelClasses(); boolean isParallelSuites(); @Deprecated @SuppressWarnings( "unused" ) boolean isParallelBoth(); boolean isPerCoreThreadCount(); int getThreadCount(); int getThreadCountMethods(); int getThreadCountClasses(); int getThreadCountSuites(); boolean isUseUnlimitedThreads(); double getParallelTestsTimeoutInSeconds(); double getParallelTestsTimeoutForcedInSeconds(); boolean isNoThreading(); boolean isParallelismSelected(); boolean isParallelOptimization(); @Override String toString(); static final String PARALLEL_KEY; static final String PERCORETHREADCOUNT_KEY; static final String THREADCOUNT_KEY; static final String THREADCOUNTSUITES_KEY; static final String THREADCOUNTCLASSES_KEY; static final String THREADCOUNTMETHODS_KEY; static final String USEUNLIMITEDTHREADS_KEY; static final String PARALLEL_TIMEOUT_KEY; static final String PARALLEL_TIMEOUTFORCED_KEY; static final String PARALLEL_OPTIMIZE_KEY; }### Answer: @Test public void isParallelClasses() { assertTrue( newTestSetClasses().isParallelClasses() ); assertFalse( newTestSetMethods().isParallelClasses() ); assertTrue( newTestSetBoth().isParallelClasses() ); }
### Question: JUnitCoreParameters { @Deprecated @SuppressWarnings( "unused" ) public boolean isParallelBoth() { return isParallelMethods() && isParallelClasses(); } JUnitCoreParameters( Map<String, String> properties ); boolean isParallelMethods(); boolean isParallelClasses(); boolean isParallelSuites(); @Deprecated @SuppressWarnings( "unused" ) boolean isParallelBoth(); boolean isPerCoreThreadCount(); int getThreadCount(); int getThreadCountMethods(); int getThreadCountClasses(); int getThreadCountSuites(); boolean isUseUnlimitedThreads(); double getParallelTestsTimeoutInSeconds(); double getParallelTestsTimeoutForcedInSeconds(); boolean isNoThreading(); boolean isParallelismSelected(); boolean isParallelOptimization(); @Override String toString(); static final String PARALLEL_KEY; static final String PERCORETHREADCOUNT_KEY; static final String THREADCOUNT_KEY; static final String THREADCOUNTSUITES_KEY; static final String THREADCOUNTCLASSES_KEY; static final String THREADCOUNTMETHODS_KEY; static final String USEUNLIMITEDTHREADS_KEY; static final String PARALLEL_TIMEOUT_KEY; static final String PARALLEL_TIMEOUTFORCED_KEY; static final String PARALLEL_OPTIMIZE_KEY; }### Answer: @Test public void isParallelBoth() { assertFalse( isParallelMethodsAndClasses( newTestSetClasses() ) ); assertFalse( isParallelMethodsAndClasses( newTestSetMethods() ) ); assertTrue( isParallelMethodsAndClasses( newTestSetBoth() ) ); }
### Question: JUnitCoreParameters { public boolean isPerCoreThreadCount() { return perCoreThreadCount; } JUnitCoreParameters( Map<String, String> properties ); boolean isParallelMethods(); boolean isParallelClasses(); boolean isParallelSuites(); @Deprecated @SuppressWarnings( "unused" ) boolean isParallelBoth(); boolean isPerCoreThreadCount(); int getThreadCount(); int getThreadCountMethods(); int getThreadCountClasses(); int getThreadCountSuites(); boolean isUseUnlimitedThreads(); double getParallelTestsTimeoutInSeconds(); double getParallelTestsTimeoutForcedInSeconds(); boolean isNoThreading(); boolean isParallelismSelected(); boolean isParallelOptimization(); @Override String toString(); static final String PARALLEL_KEY; static final String PERCORETHREADCOUNT_KEY; static final String THREADCOUNT_KEY; static final String THREADCOUNTSUITES_KEY; static final String THREADCOUNTCLASSES_KEY; static final String THREADCOUNTMETHODS_KEY; static final String USEUNLIMITEDTHREADS_KEY; static final String PARALLEL_TIMEOUT_KEY; static final String PARALLEL_TIMEOUTFORCED_KEY; static final String PARALLEL_OPTIMIZE_KEY; }### Answer: @Test public void isPerCoreThreadCount() { assertFalse( newTestSetClasses().isPerCoreThreadCount() ); assertFalse( newTestSetMethods().isPerCoreThreadCount() ); assertTrue( newTestSetBoth().isPerCoreThreadCount() ); }
### Question: JUnitCoreParameters { public int getThreadCount() { return threadCount; } JUnitCoreParameters( Map<String, String> properties ); boolean isParallelMethods(); boolean isParallelClasses(); boolean isParallelSuites(); @Deprecated @SuppressWarnings( "unused" ) boolean isParallelBoth(); boolean isPerCoreThreadCount(); int getThreadCount(); int getThreadCountMethods(); int getThreadCountClasses(); int getThreadCountSuites(); boolean isUseUnlimitedThreads(); double getParallelTestsTimeoutInSeconds(); double getParallelTestsTimeoutForcedInSeconds(); boolean isNoThreading(); boolean isParallelismSelected(); boolean isParallelOptimization(); @Override String toString(); static final String PARALLEL_KEY; static final String PERCORETHREADCOUNT_KEY; static final String THREADCOUNT_KEY; static final String THREADCOUNTSUITES_KEY; static final String THREADCOUNTCLASSES_KEY; static final String THREADCOUNTMETHODS_KEY; static final String USEUNLIMITEDTHREADS_KEY; static final String PARALLEL_TIMEOUT_KEY; static final String PARALLEL_TIMEOUTFORCED_KEY; static final String PARALLEL_OPTIMIZE_KEY; }### Answer: @Test public void getThreadCount() { assertFalse( newTestSetClasses().isPerCoreThreadCount() ); assertFalse( newTestSetMethods().isPerCoreThreadCount() ); assertTrue( newTestSetBoth().isPerCoreThreadCount() ); }
### Question: JUnitCoreParameters { public boolean isUseUnlimitedThreads() { return useUnlimitedThreads; } JUnitCoreParameters( Map<String, String> properties ); boolean isParallelMethods(); boolean isParallelClasses(); boolean isParallelSuites(); @Deprecated @SuppressWarnings( "unused" ) boolean isParallelBoth(); boolean isPerCoreThreadCount(); int getThreadCount(); int getThreadCountMethods(); int getThreadCountClasses(); int getThreadCountSuites(); boolean isUseUnlimitedThreads(); double getParallelTestsTimeoutInSeconds(); double getParallelTestsTimeoutForcedInSeconds(); boolean isNoThreading(); boolean isParallelismSelected(); boolean isParallelOptimization(); @Override String toString(); static final String PARALLEL_KEY; static final String PERCORETHREADCOUNT_KEY; static final String THREADCOUNT_KEY; static final String THREADCOUNTSUITES_KEY; static final String THREADCOUNTCLASSES_KEY; static final String THREADCOUNTMETHODS_KEY; static final String USEUNLIMITEDTHREADS_KEY; static final String PARALLEL_TIMEOUT_KEY; static final String PARALLEL_TIMEOUTFORCED_KEY; static final String PARALLEL_OPTIMIZE_KEY; }### Answer: @Test public void isUseUnlimitedThreads() { assertFalse( newTestSetClasses().isUseUnlimitedThreads() ); assertTrue( newTestSetMethods().isUseUnlimitedThreads() ); assertFalse( newTestSetBoth().isUseUnlimitedThreads() ); }
### Question: JUnitCoreParameters { public boolean isNoThreading() { return !isParallelismSelected(); } JUnitCoreParameters( Map<String, String> properties ); boolean isParallelMethods(); boolean isParallelClasses(); boolean isParallelSuites(); @Deprecated @SuppressWarnings( "unused" ) boolean isParallelBoth(); boolean isPerCoreThreadCount(); int getThreadCount(); int getThreadCountMethods(); int getThreadCountClasses(); int getThreadCountSuites(); boolean isUseUnlimitedThreads(); double getParallelTestsTimeoutInSeconds(); double getParallelTestsTimeoutForcedInSeconds(); boolean isNoThreading(); boolean isParallelismSelected(); boolean isParallelOptimization(); @Override String toString(); static final String PARALLEL_KEY; static final String PERCORETHREADCOUNT_KEY; static final String THREADCOUNT_KEY; static final String THREADCOUNTSUITES_KEY; static final String THREADCOUNTCLASSES_KEY; static final String THREADCOUNTMETHODS_KEY; static final String USEUNLIMITEDTHREADS_KEY; static final String PARALLEL_TIMEOUT_KEY; static final String PARALLEL_TIMEOUTFORCED_KEY; static final String PARALLEL_OPTIMIZE_KEY; }### Answer: @Test public void isNoThreading() { assertFalse( newTestSetClasses().isNoThreading() ); assertFalse( newTestSetMethods().isNoThreading() ); assertFalse( newTestSetBoth().isNoThreading() ); }
### Question: JUnitCoreParameters { public boolean isParallelismSelected() { return isParallelSuites() || isParallelClasses() || isParallelMethods(); } JUnitCoreParameters( Map<String, String> properties ); boolean isParallelMethods(); boolean isParallelClasses(); boolean isParallelSuites(); @Deprecated @SuppressWarnings( "unused" ) boolean isParallelBoth(); boolean isPerCoreThreadCount(); int getThreadCount(); int getThreadCountMethods(); int getThreadCountClasses(); int getThreadCountSuites(); boolean isUseUnlimitedThreads(); double getParallelTestsTimeoutInSeconds(); double getParallelTestsTimeoutForcedInSeconds(); boolean isNoThreading(); boolean isParallelismSelected(); boolean isParallelOptimization(); @Override String toString(); static final String PARALLEL_KEY; static final String PERCORETHREADCOUNT_KEY; static final String THREADCOUNT_KEY; static final String THREADCOUNTSUITES_KEY; static final String THREADCOUNTCLASSES_KEY; static final String THREADCOUNTMETHODS_KEY; static final String USEUNLIMITEDTHREADS_KEY; static final String PARALLEL_TIMEOUT_KEY; static final String PARALLEL_TIMEOUTFORCED_KEY; static final String PARALLEL_OPTIMIZE_KEY; }### Answer: @Test public void isAnyParallelismSelected() { assertTrue( newTestSetClasses().isParallelismSelected() ); assertTrue( newTestSetMethods().isParallelismSelected() ); assertTrue( newTestSetBoth().isParallelismSelected() ); }
### Question: JUnit4Provider extends AbstractProvider { static Description createTestsDescription( Iterable<Class<?>> classes ) { Description description = createDescription( "null" ); for ( Class<?> clazz : classes ) { description.addChild( createDescription( clazz.getName() ) ); } return description; } JUnit4Provider( ProviderParameters bootParams ); @Override RunResult invoke( Object forkTestSet ); @Override Iterable<Class<?>> getSuites(); }### Answer: @Test public void testShouldCreateDescription() { class A { } class B { } Description d = JUnit4Provider.createTestsDescription( asList( A.class, B.class ) ); assertThat( d, is( notNullValue() ) ); assertThat( d.getDisplayName(), not( isEmptyOrNullString() ) ); assertThat( d.getDisplayName(), is( "null" ) ); assertThat( d.getChildren(), hasSize( 2 ) ); Description a = createSuiteDescription( A.class ); Description b = createSuiteDescription( B.class ); assertThat( d.getChildren(), contains( a, b ) ); }
### Question: BooterDeserializer { public StartupConfiguration getStartupConfiguration() { boolean useSystemClassLoader = properties.getBooleanProperty( USESYSTEMCLASSLOADER ); boolean useManifestOnlyJar = properties.getBooleanProperty( USEMANIFESTONLYJAR ); String providerConfiguration = properties.getProperty( PROVIDER_CONFIGURATION ); ClassLoaderConfiguration classLoaderConfiguration = new ClassLoaderConfiguration( useSystemClassLoader, useManifestOnlyJar ); ClasspathConfiguration classpathConfiguration = new ClasspathConfiguration( properties ); String processChecker = properties.getProperty( PROCESS_CHECKER ); ProcessCheckerType processCheckerType = ProcessCheckerType.toEnum( processChecker ); return StartupConfiguration.inForkedVm( providerConfiguration, classpathConfiguration, classLoaderConfiguration, processCheckerType ); } BooterDeserializer( InputStream inputStream ); @Nonnull String getConnectionString(); String getPluginPid(); ProviderConfiguration deserialize(); StartupConfiguration getStartupConfiguration(); }### Answer: @Test public void testStartupConfiguration() throws IOException { InputStream is = new StringBufferInputStream( PROCESS_CHECKER + "=all\n" + USESYSTEMCLASSLOADER + "=true\n" + PROVIDER_CONFIGURATION + "=abc.MyProvider" ); BooterDeserializer deserializer = new BooterDeserializer( is ); assertThat( deserializer.getStartupConfiguration().getProcessChecker() ) .isEqualTo( ALL ); assertThat( deserializer.getStartupConfiguration().getClassLoaderConfiguration().isUseSystemClassLoader() ) .isTrue(); assertThat( deserializer.getStartupConfiguration().getProviderClassName() ) .isEqualTo( "abc.MyProvider" ); }
### Question: IsolatedClassLoader extends URLClassLoader { @Override public synchronized Class loadClass( String name ) throws ClassNotFoundException { if ( childDelegation ) { Class<?> c = findLoadedClass( name ); if ( c == null ) { try { c = findClass( name ); } catch ( ClassNotFoundException e ) { if ( parent == null ) { throw e; } else { c = parent.loadClass( name ); } } } return c; } else { return super.loadClass( name ); } } IsolatedClassLoader( ClassLoader parent, boolean childDelegation, String roleName ); @Override @Deprecated void addURL( URL url ); @Override synchronized Class loadClass( String name ); @Override String toString(); }### Answer: @Test public void shouldLoadIsolatedClass() throws Exception { Class<?> isolatedClass = classLoader.loadClass( AbstractProvider.class.getName() ); assertThat( isolatedClass, is( notNullValue() ) ); assertThat( isolatedClass.getName(), is( AbstractProvider.class.getName() ) ); assertThat( isolatedClass, is( not( (Class) AbstractProvider.class ) ) ); }
### Question: CommandReader implements CommandChainReader { Iterable<String> getIterableClasses( MasterProcessChannelEncoder eventChannel ) { return new ClassesIterable( eventChannel ); } CommandReader( MasterProcessChannelDecoder decoder, Shutdown shutdown, ConsoleLogger logger ); @Override boolean awaitStarted(); @Override void addSkipNextTestsListener( CommandListener listener ); @Override void addShutdownListener( CommandListener listener ); void addNoopListener( CommandListener listener ); void addByeAckListener( CommandListener listener ); void stop(); }### Answer: @Test public void manyClasses() { Iterator<String> it1 = reader.getIterableClasses( new LegacyMasterProcessChannelEncoder( nul() ) ).iterator(); assertThat( it1.next(), is( getClass().getName() ) ); addTestToPipeline( A.class.getName() ); assertThat( it1.next(), is( A.class.getName() ) ); addTestToPipeline( B.class.getName() ); assertThat( it1.next(), is( B.class.getName() ) ); addTestToPipeline( C.class.getName() ); assertThat( it1.next(), is( C.class.getName() ) ); addEndOfPipeline(); addTestToPipeline( D.class.getName() ); assertFalse( it1.hasNext() ); } @Test public void readTwoClassesInThread() throws Throwable { final CountDownLatch counter = new CountDownLatch( 1 ); Runnable runnable = new Runnable() { @Override public void run() { Iterator<String> it = reader.getIterableClasses( new LegacyMasterProcessChannelEncoder( nul() ) ).iterator(); assertThat( it.next(), is( CommandReaderTest.class.getName() ) ); counter.countDown(); assertThat( it.next(), is( Foo.class.getName() ) ); } }; FutureTask<Object> futureTask = new FutureTask<>( runnable, null ); Thread t = new Thread( futureTask ); t.start(); counter.await(); addTestToPipeline( Foo.class.getName() ); try { futureTask.get(); } catch ( ExecutionException e ) { throw e.getCause(); } }
### Question: ScannerUtil { @Nonnull public static String convertJarFileResourceToJavaClassName( @Nonnull String test ) { return StringUtils.removeEnd( test, ".class" ).replace( "/", "." ); } private ScannerUtil(); @Nonnull static String convertJarFileResourceToJavaClassName( @Nonnull String test ); static boolean isJavaClassFile( String file ); @Deprecated @Nonnull static String convertSlashToSystemFileSeparator( @Nonnull String path ); }### Answer: @Test public void shouldConvertJarFileResourceToJavaClassName() { String className = ScannerUtil.convertJarFileResourceToJavaClassName( "org/apache/pkg/MyService.class" ); assertThat( className ) .isEqualTo( "org.apache.pkg.MyService" ); className = ScannerUtil.convertJarFileResourceToJavaClassName( "META-INF/MANIFEST.MF" ); assertThat( className ) .isEqualTo( "META-INF.MANIFEST.MF" ); }
### Question: PpidChecker { static boolean canExecuteUnixPs() { return canExecuteLocalUnixPs() || canExecuteStandardUnixPs(); } PpidChecker( @Nonnull String ppid ); void stop(); @Override String toString(); }### Answer: @Test public void canExecuteUnixPs() { assumeTrue( IS_OS_UNIX ); assertThat( PpidChecker.canExecuteUnixPs() ) .as( "Surefire should be tested on real box OS, e.g. Ubuntu or FreeBSD." ) .isTrue(); }
### Question: EventConsumerThread extends CloseableDaemonThread { protected int readInt( Memento memento ) throws IOException, MalformedFrameException { read( memento, INT_LENGTH + DELIMITER_LENGTH ); int i = memento.bb.getInt(); checkDelimiter( memento ); return i; } EventConsumerThread( @Nonnull String threadName, @Nonnull ReadableByteChannel channel, @Nonnull EventHandler<Event> eventHandler, @Nonnull CountdownCloseable countdownCloseable, @Nonnull ForkNodeArguments arguments ); @Override void run(); @Override void disable(); @Override void close(); }### Answer: @Test public void shouldReadInt() throws Exception { Channel channel = new Channel( new byte[] {0x01, 0x02, 0x03, 0x04, ':'}, 1 ); EventConsumerThread thread = new EventConsumerThread( "t", channel, new MockEventHandler<Event>(), COUNTDOWN_CLOSEABLE, new MockForkNodeArguments() ); Memento memento = thread.new Memento(); memento.bb.position( 0 ).limit( 0 ); assertThat( thread.readInt( memento ) ) .isEqualTo( new BigInteger( new byte[] {0x01, 0x02, 0x03, 0x04} ).intValue() ); }
### Question: EventConsumerThread extends CloseableDaemonThread { protected Integer readInteger( Memento memento ) throws IOException, MalformedFrameException { read( memento, BYTE_LENGTH ); boolean isNullObject = memento.bb.get() == 0; if ( isNullObject ) { read( memento, DELIMITER_LENGTH ); checkDelimiter( memento ); return null; } return readInt( memento ); } EventConsumerThread( @Nonnull String threadName, @Nonnull ReadableByteChannel channel, @Nonnull EventHandler<Event> eventHandler, @Nonnull CountdownCloseable countdownCloseable, @Nonnull ForkNodeArguments arguments ); @Override void run(); @Override void disable(); @Override void close(); }### Answer: @Test public void shouldReadInteger() throws Exception { Channel channel = new Channel( new byte[] {(byte) 0xff, 0x01, 0x02, 0x03, 0x04, ':'}, 1 ); EventConsumerThread thread = new EventConsumerThread( "t", channel, new MockEventHandler<Event>(), COUNTDOWN_CLOSEABLE, new MockForkNodeArguments() ); Memento memento = thread.new Memento(); memento.bb.position( 0 ).limit( 0 ); assertThat( thread.readInteger( memento ) ) .isEqualTo( new BigInteger( new byte[] {0x01, 0x02, 0x03, 0x04} ).intValue() ); } @Test public void shouldReadNullInteger() throws Exception { Channel channel = new Channel( new byte[] {(byte) 0x00, ':'}, 1 ); EventConsumerThread thread = new EventConsumerThread( "t", channel, new MockEventHandler<Event>(), COUNTDOWN_CLOSEABLE, new MockForkNodeArguments() ); Memento memento = thread.new Memento(); memento.bb.position( 0 ).limit( 0 ); assertThat( thread.readInteger( memento ) ) .isNull(); }
### Question: ScannerUtil { public static boolean isJavaClassFile( String file ) { return file.endsWith( ".class" ); } private ScannerUtil(); @Nonnull static String convertJarFileResourceToJavaClassName( @Nonnull String test ); static boolean isJavaClassFile( String file ); @Deprecated @Nonnull static String convertSlashToSystemFileSeparator( @Nonnull String path ); }### Answer: @Test public void shouldBeClassFile() { assertThat( ScannerUtil.isJavaClassFile( "META-INF/MANIFEST.MF" ) ) .isFalse(); assertThat( ScannerUtil.isJavaClassFile( "org/apache/pkg/MyService.class" ) ) .isTrue(); }
### Question: EventConsumerThread extends CloseableDaemonThread { static Map<Segment, RunMode> mapRunModes() { Map<Segment, RunMode> map = new HashMap<>(); for ( RunMode e : RunMode.values() ) { byte[] array = e.geRunmode().getBytes( US_ASCII ); map.put( new Segment( array, 0, array.length ), e ); } return map; } EventConsumerThread( @Nonnull String threadName, @Nonnull ReadableByteChannel channel, @Nonnull EventHandler<Event> eventHandler, @Nonnull CountdownCloseable countdownCloseable, @Nonnull ForkNodeArguments arguments ); @Override void run(); @Override void disable(); @Override void close(); }### Answer: @Test public void shouldMapSegmentToEventType() { Map<Segment, RunMode> map = mapRunModes(); assertThat( map ) .hasSize( 2 ); byte[] stream = "normal-run".getBytes( US_ASCII ); Segment segment = new Segment( stream, 0, stream.length ); assertThat( map.get( segment ) ) .isEqualTo( NORMAL_RUN ); stream = "rerun-test-after-failure".getBytes( US_ASCII ); segment = new Segment( stream, 0, stream.length ); assertThat( map.get( segment ) ) .isEqualTo( RERUN_TEST_AFTER_FAILURE ); }
### Question: StreamFeeder extends CloseableDaemonThread { public static byte[] encode( MasterProcessCommand cmdType, String data ) { if ( !cmdType.hasDataType() ) { throw new IllegalArgumentException( "cannot use data without data type" ); } if ( cmdType.getDataType() != String.class ) { throw new IllegalArgumentException( "Data type can be only " + String.class ); } return encode( COMMAND_OPCODES.get( cmdType ), data ) .toString() .getBytes( US_ASCII ); } StreamFeeder( @Nonnull String threadName, @Nonnull WritableByteChannel channel, @Nonnull CommandReader commandReader, @Nonnull ConsoleLogger logger ); @Override @SuppressWarnings( "checkstyle:innerassignment" ) void run(); void disable(); Throwable getException(); @Override void close(); static byte[] encode( MasterProcessCommand cmdType, String data ); static byte[] encode( MasterProcessCommand cmdType ); }### Answer: @Test( expected = IllegalArgumentException.class ) public void shouldFailWithoutData() { StreamFeeder.encode( RUN_CLASS ); } @Test( expected = IllegalArgumentException.class ) public void shouldFailWithData() { StreamFeeder.encode( NOOP, "" ); }
### Question: JarManifestForkConfiguration extends AbstractClasspathForkConfiguration { static String relativize( @Nonnull Path parent, @Nonnull Path child ) throws IllegalArgumentException { return parent.relativize( child ) .toString(); } @SuppressWarnings( "checkstyle:parameternumber" ) JarManifestForkConfiguration( @Nonnull Classpath bootClasspath, @Nonnull File tempDirectory, @Nullable String debugLine, @Nonnull File workingDirectory, @Nonnull Properties modelProperties, @Nullable String argLine, @Nonnull Map<String, String> environmentVariables, @Nonnull String[] excludedEnvironmentVariables, boolean debug, int forkCount, boolean reuseForks, @Nonnull Platform pluginPlatform, @Nonnull ConsoleLogger log, @Nonnull ForkNodeFactory forkNodeFactory ); }### Answer: @Test public void shouldRelativizeOnRealPlatform() { Path parentDir = new File( TMP, "test-parent-1" ) .toPath(); Path testDir = new File( TMP, "@1 test with white spaces" ) .toPath(); String relativeTestDir = relativize( parentDir, testDir ); assertThat( relativeTestDir ) .isEqualTo( ".." + File.separator + "@1 test with white spaces" ); }
### Question: JarManifestForkConfiguration extends AbstractClasspathForkConfiguration { static String toAbsoluteUri( @Nonnull Path absolutePath ) { return absolutePath.toUri() .toASCIIString(); } @SuppressWarnings( "checkstyle:parameternumber" ) JarManifestForkConfiguration( @Nonnull Classpath bootClasspath, @Nonnull File tempDirectory, @Nullable String debugLine, @Nonnull File workingDirectory, @Nonnull Properties modelProperties, @Nullable String argLine, @Nonnull Map<String, String> environmentVariables, @Nonnull String[] excludedEnvironmentVariables, boolean debug, int forkCount, boolean reuseForks, @Nonnull Platform pluginPlatform, @Nonnull ConsoleLogger log, @Nonnull ForkNodeFactory forkNodeFactory ); }### Answer: @Test public void shouldMakeAbsoluteUriOnRealPlatform() throws Exception { Path testDir = new File( TMP, "@2 test with white spaces" ) .toPath(); URI testDirUri = new URI( toAbsoluteUri( testDir ) ); assertThat( testDirUri.getScheme() ) .isEqualTo( "file" ); assertThat( testDirUri.getRawPath() ) .isEqualTo( testDir.toUri().getRawPath() ); }
### Question: JarManifestForkConfiguration extends AbstractClasspathForkConfiguration { static ClasspathElementUri toClasspathElementUri( @Nonnull Path parent, @Nonnull Path classPathElement, @Nonnull File dumpLogDirectory, boolean dumpError ) { try { String relativePath = relativize( parent, classPathElement ); return relative( escapeUri( relativePath, UTF_8 ) ); } catch ( IllegalArgumentException e ) { if ( dumpError ) { String error = "Boot Manifest-JAR contains absolute paths in classpath '" + classPathElement + "'" + NL + "Hint: <argLine>-Djdk.net.URLClassPath.disableClassPathURLCheck=true</argLine>"; InPluginProcessDumpSingleton.getSingleton() .dumpStreamText( error, dumpLogDirectory ); } return absolute( toAbsoluteUri( classPathElement ) ); } } @SuppressWarnings( "checkstyle:parameternumber" ) JarManifestForkConfiguration( @Nonnull Classpath bootClasspath, @Nonnull File tempDirectory, @Nullable String debugLine, @Nonnull File workingDirectory, @Nonnull Properties modelProperties, @Nullable String argLine, @Nonnull Map<String, String> environmentVariables, @Nonnull String[] excludedEnvironmentVariables, boolean debug, int forkCount, boolean reuseForks, @Nonnull Platform pluginPlatform, @Nonnull ConsoleLogger log, @Nonnull ForkNodeFactory forkNodeFactory ); }### Answer: @Test public void shouldMakeRelativeUriOnRealPlatform() throws Exception { Path parentDir = new File( TMP, "test-parent-2" ) .toPath(); Path testDir = new File( TMP, "@3 test with white spaces" ) .toPath(); ClasspathElementUri testDirUriPath = toClasspathElementUri( parentDir, testDir, dumpDirectory, true ); assertThat( testDirUriPath.uri ) .isEqualTo( "../%403%20test%20with%20white%20spaces" ); }
### Question: ForkClient implements EventHandler<Event> { @Override public final void handleEvent( @Nonnull Event event ) { notifier.notifyEvent( event ); } ForkClient( DefaultReporterFactory defaultReporterFactory, NotifiableTestStream notifiableTestStream, int forkNumber ); void kill(); final void tryToTimeout( long currentTimeMillis, int forkedProcessTimeoutInSeconds ); final DefaultReporterFactory getDefaultReporterFactory(); @Override final void handleEvent( @Nonnull Event event ); final boolean hadTimeout(); final Map<String, String> getTestVmSystemProperties(); final RunListener getReporter(); void close( boolean hadTimeout ); final boolean isSaidGoodBye(); final StackTraceWriter getErrorInFork(); final boolean isErrorInFork(); Set<String> testsInProgress(); boolean hasTestsInProgress(); }### Answer: @Test( expected = NullPointerException.class ) public void shouldFailOnNPE() { String cwd = System.getProperty( "user.dir" ); File target = new File( cwd, "target" ); DefaultReporterFactory factory = mock( DefaultReporterFactory.class ); when( factory.getReportsDirectory() ) .thenReturn( new File( target, "surefire-reports" ) ); ForkClient client = new ForkClient( factory, null, 0 ); client.handleEvent( null ); }
### Question: ForkClient implements EventHandler<Event> { public void kill() { if ( !saidGoodBye ) { notifiableTestStream.shutdown( KILL ); } } ForkClient( DefaultReporterFactory defaultReporterFactory, NotifiableTestStream notifiableTestStream, int forkNumber ); void kill(); final void tryToTimeout( long currentTimeMillis, int forkedProcessTimeoutInSeconds ); final DefaultReporterFactory getDefaultReporterFactory(); @Override final void handleEvent( @Nonnull Event event ); final boolean hadTimeout(); final Map<String, String> getTestVmSystemProperties(); final RunListener getReporter(); void close( boolean hadTimeout ); final boolean isSaidGoodBye(); final StackTraceWriter getErrorInFork(); final boolean isErrorInFork(); Set<String> testsInProgress(); boolean hasTestsInProgress(); }### Answer: @Test public void shouldBePossibleToKill() { NotifiableTestStream notifiableTestStream = mock( NotifiableTestStream.class ); ForkClient client = new ForkClient( null, notifiableTestStream, 0 ); client.kill(); verify( notifiableTestStream, times( 1 ) ) .shutdown( eq( Shutdown.KILL ) ); }
### Question: ThreadedStreamConsumer implements EventHandler<Event>, Closeable { public ThreadedStreamConsumer( EventHandler<Event> target ) { pumper = new Pumper( target ); Thread thread = newDaemonThread( pumper, "ThreadedStreamConsumer" ); thread.start(); } ThreadedStreamConsumer( EventHandler<Event> target ); @Override void handleEvent( @Nonnull Event event ); @Override void close(); }### Answer: @Test public void testThreadedStreamConsumer() throws Exception { final CountDownLatch countDown = new CountDownLatch( 5_000_000 ); EventHandler<Event> handler = new EventHandler<Event>() { @Override public void handleEvent( @Nonnull Event event ) { countDown.countDown(); } }; ThreadedStreamConsumer streamConsumer = new ThreadedStreamConsumer( handler ); SECONDS.sleep( 1 ); System.gc(); SECONDS.sleep( 2 ); long t1 = System.currentTimeMillis(); Event event = new StandardStreamOutWithNewLineEvent( NORMAL_RUN, "" ); for ( int i = 0; i < 5_000_000; i++ ) { streamConsumer.handleEvent( event ); } assertThat( countDown.await( 3L, SECONDS ) ) .isTrue(); long t2 = System.currentTimeMillis(); System.out.println( ( t2 - t1 ) + " millis in testThreadedStreamConsumer()" ); streamConsumer.close(); }
### Question: ConsoleLoggerUtils { public static String toString( Throwable t ) { return toString( null, t ); } private ConsoleLoggerUtils(); static String toString( Throwable t ); static String toString( String message, Throwable t ); }### Answer: @Test public void shouldPrintStacktraceAsString() { Exception e = new IllegalArgumentException( "wrong param" ); String msg = ConsoleLoggerUtils.toString( e ); StringWriter text = new StringWriter(); PrintWriter writer = new PrintWriter( text ); e.printStackTrace( writer ); String s = text.toString(); assertThat( msg ) .isEqualTo( s ); } @Test public void shouldPrintStacktracWithMessageAsString() { Exception e = new IllegalArgumentException( "wrong param" ); String msg = ConsoleLoggerUtils.toString( "issue", e ); StringWriter text = new StringWriter(); PrintWriter writer = new PrintWriter( text ); writer.println( "issue" ); e.printStackTrace( writer ); String s = text.toString(); assertThat( msg ) .isEqualTo( s ); }
### Question: ReflectionUtils { public static Class<?> reloadClass( ClassLoader classLoader, Object source ) throws ReflectiveOperationException { return classLoader.loadClass( source.getClass().getName() ); } private ReflectionUtils(); static Method getMethod( Object instance, String methodName, Class<?>... parameters ); static Method getMethod( Class<?> clazz, String methodName, Class<?>... parameters ); static Method tryGetMethod( Class<?> clazz, String methodName, Class<?>... parameters ); static Object invokeGetter( Object instance, String methodName ); static Object invokeGetter( Class<?> instanceType, Object instance, String methodName ); static Constructor<?> getConstructor( Class<?> clazz, Class<?>... arguments ); static Object newInstance( Constructor<?> constructor, Object... params ); static T instantiate( ClassLoader classLoader, String classname, Class<T> returnType ); static Object instantiateOneArg( ClassLoader classLoader, String className, Class<?> param1Class, Object param1 ); static void invokeSetter( Object o, String name, Class<?> value1clazz, Object value ); static Object invokeSetter( Object target, Method method, Object value ); static Object invokeMethodWithArray( Object target, Method method, Object... args ); static Object invokeMethodWithArray2( Object target, Method method, Object... args ); static Object instantiateObject( String className, Class<?>[] types, Object[] params, ClassLoader cl ); @SuppressWarnings( "checkstyle:emptyblock" ) static Class<?> tryLoadClass( ClassLoader classLoader, String className ); static Class<?> loadClass( ClassLoader classLoader, String className ); static Class<?> reloadClass( ClassLoader classLoader, Object source ); static Object invokeStaticMethod( Class<?> clazz, String methodName, Class<?>[] parameterTypes, Object[] parameters ); static Object invokeMethodChain( Class<?>[] classesChain, String[] noArgMethodNames, Object fallback ); }### Answer: @Test public void shouldReloadClass() throws Exception { ClassLoader cl = Thread.currentThread().getContextClassLoader(); assertThat( ReflectionUtils.reloadClass( cl, new B() ) ) .isEqualTo( B.class ); }
### Question: SurefireHelper { public static String[] getDumpFilesToPrint() { return DUMP_FILES_PRINT.clone(); } private SurefireHelper(); @Nonnull static String replaceThreadNumberPlaceholders( @Nonnull String argLine, int threadNumber ); static File replaceForkThreadsInPath( File path, int replacement ); static String[] getDumpFilesToPrint(); static void reportExecution( SurefireReportParameters reportParameters, RunResult result, PluginConsoleLogger log, Exception firstForkException ); static List<CommandLineOption> commandLineOptions( MavenSession session, PluginConsoleLogger log ); static void logDebugOrCliShowErrors( String s, PluginConsoleLogger log, Collection<CommandLineOption> cli ); static String escapeToPlatformPath( String path ); static final String DUMP_FILE_PREFIX; static final String DUMP_FILENAME_FORMATTER; static final String DUMPSTREAM_FILENAME_FORMATTER; static final String DUMPSTREAM_FILENAME; static final String DUMP_FILENAME; }### Answer: @Test public void shouldBeThreeDumpFiles() { String[] dumps = SurefireHelper.getDumpFilesToPrint(); assertThat( dumps ).hasSize( 4 ); assertThat( dumps ).doesNotHaveDuplicates(); List<String> onlyStrings = new ArrayList<>(); addAll( onlyStrings, dumps ); onlyStrings.removeAll( singleton( (String) null ) ); assertThat( onlyStrings ).hasSize( 4 ); } @Test public void shouldCloneDumpFiles() { String[] dumps1 = SurefireHelper.getDumpFilesToPrint(); String[] dumps2 = SurefireHelper.getDumpFilesToPrint(); assertThat( dumps1 ).isNotSameAs( dumps2 ); }
### Question: RESTGatewayUtil { public static boolean isXml(String contentType) { return contentType != null && (contentType.startsWith(Constants.TEXT_XML) || contentType.startsWith(Constants.APPLICATION_XML)); } private RESTGatewayUtil(); static boolean isXml(String contentType); static boolean isValidContentType(String contentType); static void extractEndpoints(String key, Properties endpoints, AbstractEndpoint endpoint); static boolean isNullOrEmpty(String value); static Decrypter checkPrivateKey(Properties props); static Decrypter getDecrypter(String privateKeyFile, String privateKeyFilePassword, String privateKeyAlias, String privateKeyPassword); static Encrypter checkPublicKey(Properties props, String serviceId); static Encrypter getEncrypter(String publicKeyFile, String publicKeyFilePassword, String serviceId); static int getKeyLength(Properties props); static Encrypter createSymmetricEncrypter(int keyLength); static Decrypter getSymmetricDecrypter(Decrypter asymmetricDecrypter, String encryptedKey, String encodedIV); static void buildEncryptedBody(Encrypter symmetricEncrypter, Encrypter asymmetricEncrypter, SOAPElement msg, String encryptedData); static String getPropertiesDirectory(); static final int DEFAULT_KEY_LENGTH; }### Answer: @Test public void testIsXml1() { assertEquals(false, RESTGatewayUtil.isXml(null)); } @Test public void testIsXml2() { assertEquals(false, RESTGatewayUtil.isXml("")); } @Test public void testIsXml3() { assertEquals(true, RESTGatewayUtil.isXml("text/xml")); } @Test public void testIsXml4() { assertEquals(false, RESTGatewayUtil.isXml("application/json")); } @Test public void testIsXml5() { assertEquals(false, RESTGatewayUtil.isXml("application/XML")); } @Test public void testIsXml6() { assertEquals(false, RESTGatewayUtil.isXml("text/html")); }
### Question: SkippableLogRecord implements WritableComparable<SkippableLogRecord> { public boolean isSkipped() { return jvm.toString() == null || jvm.toString().isEmpty(); } SkippableLogRecord(); SkippableLogRecord(Text line); Text getJvm(); IntWritable getDay(); IntWritable getMonth(); IntWritable getYear(); Text getRoot(); Text getFilename(); Text getPath(); IntWritable getStatus(); LongWritable getSize(); boolean isSkipped(); @Override void readFields(DataInput in); @Override void write(DataOutput out); @Override int compareTo(SkippableLogRecord other); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer: @Test public void testReadLineForOtherApp() { String line = "https-other aac.alliedinsurance.com 0 155.188.183.17 - - [27/Feb/2015:07:18:04 -0600] " + "\"GET /download/IT%20Tech%20Writing%20Only/PL%20NB%20Billing%20Changes%20Feb%202015%20TipSheet.pdf " + "HTTP/1.1\" 200 207773 \"https: + "(compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; " + ".NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET CLR 1.1.4322; .NET4.0C; " + ".NET4.0E; InfoPath.2)\""; SkippableLogRecord rec = new SkippableLogRecord(new Text(line)); assertTrue(rec.isSkipped()); }
### Question: Trie { public String longestPrefix(String inputWord) { if (inputWord == null || inputWord.isEmpty()) { return null; } Node node = root; Node child = null; char ch = '\u0000'; final int len = inputWord.length(); StringBuilder runningPrefix = new StringBuilder(); String longestPrefix = null; for (int idx = 0; idx < len; idx++) { ch = inputWord.charAt(idx); child = node.getChild(ch); if (node.isEndOfWord) { longestPrefix = runningPrefix.toString(); } if (child != null) { runningPrefix.append(ch); node = child; } else { break; } } if (node.isEndOfWord && node.getChild(ch) == null && ch == node.value) { longestPrefix = runningPrefix.toString(); } return longestPrefix; } Trie(String[] words); String longestPrefix(String inputWord); }### Answer: @Test public void testLongestPrefix1() { trie = new Trie(new String[] { "abc", "abcd", "abcdde" }); Assert.assertEquals("abcd", trie.longestPrefix("abcdd")); } @Test public void testLongestPrefix2() { trie = new Trie(new String[] { "are", "area", "base", "cat", "cater", "basement" }); Assert.assertEquals("cater", trie.longestPrefix("caterer")); Assert.assertEquals("basement", trie.longestPrefix("basement")); Assert.assertEquals("are", trie.longestPrefix("are")); Assert.assertEquals("are", trie.longestPrefix("arex")); Assert.assertEquals("base", trie.longestPrefix("basemexz")); Assert.assertNull(trie.longestPrefix("xyz")); Assert.assertNull(trie.longestPrefix("")); Assert.assertNull(trie.longestPrefix(null)); Assert.assertNull(trie.longestPrefix(" ")); }
### Question: PracticeQuestionsCh11 { public static int firstOccurrence(final int[] arr, final int key) { int index = -1; int left = 0; int right = arr.length - 1; if (right < 0 || arr[right] <= key) { return index; } int mid = left + ((right - left) >>> 1); for (; left <= right; mid = left + ((right - left) >>> 1)) { if (arr[mid] > key) { index = mid; right = mid - 1; } else { left = mid + 1; } } return index; } static int firstOccurrence(final int[] arr, final int key); static final Logger LOGGER; }### Answer: @Test public void testFirstOccurance() { final int[] arr = { -1, -10, 2, 108, 108, 243, 285, 285, 285, 401 }; Assert.assertEquals(-1, firstOccurrence(arr, 500)); Assert.assertEquals(3, firstOccurrence(arr, 101)); }
### Question: PracticeQuestionsCh13 { public static Integer[] intersection(final int[] a, final int[] b) { Integer[] intersection = null; if (a.length < b.length) { intersection = findIntersection(a, b); } else { intersection = findIntersection(b, a); } return intersection; } static Integer[] intersection(final int[] a, final int[] b); static final Logger LOGGER; }### Answer: @Test public void testIntersection() { int[] a = { -2, -1, 5, 7, 11 }; int[] b = { 0, 1, 5, 7, 13 }; Assert.assertArrayEquals(new Integer[] { 5, 7 }, intersection(a, b)); }
### Question: PracticeQuestionsCh10 { public static int[] kSort(Integer[] arr, int k) { final int size = Math.min(2 * k, arr.length); MinHeap<Integer> minHeap = new MinHeap<Integer>(Arrays.copyOf(arr, size)); int[] sorted = new int[arr.length]; int i = 0; for (int j = size + i; j < arr.length; ++i, ++j) { sorted[i] = minHeap.delete(); minHeap.insert(arr[j]); } for (; minHeap.size() > 0; ++i) { sorted[i] = minHeap.delete(); } return sorted; } static int[] kSort(Integer[] arr, int k); static int[] runningMedian(int[] elements); static final Logger LOGGER; }### Answer: @Test public void testKSort() { final Integer[] arr = { 3, 1, 7, 4, 10 }; final int[] expected = { 1, 3, 4, 7, 10 }; int[] actual = kSort(arr, 2); Assert.assertArrayEquals(expected, actual); actual = kSort(arr, 4); Assert.assertArrayEquals(expected, actual); }
### Question: PracticeQuestionsCh10 { public static int[] runningMedian(int[] elements) { final MinHeap<Integer> minHeap = new MinHeap<Integer>(new Integer[] {}); final MaxHeap<Integer> maxHeap = new MaxHeap<Integer>(new Integer[] {}); final int[] medians = new int[elements.length]; int median = 0; int element = 0; boolean isElementLessThanMedian = false; Heap<Integer> heapWhereElementToBeInserted = null; Heap<Integer> otherHeap = null; for (int i = 0; i < elements.length; ++i) { element = elements[i]; isElementLessThanMedian = element < median; heapWhereElementToBeInserted = heapWhereElementToBeInserted(isElementLessThanMedian, minHeap, maxHeap); otherHeap = heapWhereElementToBeInserted == minHeap ? maxHeap : minHeap; transferTopItemIfRequired(heapWhereElementToBeInserted, otherHeap); heapWhereElementToBeInserted.insert(element); if (isTheSizeOfBothHeapsEqual(minHeap, maxHeap)) { median = average(minHeap.root(), maxHeap.root()); } else { median = heapWhereElementToBeInserted.root(); } medians[i] = median; } return medians; } static int[] kSort(Integer[] arr, int k); static int[] runningMedian(int[] elements); static final Logger LOGGER; }### Answer: @Test public void testRunningMedian() { int[] elements = { 5, 15, 1, 3, 2, 8, 7 }; int[] expected = { 5, 10, 5, 4, 3, 4, 5 }; int[] actual = runningMedian(elements); Assert.assertArrayEquals(expected, actual); }
### Question: PracticeQuestionsCh5 { public static long[] computeParities(final long[] input) { final int numInput = input == null || input.length == 0 ? 0 : input.length; if (numInput == 0) { return input; } final int storage = (int) (numInput >> 6) + 1; final long[] parities = new long[storage]; if (isOddParity(input[0])) { parities[0] ^= 1; } for (int i = 1; i < numInput; i++) { final int section = i >> 6; final int currentIdx = i % 64 - 1; if (isOddParity(input[i])) { parities[section] ^= 1 << currentIdx; } } return parities; } static long[] computeParities(final long[] input); static long swapBits(final long x, final int i, final int j); static void powerSet(Set<Integer> set); static int stringToInt(String s); static String changeBase(String s, int b1, int b2); static final Logger LOGGER; }### Answer: @Test public void testComputeParities() { long[] input = null; Assert.assertNull(computeParities(input)); long[] parities = computeParities(new long[87]); Assert.assertEquals(2, parities.length); input = new long[2]; input[0] = 8L; input[1] = 9L; parities = computeParities(input); Assert.assertEquals(1, parities.length); Assert.assertEquals(1, parities[0]); }
### Question: PracticeQuestionsCh5 { public static long swapBits(final long x, final int i, final int j) { if (j <= i || i < 0 || j > 63) { return x; } final long mask1 = 1L << i; final long mask2 = 1L << j; final long mask = mask1 | mask2; return x ^ mask; } static long[] computeParities(final long[] input); static long swapBits(final long x, final int i, final int j); static void powerSet(Set<Integer> set); static int stringToInt(String s); static String changeBase(String s, int b1, int b2); static final Logger LOGGER; }### Answer: @Test public void testSwapBits() { Assert.assertEquals(2, swapBits(2, 1, 1)); Assert.assertEquals(2, swapBits(2, -1, 1)); Assert.assertEquals(2, swapBits(2, 1, 65)); Assert.assertEquals(1, swapBits(2, 0, 1)); Assert.assertEquals(14, swapBits(7, 0, 3)); }
### Question: PracticeQuestionsCh5 { public static void powerSet(Set<Integer> set) { if (set == null) { LOGGER.info("Null input."); return; } LOGGER.info("{}.", set.toString()); LOGGER.info("{" + "Ø" + "}"); final Integer[] elements = set.toArray(new Integer[] {}); final int numElements = elements.length; final StringBuilder identitySet = new StringBuilder(); for (int currentIdx = 0; currentIdx < numElements; currentIdx++) { int currentElement = elements[currentIdx]; identitySet.append(currentElement); if (currentIdx != numElements - 1) { identitySet.append(", "); } for (int lookAheadIdx = currentIdx + 1; lookAheadIdx < numElements; lookAheadIdx++) { int lookAheadElement = elements[lookAheadIdx]; LOGGER.info("{" + "{}, {}" + "}.", currentElement, lookAheadElement); } } LOGGER.info("{" + "{}" + "}.", identitySet.toString()); } static long[] computeParities(final long[] input); static long swapBits(final long x, final int i, final int j); static void powerSet(Set<Integer> set); static int stringToInt(String s); static String changeBase(String s, int b1, int b2); static final Logger LOGGER; }### Answer: @SuppressWarnings("unchecked") @Test public void testPowerSet() { powerSet(null); powerSet(Collections.EMPTY_SET); Set<Integer> set = new HashSet<>(); set.add(1); set.add(2); set.add(3); powerSet(set); }