src_fm_fc_ms_ff
stringlengths 43
86.8k
| target
stringlengths 20
276k
|
---|---|
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; } | @Test @Ignore("Need a running Docker daemon") public void testRestartContainer() throws Exception { dockerClient.restart("test", 30); } |
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; } | @Test @Ignore("Need a running Docker daemon") public void testKillContainer() throws Exception { dockerClient.kill("test", "SIGKILL"); } |
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; } | @Test @Ignore("Need a running Docker daemon") public void testRemoveContainer() throws Exception { dockerClient.rm("test", true, true); } |
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; } | @Test @Ignore("Need a running Docker daemon") public void testRenameContainer() throws Exception { dockerClient.rename("test", "karaf-test"); } |
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; } | @Test @Ignore("Need a running Docker daemon") public void testPauseContainer() throws Exception { dockerClient.pause("test"); } |
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; } | @Test @Ignore("Need a running Docker daemon") public void testUnpauseContainer() throws Exception { dockerClient.unpause("test"); } |
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 + "×tamps=" + 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; } | @Test @Ignore("Need a running Docker daemon") public void testContainerLog() throws Exception { System.out.println(dockerClient.logs("test", true, true, true, true)); } |
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; } | @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(); } } |
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); } | @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)); } |
DockerServiceImpl implements DockerService { @Override public void provision(String name, String sshPort, String jmxRmiPort, String jmxRmiRegistryPort, String httpPort, boolean copy, String url) throws Exception { pull("java", "8-jre-alpine", true, url); File karafBase = new File(System.getProperty("karaf.base")); File containerStorage; if (copy) { containerStorage = new File(storageLocation, name); containerStorage.mkdirs(); copy(karafBase, containerStorage); makeFileExecutable(new File(containerStorage, "bin/karaf")); makeFileExecutable(new File(containerStorage, "bin/client")); makeFileExecutable(new File(containerStorage, "bin/inc")); makeFileExecutable(new File(containerStorage, "bin/instance")); makeFileExecutable(new File(containerStorage, "bin/setenv")); makeFileExecutable(new File(containerStorage, "bin/shell")); makeFileExecutable(new File(containerStorage, "bin/start")); makeFileExecutable(new File(containerStorage, "bin/status")); makeFileExecutable(new File(containerStorage, "bin/stop")); } else { containerStorage = karafBase; } DockerClient dockerClient = new DockerClient(url); ContainerConfig config = new ContainerConfig(); config.setTty(true); config.setAttachStdout(true); config.setAttachStderr(true); config.setAttachStdin(true); config.setImage("java:8-jre-alpine"); config.setHostname(""); config.setUser(""); config.setCmd(new String[]{ "/opt/apache-karaf/bin/karaf" }); config.setWorkingDir(""); config.setOpenStdin(true); config.setStdinOnce(true); Map<String, Map<String, String>> exposedPorts = new HashMap<>(); exposedPorts.put("8101/tcp", new HashMap<>()); exposedPorts.put("1099/tcp", new HashMap<>()); exposedPorts.put("44444/tcp", new HashMap<>()); exposedPorts.put("8181/tcp", new HashMap<>()); config.setExposedPorts(exposedPorts); HostConfig hostConfig = new HostConfig(); hostConfig.setPrivileged(false); hostConfig.setPublishAllPorts(false); hostConfig.setBinds(new String[]{containerStorage.getAbsolutePath() + ":/opt/apache-karaf"}); hostConfig.setNetworkMode("bridge"); hostConfig.setLxcConf(new String[]{}); Map<String, List<HostPortBinding>> portBindings = new HashMap<>(); List<HostPortBinding> sshPortBindings = new ArrayList<>(); HostPortBinding sshPortBinding = new HostPortBinding(); sshPortBinding.setHostIp(""); sshPortBinding.setHostPort(sshPort); sshPortBindings.add(sshPortBinding); portBindings.put("8101/tcp", sshPortBindings); List<HostPortBinding> jmxPortBindings = new ArrayList<>(); HostPortBinding jmxPortBinding = new HostPortBinding(); jmxPortBinding.setHostIp(""); jmxPortBinding.setHostPort(jmxRmiPort); jmxPortBindings.add(jmxPortBinding); portBindings.put("1099/tcp", jmxPortBindings); List<HostPortBinding> jmxRegistryPortBindings = new ArrayList<>(); HostPortBinding jmxRegistryPortBinding = new HostPortBinding(); jmxRegistryPortBinding.setHostIp(""); jmxRegistryPortBinding.setHostPort(jmxRmiRegistryPort); jmxRegistryPortBindings.add(jmxRegistryPortBinding); portBindings.put("44444/tcp", jmxRegistryPortBindings); List<HostPortBinding> httpPortBindings = new ArrayList<>(); HostPortBinding httpPortBinding = new HostPortBinding(); httpPortBinding.setHostIp(""); httpPortBinding.setHostPort(httpPort); httpPortBindings.add(httpPortBinding); portBindings.put("8181/tcp", httpPortBindings); hostConfig.setPortBindings(portBindings); config.setHostConfig(hostConfig); dockerClient.create(config, name); } File getStorageLocation(); void setStorageLocation(File storageLocation); @Override List<Container> ps(boolean showAll, String url); @Override Info info(String url); @Override Version version(String url); @Override void create(String name, String url); @Override void create(String name, String url, ContainerConfig config); @Override void provision(String name, String sshPort, String jmxRmiPort, String jmxRmiRegistryPort, String httpPort, boolean copy, String url); @Override void start(String name, String url); @Override void stop(String name, int timeToWait, String url); @Override void restart(String name, int timeToWait, String url); @Override void kill(String name, String signal, String url); @Override void pause(String name, String url); @Override void unpause(String name, String url); @Override void rename(String name, String newName, String url); @Override void rm(String name, boolean removeVolumes, boolean force, String url); @Override String logs(String name, boolean stdout, boolean stderr, boolean timestamps, boolean details, String url); @Override Top top(String name, String url); @Override void commit(String name, String repo, String tag, String message, String url); @Override List<Image> images(String url); @Override void pull(String image, String tag, boolean verbose, String url); @Override List<ImageSearch> search(String term, String url); @Override Container inspect(String name, String url); @Override void push(String image, String tag, boolean verbose, String url); @Override List<ImageHistory> history(String image, String url); @Override void tag(String image, String repo, String tag, String url); @Override void rmi(String image, boolean force, boolean noprune, String url); } | @Test @Ignore("Require a running docker daemon") public void testProvision() throws Exception { dockerService.provision("test", "8101", "1099", "44444", "8181", false, null); } |
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); } | @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()); } |
RunMojo extends MojoSupport { public void execute() throws MojoExecutionException, MojoFailureException { final Properties originalProperties = new Properties(); originalProperties.putAll(System.getProperties()); final String[] args = handleArgs(karafDirectory, mainArgs == null ? new String[0] : mainArgs); if (karafDirectory.exists()) { getLog().info("Using Karaf container located " + karafDirectory.getAbsolutePath()); } else { getLog().info("Extracting Karaf container"); try { File karafArchiveFile = resolveFile(karafDistribution); extract(karafArchiveFile, karafDirectory); } catch (Exception e) { throw new MojoFailureException("Can't extract Karaf container", e); } } getLog().info("Starting Karaf container"); System.setProperty("karaf.home", karafDirectory.getAbsolutePath()); System.setProperty("karaf.base", karafDirectory.getAbsolutePath()); System.setProperty("karaf.data", karafDirectory.getAbsolutePath() + "/data"); System.setProperty("karaf.etc", karafDirectory.getAbsolutePath() + "/etc"); System.setProperty("karaf.log", karafDirectory.getAbsolutePath() + "/data/log"); System.setProperty("karaf.instances", karafDirectory.getAbsolutePath() + "/instances"); if (System.getProperty("karaf.startLocalConsole") == null) { System.setProperty("karaf.startLocalConsole", "false"); } System.setProperty("karaf.startRemoteShell", startSsh); System.setProperty("karaf.lock", "false"); if (consoleLogLevel != null && !consoleLogLevel.isEmpty()) { System.setProperty("karaf.log.console", consoleLogLevel); } if (systemProperties != null) { systemProperties.forEach(System::setProperty); } String featureBootFinished = BootFinished.class.getName(); Thread bootThread = Thread.currentThread(); ClassLoader classRealm = bootThread.getContextClassLoader(); ClassLoader bootLoader = new ClassLoader(classRealm) { @Override protected Class<?> loadClass(final String name, final boolean resolve) throws ClassNotFoundException { if (featureBootFinished.equals(name)) { throw new ClassNotFoundException( "avoid to use the classrealm loader which will prevent felix to match its reference"); } if (name != null && forbiddenDelegationPackages != null && forbiddenDelegationPackages.stream().anyMatch(name::startsWith)) { throw new ClassNotFoundException(name); } return super.loadClass(name, resolve); } }; final Main main = newMain(bootLoader, args); try { long start = System.nanoTime(); main.launch(); while (main.getFramework().getState() != Bundle.ACTIVE && checkDurationTimeout(start)) { waitForValidState(); } if (main.getFramework().getState() != Bundle.ACTIVE) { try { main.destroy(); } catch (final Throwable e) { getLog().debug(e.getMessage(), e); } throw startupTimeout(start); } BundleContext featureBundleCtx = null; Object bootFinished = null; while (bootFinished == null && checkDurationTimeout(start)) { waitForValidState(); if (featureBundleCtx == null) { featureBundleCtx = Stream.of(main.getFramework().getBundleContext().getBundles()) .filter(b -> b.getSymbolicName().equals("org.apache.karaf.deployer.features")) .findFirst() .map(Bundle::getBundleContext) .orElse(null); } if (featureBundleCtx == null) { continue; } ServiceReference<?> ref = featureBundleCtx.getServiceReference(featureBundleCtx.getBundle().loadClass(featureBootFinished)); if (ref != null) { bootFinished = featureBundleCtx.getService(ref); } } if (bootFinished == null) { try { main.destroy(); } catch (final Throwable e) { getLog().debug(e.getMessage(), e); } throw startupTimeout(start); } Object featureService = findFeatureService(featureBundleCtx); addFeatureRepositories(featureService); if (!deployAfterFeatures) { deploy(featureBundleCtx, featureService); } addFeatures(featureService); if (deployAfterFeatures) { deploy(featureBundleCtx, featureService); } if (keepRunning) main.awaitShutdown(); main.destroy(); } catch (Throwable e) { throw new MojoExecutionException("Can't start container", e); } finally { System.gc(); System.getProperties().clear(); System.getProperties().putAll(originalProperties); } } void execute(); static void extract(File sourceFile, File targetFolder); } | @Test public void testArgs() throws IllegalAccessException, MojoFailureException, MojoExecutionException, IOException { final AtomicReference<String[]> capturedArgs = new AtomicReference<>(); final RunMojo mojo = newRunMojo(args -> { capturedArgs.set(args); throw new FastExit(); }); setPrivateField(mojo, "mainArgs", new String[]{"foo"}); try { mojo.execute(); } catch (final FastExit fe) { } assertArrayEquals(new String[]{"foo"}, capturedArgs.get()); }
@Test public void testSystemProperties() throws IllegalAccessException, MojoFailureException, MojoExecutionException, IOException { final RunMojo mojo = newRunMojo(args -> { throw new FastExit(); }); setPrivateField(mojo, "systemProperties", singletonMap("RunMojoTest.testSystemProperties", "set")); try { mojo.execute(); } catch (final FastExit fe) { } assertEquals("set", System.clearProperty("RunMojoTest.testSystemProperties")); }
@Test public void testConsoleLevel() throws IllegalAccessException, MojoFailureException, MojoExecutionException, IOException { final RunMojo mojo = newRunMojo(args -> { throw new FastExit(); }); setPrivateField(mojo, "consoleLogLevel", "INFO"); try { mojo.execute(); } catch (final FastExit fe) { } assertEquals("INFO", System.clearProperty("karaf.log.console")); } |
RunMojo extends MojoSupport { void addFeatureRepositories(Object featureService) throws MojoExecutionException { if (featureRepositories != null) { try { Class<? extends Object> serviceClass = featureService.getClass(); Method addRepositoryMethod = serviceClass.getMethod("addRepository", URI.class); for (String featureRepo : featureRepositories) { addRepositoryMethod.invoke(featureService, URI.create(featureRepo)); } } catch (Exception e) { throw new MojoExecutionException("Failed to add feature repositories to karaf", e); } } } void execute(); static void extract(File sourceFile, File targetFolder); } | @Test public void testAddFeatureRepositoriesWithNullRepoList() throws MojoExecutionException { FeaturesService featureService = mock(FeaturesService.class); replay(featureService); RunMojo mojo = new RunMojo(); mojo.addFeatureRepositories(featureService); verify(featureService); }
@Test public void testAddFeatureRepositoriesWithEmptyRepoListAndNullFeatureService() throws SecurityException, IllegalArgumentException, IllegalAccessException, MojoExecutionException { RunMojo mojo = new RunMojo(); String[] empty = new String[0]; setPrivateField(mojo, "featureRepositories", empty); try { mojo.addFeatureRepositories(null); fail("Expected MojoExecutionException to be thrown"); } catch(MojoExecutionException e) { assertEquals("Failed to add feature repositories to karaf", e.getMessage()); } }
@Test public void testAddFeatureRepositoriesWithEmptyRepoList() throws MojoExecutionException, SecurityException, IllegalArgumentException, IllegalAccessException { FeaturesService featureService = mock(FeaturesService.class); replay(featureService); RunMojo mojo = new RunMojo(); String[] empty = new String[0]; setPrivateField(mojo, "featureRepositories", empty); mojo.addFeatureRepositories(featureService); verify(featureService); }
@Test public void testAddFeatureRepositories() throws Exception { FeaturesService featureService = niceMock(FeaturesService.class); featureService.addRepository(anyObject(URI.class)); EasyMock.expectLastCall().once(); replay(featureService); RunMojo mojo = new RunMojo(); String[] features = { "liquibase-core", "ukelonn" }; setPrivateField(mojo, "featureRepositories", features); mojo.addFeatureRepositories(featureService); verify(featureService); } |
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; } | @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()); } |
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); } | @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)); } |
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); } | @Test public void testWhenMultiple() { assertEquals("git clone git: + "git clone git: .apply( ImmutableMap.of("puppet.nginx.module", "git: "puppet.http.module", "git: OsFamily.UNIX)); } |
PuppetClusterActionHandlerFactory extends ClusterActionHandlerFactory { @Override public ClusterActionHandler create(String roleName) { return new PuppetClusterActionHandler(checkNotNull(roleName, "roleName")); } @Override String getRolePrefix(); @Override ClusterActionHandler create(String roleName); } | @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")); } |
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; } | @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")); } |
ElasticSearchConfigurationBuilder { public static Configuration buildConfig(ClusterSpec spec, Cluster cluster) { CompositeConfiguration config = new CompositeConfiguration(); config.addConfiguration(spec.getConfiguration()); try { config.addConfiguration( new PropertiesConfiguration(ElasticSearchConfigurationBuilder.class.getResource("/whirr-elasticsearch-default.properties"))); } catch (ConfigurationException e) { LOG.error("Configuration error", e); } if ("aws-ec2".equals(spec.getProvider()) || "ec2".equals(spec.getProvider())) { addDefaultsForEC2(spec, config); } else { addDefaultsForUnicast(cluster, config); } if (!config.containsKey("es.cluster.name")) { config.addProperty("es.cluster.name", spec.getClusterName()); } return config; } 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; } | @Test public void testDefaultConfigAwsEC2() throws Exception { Configuration baseConfig = new PropertiesConfiguration(); baseConfig.addProperty("whirr.provider", "aws-ec2"); baseConfig.addProperty("es.plugins", "lang-javascript, lang-python"); ClusterSpec spec = ClusterSpec.withTemporaryKeys(baseConfig); Configuration config = ElasticSearchConfigurationBuilder.buildConfig(spec, null); assertThat(config.getStringArray("es.plugins"), is(new String[]{"lang-javascript", "lang-python", "elasticsearch/elasticsearch-cloud-aws/1.5.0"})); assertThat(config.getString("es.discovery.type"), is("ec2")); }
@Test public void testOverrideDefaults() throws Exception { Configuration baseConfig = new PropertiesConfiguration(); baseConfig.addProperty("whirr.provider", "aws-ec2"); baseConfig.addProperty("es.index.store.type", "fs"); ClusterSpec spec = ClusterSpec.withTemporaryKeys(baseConfig); Configuration config = ElasticSearchConfigurationBuilder.buildConfig(spec, null); assertThat(config.getString("es.index.store.type"), is("fs")); } |
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; } | @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)); } |
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; } | @Test public void testComputeInitialTokens() { List<String> result = new CassandraClusterActionHandler().computeInitialTokens(5); assertEquals(result, ImmutableList.of( "0", "34028236692093846346337460743176821145", "68056473384187692692674921486353642290", "102084710076281539039012382229530463435", "136112946768375385385349842972707284580" )); } |
HadoopConfigurationBuilder { @VisibleForTesting static Configuration buildCommonConfiguration(ClusterSpec clusterSpec, Cluster cluster, Configuration defaults) throws ConfigurationException, IOException { Configuration config = build(clusterSpec, cluster, defaults, "hadoop-common"); Instance namenode = cluster .getInstanceMatching(role(HadoopNameNodeClusterActionHandler.ROLE)); LOG.debug("hadoop building common configuration, with hostname "+namenode.getPublicHostName()); config.setProperty("fs.default.name", String.format("hdfs: namenode.getPublicHostName())); 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); } | @Test public void testCommon() throws Exception { Configuration conf = HadoopConfigurationBuilder.buildCommonConfiguration( clusterSpec, cluster, defaults); assertThat(Iterators.size(conf.getKeys()), is(3)); assertThat(conf.getString("p1"), is("common1")); assertThat(conf.getString("p2"), is("common2")); assertThat(conf.getString("fs.default.name"), matches("hdfs: }
@Test public void testOverrides() throws Exception { Configuration overrides = new PropertiesConfiguration(); overrides.addProperty("hadoop-common.p1", "overridden1"); overrides.addProperty("hadoop-common.p2", "overridden2"); overrides.addProperty("hadoop-common.fs.default.name", "not-overridden"); clusterSpec = ClusterSpec.withNoDefaults(overrides); Configuration conf = HadoopConfigurationBuilder.buildCommonConfiguration( clusterSpec, cluster, defaults); assertThat(Iterators.size(conf.getKeys()), is(3)); assertThat(conf.getString("p1"), is("overridden1")); assertThat(conf.getString("p2"), is("overridden2")); assertThat("Can't override dynamically set properties", conf.getString("fs.default.name"), matches("hdfs: } |
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); } | @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")); } |
HadoopConfigurationBuilder { @VisibleForTesting static Configuration buildMapReduceConfiguration(ClusterSpec clusterSpec, Cluster cluster, Configuration defaults, Set<String> dataDirectories) throws ConfigurationException, IOException { Configuration config = build(clusterSpec, cluster, defaults, "hadoop-mapreduce"); setIfAbsent(config, "mapred.local.dir", appendToDataDirectories(dataDirectories, "/hadoop/mapred/local")); Set<Instance> taskTrackers = cluster .getInstancesMatching(role(HadoopTaskTrackerClusterActionHandler.ROLE)); if (!taskTrackers.isEmpty()) { Hardware hardware = Iterables.getFirst(taskTrackers, null) .getNodeMetadata().getHardware(); if (hardware != null) { int coresPerNode = 0; for (Processor processor : hardware.getProcessors()) { coresPerNode += processor.getCores(); } int mapTasksPerNode = (int) Math.ceil(coresPerNode * 1.0); int reduceTasksPerNode = (int) Math.ceil(coresPerNode * 0.75); setIfAbsent(config, "mapred.tasktracker.map.tasks.maximum", mapTasksPerNode + ""); setIfAbsent(config, "mapred.tasktracker.reduce.tasks.maximum", reduceTasksPerNode + ""); int clusterReduceSlots = taskTrackers.size() * reduceTasksPerNode; setIfAbsent(config, "mapred.reduce.tasks", clusterReduceSlots + ""); } } Set<Instance> jobtracker = cluster .getInstancesMatching(role(HadoopJobTrackerClusterActionHandler.ROLE)); if (!jobtracker.isEmpty()) { config.setProperty("mapred.job.tracker", String.format("%s:8021", Iterables.getOnlyElement(jobtracker).getPublicHostName())); } 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); } | @Test public void testMapReduce() throws Exception { Cluster cluster = newCluster(5); Configuration conf = HadoopConfigurationBuilder .buildMapReduceConfiguration(clusterSpec, cluster, defaults, Sets.newLinkedHashSet(Lists.newArrayList("/data0", "/data1"))); assertThat(conf.getString("p1"), is("mapred1")); assertThat(conf.getString("mapred.job.tracker"), matches(".+:8021")); assertThat(conf.getString("mapred.tasktracker.map.tasks.maximum"), is("4")); assertThat(conf.getString("mapred.tasktracker.reduce.tasks.maximum"), is("3")); assertThat(conf.getString("mapred.reduce.tasks"), is("15")); assertThat(conf.getString("mapred.local.dir"), is("/data0/hadoop/mapred/local,/data1/hadoop/mapred/local")); }
@Test public void testOverridesNumberOfMappers() throws Exception { Configuration overrides = new PropertiesConfiguration(); overrides.addProperty("hadoop-mapreduce.mapred.tasktracker.map.tasks.maximum", "70"); clusterSpec = ClusterSpec.withNoDefaults(overrides); Configuration conf = HadoopConfigurationBuilder.buildMapReduceConfiguration( clusterSpec, cluster, defaults, Sets.newLinkedHashSet(Lists.newArrayList("/data0", "/data1"))); assertThat(conf.getString("mapred.tasktracker.map.tasks.maximum"), is("70")); }
@Test public void testOverridesNumberOfReducers() throws Exception { Configuration overrides = new PropertiesConfiguration(); overrides.addProperty("hadoop-mapreduce.mapred.reduce.tasks", "7"); clusterSpec = ClusterSpec.withNoDefaults(overrides); Configuration conf = HadoopConfigurationBuilder.buildMapReduceConfiguration( clusterSpec, cluster, defaults, Sets.newLinkedHashSet(Lists.newArrayList("/data0", "/data1"))); assertThat(conf.getString("mapred.reduce.tasks"), is("7")); } |
HadoopConfigurationConverter { @VisibleForTesting static List<String> asXmlConfigurationLines(Configuration hadoopConfig) { List<String> lines = Lists.newArrayList(); lines.add("<configuration>"); for (@SuppressWarnings("unchecked") Iterator<String> it = hadoopConfig.getKeys(); it.hasNext(); ) { String key = it.next(); if (key.endsWith(FINAL_SUFFIX)) { continue; } String value = StringUtils.join(hadoopConfig.getStringArray(key), AbstractConfiguration.getDefaultListDelimiter()); lines.add(" <property>"); lines.add(String.format(" <name>%s</name>", key)); lines.add(String.format(" <value>%s</value>", value)); String finalValue = hadoopConfig.getString(key + FINAL_SUFFIX); if (finalValue != null) { lines.add(String.format(" <final>%s</final>", finalValue)); } lines.add(" </property>"); } lines.add("</configuration>"); return lines; } static Statement asCreateXmlConfigurationFileStatement(String path,
Configuration hadoopConfig); static Statement asCreateEnvironmentVariablesFileStatement(String path,
Configuration config); static void createClientSideHadoopSiteFile(File file, Properties config); } | @Test public void testConversion() { Configuration conf = new PropertiesConfiguration(); conf.setProperty("p1", "v1,v2"); conf.setProperty("p2", "v3"); List<String> lines = HadoopConfigurationConverter.asXmlConfigurationLines(conf); assertThat(lines, is((List<String>) Lists.newArrayList( "<configuration>", " <property>", " <name>p1</name>", " <value>v1,v2</value>", " </property>", " <property>", " <name>p2</name>", " <value>v3</value>", " </property>", "</configuration>" ))); }
@Test public void testFinal() { Configuration conf = new PropertiesConfiguration(); conf.setProperty("p1", "v1"); conf.setProperty("p2", "v2"); conf.setProperty("p2.final", "true"); List<String> lines = HadoopConfigurationConverter.asXmlConfigurationLines(conf); assertThat(lines, is((List<String>) Lists.newArrayList( "<configuration>", " <property>", " <name>p1</name>", " <value>v1</value>", " </property>", " <property>", " <name>p2</name>", " <value>v2</value>", " <final>true</final>", " </property>", "</configuration>" ))); } |
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; } | @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()); } |
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; } | @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)); } |
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); } | @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")); } |
Utils { public static void printSSHConnectionDetails(PrintStream out, ClusterSpec clusterSpec, Cluster cluster, int maxPrint) { out.println("\nYou can log into instances using the following ssh commands:"); String user = clusterSpec.getClusterUser() != null ? clusterSpec .getClusterUser() : clusterSpec.getTemplate().getLoginUser(); String pkFile = clusterSpec.getPrivateKeyFile().getAbsolutePath(); int counter = 0; for (Instance instance : cluster.getInstances()) { StringBuilder roles = new StringBuilder(); for (String role : instance.getRoles()) { if (roles.length() != 0) { roles.append('+'); } roles.append(role); } out.printf( "[%s]: ssh -i %s -o \"UserKnownHostsFile /dev/null\" -o StrictHostKeyChecking=no %s@%s\n", roles.toString(), pkFile, user, instance.getPublicIp()); if (counter > maxPrint) { out.println("... Too many instances, truncating."); break; } counter++; } } static LoadingCache<K, V> convertMapToLoadingCache(Map<K, V> in); static void printSSHConnectionDetails(PrintStream out, ClusterSpec clusterSpec,
Cluster cluster, int maxPrint); } | @Test public void testPrintAccess() { final Instance instance = mock(Instance.class); when(instance.getPublicIp()).thenReturn("test-public-ip"); when(instance.getRoles()).thenReturn(ImmutableSet.of("test-role")); Cluster cluster = mock(Cluster.class); when(cluster.getInstances()).thenReturn(ImmutableSet.<Cluster.Instance>of(instance)); ClusterSpec spec = mock(ClusterSpec.class); when(spec.getClusterUser()).thenReturn("test-identity"); when(spec.getPrivateKeyFile()).thenReturn(new File("/test/key/path")); ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); Utils.printSSHConnectionDetails(ps, spec, cluster, 20); assertEquals("The ssh command did not match", EXPECTED_SSH_COMMAND, new String(baos.toByteArray())); } |
ClusterSpec { public Configuration getConfigurationForKeysWithPrefix(String prefix) { Configuration c = new PropertiesConfiguration(); for (@SuppressWarnings("unchecked") Iterator<String> it = config.getKeys(prefix); it.hasNext(); ) { String key = it.next(); c.setProperty(key, config.getProperty(key)); } return c; } ClusterSpec(); ClusterSpec(Configuration config); ClusterSpec(Configuration userConfig, boolean loadDefaults); ClusterSpec(Configuration userConfig, boolean loadDefaults, Map<String,Node> byonNodes); @VisibleForTesting static ClusterSpec withTemporaryKeys(); @VisibleForTesting static ClusterSpec withTemporaryKeys(Configuration conf); @VisibleForTesting static ClusterSpec withNoDefaults(); @VisibleForTesting static ClusterSpec withNoDefaults(Configuration conf); ClusterSpec copy(); List<InstanceTemplate> getInstanceTemplates(); InstanceTemplate getInstanceTemplate(final Set<String> roles); InstanceTemplate getInstanceTemplate(String... roles); int getMaxStartupRetries(); String getContextName(); String getProvider(); boolean isStub(); String getEndpoint(); String getIdentity(); String getCredential(); String getClusterName(); String getBlobStoreContextName(); String getBlobStoreProvider(); boolean isQuiet(); String getBlobStoreEndpoint(); String getBlobStoreIdentity(); String getBlobStoreCredential(); String getBlobStoreLocationId(); String getBlobStoreCacheContainer(); String getStateStore(); String getStateStoreContainer(); String getStateStoreBlob(); @Nullable Float getAwsEc2SpotPrice(); String getServiceName(); String getPrivateKey(); File getPrivateKeyFile(); String getPublicKey(); TemplateBuilderSpec getTemplate(); List<String> getClientCidrs(); Map<String, List<String>> getFirewallRules(); Map<String, Node> getByonNodes(); ClusterActionHandlerListener getHandlerListener(); String getVersion(); String getRunUrlBase(); String getClusterUser(); void setInstanceTemplates(List<InstanceTemplate> instanceTemplates); void setMaxStartupRetries(int maxStartupRetries); void setContextName(String contextName); void setProvider(String provider); void setEndpoint(String endpoint); void setIdentity(String identity); void setCredential(String credential); void setBlobStoreContextName(String blobStoreContextName); void setBlobStoreProvider(String provider); void setBlobStoreEndpoint(String endpoint); void setBlobStoreIdentity(String identity); void setBlobStoreCredential(String credential); void setBlobStoreLocationId(String locationId); void setBlobStoreCacheContainer(String container); void setStateStore(String type); void setStateStoreContainer(String container); void setStateStoreBlob(String blob); void setAwsEc2SpotPrice(@Nullable Float value); void setClusterName(String clusterName); void setServiceName(String serviceName); boolean isTerminateAllOnLaunchFailure(); void setTerminateAllOnLaunchFailure(boolean terminateAllOnLaunchFailure); boolean isStoreClusterInEtcHosts(); void setStoreClusterInEtcHosts(boolean storeClusterInEtcHosts); String getAwsEc2PlacementGroup(); void setAwsEc2PlacementGroup(String awsEc2PlacementGroup); String getAutoHostnameSuffix(); void setAutoHostnameSuffix(String autoHostnameSuffix); String getAutoHostnamePrefix(); void setAutoHostnamePrefix(String autoHostnamePrefix); String getJdkInstallUrl(); void setJdkInstallUrl(String jdkInstallUrl); String getKerberosRealm(); void setKerberosRealm(String kerberosRealm); void setPublicKey(String publicKey); void setPublicKey(File publicKey); void setPrivateKey(String privateKey); void setPrivateKey(File privateKey); void setTemplate(TemplateBuilderSpec template); void setClientCidrs(List<String> clientCidrs); void setFirewallRules(Map<String,List<String>> firewallRules); @VisibleForTesting void setByonNodes(Map<String,Node> byonNodes); void setQuiet(boolean isQuiet); void setHandlerListener(ClusterActionHandlerListener handlerListener); void setVersion(String version); void setRunUrlBase(String runUrlBase); void setClusterUser(String user); Configuration getConfiguration(); Configuration getConfigurationForKeysWithPrefix(String prefix); Configuration getConfigurationForKeysMatching(Pattern pattern); File getClusterDirectory(); boolean equals(Object o); int hashCode(); String toString(); } | @Test public void testGetConfigurationForKeysWithPrefix() throws ConfigurationException, JSchException, IOException { Configuration conf = new PropertiesConfiguration(); conf.setProperty("a.b", 1); conf.setProperty("b.a", 2); conf.setProperty("a.c", 3); ClusterSpec spec = ClusterSpec.withNoDefaults(conf); Configuration prefixConf = spec.getConfigurationForKeysWithPrefix("a"); List<String> prefixKeys = Lists.newArrayList(); Iterators.addAll(prefixKeys, prefixConf.getKeys()); assertThat(prefixKeys.size(), is(2)); assertThat(prefixKeys.get(0), is("a.b")); assertThat(prefixKeys.get(1), is("a.c")); } |
ClusterSpec { private String getString(Property key) { return config.getString(key.getConfigName(), null); } ClusterSpec(); ClusterSpec(Configuration config); ClusterSpec(Configuration userConfig, boolean loadDefaults); ClusterSpec(Configuration userConfig, boolean loadDefaults, Map<String,Node> byonNodes); @VisibleForTesting static ClusterSpec withTemporaryKeys(); @VisibleForTesting static ClusterSpec withTemporaryKeys(Configuration conf); @VisibleForTesting static ClusterSpec withNoDefaults(); @VisibleForTesting static ClusterSpec withNoDefaults(Configuration conf); ClusterSpec copy(); List<InstanceTemplate> getInstanceTemplates(); InstanceTemplate getInstanceTemplate(final Set<String> roles); InstanceTemplate getInstanceTemplate(String... roles); int getMaxStartupRetries(); String getContextName(); String getProvider(); boolean isStub(); String getEndpoint(); String getIdentity(); String getCredential(); String getClusterName(); String getBlobStoreContextName(); String getBlobStoreProvider(); boolean isQuiet(); String getBlobStoreEndpoint(); String getBlobStoreIdentity(); String getBlobStoreCredential(); String getBlobStoreLocationId(); String getBlobStoreCacheContainer(); String getStateStore(); String getStateStoreContainer(); String getStateStoreBlob(); @Nullable Float getAwsEc2SpotPrice(); String getServiceName(); String getPrivateKey(); File getPrivateKeyFile(); String getPublicKey(); TemplateBuilderSpec getTemplate(); List<String> getClientCidrs(); Map<String, List<String>> getFirewallRules(); Map<String, Node> getByonNodes(); ClusterActionHandlerListener getHandlerListener(); String getVersion(); String getRunUrlBase(); String getClusterUser(); void setInstanceTemplates(List<InstanceTemplate> instanceTemplates); void setMaxStartupRetries(int maxStartupRetries); void setContextName(String contextName); void setProvider(String provider); void setEndpoint(String endpoint); void setIdentity(String identity); void setCredential(String credential); void setBlobStoreContextName(String blobStoreContextName); void setBlobStoreProvider(String provider); void setBlobStoreEndpoint(String endpoint); void setBlobStoreIdentity(String identity); void setBlobStoreCredential(String credential); void setBlobStoreLocationId(String locationId); void setBlobStoreCacheContainer(String container); void setStateStore(String type); void setStateStoreContainer(String container); void setStateStoreBlob(String blob); void setAwsEc2SpotPrice(@Nullable Float value); void setClusterName(String clusterName); void setServiceName(String serviceName); boolean isTerminateAllOnLaunchFailure(); void setTerminateAllOnLaunchFailure(boolean terminateAllOnLaunchFailure); boolean isStoreClusterInEtcHosts(); void setStoreClusterInEtcHosts(boolean storeClusterInEtcHosts); String getAwsEc2PlacementGroup(); void setAwsEc2PlacementGroup(String awsEc2PlacementGroup); String getAutoHostnameSuffix(); void setAutoHostnameSuffix(String autoHostnameSuffix); String getAutoHostnamePrefix(); void setAutoHostnamePrefix(String autoHostnamePrefix); String getJdkInstallUrl(); void setJdkInstallUrl(String jdkInstallUrl); String getKerberosRealm(); void setKerberosRealm(String kerberosRealm); void setPublicKey(String publicKey); void setPublicKey(File publicKey); void setPrivateKey(String privateKey); void setPrivateKey(File privateKey); void setTemplate(TemplateBuilderSpec template); void setClientCidrs(List<String> clientCidrs); void setFirewallRules(Map<String,List<String>> firewallRules); @VisibleForTesting void setByonNodes(Map<String,Node> byonNodes); void setQuiet(boolean isQuiet); void setHandlerListener(ClusterActionHandlerListener handlerListener); void setVersion(String version); void setRunUrlBase(String runUrlBase); void setClusterUser(String user); Configuration getConfiguration(); Configuration getConfigurationForKeysWithPrefix(String prefix); Configuration getConfigurationForKeysMatching(Pattern pattern); File getClusterDirectory(); boolean equals(Object o); int hashCode(); String toString(); } | @Test public void testEnvVariableInterpolation() { Map<String, String> envMap = System.getenv(); assertThat(envMap.isEmpty(), is(false)); String undefinedEnvVar = "UNDEFINED_ENV_VAR"; assertThat(envMap.containsKey(undefinedEnvVar), is(false)); Entry<String, String> firstEntry = Iterables.get(envMap.entrySet(), 0); Configuration conf = new PropertiesConfiguration(); conf.setProperty("a", String.format("${env:%s}", firstEntry.getKey())); conf.setProperty("b", String.format("${env:%s}", undefinedEnvVar)); assertThat(conf.getString("a"), is(firstEntry.getValue())); assertThat(conf.getString("b"), is(String.format("${env:%s}", undefinedEnvVar))); } |
ClusterSpec { @VisibleForTesting public static ClusterSpec withNoDefaults() throws ConfigurationException { return withNoDefaults(new PropertiesConfiguration()); } ClusterSpec(); ClusterSpec(Configuration config); ClusterSpec(Configuration userConfig, boolean loadDefaults); ClusterSpec(Configuration userConfig, boolean loadDefaults, Map<String,Node> byonNodes); @VisibleForTesting static ClusterSpec withTemporaryKeys(); @VisibleForTesting static ClusterSpec withTemporaryKeys(Configuration conf); @VisibleForTesting static ClusterSpec withNoDefaults(); @VisibleForTesting static ClusterSpec withNoDefaults(Configuration conf); ClusterSpec copy(); List<InstanceTemplate> getInstanceTemplates(); InstanceTemplate getInstanceTemplate(final Set<String> roles); InstanceTemplate getInstanceTemplate(String... roles); int getMaxStartupRetries(); String getContextName(); String getProvider(); boolean isStub(); String getEndpoint(); String getIdentity(); String getCredential(); String getClusterName(); String getBlobStoreContextName(); String getBlobStoreProvider(); boolean isQuiet(); String getBlobStoreEndpoint(); String getBlobStoreIdentity(); String getBlobStoreCredential(); String getBlobStoreLocationId(); String getBlobStoreCacheContainer(); String getStateStore(); String getStateStoreContainer(); String getStateStoreBlob(); @Nullable Float getAwsEc2SpotPrice(); String getServiceName(); String getPrivateKey(); File getPrivateKeyFile(); String getPublicKey(); TemplateBuilderSpec getTemplate(); List<String> getClientCidrs(); Map<String, List<String>> getFirewallRules(); Map<String, Node> getByonNodes(); ClusterActionHandlerListener getHandlerListener(); String getVersion(); String getRunUrlBase(); String getClusterUser(); void setInstanceTemplates(List<InstanceTemplate> instanceTemplates); void setMaxStartupRetries(int maxStartupRetries); void setContextName(String contextName); void setProvider(String provider); void setEndpoint(String endpoint); void setIdentity(String identity); void setCredential(String credential); void setBlobStoreContextName(String blobStoreContextName); void setBlobStoreProvider(String provider); void setBlobStoreEndpoint(String endpoint); void setBlobStoreIdentity(String identity); void setBlobStoreCredential(String credential); void setBlobStoreLocationId(String locationId); void setBlobStoreCacheContainer(String container); void setStateStore(String type); void setStateStoreContainer(String container); void setStateStoreBlob(String blob); void setAwsEc2SpotPrice(@Nullable Float value); void setClusterName(String clusterName); void setServiceName(String serviceName); boolean isTerminateAllOnLaunchFailure(); void setTerminateAllOnLaunchFailure(boolean terminateAllOnLaunchFailure); boolean isStoreClusterInEtcHosts(); void setStoreClusterInEtcHosts(boolean storeClusterInEtcHosts); String getAwsEc2PlacementGroup(); void setAwsEc2PlacementGroup(String awsEc2PlacementGroup); String getAutoHostnameSuffix(); void setAutoHostnameSuffix(String autoHostnameSuffix); String getAutoHostnamePrefix(); void setAutoHostnamePrefix(String autoHostnamePrefix); String getJdkInstallUrl(); void setJdkInstallUrl(String jdkInstallUrl); String getKerberosRealm(); void setKerberosRealm(String kerberosRealm); void setPublicKey(String publicKey); void setPublicKey(File publicKey); void setPrivateKey(String privateKey); void setPrivateKey(File privateKey); void setTemplate(TemplateBuilderSpec template); void setClientCidrs(List<String> clientCidrs); void setFirewallRules(Map<String,List<String>> firewallRules); @VisibleForTesting void setByonNodes(Map<String,Node> byonNodes); void setQuiet(boolean isQuiet); void setHandlerListener(ClusterActionHandlerListener handlerListener); void setVersion(String version); void setRunUrlBase(String runUrlBase); void setClusterUser(String user); Configuration getConfiguration(); Configuration getConfigurationForKeysWithPrefix(String prefix); Configuration getConfigurationForKeysMatching(Pattern pattern); File getClusterDirectory(); boolean equals(Object o); int hashCode(); String toString(); } | @Test(expected = ConfigurationException.class) public void testDummyPrivateKey() throws JSchException, IOException, ConfigurationException { File privateKeyFile = File.createTempFile("private", "key"); privateKeyFile.deleteOnExit(); Files.write(("-----BEGIN RSA PRIVATE KEY-----\n" + "DUMMY FILE\n" + "-----END RSA PRIVATE KEY-----").getBytes(), privateKeyFile); Configuration conf = new PropertiesConfiguration(); conf.setProperty("whirr.private-key-file", privateKeyFile.getAbsolutePath()); ClusterSpec.withNoDefaults(conf); }
@Test(expected = ConfigurationException.class) public void testEncryptedPrivateKey() throws JSchException, IOException, ConfigurationException { File privateKey = KeyPair.generateTemporaryFiles("dummy").get("private"); Configuration conf = new PropertiesConfiguration(); conf.setProperty("whirr.private-key-file", privateKey.getAbsolutePath()); ClusterSpec.withNoDefaults(conf); }
@Test(expected = ConfigurationException.class) public void testMissingPrivateKey() throws ConfigurationException { Configuration conf = new PropertiesConfiguration(); conf.setProperty("whirr.private-key-file", "/dummy/path/that/does/not/exists"); ClusterSpec.withNoDefaults(conf); }
@Test(expected = ConfigurationException.class) public void testMissingPublicKey() throws JSchException, IOException, ConfigurationException { File privateKey = KeyPair.generateTemporaryFiles().get("private"); Configuration conf = new PropertiesConfiguration(); conf.setProperty("whirr.private-key-file", privateKey.getAbsolutePath()); conf.setProperty("whirr.public-key-file", "/dummy/path/that/does/not/exists"); ClusterSpec.withNoDefaults(conf); }
@Test(expected = ConfigurationException.class) public void testBrokenPublicKey() throws IOException, JSchException, ConfigurationException { File privateKey = KeyPair.generateTemporaryFiles().get("private"); File publicKey = File.createTempFile("public", "key"); publicKey.deleteOnExit(); Files.write("ssh-rsa BROKEN PUBLIC KEY".getBytes(), publicKey); Configuration conf = new PropertiesConfiguration(); conf.setProperty("whirr.private-key-file", privateKey.getAbsolutePath()); conf.setProperty("whirr.public-key-file", publicKey.getAbsolutePath()); ClusterSpec.withNoDefaults(conf); }
@Test(expected = ConfigurationException.class) public void testNotSameKeyPair() throws JSchException, IOException, ConfigurationException { Map<String, File> first = KeyPair.generateTemporaryFiles(); Map<String, File> second = KeyPair.generateTemporaryFiles(); Configuration conf = new PropertiesConfiguration(); conf.setProperty("whirr.private-key-file", first.get("private").getAbsolutePath()); conf.setProperty("whirr.public-key-file", second.get("public").getAbsolutePath()); ClusterSpec.withNoDefaults(conf); }
@Test(expected = IllegalArgumentException.class) public void testFailIfRunningAsRootOrClusterUserIsRoot() throws ConfigurationException { PropertiesConfiguration conf = new PropertiesConfiguration("whirr-core-test.properties"); conf.setProperty("whirr.cluster-user", "root"); ClusterSpec.withNoDefaults(conf); } |
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; } | @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()); } |
ClusterSpec { @VisibleForTesting public static ClusterSpec withTemporaryKeys() throws ConfigurationException, JSchException, IOException { return withTemporaryKeys(new PropertiesConfiguration()); } ClusterSpec(); ClusterSpec(Configuration config); ClusterSpec(Configuration userConfig, boolean loadDefaults); ClusterSpec(Configuration userConfig, boolean loadDefaults, Map<String,Node> byonNodes); @VisibleForTesting static ClusterSpec withTemporaryKeys(); @VisibleForTesting static ClusterSpec withTemporaryKeys(Configuration conf); @VisibleForTesting static ClusterSpec withNoDefaults(); @VisibleForTesting static ClusterSpec withNoDefaults(Configuration conf); ClusterSpec copy(); List<InstanceTemplate> getInstanceTemplates(); InstanceTemplate getInstanceTemplate(final Set<String> roles); InstanceTemplate getInstanceTemplate(String... roles); int getMaxStartupRetries(); String getContextName(); String getProvider(); boolean isStub(); String getEndpoint(); String getIdentity(); String getCredential(); String getClusterName(); String getBlobStoreContextName(); String getBlobStoreProvider(); boolean isQuiet(); String getBlobStoreEndpoint(); String getBlobStoreIdentity(); String getBlobStoreCredential(); String getBlobStoreLocationId(); String getBlobStoreCacheContainer(); String getStateStore(); String getStateStoreContainer(); String getStateStoreBlob(); @Nullable Float getAwsEc2SpotPrice(); String getServiceName(); String getPrivateKey(); File getPrivateKeyFile(); String getPublicKey(); TemplateBuilderSpec getTemplate(); List<String> getClientCidrs(); Map<String, List<String>> getFirewallRules(); Map<String, Node> getByonNodes(); ClusterActionHandlerListener getHandlerListener(); String getVersion(); String getRunUrlBase(); String getClusterUser(); void setInstanceTemplates(List<InstanceTemplate> instanceTemplates); void setMaxStartupRetries(int maxStartupRetries); void setContextName(String contextName); void setProvider(String provider); void setEndpoint(String endpoint); void setIdentity(String identity); void setCredential(String credential); void setBlobStoreContextName(String blobStoreContextName); void setBlobStoreProvider(String provider); void setBlobStoreEndpoint(String endpoint); void setBlobStoreIdentity(String identity); void setBlobStoreCredential(String credential); void setBlobStoreLocationId(String locationId); void setBlobStoreCacheContainer(String container); void setStateStore(String type); void setStateStoreContainer(String container); void setStateStoreBlob(String blob); void setAwsEc2SpotPrice(@Nullable Float value); void setClusterName(String clusterName); void setServiceName(String serviceName); boolean isTerminateAllOnLaunchFailure(); void setTerminateAllOnLaunchFailure(boolean terminateAllOnLaunchFailure); boolean isStoreClusterInEtcHosts(); void setStoreClusterInEtcHosts(boolean storeClusterInEtcHosts); String getAwsEc2PlacementGroup(); void setAwsEc2PlacementGroup(String awsEc2PlacementGroup); String getAutoHostnameSuffix(); void setAutoHostnameSuffix(String autoHostnameSuffix); String getAutoHostnamePrefix(); void setAutoHostnamePrefix(String autoHostnamePrefix); String getJdkInstallUrl(); void setJdkInstallUrl(String jdkInstallUrl); String getKerberosRealm(); void setKerberosRealm(String kerberosRealm); void setPublicKey(String publicKey); void setPublicKey(File publicKey); void setPrivateKey(String privateKey); void setPrivateKey(File privateKey); void setTemplate(TemplateBuilderSpec template); void setClientCidrs(List<String> clientCidrs); void setFirewallRules(Map<String,List<String>> firewallRules); @VisibleForTesting void setByonNodes(Map<String,Node> byonNodes); void setQuiet(boolean isQuiet); void setHandlerListener(ClusterActionHandlerListener handlerListener); void setVersion(String version); void setRunUrlBase(String runUrlBase); void setClusterUser(String user); Configuration getConfiguration(); Configuration getConfigurationForKeysWithPrefix(String prefix); Configuration getConfigurationForKeysMatching(Pattern pattern); File getClusterDirectory(); boolean equals(Object o); int hashCode(); String toString(); } | @Test(expected = IllegalArgumentException.class) public void testMissingCommaInInstanceTemplates() throws Exception { Configuration conf = new PropertiesConfiguration(); conf.setProperty(ClusterSpec.Property.INSTANCE_TEMPLATES.getConfigName(), "1 a+b 2 c+d"); ClusterSpec.withTemporaryKeys(conf); }
@Test(expected = ConfigurationException.class) public void testInstanceTemplateNotFoundForHardwareId() throws Exception { PropertiesConfiguration conf = new PropertiesConfiguration("whirr-core-test.properties"); conf.setProperty("whirr.instance-templates", "1 role1+role2"); conf.setProperty("whirr.templates.role1.hardware-id", "m1.large"); ClusterSpec.withTemporaryKeys(conf); } |
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); } | @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: } |
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); } | @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: } |
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; } | @Test public void testPuppetConversionHiera() { Manifest postgress = new Manifest("postgresql", "server"); assertEquals("Puppet/Name representation is incorrect.", POSTGRES_PUPPET_NAME, postgress.getName()); } |
AbstractClusterCommand extends Command { protected ClusterSpec getClusterSpec(OptionSet optionSet) throws ConfigurationException { Configuration optionsConfig = new PropertiesConfiguration(); for (Map.Entry<Property, OptionSpec<?>> entry : optionSpecs.entrySet()) { Property property = entry.getKey(); OptionSpec<?> option = entry.getValue(); Object value; if (property.hasMultipleArguments()) { value = optionSet.valuesOf(option); } else { value = optionSet.valueOf(option); } if (value == null && property.getType().equals(Boolean.class) && optionSet.has(property.getSimpleName())) { value = Boolean.TRUE.toString(); } if (value != null) { optionsConfig.setProperty(property.getConfigName(), value); } } CompositeConfiguration config = new CompositeConfiguration(); config.addConfiguration(optionsConfig); if (optionSet.has(configOption)) { Configuration defaults = new PropertiesConfiguration(optionSet.valueOf(configOption)); config.addConfiguration(defaults); } ClusterSpec clusterSpec = new ClusterSpec(config); for (Property required : EnumSet.of(CLUSTER_NAME, PROVIDER, IDENTITY, CREDENTIAL, INSTANCE_TEMPLATES, PRIVATE_KEY_FILE)) { if (clusterSpec.getConfiguration().getString(required.getConfigName()) == null) { throw new IllegalArgumentException(String.format("Option '%s' not set.", required.getSimpleName())); } } return clusterSpec; } AbstractClusterCommand(String name, String description, ClusterControllerFactory factory); AbstractClusterCommand(String name, String description, ClusterControllerFactory factory,
ClusterStateStoreFactory stateStoreFactory); @Override void printUsage(PrintStream stream); } | @Test public void testOverrides() 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; } }; Map<String, File> keys = KeyPair.generateTemporaryFiles(); OptionSet optionSet = clusterCommand.parser.parse("--quiet", "--service-name", "overridden-test-service", "--config", "whirr-override-test.properties", "--private-key-file", keys.get("private").getAbsolutePath() ); ClusterSpec clusterSpec = clusterCommand.getClusterSpec(optionSet); assertThat(optionSet.has("quiet"), is(true)); assertThat(clusterSpec.isQuiet(), is(true)); assertThat(clusterSpec.getServiceName(), is("overridden-test-service")); assertThat(clusterSpec.getClusterName(), is("test-cluster")); optionSet = clusterCommand.parser.parse("--quiet", "true", "--service-name", "overridden-test-service", "--config", "whirr-override-test.properties", "--private-key-file", keys.get("private").getAbsolutePath() ); clusterSpec = clusterCommand.getClusterSpec(optionSet); assertThat(optionSet.has("quiet"), is(true)); assertThat(clusterSpec.isQuiet(), is(true)); assertThat(clusterSpec.getServiceName(), is("overridden-test-service")); assertThat(clusterSpec.getClusterName(), is("test-cluster")); optionSet = clusterCommand.parser.parse("--quiet", "false", "--service-name", "overridden-test-service", "--config", "whirr-override-test.properties", "--private-key-file", keys.get("private").getAbsolutePath() ); clusterSpec = clusterCommand.getClusterSpec(optionSet); assertThat(optionSet.has("quiet"), is(true)); assertThat(clusterSpec.isQuiet(), is(false)); assertThat(clusterSpec.getServiceName(), is("overridden-test-service")); assertThat(clusterSpec.getClusterName(), is("test-cluster")); optionSet = clusterCommand.parser.parse("--quiet", "some-value", "--service-name", "overridden-test-service", "--config", "whirr-override-test.properties", "--private-key-file", keys.get("private").getAbsolutePath() ); clusterSpec = clusterCommand.getClusterSpec(optionSet); assertThat(optionSet.has("quiet"), is(true)); assertThat(clusterSpec.isQuiet(), is(false)); assertThat(clusterSpec.getServiceName(), is("overridden-test-service")); assertThat(clusterSpec.getClusterName(), is("test-cluster")); optionSet = clusterCommand.parser.parse( "--service-name", "overridden-test-service", "--config", "whirr-override-test.properties", "--private-key-file", keys.get("private").getAbsolutePath() ); clusterSpec = clusterCommand.getClusterSpec(optionSet); assertThat(optionSet.has("quiet"), is(false)); assertThat(clusterSpec.isQuiet(), is(false)); assertThat(clusterSpec.getServiceName(), is("overridden-test-service")); assertThat(clusterSpec.getClusterName(), is("test-cluster")); } |
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); } | @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"); } |
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(); } | @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")); } |
ScriptBasedClusterAction extends ClusterAction { public Cluster execute(ClusterSpec clusterSpec, Cluster cluster) throws IOException, InterruptedException { if (clusterSpec.getInstanceTemplates().size() == 0) { throw new IllegalArgumentException("No instance templates specified."); } Map<InstanceTemplate, ClusterActionEvent> eventMap = Maps.newHashMap(); Cluster newCluster = cluster; for (InstanceTemplate instanceTemplate : clusterSpec.getInstanceTemplates()) { if (shouldIgnoreInstanceTemplate(instanceTemplate)) { continue; } StatementBuilder statementBuilder = new StatementBuilder(); ComputeServiceContext computeServiceContext = getCompute().apply(clusterSpec); FirewallManager firewallManager = new FirewallManager( computeServiceContext, clusterSpec, newCluster); VelocityEngine velocityEngine = TemplateUtils.newVelocityEngine(); ClusterActionEvent event = new ClusterActionEvent(getAction(), clusterSpec, instanceTemplate, newCluster, statementBuilder, getCompute(), firewallManager, velocityEngine); eventMap.put(instanceTemplate, event); eventSpecificActions(instanceTemplate, event); for (String role : instanceTemplate.getRoles()) { if (roleIsInTarget(role)) { safeGetActionHandler(role).beforeAction(event); } } newCluster = event.getCluster(); } doAction(eventMap); newCluster = Iterables.get(eventMap.values(), 0).getCluster(); for (InstanceTemplate instanceTemplate : clusterSpec.getInstanceTemplates()) { if (shouldIgnoreInstanceTemplate(instanceTemplate)) { continue; } ClusterActionEvent event = eventMap.get(instanceTemplate); for (String role : instanceTemplate.getRoles()) { if (roleIsInTarget(role)) { event.setCluster(newCluster); safeGetActionHandler(role).afterAction(event); newCluster = event.getCluster(); } } } return newCluster; } protected ScriptBasedClusterAction(
Function<ClusterSpec, ComputeServiceContext> getCompute,
LoadingCache<String, ClusterActionHandler> handlerMap
); protected ScriptBasedClusterAction(
Function<ClusterSpec, ComputeServiceContext> getCompute,
LoadingCache<String, ClusterActionHandler> handlerMap,
Set<String> targetRoles,
Set<String> targetInstanceIds
); Cluster execute(ClusterSpec clusterSpec, Cluster cluster); ListenableFuture<ExecResponse> runStatementOnInstanceInCluster(StatementBuilder statementBuilder,
Instance instance, ClusterSpec clusterSpec, RunScriptOptions options); } | @Test(expected = IllegalArgumentException.class) public void testEmptyInstanceTemplates() throws Exception { T action = newClusterActionInstance(EMPTYSET, EMPTYSET); DryRun dryRun = getDryRunForAction(action).reset(); ClusterSpec tempSpec = ClusterSpec.withTemporaryKeys(); tempSpec.setClusterName("test-cluster-for-script-exection"); tempSpec.setProvider("stub"); tempSpec.setIdentity("dummy"); tempSpec.setStateStore("none"); ClusterController controller = new ClusterController(); Cluster tempCluster = controller.launchCluster(tempSpec); action.execute(tempSpec, tempCluster); List<StatementOnNode> executions = dryRun.getTotallyOrderedExecutions(); }
@Test public void testActionIsExecutedOnAllRelevantNodes() throws Exception { T action = newClusterActionInstance(EMPTYSET, EMPTYSET); DryRun dryRun = getDryRunForAction(action).reset(); action.execute(clusterSpec, cluster); List<StatementOnNode> executions = dryRun.getTotallyOrderedExecutions(); assertThat(executions.size(), is(2)); }
@Test public void testFilterScriptExecutionByRole() throws Exception { String instanceId = getInstaceForRole(cluster, "noop2").getId(); T action = newClusterActionInstance(ImmutableSet.of("noop2"), EMPTYSET); DryRun dryRun = getDryRunForAction(action).reset(); action.execute(clusterSpec, cluster); List<StatementOnNode> executions = dryRun.getTotallyOrderedExecutions(); assertThat(executions.size(), is(1)); assertHasRole(executions.get(0), cluster, "noop2"); assertEquals(executions.get(0).getNode().getId(), instanceId); assertAnyStatementContains(dryRun, "noop2-" + getActionName()); assertNoStatementContains(dryRun, "noop1-" + getActionName(), "noop3-" + getActionName()); }
@Test public void testFilterScriptExecutionByInstanceId() throws Exception { String instanceId = getInstaceForRole(cluster, "noop3").getId(); T action = newClusterActionInstance(EMPTYSET, newHashSet(instanceId)); DryRun dryRun = getDryRunForAction(action).reset(); action.execute(clusterSpec, cluster); List<StatementOnNode> executions = dryRun.getTotallyOrderedExecutions(); assertThat(executions.size(), is(1)); assertHasRole(executions.get(0), cluster, "noop3"); assertEquals(executions.get(0).getNode().getId(), instanceId); assertAnyStatementContains(dryRun, "noop1-" + getActionName(), "noop3-" + getActionName()); }
@Test public void testFilterScriptExecutionByRoleAndInstanceId() throws Exception { String instanceId = getInstaceForRole(cluster, "noop1").getId(); T action = newClusterActionInstance(newHashSet("noop1"), newHashSet(instanceId)); DryRun dryRun = getDryRunForAction(action).reset(); action.execute(clusterSpec, cluster); List<StatementOnNode> executions = dryRun.getTotallyOrderedExecutions(); assertThat(executions.size(), is(1)); assertHasRole(executions.get(0), cluster, "noop1"); assertEquals(executions.get(0).getNode().getId(), instanceId); assertAnyStatementContains(dryRun, "noop1-" + getActionName()); assertNoStatementContains(dryRun, "noop2-" + getActionName(), "noop3-" + getActionName()); }
@Test public void testNoScriptExecutionsForNoop() throws Exception { T action = newClusterActionInstance(ImmutableSet.of("noop"), EMPTYSET); DryRun dryRun = getDryRunForAction(action).reset(); action.execute(clusterSpec, cluster); List<StatementOnNode> executions = dryRun.getTotallyOrderedExecutions(); assertThat(executions.size(), is(0)); } |
CreateSitePpAndApplyRoles implements Statement { @Override public String render(OsFamily arg0) { Boolean isHiera = config.getBoolean(PUPPET_HIERA_CLASSES, false); Builder<Statement> statements = ImmutableList.<Statement> builder(); statements.add(Statements.rm(SITE_PP_FILE_LOCATION)); statements.add(Statements.rm(CONF_PP_FILE_LOCATION)); statements.add(Statements.rm(HIERA_COMMON_FILE_LOCATION)); Builder<String> sitePp = ImmutableList.<String> builder(); Map<String, Set<String>> puppetRoles = Maps.newHashMap(); for (Cluster.Instance instance : instances) { for (String role : instance.getRoles()) { int firstColon = role.indexOf(':'); if (firstColon != -1 && role.substring(0, firstColon).equals(PUPPET)) { String puppetClass = role.substring(firstColon + 1); if (!puppetRoles.containsKey(puppetClass)) { puppetRoles.put(puppetClass, Sets.<String>newHashSet()); } puppetRoles.get(puppetClass).add(instance.getPrivateIp()); } } } Builder<String> confPp = ImmutableList.<String> builder(); for (String puppetClass : puppetRoles.keySet()) { confPp.add(puppetClass + "," + Joiner.on(',').join(puppetRoles.get(puppetClass))); } Builder<String> confHiera = ImmutableList.<String> builder(); for (String puppetClass : puppetRoles.keySet()) { confHiera.add(puppetClass + ":\n - " + Joiner.on("\n - ").join(puppetRoles.get(puppetClass))); } sitePp.add("$extlookup_datadir='/etc/puppet/manifests/extdata'"); sitePp.add("$extlookup_precedence = ['common']"); sitePp.add("node default {"); for (String role : roles) { String manifestAttribPrefix = role.replaceAll(":+", "."); Configuration manifestProps = new PropertiesConfiguration(); for (@SuppressWarnings("unchecked") Iterator<String> it = config.getKeys(manifestAttribPrefix); it.hasNext();) { String key = it.next(); manifestProps.setProperty(key, config.getProperty(key)); } Manifest roleManifest = getManifestForClusterSpecAndRole(role, manifestProps); if (isHiera) { sitePp.add("include " + roleManifest.getName()); confHiera.add(roleManifest.getHiera()); } else { sitePp.add(roleManifest.toString()); } } sitePp.add("}"); if (isHiera) { Builder<String> confPuppetHiera = ImmutableList.<String> builder(); confPuppetHiera.add("---", ":backends:", " - yaml", ":yaml:", " :datadir: /etc/puppet/hieradata", ":hierarchy:", " - common"); statements.add(createOrOverwriteFile(HIERA_CONF_FILE_LOCATION, confPuppetHiera.build())); statements.add(exec("mkdir -p /etc/puppet/hieradata")); } statements.add(createOrOverwriteFile(HIERA_COMMON_FILE_LOCATION, confHiera.build())); statements.add(createOrOverwriteFile(CONF_PP_FILE_LOCATION, confPp.build())); statements.add(createOrOverwriteFile(SITE_PP_FILE_LOCATION, sitePp.build())); statements.add(exec("puppet apply " + SITE_PP_FILE_LOCATION)); return new StatementList(statements.build()).render(arg0); } CreateSitePpAndApplyRoles(Iterable<String> roles, Iterable<Cluster.Instance> instances, Configuration config); @Override Iterable<String> functionDependencies(OsFamily arg0); @Override String render(OsFamily arg0); } | @Test public void testWithAttribs() throws IOException { Configuration conf = new PropertiesConfiguration(); conf.setProperty("puppet.nginx.module", "git: conf.setProperty("nginx.server.hostname", "foohost"); CreateSitePpAndApplyRoles nginx = new CreateSitePpAndApplyRoles(ImmutableSet.of("nginx::server"), ImmutableSet.of(new Cluster.Instance( new Credentials("dummy", "dummy"), Sets.newHashSet("puppet:nginx::server"), "127.0.0.1", "127.0.0.1", "id-1", null)), conf); assertEquals(CharStreams.toString(Resources.newReaderSupplier(Resources.getResource("nginx-with-attribs.txt"), Charsets.UTF_8)), nginx.render(OsFamily.UNIX)); } |
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(); } | @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)); } |
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); } | @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); } |
LaunchClusterCommand extends AbstractClusterCommand { @Override public int run(InputStream in, PrintStream out, PrintStream err, List<String> args) throws Exception { OptionSet optionSet = parser.parse(args.toArray(new String[args.size()])); if (!optionSet.nonOptionArguments().isEmpty()) { printUsage(err); return -1; } try { ClusterSpec clusterSpec = getClusterSpec(optionSet); printProviderInfo(out, err, clusterSpec, optionSet); return run(in, out, err, clusterSpec); } catch (IllegalArgumentException e) { printErrorAndHelpHint(err, e); return -1; } } LaunchClusterCommand(); LaunchClusterCommand(ClusterControllerFactory factory); @Override int run(InputStream in, PrintStream out, PrintStream err,
List<String> args); int run(InputStream in, PrintStream out, PrintStream err, ClusterSpec clusterSpec); } | @Test public void testInsufficientArgs() throws Exception { LaunchClusterCommand command = new LaunchClusterCommand(); Map<String, File> keys = KeyPair.generateTemporaryFiles(); int rc = command.run(null, null, err, Lists.<String>newArrayList( "--private-key-file", keys.get("private").getAbsolutePath()) ); assertThat(rc, is(-1)); assertThat(errBytes.toString(), containsString("Option 'cluster-name' not set.")); }
@Test public void testAllOptions() throws Exception { ClusterControllerFactory factory = mock(ClusterControllerFactory.class); ClusterController controller = mock(ClusterController.class); Cluster cluster = mock(Cluster.class); when(factory.create((String) any())).thenReturn(controller); when(controller.launchCluster((ClusterSpec) any())).thenReturn(cluster); LaunchClusterCommand command = new LaunchClusterCommand(factory); Map<String, File> keys = KeyPair.generateTemporaryFiles(); int rc = command.run(null, out, null, Lists.newArrayList( "--service-name", "test-service", "--cluster-name", "test-cluster", "--instance-templates", "1 role1+role2,2 role3", "--provider", "rackspace", "--endpoint", "http: "--blobstore-endpoint", "http: "--identity", "myusername", "--credential", "mypassword", "--private-key-file", keys.get("private").getAbsolutePath(), "--version", "version-string" )); assertThat(rc, is(0)); Configuration conf = new PropertiesConfiguration(); conf.addProperty("whirr.version", "version-string"); ClusterSpec expectedClusterSpec = ClusterSpec.withTemporaryKeys(conf); expectedClusterSpec.setInstanceTemplates(Lists.newArrayList( InstanceTemplate.builder().numberOfInstance(1).roles("role1", "role2").build(), InstanceTemplate.builder().numberOfInstance(2).roles("role3").build() )); expectedClusterSpec.setServiceName("test-service"); expectedClusterSpec.setProvider("rackspace"); expectedClusterSpec.setEndpoint("http: expectedClusterSpec.setIdentity("myusername"); expectedClusterSpec.setCredential("mypassword"); expectedClusterSpec.setBlobStoreEndpoint("http: expectedClusterSpec.setClusterName("test-cluster"); expectedClusterSpec.setPrivateKey(keys.get("private")); expectedClusterSpec.setPublicKey(keys.get("public")); verify(factory).create("test-service"); verify(controller).launchCluster(expectedClusterSpec); assertThat(outBytes.toString(), containsString("Started cluster of 0 instances")); }
@Test public void testMaxPercentFailure() throws Exception { ClusterControllerFactory factory = mock(ClusterControllerFactory.class); ClusterController controller = mock(ClusterController.class); Cluster cluster = mock(Cluster.class); when(factory.create((String) any())).thenReturn(controller); when(controller.launchCluster((ClusterSpec) any())).thenReturn(cluster); LaunchClusterCommand command = new LaunchClusterCommand(factory); Map<String, File> keys = KeyPair.generateTemporaryFiles(); int rc = command.run(null, out, null, Lists.newArrayList( "--service-name", "hadoop", "--cluster-name", "test-cluster", "--instance-templates", "1 hadoop-namenode+hadoop-jobtracker,3 hadoop-datanode+hadoop-tasktracker", "--instance-templates-max-percent-failures", "60 hadoop-datanode+hadoop-tasktracker", "--provider", "aws-ec2", "--identity", "myusername", "--credential", "mypassword", "--private-key-file", keys.get("private").getAbsolutePath(), "--version", "version-string" )); assertThat(rc, is(0)); Configuration conf = new PropertiesConfiguration(); conf.addProperty("whirr.provider", "aws-ec2"); conf.addProperty("whirr.version", "version-string"); conf.addProperty("whirr.instance-templates-max-percent-failure", "60 hadoop-datanode+hadoop-tasktracker"); ClusterSpec expectedClusterSpec = ClusterSpec.withTemporaryKeys(conf); expectedClusterSpec.setInstanceTemplates(Lists.newArrayList( InstanceTemplate.builder().numberOfInstance(1).minNumberOfInstances(1) .roles("hadoop-namenode", "hadoop-jobtracker").build(), InstanceTemplate.builder().numberOfInstance(3).minNumberOfInstances(2) .roles("hadoop-datanode", "hadoop-tasktracker").build() )); expectedClusterSpec.setServiceName("hadoop"); expectedClusterSpec.setIdentity("myusername"); expectedClusterSpec.setCredential("mypassword"); expectedClusterSpec.setClusterName("test-cluster"); expectedClusterSpec.setPrivateKey(keys.get("private")); expectedClusterSpec.setPublicKey(keys.get("public")); verify(factory).create("hadoop"); verify(controller).launchCluster(expectedClusterSpec); assertThat(outBytes.toString(), containsString("Started cluster of 0 instances")); }
@Test public void testLaunchClusterUsingDryRun() throws Exception { ClusterControllerFactory factory = new ClusterControllerFactory(); TestLaunchClusterCommand launchCluster = new TestLaunchClusterCommand(factory); Map<String, File> keys = KeyPair.generateTemporaryFiles(); int rc = launchCluster.run(null, out, err, Lists.<String>newArrayList( "--cluster-name", "test-cluster-launch", "--state-store", "none", "--instance-templates", "1 zookeeper+cassandra, 1 zookeeper+elasticsearch", "--provider", "stub", "--identity", "dummy", "--private-key-file", keys.get("private").getAbsolutePath() )); MatcherAssert.assertThat(rc, is(0)); assertExecutedPhases(launchCluster.dryRun, "bootstrap", "configure", "start"); } |
RunScriptCommand extends AbstractClusterCommand { @Override public int run(InputStream in, PrintStream out, PrintStream err, List<String> args) throws Exception { OptionSet optionSet = parser.parse(args.toArray(new String[0])); if (!optionSet.has(scriptOption)) { err.println("Please specify a script file to be executed."); err.println("Get more help: whirr help " + getName()); return -1; } if (!(new File(optionSet.valueOf(scriptOption))).exists()) { err.printf("Script file '%s' not found.", optionSet.valueOf(scriptOption)); err.println("Get more help: whirr help " + getName()); return -2; } try { ClusterSpec clusterSpec = getClusterSpec(optionSet); String[] ids = null; String[] roles = null; if (optionSet.has(instancesOption)) { ids = optionSet.valueOf(instancesOption).split(","); } if (optionSet.has(rolesOption)) { roles = optionSet.valueOf(rolesOption).split(","); } printProviderInfo(out, err, clusterSpec, optionSet); return run(in, out, err, clusterSpec, ids, roles, optionSet.valueOf(scriptOption)); } catch (IllegalArgumentException e) { printErrorAndHelpHint(err, e); return -3; } } RunScriptCommand(); RunScriptCommand(ClusterControllerFactory factory); RunScriptCommand(ClusterControllerFactory factory,
ClusterStateStoreFactory stateStoreFactory); @Override int run(InputStream in, PrintStream out, PrintStream err,
List<String> args); int run(InputStream in, PrintStream out, PrintStream err,
ClusterSpec clusterSpec, String[] instances, String[] roles,
String fileName); @Override void printUsage(PrintStream stream); } | @Test public void testScriptPathIsMandatory() throws Exception { RunScriptCommand command = new RunScriptCommand(); int rc = command.run(null, out, err, Lists.<String>newArrayList()); assertThat(rc, is(-1)); assertThat(errBytes.toString(), containsString("Please specify a script file to be executed.")); }
@Test public void testRunScriptByInstanceId() throws Exception { ClusterControllerFactory factory = mock(ClusterControllerFactory.class); ClusterController controller = mock(ClusterController.class); when(factory.create((String)any())).thenReturn(controller); RunScriptCommand command = new RunScriptCommand(factory); Map<String, File> keys = KeyPair.generateTemporaryFiles(); int rc = command.run(null, out, System.err, Lists.newArrayList( "--script", "/dev/null", "--instance-templates", "1 noop", "--instances", "A,B", "--cluster-name", "test-cluster", "--provider", "provider", "--identity", "myusername", "--credential", "mypassword", "--private-key-file", keys.get("private").getAbsolutePath() )); assertThat(rc, is(0)); ArgumentCaptor<Predicate> predicate = ArgumentCaptor.forClass(Predicate.class); verify(controller).runScriptOnNodesMatching( (ClusterSpec)any(), predicate.capture(), (Statement) any()); Predicate<NodeMetadata> expected = Predicates.and( Predicates.<NodeMetadata>alwaysTrue(), withIds("A", "B")); assertThat(predicate.getValue().toString(), is(expected.toString())); }
@Test public void testRunScriptByRole() throws Exception { ClusterControllerFactory factory = mock(ClusterControllerFactory.class); ClusterController controller = mock(ClusterController.class); when(factory.create((String)any())).thenReturn(controller); ClusterStateStore memStore = new MemoryClusterStateStore(); memStore.save(createTestCluster( new String[]{"reg/A", "reg/B"}, new String[]{"A", "B"})); ClusterStateStoreFactory stateStoreFactory = mock(ClusterStateStoreFactory.class); when(stateStoreFactory.create((ClusterSpec) any())).thenReturn(memStore); RunScriptCommand command = new RunScriptCommand(factory, stateStoreFactory); Map<String, File> keys = KeyPair.generateTemporaryFiles(); int rc = command.run(null, out, System.err, Lists.newArrayList( "--instance-templates", "1 noop", "--script", "/dev/null", "--roles", "A", "--cluster-name", "test-cluster", "--provider", "provider", "--identity", "myusername", "--credential", "mypassword", "--private-key-file", keys.get("private").getAbsolutePath() )); assertThat(rc, is(0)); ArgumentCaptor<Predicate> predicate = ArgumentCaptor.forClass(Predicate.class); verify(controller).runScriptOnNodesMatching( (ClusterSpec)any(), predicate.capture(), (Statement) any()); Predicate<NodeMetadata> expected = Predicates.and( Predicates.<NodeMetadata>alwaysTrue(), withIds("reg/A")); assertThat(predicate.getValue().toString(), is(expected.toString())); } |
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); } | @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)); } |
DestroyClusterCommand extends AbstractClusterCommand { @Override public int run(InputStream in, PrintStream out, PrintStream err, List<String> args) throws Exception { OptionSet optionSet = parser.parse(args.toArray(new String[args.size()])); if (!optionSet.nonOptionArguments().isEmpty()) { printUsage(err); return -1; } try { ClusterSpec clusterSpec = getClusterSpec(optionSet); printProviderInfo(out, err, clusterSpec, optionSet); return run(in, out, err, clusterSpec); } catch (IllegalArgumentException e) { printErrorAndHelpHint(err, e); return -1; } } DestroyClusterCommand(); DestroyClusterCommand(ClusterControllerFactory factory); @Override int run(InputStream in, PrintStream out, PrintStream err,
List<String> args); int run(InputStream in, PrintStream out, PrintStream err,
ClusterSpec clusterSpec); } | @Test public void testInsufficientOptions() throws Exception { DestroyClusterCommand command = new DestroyClusterCommand(); Map<String, File> keys = KeyPair.generateTemporaryFiles(); int rc = command.run(null, null, err, Lists.<String>newArrayList( "--private-key-file", keys.get("private").getAbsolutePath()) ); assertThat(rc, is(-1)); assertThat(errBytes.toString(), containsString("Option 'cluster-name' not set")); }
@Test public void testAllOptions() throws Exception { ClusterControllerFactory factory = mock(ClusterControllerFactory.class); ClusterController controller = mock(ClusterController.class); when(factory.create((String) any())).thenReturn(controller); DestroyClusterCommand command = new DestroyClusterCommand(factory); Map<String, File> keys = KeyPair.generateTemporaryFiles(); int rc = command.run(null, out, null, Lists.newArrayList( "--instance-templates", "1 noop", "--service-name", "test-service", "--cluster-name", "test-cluster", "--provider", "rackspace", "--identity", "myusername", "--credential", "mypassword", "--private-key-file", keys.get("private").getAbsolutePath(), "--version", "version-string" )); assertThat(rc, is(0)); Configuration conf = new PropertiesConfiguration(); conf.addProperty("whirr.version", "version-string"); conf.addProperty("whirr.instance-templates", "1 noop"); ClusterSpec expectedClusterSpec = ClusterSpec.withTemporaryKeys(conf); expectedClusterSpec.setServiceName("test-service"); expectedClusterSpec.setProvider("rackspace"); expectedClusterSpec.setIdentity("myusername"); expectedClusterSpec.setCredential("mypassword"); expectedClusterSpec.setClusterName("test-cluster"); expectedClusterSpec.setPrivateKey(keys.get("private")); expectedClusterSpec.setPublicKey(keys.get("public")); verify(factory).create("test-service"); verify(controller).destroyCluster(expectedClusterSpec); } |
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); } | @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")); } |
ListClusterCommand extends AbstractClusterCommand { @Override public int run(InputStream in, PrintStream out, PrintStream err, List<String> args) throws Exception { OptionSet optionSet = parser.parse(args.toArray(new String[args.size()])); if (!optionSet.nonOptionArguments().isEmpty()) { printUsage(err); return -1; } try { ClusterSpec clusterSpec = getClusterSpec(optionSet); printProviderInfo(out, err, clusterSpec, optionSet); return run(in, out, err, clusterSpec); } catch (IllegalArgumentException e) { printErrorAndHelpHint(err, e); return -1; } } ListClusterCommand(); ListClusterCommand(ClusterControllerFactory factory); ListClusterCommand(ClusterControllerFactory factory,
ClusterStateStoreFactory stateStoreFactory); @Override int run(InputStream in, PrintStream out, PrintStream err,
List<String> args); int run(InputStream in, PrintStream out, PrintStream err, ClusterSpec clusterSpec); } | @Test public void testInsufficientOptions() throws Exception { ListClusterCommand command = new ListClusterCommand(); Map<String, File> keys = KeyPair.generateTemporaryFiles(); int rc = command.run(null, null, err, Lists.<String>newArrayList( "--private-key-file", keys.get("private").getAbsolutePath()) ); assertThat(rc, is(-1)); assertThat(errBytes.toString(), containsString("Option 'cluster-name' not set.")); }
@Test public void testAllOptions() throws Exception { ClusterControllerFactory factory = mock(ClusterControllerFactory.class); ClusterController controller = mock(ClusterController.class); when(factory.create((String) any())).thenReturn(controller); NodeMetadata node1 = new NodeMetadataBuilder().name("name1").ids("id1") .location(new LocationBuilder().scope(LocationScope.PROVIDER) .id("location-id1").description("location-desc1").build()) .imageId("image-id").status(NodeMetadata.Status.RUNNING) .publicAddresses(Lists.newArrayList("127.0.0.1")) .privateAddresses(Lists.newArrayList("127.0.0.1")).build(); NodeMetadata node2 = new NodeMetadataBuilder().name("name2").ids("id2") .location(new LocationBuilder().scope(LocationScope.PROVIDER) .id("location-id2").description("location-desc2").build()) .imageId("image-id").status(NodeMetadata.Status.RUNNING) .publicAddresses(Lists.newArrayList("127.0.0.2")) .privateAddresses(Lists.newArrayList("127.0.0.2")).build(); when(controller.getNodes((ClusterSpec) any())).thenReturn( (Set) Sets.newLinkedHashSet(Lists.newArrayList(node1, node2))); when(controller.getInstances((ClusterSpec)any(), (ClusterStateStore)any())) .thenCallRealMethod(); ClusterStateStore memStore = new MemoryClusterStateStore(); memStore.save(createTestCluster( new String[]{"id1", "id2"}, new String[]{"role1", "role2"})); ClusterStateStoreFactory stateStoreFactory = mock(ClusterStateStoreFactory.class); when(stateStoreFactory.create((ClusterSpec) any())).thenReturn(memStore); ListClusterCommand command = new ListClusterCommand(factory, stateStoreFactory); Map<String, File> keys = KeyPair.generateTemporaryFiles(); int rc = command.run(null, out, null, Lists.newArrayList( "--instance-templates", "1 noop", "--service-name", "test-service", "--cluster-name", "test-cluster", "--identity", "myusername", "--quiet", "--private-key-file", keys.get("private").getAbsolutePath()) ); assertThat(rc, is(0)); assertThat(outBytes.toString(), is( "id1\timage-id\t127.0.0.1\t127.0.0.1\tRUNNING\tlocation-id1\trole1\n" + "id2\timage-id\t127.0.0.2\t127.0.0.2\tRUNNING\tlocation-id2\trole2\n")); verify(factory).create("test-service"); } |
DestroyInstanceCommand extends AbstractClusterCommand { @Override public int run(InputStream in, PrintStream out, PrintStream err, List<String> args) throws Exception { OptionSet optionSet = parser.parse(args.toArray(new String[args.size()])); if (!optionSet.nonOptionArguments().isEmpty()) { printUsage(err); return -1; } try { if (!optionSet.hasArgument(instanceOption)) { throw new IllegalArgumentException("--instance-id is a mandatory argument"); } ClusterSpec clusterSpec = getClusterSpec(optionSet); String instanceId = optionSet.valueOf(instanceOption); printProviderInfo(out, err, clusterSpec, optionSet); return run(in, out, err, clusterSpec, instanceId); } catch (IllegalArgumentException e) { printErrorAndHelpHint(err, e); return -1; } } DestroyInstanceCommand(); DestroyInstanceCommand(ClusterControllerFactory factory); @Override int run(InputStream in, PrintStream out,
PrintStream err, List<String> args); int run(InputStream in, PrintStream out, PrintStream err,
ClusterSpec clusterSpec, String instanceId); @Override void printUsage(PrintStream stream); } | @Test public void testInstanceIdMandatory() throws Exception { DestroyInstanceCommand command = new DestroyInstanceCommand(); int rc = command.run(null, out, err, Collections.<String>emptyList()); assertThat(rc, is(-1)); String errOutput = errBytes.toString(); assertThat(errOutput, containsString("--instance-id is a mandatory argument")); }
@Test public void testDestroyInstanceById() throws Exception { ClusterControllerFactory factory = mock(ClusterControllerFactory.class); ClusterController controller = mock(ClusterController.class); when(factory.create((String) any())).thenReturn(controller); DestroyInstanceCommand command = new DestroyInstanceCommand(factory); Map<String, File> keys = KeyPair.generateTemporaryFiles(); int rc = command.run(null, out, null, Lists.newArrayList( "--instance-templates", "1 noop", "--instance-id", "region/instanceid", "--service-name", "test-service", "--cluster-name", "test-cluster", "--provider", "rackspace", "--identity", "myusername", "--credential", "mypassword", "--private-key-file", keys.get("private").getAbsolutePath(), "--version", "version-string" )); assertThat(rc, is(0)); verify(controller).destroyInstance((ClusterSpec) any(), eq("region/instanceid")); } |
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); } | @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")); } |
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(); } | @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 ) ); } |
FilterFactory { public Filter createMethodFilter( String requestedTestMethod ) { return new MethodFilter( requestedTestMethod ); } FilterFactory( ClassLoader testClassLoader ); boolean canCreateGroupFilter( Map<String, String> providerProperties ); Filter createGroupFilter( Map<String, String> providerProperties ); Filter createMethodFilter( String requestedTestMethod ); Filter createMethodFilter( TestListResolver resolver ); Filter createMatchAnyDescriptionFilter( Iterable<Description> descriptions ); Filter and( Filter filter1, Filter filter2 ); } | @Test public void testRegexWithTwoClassesAndRegexMethodsComplement() { Filter filter = createMethodFilter( "!%regex[" + firstClassRegex + ".*|" + secondClassRegex + ".* # test.*|other.* ]" ); JUnitCore core = new JUnitCore(); Result result = core.run( Request.classes( FirstClass.class, SecondClass.class, ThirdClass.class ) .filterWith( filter ) ); assertTrue( result.wasSuccessful() ); assertEquals( 4, result.getRunCount() ); assertEquals( 0, result.getFailureCount() ); assertEquals( 0, result.getIgnoreCount() ); }
@Test public void testMultipleRegexClasses() { Filter filter = createMethodFilter( "%regex[" + firstClassRegex + ".*], %regex[" + secondClassRegex + ".*]" ); JUnitCore core = new JUnitCore(); Result result = core.run( Request.classes( FirstClass.class, SecondClass.class, ThirdClass.class ) .filterWith( filter ) ); assertTrue( result.wasSuccessful() ); assertEquals( 5, result.getRunCount() ); assertEquals( 0, result.getFailureCount() ); assertEquals( 0, result.getIgnoreCount() ); }
@Test public void testMultipleRegexClassesComplement() { Filter filter = createMethodFilter( "!%regex[" + firstClassRegex + ".*] , !%regex[" + secondClassRegex + ".*]" ); JUnitCore core = new JUnitCore(); Result result = core.run( Request.classes( FirstClass.class, SecondClass.class, ThirdClass.class ) .filterWith( filter ) ); assertTrue( result.wasSuccessful() ); assertEquals( 2, result.getRunCount() ); assertEquals( 0, result.getFailureCount() ); assertEquals( 0, result.getIgnoreCount() ); }
@Test public void testMultipleClasses() { Filter filter = createMethodFilter( firstClassName + "," + secondClassName ); JUnitCore core = new JUnitCore(); Result result = core.run( Request.classes( FirstClass.class, SecondClass.class, ThirdClass.class ) .filterWith( filter ) ); assertTrue( result.wasSuccessful() ); assertEquals( 5, result.getRunCount() ); assertEquals( 0, result.getFailureCount() ); assertEquals( 0, result.getIgnoreCount() ); }
@Test public void testMultipleClassesMethods() { Filter filter = createMethodFilter( firstClassName + "#other*," + secondClassName + "#*TestMethod" ); JUnitCore core = new JUnitCore(); Result result = core.run( Request.classes( FirstClass.class, SecondClass.class, ThirdClass.class ) .filterWith( filter ) ); assertTrue( result.wasSuccessful() ); assertEquals( 2, result.getRunCount() ); assertEquals( 0, result.getFailureCount() ); assertEquals( 0, result.getIgnoreCount() ); }
@Test public void testMultipleClassesAndMultipleMethodsWithWildcards() { Filter filter = createMethodFilter( firstClassName + "#other*+second*Method," + secondClassName + "#*TestMethod" ); JUnitCore core = new JUnitCore(); Result result = core.run( Request.classes( FirstClass.class, SecondClass.class, ThirdClass.class ) .filterWith( filter ) ); assertTrue( result.wasSuccessful() ); assertEquals( 3, result.getRunCount() ); assertEquals( 0, result.getFailureCount() ); assertEquals( 0, result.getIgnoreCount() ); }
@Test public void testMultipleClassesAndMultipleMethodsWithRegex() { Filter filter = createMethodFilter( "%regex[" + firstClassRegex + ".class#other.*|second.*Method]," + "%regex[" + secondClassRegex + ".class#.*TestMethod]" ); JUnitCore core = new JUnitCore(); Result result = core.run( Request.classes( FirstClass.class, SecondClass.class, ThirdClass.class ) .filterWith( filter ) ); assertTrue( result.wasSuccessful() ); assertEquals( 3, result.getRunCount() ); assertEquals( 0, result.getFailureCount() ); assertEquals( 0, result.getIgnoreCount() ); }
@Test public void testMultipleClassesAndMultipleMethodsMix() { Filter filter = createMethodFilter( "%regex[" + firstClassRegex + ".class # other.*|second.*Method]," + secondClassName + "#*TestMethod" ); JUnitCore core = new JUnitCore(); Result result = core.run( Request.classes( FirstClass.class, SecondClass.class, ThirdClass.class ) .filterWith( filter ) ); assertTrue( result.wasSuccessful() ); assertEquals( 3, result.getRunCount() ); assertEquals( 0, result.getFailureCount() ); assertEquals( 0, result.getIgnoreCount() ); }
@Test public void testMultipleClassesAndMultipleMethods() { Filter filter = createMethodFilter( firstClassName + "#other*+secondTestMethod," + secondClassName + "#*TestMethod" ); JUnitCore core = new JUnitCore(); Result result = core.run( Request.classes( FirstClass.class, SecondClass.class, ThirdClass.class ) .filterWith( filter ) ); assertTrue( result.wasSuccessful() ); assertEquals( 3, result.getRunCount() ); assertEquals( 0, result.getFailureCount() ); assertEquals( 0, result.getIgnoreCount() ); }
@Test public void testMultipleClassesComplement() { Filter filter = createMethodFilter( "!" + firstClassName + ",!" + secondClassName ); JUnitCore core = new JUnitCore(); Result result = core.run( Request.classes( FirstClass.class, SecondClass.class, ThirdClass.class ) .filterWith( filter ) ); assertTrue( result.wasSuccessful() ); assertEquals( 2, result.getRunCount() ); assertEquals( 0, result.getFailureCount() ); assertEquals( 0, result.getIgnoreCount() ); }
@Test public void testMultipleRegexClassesMethods() { Filter filter = createMethodFilter( "%regex[" + firstClassRegex + ".* # test.*|other.*]," + "%regex[" + secondClassRegex + ".*#second.*]" ); JUnitCore core = new JUnitCore(); Result result = core.run( Request.classes( FirstClass.class, SecondClass.class, ThirdClass.class ) .filterWith( filter ) ); assertTrue( result.wasSuccessful() ); assertEquals( 3, result.getRunCount() ); assertEquals( 0, result.getFailureCount() ); assertEquals( 0, result.getIgnoreCount() ); }
@Test public void testMultipleRegexClassesMethodsComplement() { Filter filter = createMethodFilter( "!%regex[" + firstClassRegex + ".* # test.*|other.*]," + "!%regex[" + secondClassRegex + ".*#second.*]" ); JUnitCore core = new JUnitCore(); Result result = core.run( Request.classes( FirstClass.class, SecondClass.class, ThirdClass.class ) .filterWith( filter ) ); assertTrue( result.wasSuccessful() ); assertEquals( 4, result.getRunCount() ); assertEquals( 0, result.getFailureCount() ); assertEquals( 0, result.getIgnoreCount() ); }
@Test public void testShouldMatchExactMethodName() { Filter exactFilter = createMethodFilter( "#testMethod" ); assertTrue( "exact match on name should run", exactFilter.shouldRun( testMethod ) ); }
@Test public void testShouldMatchExactMethodNameComplement() { Filter exactFilter = createMethodFilter( "!#testMethod" ); assertFalse( "should not run testMethod", exactFilter.shouldRun( testMethod ) ); assertTrue( "should run other than testMethod", exactFilter.shouldRun( secondTestMethod ) ); assertFalse( "should not run testMethod", exactFilter.shouldRun( testMethodInSecondClass ) ); assertTrue( "should run other than testMethod", exactFilter.shouldRun( secondTestMethodInSecondClass ) ); exactFilter = createMethodFilter( "!FilterFactoryTest$FirstClass#testMethod" ); assertFalse( "should not run testMethod", exactFilter.shouldRun( testMethod ) ); assertTrue( "should run other than testMethod", exactFilter.shouldRun( secondTestMethod ) ); assertTrue( "should not run testMethod", exactFilter.shouldRun( testMethodInSecondClass ) ); assertTrue( "should run other than testMethod", exactFilter.shouldRun( secondTestMethodInSecondClass ) ); exactFilter = createMethodFilter( "!FilterFactoryTest$FirstClass#testMethod, !FilterFactoryTest$SecondClass#testMethod" ); assertFalse( "should not run testMethod", exactFilter.shouldRun( testMethod ) ); assertTrue( "should run other than testMethod", exactFilter.shouldRun( secondTestMethod ) ); assertFalse( "should not run testMethod", exactFilter.shouldRun( testMethodInSecondClass ) ); assertTrue( "should run other than testMethod", exactFilter.shouldRun( secondTestMethodInSecondClass ) ); }
@Test public void testShouldMatchExactMethodNameWithHash() { final Filter exactFilter = createMethodFilter( "#testMethod" ); assertTrue( "exact match on name should run", exactFilter.shouldRun( testMethod ) ); }
@Test public void testShouldNotRunDifferentMethods() { final Filter exactFilter = createMethodFilter( "#testMethod" ); Description testCase = createSuiteDescription( FirstClass.class ); testCase.addChild( otherMethod ); assertFalse( "exact match test case", exactFilter.shouldRun( testCase ) ); }
@Test public void testShouldNotRunExactMethodWithoutClass() { Filter exactFilter = createMethodFilter( "#testMethod" ); assertFalse( "should run containing matching method", exactFilter.shouldRun( secondTestMethod ) ); }
@Test public void testShouldNotMatchExactOnOtherMethod() { Filter exactFilter = createMethodFilter( "#testMethod" ); assertFalse( "should not run other methods", exactFilter.shouldRun( otherMethod ) ); }
@Test public void testShouldMatchWildCardsInMethodName() { Filter starAtEnd = createMethodFilter( "#test*" ); assertTrue( "match ending with star should run", starAtEnd.shouldRun( testMethod ) ); Filter starAtBeginning = createMethodFilter( "#*Method" ); assertTrue( "match starting with star should run", starAtBeginning.shouldRun( testMethod ) ); Filter starInMiddle = createMethodFilter( "#test*thod" ); assertTrue( "match containing star should run", starInMiddle.shouldRun( testMethod ) ); Filter questionAtEnd = createMethodFilter( "#testMetho?" ); assertTrue( "match ending with question mark should run", questionAtEnd.shouldRun( testMethod ) ); Filter questionAtBeginning = createMethodFilter( "#????Method" ); assertTrue( "match starting with question mark should run", questionAtBeginning.shouldRun( testMethod ) ); Filter questionInMiddle = createMethodFilter( "#testM?thod" ); assertTrue( "match containing question mark should run", questionInMiddle.shouldRun( testMethod ) ); Filter starAndQuestion = createMethodFilter( "#t?st*thod" ); assertTrue( "match containing star and question mark should run", starAndQuestion.shouldRun( testMethod ) ); }
@Test public void testShouldMatchExactClassAndMethod() { Filter exactFilter = createMethodFilter( firstClassName + "#testMethod" ); assertTrue( "exact match on name should run", exactFilter.shouldRun( testMethod ) ); }
@Test public void testShouldMatchSimpleClassNameWithMethod() { Filter exactFilter = createMethodFilter( "FilterFactoryTest$FirstClass#testMethod" ); assertTrue( "exact match on name should run", exactFilter.shouldRun( testMethod ) ); assertFalse( "other method should not match", exactFilter.shouldRun( otherMethod ) ); }
@Test public void testShouldMatchNestedClassAsRegexWithMethod() { Filter exactFilter = createMethodFilter( "%regex[.*.common.junit48.FilterFactoryTest\\$FirstClass.class#testMethod]" ); assertTrue( "exact match on name should run", exactFilter.shouldRun( testMethod ) ); assertFalse( "other method should not match", exactFilter.shouldRun( otherMethod ) ); }
@Test public void testShouldMatchNestedCanonicalClassAsRegexWithMethod() { Filter exactFilter = createMethodFilter( "%regex[.*.common.junit48.FilterFactoryTest.FirstClass.class#testMethod]" ); assertTrue( "exact match on name should run", exactFilter.shouldRun( testMethod ) ); assertFalse( "other method should not match", exactFilter.shouldRun( otherMethod ) ); }
@Test public void testShouldMatchClassNameWithWildcardAndMethod() { Filter exactFilter = createMethodFilter( "*First*#testMethod" ); assertTrue( "exact match on name should run", exactFilter.shouldRun( testMethod ) ); assertFalse( "other method should not match", exactFilter.shouldRun( otherMethod ) ); }
@Test public void testShouldMatchClassNameWithWildcardCompletely() { Filter exactFilter = createMethodFilter( "First*#testMethod" ); assertFalse( "other method should not match", exactFilter.shouldRun( testMethod ) ); assertFalse( "other method should not match", exactFilter.shouldRun( otherMethod ) ); }
@Test public void testShouldMatchMultipleMethodsSeparatedByComma() { Filter exactFilter = createMethodFilter( firstClassName + "#testMethod,#secondTestMethod" ); assertTrue( "exact match on name should run", exactFilter.shouldRun( testMethod ) ); assertTrue( "exact match on name should run", exactFilter.shouldRun( secondTestMethod ) ); assertTrue( "exact match on name should run", exactFilter.shouldRun( secondTestMethodInSecondClass ) ); assertFalse( "other method should not match", exactFilter.shouldRun( otherMethod ) ); }
@Test public void testShouldMatchMultipleMethodsInSameClassSeparatedByPlus() { Filter exactFilter = createMethodFilter( firstClassName + "#testMethod+secondTestMethod" ); assertTrue( "exact match on name should run", exactFilter.shouldRun( testMethod ) ); assertTrue( "exact match on name should run", exactFilter.shouldRun( secondTestMethod ) ); assertFalse( "method in another class should not match", exactFilter.shouldRun( secondTestMethodInSecondClass ) ); assertFalse( "other method should not match", exactFilter.shouldRun( otherMethod ) ); }
@Test public void testShouldRunCompleteClassWhenSeparatedByCommaWithoutHash() { Filter exactFilter = createMethodFilter( firstClassName + "#testMethod," + secondClassName ); assertTrue( "exact match on name should run", exactFilter.shouldRun( testMethod ) ); assertFalse( "other method should not match", exactFilter.shouldRun( secondTestMethod ) ); assertFalse( "other method should not match", exactFilter.shouldRun( otherMethod ) ); assertTrue( "should run complete second class", exactFilter.shouldRun( testMethodInSecondClass ) ); assertTrue( "should run complete second class", exactFilter.shouldRun( secondTestMethodInSecondClass ) ); }
@Test public void testShouldRunSuitesContainingExactMethodName() { Description suite = Description.createSuiteDescription( Suite.class ); suite.addChild( testMethod ); suite.addChild( secondTestMethod ); Filter exactFilter = createMethodFilter( "#testMethod" ); assertTrue( "should run suites containing matching method", exactFilter.shouldRun( suite ) ); }
@Test public void testShouldSkipSuitesNotContainingExactMethodName() { Filter exactFilter = createMethodFilter( "#otherMethod" ); assertFalse( "should not run method", exactFilter.shouldRun( testMethod ) ); assertFalse( "should not run method", exactFilter.shouldRun( secondTestMethod ) ); Description suite = Description.createSuiteDescription( Suite.class ); suite.addChild( testMethod ); suite.addChild( secondTestMethod ); assertFalse( "should not run suites containing no matches", exactFilter.shouldRun( suite ) ); }
@Test public void testSingleMethodWithJUnitCoreSuite() { Filter filter = createMethodFilter( "#testMethod" ); JUnitCore core = new JUnitCore(); Result result = core.run( Request.classes( Suite.class ).filterWith( filter ) ); assertTrue( result.wasSuccessful() ); assertEquals( 2, result.getRunCount() ); assertEquals( 0, result.getFailureCount() ); assertEquals( 0, result.getIgnoreCount() ); }
@Test public void testShouldNotRunNonExistingMethodJUnitCoreSuite() { Filter filter = createMethodFilter( "#nonExisting" ); JUnitCore core = new JUnitCore(); Result result = core.run( Request.classes( Suite.class ).filterWith( filter ) ); assertTrue( result.wasSuccessful() ); assertEquals( 0, result.getRunCount() ); assertEquals( 0, result.getFailureCount() ); assertEquals( 0, result.getIgnoreCount() ); }
@Test public void testShouldRunNonExistingMethodJUnitCoreSuite() { Filter filter = createMethodFilter( "!#nonExisting" ); JUnitCore core = new JUnitCore(); Result result = core.run( Request.classes( Suite.class ).filterWith( filter ) ); assertTrue( result.wasSuccessful() ); assertEquals( 5, result.getRunCount() ); assertEquals( 0, result.getFailureCount() ); assertEquals( 0, result.getIgnoreCount() ); }
@Test public void testClassAndMethodJUnitCoreSuite() { Filter filter = createMethodFilter( "FilterFactoryTest$FirstClass#testMethod" ); JUnitCore core = new JUnitCore(); Result result = core.run( Request.classes( Suite.class, FirstClass.class, SecondClass.class ) .filterWith( filter ) ); assertTrue( result.wasSuccessful() ); assertEquals( 2, result.getRunCount() ); assertEquals( 0, result.getFailureCount() ); assertEquals( 0, result.getIgnoreCount() ); }
@Test public void testSingleMethodWithJUnitCoreFirstClass() { Filter filter = createMethodFilter( "#testMethod" ); JUnitCore core = new JUnitCore(); Result result = core.run( Request.classes( FirstClass.class ).filterWith( filter ) ); assertTrue( result.wasSuccessful() ); assertEquals( 1, result.getRunCount() ); assertEquals( 0, result.getFailureCount() ); assertEquals( 0, result.getIgnoreCount() ); }
@Test public void testWithJUnitCoreFirstClassAndSingleMethod() { Filter filter = createMethodFilter( "FilterFactoryTest$FirstClass#testMethod" ); JUnitCore core = new JUnitCore(); Result result = core.run( Request.classes( FirstClass.class ).filterWith( filter ) ); assertTrue( result.wasSuccessful() ); assertEquals( 1, result.getRunCount() ); assertEquals( 0, result.getFailureCount() ); assertEquals( 0, result.getIgnoreCount() ); }
@Test public void testBackwardsCompatibilityNullMethodFilter() { Filter filter = createMethodFilter( null ); JUnitCore core = new JUnitCore(); Result result = core.run( Request.classes( FirstClass.class, SecondClass.class ).filterWith( filter ) ); assertTrue( result.wasSuccessful() ); assertEquals( 5, result.getRunCount() ); assertEquals( 0, result.getFailureCount() ); assertEquals( 0, result.getIgnoreCount() ); }
@Test public void testBackwardsCompatibilityEmptyMethodFilter() { Filter filter = createMethodFilter( "" ); JUnitCore core = new JUnitCore(); Result result = core.run( Request.classes( FirstClass.class, SecondClass.class ).filterWith( filter ) ); assertTrue( result.wasSuccessful() ); assertEquals( 5, result.getRunCount() ); assertEquals( 0, result.getFailureCount() ); assertEquals( 0, result.getIgnoreCount() ); }
@Test public void testBackwardsCompatibilityBlankMethodFilter() { Filter filter = createMethodFilter( " \n" ); JUnitCore core = new JUnitCore(); Result result = core.run( Request.classes( FirstClass.class, SecondClass.class ).filterWith( filter ) ); assertTrue( result.wasSuccessful() ); assertEquals( 5, result.getRunCount() ); assertEquals( 0, result.getFailureCount() ); assertEquals( 0, result.getIgnoreCount() ); }
@Test public void testBackwardsCompatibilityTestParameterClass() { Filter filter = createMethodFilter( firstClassName ); JUnitCore core = new JUnitCore(); Result result = core.run( Request.classes( FirstClass.class, SecondClass.class ).filterWith( filter ) ); assertTrue( result.wasSuccessful() ); assertEquals( 3, result.getRunCount() ); assertEquals( 0, result.getFailureCount() ); assertEquals( 0, result.getIgnoreCount() ); }
@Test public void testBackwardsCompatibilityTestParameterJavaClass() { Filter filter = createMethodFilter( firstClassName + ".java" ); JUnitCore core = new JUnitCore(); Result result = core.run( Request.classes( FirstClass.class, SecondClass.class ).filterWith( filter ) ); assertTrue( result.wasSuccessful() ); assertEquals( 3, result.getRunCount() ); assertEquals( 0, result.getFailureCount() ); assertEquals( 0, result.getIgnoreCount() ); }
@Test public void testBackwardsCompatibilityTestParameterMethod1() { Filter filter = createMethodFilter( firstClassName + ".java#testMethod" ); JUnitCore core = new JUnitCore(); Result result = core.run( Request.classes( FirstClass.class, SecondClass.class ).filterWith( filter ) ); assertTrue( result.wasSuccessful() ); assertEquals( 1, result.getRunCount() ); assertEquals( 0, result.getFailureCount() ); assertEquals( 0, result.getIgnoreCount() ); }
@Test public void testBackwardsCompatibilityTestParameterMethod2() { Filter filter = createMethodFilter( firstClassName + "#testMethod" ); JUnitCore core = new JUnitCore(); Result result = core.run( Request.classes( FirstClass.class, SecondClass.class ).filterWith( filter ) ); assertTrue( result.wasSuccessful() ); assertEquals( 1, result.getRunCount() ); assertEquals( 0, result.getFailureCount() ); assertEquals( 0, result.getIgnoreCount() ); }
@Test public void testBackwardsCompatibilityTestParameterMethod3() { Filter filter = createMethodFilter( firstClassName + "#testMethod" ); JUnitCore core = new JUnitCore(); Result result = core.run( Request.classes( FirstClass.class, SecondClass.class ).filterWith( filter ) ); assertTrue( result.wasSuccessful() ); assertEquals( 1, result.getRunCount() ); assertEquals( 0, result.getFailureCount() ); assertEquals( 0, result.getIgnoreCount() ); }
@Test public void testRegexWithWildcard() { Filter filter = createMethodFilter( "%regex[" + firstClassRegex + ".*]" ); JUnitCore core = new JUnitCore(); Result result = core.run( Request.classes( FirstClass.class, SecondClass.class ).filterWith( filter ) ); assertTrue( result.wasSuccessful() ); assertEquals( 3, result.getRunCount() ); assertEquals( 0, result.getFailureCount() ); assertEquals( 0, result.getIgnoreCount() ); }
@Test public void testRegexWithWildcardClass() { Filter filter = createMethodFilter( "%regex[" + firstClassRegex + ".*.class]" ); JUnitCore core = new JUnitCore(); Result result = core.run( Request.classes( FirstClass.class, SecondClass.class ).filterWith( filter ) ); assertTrue( result.wasSuccessful() ); assertEquals( 3, result.getRunCount() ); assertEquals( 0, result.getFailureCount() ); assertEquals( 0, result.getIgnoreCount() ); }
@Test public void testRegexWithExactClass() { Filter filter = createMethodFilter( "%regex[" + firstClassRegex + ".class]" ); JUnitCore core = new JUnitCore(); Result result = core.run( Request.classes( FirstClass.class, SecondClass.class ).filterWith( filter ) ); assertTrue( result.wasSuccessful() ); assertEquals( 3, result.getRunCount() ); assertEquals( 0, result.getFailureCount() ); assertEquals( 0, result.getIgnoreCount() ); }
@Test public void testRegexWithWildcardJavaClassNegativeTest() { Filter filter = createMethodFilter( "%regex[" + firstClassRegex + ".*.class]" ); JUnitCore core = new JUnitCore(); Result result = core.run( Request.classes( FirstClass.class, SecondClass.class ).filterWith( filter ) ); assertTrue( result.wasSuccessful() ); assertEquals( 3, result.getRunCount() ); assertEquals( 0, result.getFailureCount() ); assertEquals( 0, result.getIgnoreCount() ); }
@Test public void testRegexWithTwoClasses() { Filter filter = createMethodFilter( "%regex[" + firstClassRegex + ".*|" + secondClassRegex + ".*]" ); JUnitCore core = new JUnitCore(); Result result = core.run( Request.classes( FirstClass.class, SecondClass.class, ThirdClass.class ) .filterWith( filter ) ); assertTrue( result.wasSuccessful() ); assertEquals( 5, result.getRunCount() ); assertEquals( 0, result.getFailureCount() ); assertEquals( 0, result.getIgnoreCount() ); }
@Test public void testRegexWithTwoClassesComplement() { Filter filter = createMethodFilter( "!%regex[" + firstClassRegex + ".*|" + secondClassRegex + ".*]" ); JUnitCore core = new JUnitCore(); Result result = core.run( Request.classes( FirstClass.class, SecondClass.class, ThirdClass.class ) .filterWith( filter ) ); assertTrue( result.wasSuccessful() ); assertEquals( 2, result.getRunCount() ); assertEquals( 0, result.getFailureCount() ); assertEquals( 0, result.getIgnoreCount() ); }
@Test public void testRegexWithTwoClassesAndOneMethod() { Filter filter = createMethodFilter( "%regex[" + firstClassRegex + ".*|" + secondClassRegex + ".* # otherMethod]" ); JUnitCore core = new JUnitCore(); Result result = core.run( Request.classes( FirstClass.class, SecondClass.class, ThirdClass.class ) .filterWith( filter ) ); assertTrue( result.wasSuccessful() ); assertEquals( 1, result.getRunCount() ); assertEquals( 0, result.getFailureCount() ); assertEquals( 0, result.getIgnoreCount() ); }
@Test public void testRegexWithTwoClassesAndOneMethodComplement() { Filter filter = createMethodFilter( "!%regex[" + firstClassRegex + ".*|" + secondClassRegex + ".*# otherMethod]" ); JUnitCore core = new JUnitCore(); Result result = core.run( Request.classes( FirstClass.class, SecondClass.class, ThirdClass.class ) .filterWith( filter ) ); assertTrue( result.wasSuccessful() ); assertEquals( 6, result.getRunCount() ); assertEquals( 0, result.getFailureCount() ); assertEquals( 0, result.getIgnoreCount() ); }
@Test public void testRegexWithTwoClassesAndWildcardMethod() { Filter filter = createMethodFilter( "%regex[" + firstClassRegex + ".*|" + secondClassRegex + ".*#test.* ]" ); JUnitCore core = new JUnitCore(); Result result = core.run( Request.classes( FirstClass.class, SecondClass.class, ThirdClass.class ) .filterWith( filter ) ); assertTrue( result.wasSuccessful() ); assertEquals( 2, result.getRunCount() ); assertEquals( 0, result.getFailureCount() ); assertEquals( 0, result.getIgnoreCount() ); }
@Test public void testRegexWithTwoClassesAndRegexMethodComplement() { Filter filter = createMethodFilter( "!%regex[" + firstClassRegex + ".*|" + secondClassRegex + ".*#test.*]" ); JUnitCore core = new JUnitCore(); Result result = core.run( Request.classes( FirstClass.class, SecondClass.class, ThirdClass.class ) .filterWith( filter ) ); assertTrue( result.wasSuccessful() ); assertEquals( 5, result.getRunCount() ); assertEquals( 0, result.getFailureCount() ); assertEquals( 0, result.getIgnoreCount() ); }
@Test public void testRegexWithTwoClassesAndRegexMethods() { Filter filter = createMethodFilter( "%regex[ " + firstClassRegex + ".*|" + secondClassRegex + ".* # test.*|other.* ]" ); JUnitCore core = new JUnitCore(); Result result = core.run( Request.classes( FirstClass.class, SecondClass.class, ThirdClass.class ) .filterWith( filter ) ); assertTrue( result.wasSuccessful() ); assertEquals( 3, result.getRunCount() ); assertEquals( 0, result.getFailureCount() ); assertEquals( 0, result.getIgnoreCount() ); } |
SurefireDependencyResolver { static boolean isWithinVersionSpec( @Nullable Artifact artifact, @Nonnull String versionSpec ) { if ( artifact == null ) { return false; } try { VersionRange range = createFromVersionSpec( versionSpec ); try { return range.containsVersion( artifact.getSelectedVersion() ); } catch ( NullPointerException e ) { return range.containsVersion( new DefaultArtifactVersion( artifact.getBaseVersion() ) ); } } catch ( InvalidVersionSpecificationException | OverConstrainedVersionException e ) { throw new RuntimeException( "Bug in plugin. Please report with stacktrace" ); } } SurefireDependencyResolver( RepositorySystem repositorySystem, ConsoleLogger log,
ArtifactRepository localRepository,
List<ArtifactRepository> pluginRemoteRepositories,
List<ArtifactRepository> projectRemoteRepositories, String pluginName,
DependencyResolver dependencyResolver, boolean offline ); } | @Test public void shouldNotBeWithinRangeNullArtifact() { boolean result = SurefireDependencyResolver.isWithinVersionSpec( null, "[4.7,)" ); assertThat( result ) .isFalse(); }
@Test public void shouldNotBeWithinRange() throws InvalidVersionSpecificationException { Artifact api = createArtifact( "junit", "junit", "4.6" ); boolean result = SurefireDependencyResolver.isWithinVersionSpec( api, "[4.7,)" ); assertThat( result ) .isFalse(); }
@Test public void shouldBeWithinRange() throws InvalidVersionSpecificationException { Artifact api = createArtifact( "junit", "junit", "4.7" ); boolean result = SurefireDependencyResolver.isWithinVersionSpec( api, "[4.7,)" ); assertThat( result ) .isTrue(); }
@Test public void shouldBeFarWithinRange() throws InvalidVersionSpecificationException { Artifact api = createArtifact( "junit", "junit", "4.13" ); boolean result = SurefireDependencyResolver.isWithinVersionSpec( api, "[4.7,)" ); assertThat( result ) .isTrue(); }
@Test public void shouldBeFailWithinRange() throws InvalidVersionSpecificationException { Artifact api = createArtifact( "junit", "junit", "" ); expectedException.expect( RuntimeException.class ); expectedException.expectMessage( "Bug in plugin. Please report with stacktrace" ); SurefireDependencyResolver.isWithinVersionSpec( api, "[4.7,)" ); } |
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 ); } | @Test public void notNotifiedWhenEngineExecutionStarted() { adapter.executionStarted( newEngineIdentifier() ); verify( listener, never() ).testStarting( any() ); } |
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 ); } | @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() ); } |
RunListenerAdapter implements TestExecutionListener { @Override public void executionFinished( TestIdentifier testIdentifier, TestExecutionResult testExecutionResult ) { boolean isClass = testIdentifier.isContainer() && testIdentifier.getSource().filter( ClassSource.class::isInstance ).isPresent(); boolean isTest = testIdentifier.isTest(); boolean failed = testExecutionResult.getStatus() == FAILED; boolean isAssertionError = testExecutionResult.getThrowable() .filter( AssertionError.class::isInstance ).isPresent(); boolean isRootContainer = testIdentifier.isContainer() && !testIdentifier.getParentId().isPresent(); if ( failed || isClass || isTest ) { Integer elapsed = computeElapsedTime( testIdentifier ); switch ( testExecutionResult.getStatus() ) { case ABORTED: if ( isTest ) { runListener.testAssumptionFailure( createReportEntry( testIdentifier, testExecutionResult, elapsed ) ); } else { runListener.testSetCompleted( createReportEntry( testIdentifier, testExecutionResult, systemProps(), null, elapsed ) ); } break; case FAILED: if ( isAssertionError ) { runListener.testFailed( createReportEntry( testIdentifier, testExecutionResult, elapsed ) ); } else { runListener.testError( createReportEntry( testIdentifier, testExecutionResult, elapsed ) ); } if ( isClass || isRootContainer ) { runListener.testSetCompleted( createReportEntry( testIdentifier, null, systemProps(), null, elapsed ) ); } failures.put( testIdentifier, testExecutionResult ); break; default: if ( isTest ) { runListener.testSucceeded( createReportEntry( testIdentifier, null, elapsed ) ); } else { runListener.testSetCompleted( createReportEntry( testIdentifier, null, systemProps(), null, elapsed ) ); } } } } 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 ); } | @Test public void notifiedWhenMethodExecutionAborted() throws Exception { adapter.executionFinished( newMethodIdentifier(), aborted( null ) ); verify( listener ).testAssumptionFailure( any() ); }
@Test public void notifiedWhenClassExecutionAborted() { TestSkippedException t = new TestSkippedException( "skipped" ); adapter.executionFinished( newClassIdentifier(), aborted( t ) ); String source = MyTestClass.class.getName(); StackTraceWriter stw = new PojoStackTraceWriter( source, null, t ); ArgumentCaptor<SimpleReportEntry> report = ArgumentCaptor.forClass( SimpleReportEntry.class ); verify( listener ).testSetCompleted( report.capture() ); assertThat( report.getValue().getSourceName() ) .isEqualTo( source ); assertThat( report.getValue().getStackTraceWriter() ) .isEqualTo( stw ); }
@Test public void notifiedOfContainerFailureWhenErrored() throws Exception { adapter.executionFinished( newContainerIdentifier(), failed( new RuntimeException() ) ); verify( listener ).testError( any() ); }
@Test public void notifiedOfContainerFailureWhenFailed() throws Exception { adapter.executionFinished( newContainerIdentifier(), failed( new AssertionError() ) ); verify( listener ).testFailed( any() ); }
@Test public void notifiedWhenMethodExecutionFailed() throws Exception { adapter.executionFinished( newMethodIdentifier(), failed( new AssertionError() ) ); verify( listener ).testFailed( any() ); }
@Test public void notifiedWhenMethodExecutionFailedWithError() throws Exception { adapter.executionFinished( newMethodIdentifier(), failed( new RuntimeException() ) ); verify( listener ).testError( any() ); }
@Test public void notifiedWhenMethodExecutionSucceeded() throws Exception { adapter.executionFinished( newMethodIdentifier(), successful() ); verify( listener ).testSucceeded( any() ); }
@Test public void stackTraceWriterPresentEvenWithoutException() throws Exception { adapter.executionFinished( newMethodIdentifier(), failed( null ) ); ArgumentCaptor<ReportEntry> entryCaptor = ArgumentCaptor.forClass( ReportEntry.class ); verify( listener ).testError( entryCaptor.capture() ); assertNotNull( entryCaptor.getValue().getStackTraceWriter() ); } |
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 ); } | @Test public void getSuitesReturnsScannedClasses() { ProviderParameters providerParameters = providerParametersMock( TestClass1.class, TestClass2.class ); JUnitPlatformProvider provider = new JUnitPlatformProvider( providerParameters ); assertThat( provider.getSuites() ) .containsOnly( TestClass1.class, TestClass2.class ); } |
JUnitPlatformProvider extends AbstractProvider { Filter<?>[] getFilters() { return filters; } JUnitPlatformProvider( ProviderParameters parameters ); JUnitPlatformProvider( ProviderParameters parameters, Launcher launcher ); @Override Iterable<Class<?>> getSuites(); @Override RunResult invoke( Object forkTestSet ); } | @Test public void onlyGroupsIsDeclared() { Map<String, String> properties = singletonMap( TESTNG_GROUPS_PROP, "groupOne, groupTwo" ); ProviderParameters providerParameters = providerParametersMock( TestClass1.class ); when( providerParameters.getProviderProperties() ).thenReturn( properties ); JUnitPlatformProvider provider = new JUnitPlatformProvider( providerParameters ); assertEquals( 1, provider.getFilters().length ); }
@Test public void onlyExcludeTagsIsDeclared() { Map<String, String> properties = singletonMap( TESTNG_EXCLUDEDGROUPS_PROP, "tagOne, tagTwo" ); ProviderParameters providerParameters = providerParametersMock( TestClass1.class ); when( providerParameters.getProviderProperties() ).thenReturn( properties ); JUnitPlatformProvider provider = new JUnitPlatformProvider( providerParameters ); assertEquals( 1, provider.getFilters().length ); }
@Test public void noFiltersAreCreatedIfTagsAreEmpty() { Map<String, String> properties = singletonMap( TESTNG_GROUPS_PROP, "" ); ProviderParameters providerParameters = providerParametersMock( TestClass1.class ); when( providerParameters.getProviderProperties() ).thenReturn( properties ); JUnitPlatformProvider provider = new JUnitPlatformProvider( providerParameters ); assertEquals( 0, provider.getFilters().length ); }
@Test public void filtersWithEmptyTagsAreNotRegistered() { Map<String, String> properties = singletonMap( TESTNG_EXCLUDEDGROUPS_PROP, "tagOne," ); ProviderParameters providerParameters = providerParametersMock( TestClass1.class ); when( providerParameters.getProviderProperties() ).thenReturn( properties ); JUnitPlatformProvider provider = new JUnitPlatformProvider( providerParameters ); assertEquals( 1, provider.getFilters().length ); }
@Test public void bothIncludeAndExcludeAreAllowed() { Map<String, String> properties = new HashMap<>(); properties.put( TESTNG_GROUPS_PROP, "tagOne, tagTwo" ); properties.put( TESTNG_EXCLUDEDGROUPS_PROP, "tagThree, tagFour" ); ProviderParameters providerParameters = providerParametersMock( TestClass1.class ); when( providerParameters.getProviderProperties() ).thenReturn( properties ); JUnitPlatformProvider provider = new JUnitPlatformProvider( providerParameters ); assertEquals( 2, provider.getFilters().length ); }
@Test public void tagExpressionsAreSupportedForIncludeTagsContainingVerticalBar() { Map<String, String> properties = new HashMap<>(); properties.put( TESTNG_GROUPS_PROP, "tagOne | tagTwo" ); properties.put( TESTNG_EXCLUDEDGROUPS_PROP, "tagThree | tagFour" ); ProviderParameters providerParameters = providerParametersMock( TestClass1.class ); when( providerParameters.getProviderProperties() ).thenReturn( properties ); JUnitPlatformProvider provider = new JUnitPlatformProvider( providerParameters ); assertEquals( 2, provider.getFilters().length ); }
@Test public void tagExpressionsAreSupportedForIncludeTagsContainingAmpersand() { Map<String, String> properties = new HashMap<>(); properties.put( TESTNG_GROUPS_PROP, "tagOne & !tagTwo" ); properties.put( TESTNG_EXCLUDEDGROUPS_PROP, "tagThree & !tagFour" ); ProviderParameters providerParameters = providerParametersMock( TestClass1.class ); when( providerParameters.getProviderProperties() ).thenReturn( properties ); JUnitPlatformProvider provider = new JUnitPlatformProvider( providerParameters ); assertEquals( 2, provider.getFilters().length ); }
@Test public void noFiltersAreCreatedIfNoPropertiesAreDeclared() { ProviderParameters providerParameters = providerParametersMock( TestClass1.class ); JUnitPlatformProvider provider = new JUnitPlatformProvider( providerParameters ); assertEquals( 0, provider.getFilters().length ); } |
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 ); } | @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" ) ); } |
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 ); } | @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() ); } |
SurefireDependencyResolver { private ArtifactResolutionResult resolveArtifact( Artifact artifact, List<ArtifactRepository> repositories, ArtifactFilter filter ) { ArtifactResolutionRequest request = new ArtifactResolutionRequest() .setOffline( offline ) .setArtifact( artifact ) .setLocalRepository( localRepository ) .setResolveTransitively( true ) .setCollectionFilter( filter ) .setRemoteRepositories( repositories ); return repositorySystem.resolve( request ); } SurefireDependencyResolver( RepositorySystem repositorySystem, ConsoleLogger log,
ArtifactRepository localRepository,
List<ArtifactRepository> pluginRemoteRepositories,
List<ArtifactRepository> projectRemoteRepositories, String pluginName,
DependencyResolver dependencyResolver, boolean offline ); } | @Test public void testResolveArtifact() throws InvalidVersionSpecificationException { final Artifact provider = createArtifact( "surefire-junit-platform" ); RepositorySystem repositorySystem = mock( RepositorySystem.class ); final ArtifactResolutionResult expectedResult = mock( ArtifactResolutionResult.class ); when( repositorySystem.resolve( any( ArtifactResolutionRequest.class ) ) ) .then( new Answer<ArtifactResolutionResult>() { @Override public ArtifactResolutionResult answer( InvocationOnMock invocation ) { Object[] args = invocation.getArguments(); assertThat( args ) .hasSize( 1 ); ArtifactResolutionRequest request = (ArtifactResolutionRequest) args[0]; assertThat( request.getArtifact() ) .isSameAs( provider ); assertThat( request.isResolveTransitively() ) .isTrue(); assertThat( request.getArtifactDependencies() ) .isNull(); assertThat( request.getRemoteRepositories() ) .isNull(); assertThat( request.getLocalRepository() ) .isNull(); assertThat( request.getCache() ) .isNull(); assertThat( request.getCollectionFilter() ) .isNotNull(); assertThat( request.getCollectionFilter() ) .isInstanceOf( RuntimeArtifactFilter.class ); assertThat( request.getManagedVersionMap() ) .isNull(); assertThat( request.getMirrors() ) .isEmpty(); assertThat( request.getProxies() ) .isEmpty(); assertThat( request.getResolutionFilter() ) .isNull(); assertThat( request.getServers() ) .isEmpty(); return expectedResult; } } ); SurefireDependencyResolver surefireDependencyResolver = new SurefireDependencyResolver( repositorySystem, null, null, null, null, null, null, false ); ArtifactResolutionResult actualResult = surefireDependencyResolver.resolvePluginArtifact( provider ); assertThat( actualResult ) .isSameAs( expectedResult ); } |
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 ); } | @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 ); } |
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 ); } | @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 ); } |
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 ); } | @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 ); } |
ParallelComputerUtil { static Concurrency resolveConcurrency( JUnitCoreParameters params, RunnerCounter counts ) throws TestSetFailedException { if ( !params.isParallelismSelected() ) { throw new TestSetFailedException( "Unspecified parameter '" + JUnitCoreParameters.PARALLEL_KEY + "'." ); } if ( !params.isUseUnlimitedThreads() && !hasThreadCount( params ) && !hasThreadCounts( params ) ) { throw new TestSetFailedException( "Unspecified thread-count(s). " + "See the parameters " + JUnitCoreParameters.USEUNLIMITEDTHREADS_KEY + ", " + JUnitCoreParameters.THREADCOUNT_KEY + ", " + JUnitCoreParameters.THREADCOUNTSUITES_KEY + ", " + JUnitCoreParameters.THREADCOUNTCLASSES_KEY + ", " + JUnitCoreParameters.THREADCOUNTMETHODS_KEY + "." ); } if ( params.isUseUnlimitedThreads() ) { return concurrencyForUnlimitedThreads( params ); } else if ( hasThreadCount( params ) ) { if ( hasThreadCounts( params ) ) { return isLeafUnspecified( params ) ? concurrencyFromAllThreadCountsButUnspecifiedLeafCount( params, counts ) : concurrencyFromAllThreadCounts( params ); } else { return estimateConcurrency( params, counts ); } } else { return concurrencyFromThreadCounts( params ); } } private ParallelComputerUtil(); } | @Test public void unknownParallel() throws TestSetFailedException { Map<String, String> properties = new HashMap<>(); exception.expect( TestSetFailedException.class ); resolveConcurrency( new JUnitCoreParameters( properties ), null ); }
@Test public void unknownThreadCountSuites() throws TestSetFailedException { JUnitCoreParameters params = new JUnitCoreParameters( parallel( "suites" ) ); assertTrue( params.isParallelSuites() ); assertFalse( params.isParallelClasses() ); assertFalse( params.isParallelMethods() ); exception.expect( TestSetFailedException.class ); resolveConcurrency( params, null ); }
@Test public void unknownThreadCountClasses() throws TestSetFailedException { JUnitCoreParameters params = new JUnitCoreParameters( parallel( "classes" ) ); assertFalse( params.isParallelSuites() ); assertTrue( params.isParallelClasses() ); assertFalse( params.isParallelMethods() ); exception.expect( TestSetFailedException.class ); resolveConcurrency( params, null ); }
@Test public void unknownThreadCountMethods() throws TestSetFailedException { JUnitCoreParameters params = new JUnitCoreParameters( parallel( "methods" ) ); assertFalse( params.isParallelSuites() ); assertFalse( params.isParallelClasses() ); assertTrue( params.isParallelMethods() ); exception.expect( TestSetFailedException.class ); resolveConcurrency( params, null ); }
@Test public void unknownThreadCountBoth() throws TestSetFailedException { JUnitCoreParameters params = new JUnitCoreParameters( parallel( "both" ) ); assertFalse( params.isParallelSuites() ); assertTrue( params.isParallelClasses() ); assertTrue( params.isParallelMethods() ); exception.expect( TestSetFailedException.class ); resolveConcurrency( params, null ); }
@Test public void unknownThreadCountAll() throws TestSetFailedException { JUnitCoreParameters params = new JUnitCoreParameters( parallel( "all" ) ); assertTrue( params.isParallelSuites() ); assertTrue( params.isParallelClasses() ); assertTrue( params.isParallelMethods() ); exception.expect( TestSetFailedException.class ); resolveConcurrency( params, null ); }
@Test public void unknownThreadCountSuitesAndClasses() throws TestSetFailedException { JUnitCoreParameters params = new JUnitCoreParameters( parallel( "suitesAndClasses" ) ); assertTrue( params.isParallelSuites() ); assertTrue( params.isParallelClasses() ); assertFalse( params.isParallelMethods() ); exception.expect( TestSetFailedException.class ); resolveConcurrency( params, null ); }
@Test public void unknownThreadCountSuitesAndMethods() throws TestSetFailedException { JUnitCoreParameters params = new JUnitCoreParameters( parallel( "suitesAndMethods" ) ); assertTrue( params.isParallelSuites() ); assertFalse( params.isParallelClasses() ); assertTrue( params.isParallelMethods() ); exception.expect( TestSetFailedException.class ); resolveConcurrency( params, null ); }
@Test public void unknownThreadCountClassesAndMethods() throws TestSetFailedException { JUnitCoreParameters params = new JUnitCoreParameters( parallel( "classesAndMethods" ) ); assertFalse( params.isParallelSuites() ); assertTrue( params.isParallelClasses() ); assertTrue( params.isParallelMethods() ); exception.expect( TestSetFailedException.class ); resolveConcurrency( params, null ); }
@Test public void unknownParallel() throws TestSetFailedException { Map<String, String> properties = new HashMap<String, String>(); exception.expect( TestSetFailedException.class ); resolveConcurrency( new JUnitCoreParameters( properties ), null ); } |
SurefireDependencyResolver { @Nonnull Set<Artifact> getProviderClasspath( String providerArtifactId, String providerVersion ) { Dependency provider = toProviderDependency( providerArtifactId, providerVersion ); Artifact providerArtifact = repositorySystem.createDependencyArtifact( provider ); ArtifactResolutionResult result = resolvePluginArtifact( providerArtifact ); if ( log.isDebugEnabled() ) { for ( Artifact artifact : result.getArtifacts() ) { String artifactPath = artifact.getFile().getAbsolutePath(); String scope = artifact.getScope(); log.debug( "Adding to " + pluginName + " test classpath: " + artifactPath + " Scope: " + scope ); } } return orderProviderArtifacts( result.getArtifacts() ); } SurefireDependencyResolver( RepositorySystem repositorySystem, ConsoleLogger log,
ArtifactRepository localRepository,
List<ArtifactRepository> pluginRemoteRepositories,
List<ArtifactRepository> projectRemoteRepositories, String pluginName,
DependencyResolver dependencyResolver, boolean offline ); } | @Test public void testGetProviderClasspath() throws Exception { Artifact api = createArtifact( "surefire-api" ); api.setFile( new File( "" ) ); final Artifact provider = createArtifact( "surefire-junit-platform" ); provider.setFile( new File( "" ) ); Artifact ext = createArtifact( "org.apiguardian", "apiguardian-api" ); ext.setFile( new File( "" ) ); Artifact logger = createArtifact( "surefire-logger-api" ); logger.setFile( new File( "" ) ); Set<Artifact> providerArtifacts = new LinkedHashSet<>(); providerArtifacts.add( api ); providerArtifacts.add( provider ); providerArtifacts.add( ext ); providerArtifacts.add( logger ); final ArtifactResolutionResult result = mock( ArtifactResolutionResult.class ); when( result.getArtifacts() ) .thenReturn( providerArtifacts ); RepositorySystem repositorySystem = mock( RepositorySystem.class ); when( repositorySystem.resolve( any( ArtifactResolutionRequest.class ) ) ) .then( new Answer<ArtifactResolutionResult>() { @Override public ArtifactResolutionResult answer( InvocationOnMock invocation ) { Object[] args = invocation.getArguments(); assertThat( args ) .hasSize( 1 ); ArtifactResolutionRequest request = (ArtifactResolutionRequest) args[0]; assertThat( request.getArtifact() ) .isSameAs( provider ); assertThat( request.isResolveTransitively() ) .isTrue(); assertThat( request.getArtifactDependencies() ) .isNull(); assertThat( request.getRemoteRepositories() ) .isNull(); assertThat( request.getLocalRepository() ) .isNull(); assertThat( request.getCache() ) .isNull(); assertThat( request.getCollectionFilter() ) .isNotNull(); assertThat( request.getCollectionFilter() ) .isInstanceOf( RuntimeArtifactFilter.class ); assertThat( request.getManagedVersionMap() ) .isNull(); assertThat( request.getMirrors() ) .isEmpty(); assertThat( request.getProxies() ) .isEmpty(); assertThat( request.getResolutionFilter() ) .isNull(); assertThat( request.getServers() ) .isEmpty(); return result; } } ); when( repositorySystem.createDependencyArtifact( any( Dependency.class ) ) ) .then( new Answer<Artifact>() { @Override public Artifact answer( InvocationOnMock invocation ) { Object[] args = invocation.getArguments(); assertThat( args ) .hasSize( 1 ); Dependency request = (Dependency) args[0]; assertThat( request.getGroupId() ) .isEqualTo( provider.getGroupId() ); assertThat( request.getArtifactId() ) .isEqualTo( provider.getArtifactId() ); assertThat( request.getVersion() ) .isEqualTo( provider.getVersion() ); assertThat( request.getType() ) .isEqualTo( provider.getType() ); assertThat( request.getScope() ) .isNull(); return provider; } } ); ConsoleLogger log = mock( ConsoleLogger.class ); SurefireDependencyResolver surefireDependencyResolver = new SurefireDependencyResolver( repositorySystem, log, null, null, null, null, null, false ); when( log.isDebugEnabled() ) .thenReturn( true ); Set<Artifact> classpath = surefireDependencyResolver.getProviderClasspath( "surefire-junit-platform", "1" ); assertThat( classpath ) .hasSize( 4 ); Iterator<Artifact> it = classpath.iterator(); assertThat( it.next() ) .isSameAs( provider ); assertThat( it.next() ) .isSameAs( api ); assertThat( it.next() ) .isSameAs( logger ); assertThat( it.next() ) .isSameAs( ext ); } |
ParallelComputerBuilder { public ParallelComputer buildComputer() { return new PC(); } ParallelComputerBuilder( ConsoleStream logger ); ParallelComputerBuilder( ConsoleStream logger, JUnitCoreParameters parameters ); ParallelComputer buildComputer(); } | @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 ) ); } |
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(); } | @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(); } |
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; } | @Test public void optimizationParameter() { assertFalse( newTestSetOptimization( false ).isParallelOptimization() ); } |
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; } | @Test public void isParallelMethod() { assertFalse( newTestSetClasses().isParallelMethods() ); assertTrue( newTestSetMethods().isParallelMethods() ); assertTrue( newTestSetBoth().isParallelMethods() ); } |
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; } | @Test public void isParallelClasses() { assertTrue( newTestSetClasses().isParallelClasses() ); assertFalse( newTestSetMethods().isParallelClasses() ); assertTrue( newTestSetBoth().isParallelClasses() ); } |
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; } | @Test public void isParallelBoth() { assertFalse( isParallelMethodsAndClasses( newTestSetClasses() ) ); assertFalse( isParallelMethodsAndClasses( newTestSetMethods() ) ); assertTrue( isParallelMethodsAndClasses( newTestSetBoth() ) ); } |
SurefireDependencyResolver { Map<String, Artifact> resolvePluginDependencies( ProjectBuildingRequest request, Plugin plugin, Map<String, Artifact> pluginResolvedDependencies ) throws MojoExecutionException { Collection<Dependency> pluginDependencies = plugin.getDependencies(); try { Iterable<ArtifactResult> resolvedArtifacts = dependencyResolver.resolveDependencies( request, pluginDependencies, null, including( RuntimeArtifactFilter.SCOPES ) ); Map<String, Artifact> resolved = new LinkedHashMap<>(); for ( ArtifactResult resolvedArtifact : resolvedArtifacts ) { Artifact artifact = resolvedArtifact.getArtifact(); String key = artifact.getGroupId() + ":" + artifact.getArtifactId(); Artifact resolvedPluginDependency = pluginResolvedDependencies.get( key ); if ( resolvedPluginDependency != null ) { resolved.put( key, artifact ); } } return resolved; } catch ( DependencyResolverException e ) { throw new MojoExecutionException( e.getLocalizedMessage(), e ); } } SurefireDependencyResolver( RepositorySystem repositorySystem, ConsoleLogger log,
ArtifactRepository localRepository,
List<ArtifactRepository> pluginRemoteRepositories,
List<ArtifactRepository> projectRemoteRepositories, String pluginName,
DependencyResolver dependencyResolver, boolean offline ); } | @Test public void testAddProviderToClasspath() throws Exception { Dependency providerAsDependency = new Dependency(); providerAsDependency.setGroupId( PROVIDER_GROUP_ID ); providerAsDependency.setArtifactId( "surefire-shadefire" ); providerAsDependency.setVersion( "1" ); final Artifact providerAsArtifact = createArtifact( "surefire-shadefire" ); PluginDescriptor pluginDescriptor = PowerMockito.mock( PluginDescriptor.class ); Plugin plugin = PowerMockito.mock( Plugin.class ); when( pluginDescriptor.getPlugin() ) .thenReturn( plugin ); when( plugin.getDependencies() ) .thenReturn( singletonList( providerAsDependency ) ); DependencyResolver depencencyResolver = mock( DependencyResolver.class ); SurefireDependencyResolver surefireDependencyResolver = new SurefireDependencyResolver( null, null, null, null, null, null, depencencyResolver, false ); ProjectBuildingRequest request = mock( ProjectBuildingRequest.class ); ArgumentCaptor<Collection<Dependency>> dep = ArgumentCaptor.forClass( Collection.class ); ArgumentCaptor<ScopeFilter> filter = ArgumentCaptor.forClass( ScopeFilter.class ); ArtifactResult result = mock( ArtifactResult.class ); when( result.getArtifact() ).thenReturn( providerAsArtifact ); when( depencencyResolver.resolveDependencies( same( request ), dep.capture(), isNull( Collection.class ), filter.capture() ) ) .thenReturn( singleton( result ) ); final ArtifactResolutionResult resolutionResult = mock( ArtifactResolutionResult.class ); when( resolutionResult.getArtifacts() ) .thenReturn( singleton( providerAsArtifact ) ); Map<String, Artifact> pluginResolvedDependencies = singletonMap( PROVIDER_GROUP_ID + ":surefire-shadefire", providerAsArtifact ); Map<String, Artifact> providers = surefireDependencyResolver.resolvePluginDependencies( request, plugin, pluginResolvedDependencies ); verify( depencencyResolver, times( 1 ) ) .resolveDependencies( request, dep.getValue(), null, filter.getValue() ); assertThat( providers.values() ) .hasSize( 1 ) .containsOnly( providerAsArtifact ); assertThat( dep.getValue() ) .hasSize( 1 ) .containsOnly( providerAsDependency ); assertThat( filter.getValue().getIncluded() ) .containsOnly( SCOPE_COMPILE, SCOPE_COMPILE_PLUS_RUNTIME, SCOPE_RUNTIME ); assertThat( filter.getValue().getExcluded() ) .isNull(); } |
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; } | @Test public void isPerCoreThreadCount() { assertFalse( newTestSetClasses().isPerCoreThreadCount() ); assertFalse( newTestSetMethods().isPerCoreThreadCount() ); assertTrue( newTestSetBoth().isPerCoreThreadCount() ); } |
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; } | @Test public void getThreadCount() { assertFalse( newTestSetClasses().isPerCoreThreadCount() ); assertFalse( newTestSetMethods().isPerCoreThreadCount() ); assertTrue( newTestSetBoth().isPerCoreThreadCount() ); } |
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; } | @Test public void isUseUnlimitedThreads() { assertFalse( newTestSetClasses().isUseUnlimitedThreads() ); assertTrue( newTestSetMethods().isUseUnlimitedThreads() ); assertFalse( newTestSetBoth().isUseUnlimitedThreads() ); } |
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; } | @Test public void isNoThreading() { assertFalse( newTestSetClasses().isNoThreading() ); assertFalse( newTestSetMethods().isNoThreading() ); assertFalse( newTestSetBoth().isNoThreading() ); } |
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; } | @Test public void isAnyParallelismSelected() { assertTrue( newTestSetClasses().isParallelismSelected() ); assertTrue( newTestSetMethods().isParallelismSelected() ); assertTrue( newTestSetBoth().isParallelismSelected() ); } |
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(); } | @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 ) ); } |
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(); } | @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" ); } |
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(); } | @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 ) ) ); } |
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(); } | @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(); } } |
AbstractSurefireMojo extends AbstractMojo implements SurefireExecutionParameters { protected abstract boolean useModulePath(); @Override abstract List<String> getIncludes(); abstract File getIncludesFile(); @Override abstract void setIncludes( List<String> includes ); abstract File getExcludesFile(); abstract File[] getSuiteXmlFiles(); abstract void setSuiteXmlFiles( File[] suiteXmlFiles ); abstract String getRunOrder(); abstract void setRunOrder( String runOrder ); abstract Long getRunOrderRandomSeed(); abstract void setRunOrderRandomSeed( Long runOrderRandomSeed ); @Override void execute(); static SurefireProperties createCopyAndReplaceForkNumPlaceholder(
SurefireProperties effectiveSystemProperties, int threadNumber ); RepositorySystem getRepositorySystem(); void setRepositorySystem( RepositorySystem repositorySystem ); DependencyResolver getDependencyResolver(); void setDependencyResolver( DependencyResolver dependencyResolver ); TestListResolver getSpecificTests(); @Override List<String> getExcludes(); @Override void setExcludes( List<String> excludes ); @Override ArtifactRepository getLocalRepository(); @Override void setLocalRepository( ArtifactRepository localRepository ); Properties getSystemProperties(); @SuppressWarnings( "UnusedDeclaration" ) void setSystemProperties( Properties systemProperties ); Map<String, String> getSystemPropertyVariables(); @SuppressWarnings( "UnusedDeclaration" ) void setSystemPropertyVariables( Map<String, String> systemPropertyVariables ); abstract File getSystemPropertiesFile(); @SuppressWarnings( "UnusedDeclaration" ) abstract void setSystemPropertiesFile( File systemPropertiesFile ); void setProperties( Properties properties ); Map<String, Artifact> getPluginArtifactMap(); @SuppressWarnings( "UnusedDeclaration" ) void setPluginArtifactMap( Map<String, Artifact> pluginArtifactMap ); Map<String, Artifact> getProjectArtifactMap(); @SuppressWarnings( "UnusedDeclaration" ) void setProjectArtifactMap( Map<String, Artifact> projectArtifactMap ); String getReportNameSuffix(); @SuppressWarnings( "UnusedDeclaration" ) void setReportNameSuffix( String reportNameSuffix ); boolean isRedirectTestOutputToFile(); @SuppressWarnings( "UnusedDeclaration" ) void setRedirectTestOutputToFile( boolean redirectTestOutputToFile ); Boolean getFailIfNoTests(); void setFailIfNoTests( boolean failIfNoTests ); String getForkMode(); @SuppressWarnings( "UnusedDeclaration" ) void setForkMode( String forkMode ); String getJvm(); String getArgLine(); @SuppressWarnings( "UnusedDeclaration" ) void setArgLine( String argLine ); Map<String, String> getEnvironmentVariables(); @SuppressWarnings( "UnusedDeclaration" ) void setEnvironmentVariables( Map<String, String> environmentVariables ); File getWorkingDirectory(); @SuppressWarnings( "UnusedDeclaration" ) void setWorkingDirectory( File workingDirectory ); boolean isChildDelegation(); @SuppressWarnings( "UnusedDeclaration" ) void setChildDelegation( boolean childDelegation ); String getGroups(); @SuppressWarnings( "UnusedDeclaration" ) void setGroups( String groups ); String getExcludedGroups(); @SuppressWarnings( "UnusedDeclaration" ) void setExcludedGroups( String excludedGroups ); String getJunitArtifactName(); @SuppressWarnings( "UnusedDeclaration" ) void setJunitArtifactName( String junitArtifactName ); String getTestNGArtifactName(); @SuppressWarnings( "UnusedDeclaration" ) void setTestNGArtifactName( String testNGArtifactName ); int getThreadCount(); @SuppressWarnings( "UnusedDeclaration" ) void setThreadCount( int threadCount ); boolean getPerCoreThreadCount(); @SuppressWarnings( "UnusedDeclaration" ) void setPerCoreThreadCount( boolean perCoreThreadCount ); boolean getUseUnlimitedThreads(); @SuppressWarnings( "UnusedDeclaration" ) void setUseUnlimitedThreads( boolean useUnlimitedThreads ); String getParallel(); @SuppressWarnings( "UnusedDeclaration" ) void setParallel( String parallel ); boolean isParallelOptimized(); @SuppressWarnings( "UnusedDeclaration" ) void setParallelOptimized( boolean parallelOptimized ); int getThreadCountSuites(); void setThreadCountSuites( int threadCountSuites ); int getThreadCountClasses(); void setThreadCountClasses( int threadCountClasses ); int getThreadCountMethods(); void setThreadCountMethods( int threadCountMethods ); boolean isTrimStackTrace(); @SuppressWarnings( "UnusedDeclaration" ) void setTrimStackTrace( boolean trimStackTrace ); List<ArtifactRepository> getProjectRemoteRepositories(); @SuppressWarnings( "UnusedDeclaration" ) void setProjectRemoteRepositories( List<ArtifactRepository> projectRemoteRepositories ); List<ArtifactRepository> getRemoteRepositories(); @SuppressWarnings( "UnusedDeclaration" ) void setRemoteRepositories( List<ArtifactRepository> remoteRepositories ); boolean isDisableXmlReport(); @SuppressWarnings( "UnusedDeclaration" ) void setDisableXmlReport( boolean disableXmlReport ); boolean isEnableAssertions(); boolean effectiveIsEnableAssertions(); @SuppressWarnings( "UnusedDeclaration" ) void setEnableAssertions( boolean enableAssertions ); MavenSession getSession(); @SuppressWarnings( "UnusedDeclaration" ) void setSession( MavenSession session ); String getObjectFactory(); @SuppressWarnings( "UnusedDeclaration" ) void setObjectFactory( String objectFactory ); ToolchainManager getToolchainManager(); @SuppressWarnings( "UnusedDeclaration" ) void setToolchainManager( ToolchainManager toolchainManager ); boolean isMavenParallel(); String[] getDependenciesToScan(); void setDependenciesToScan( String[] dependenciesToScan ); PluginDescriptor getPluginDescriptor(); MavenProject getProject(); @SuppressWarnings( "UnusedDeclaration" ) void setProject( MavenProject project ); @Override File getTestSourceDirectory(); @Override void setTestSourceDirectory( File testSourceDirectory ); String getForkCount(); boolean isReuseForks(); String[] getAdditionalClasspathElements(); void setAdditionalClasspathElements( String[] additionalClasspathElements ); String[] getClasspathDependencyExcludes(); void setClasspathDependencyExcludes( String[] classpathDependencyExcludes ); String getClasspathDependencyScopeExclude(); void setClasspathDependencyScopeExclude( String classpathDependencyScopeExclude ); File getProjectBuildDirectory(); void setProjectBuildDirectory( File projectBuildDirectory ); Map<String, String> getJdkToolchain(); void setJdkToolchain( Map<String, String> jdkToolchain ); String getTempDir(); void setTempDir( String tempDir ); } | @Test public void noModuleDescriptorFile() throws Exception { AbstractSurefireMojo mojo = spy( new Mojo() ); mojo.setMainBuildPath( tempFolder.newFolder() ); File testClassesDir = tempFolder.newFolder(); mojo.setTestClassesDirectory( testClassesDir ); File jdkHome = new File( System.getProperty( "java.home" ) ); ResolvePathResultWrapper wrapper = invokeMethod( mojo, "findModuleDescriptor", jdkHome ); assertThat( wrapper ) .isNotNull(); assertThat( wrapper.getResolvePathResult() ) .isNull(); assertThat( invokeMethod( mojo, "existsModuleDescriptor", wrapper ) ) .isEqualTo( false ); when( mojo.useModulePath() ).thenReturn( true ); File jvmExecutable = new File( jdkHome, IS_OS_WINDOWS ? "bin\\java.exe" : "bin/java" ); JdkAttributes jdkAttributes = new JdkAttributes( jvmExecutable, jdkHome, true ); Platform platform = new Platform().withJdkExecAttributesForTests( jdkAttributes ); assertThat( invokeMethod( mojo, "canExecuteProviderWithModularPath", platform, wrapper ) ) .isEqualTo( false ); }
@Test public void correctModuleDescriptor() throws Exception { AbstractSurefireMojo mojo = spy( new Mojo() ); LocationManager locationManager = mock( LocationManager.class ); ResolvePathResult result = mock( ResolvePathResult.class ); when( result.getModuleNameSource() ).thenReturn( MODULEDESCRIPTOR ); JavaModuleDescriptor descriptor = mock( JavaModuleDescriptor.class ); when( result.getModuleDescriptor() ).thenReturn( descriptor ); when( locationManager.resolvePath( any( ResolvePathRequest.class ) ) ).thenReturn( result ); doReturn( locationManager ) .when( mojo, "getLocationManager" ); File classesDir = tempFolder.newFolder(); mojo.setMainBuildPath( classesDir ); File testClassesDir = tempFolder.newFolder(); mojo.setTestClassesDirectory( testClassesDir ); File descriptorFile = new File( classesDir, "module-info.class" ); assertThat( descriptorFile.createNewFile() ).isTrue(); File jdkHome = new File( System.getProperty( "java.home" ) ); ResolvePathResultWrapper wrapper = invokeMethod( mojo, "findModuleDescriptor", jdkHome ); assertThat( wrapper ) .isNotNull(); assertThat( wrapper.getResolvePathResult() ) .isSameAs( result ); assertThat( wrapper.getResolvePathResult().getModuleNameSource() ) .isSameAs( MODULEDESCRIPTOR ); assertThat( wrapper.getResolvePathResult().getModuleDescriptor() ) .isSameAs( descriptor ); assertThat( invokeMethod( mojo, "existsModuleDescriptor", wrapper ) ) .isEqualTo( true ); when( mojo.useModulePath() ).thenReturn( true ); File jvmExecutable = new File( jdkHome, IS_OS_WINDOWS ? "bin\\java.exe" : "bin/java" ); JdkAttributes jdkAttributes = new JdkAttributes( jvmExecutable, jdkHome, true ); Platform platform = new Platform().withJdkExecAttributesForTests( jdkAttributes ); assertThat( invokeMethod( mojo, "canExecuteProviderWithModularPath", platform, wrapper ) ) .isEqualTo( true ); jdkAttributes = new JdkAttributes( jvmExecutable, jdkHome, false ); platform = new Platform().withJdkExecAttributesForTests( jdkAttributes ); assertThat( invokeMethod( mojo, "canExecuteProviderWithModularPath", platform, wrapper ) ) .isEqualTo( false ); when( mojo.useModulePath() ).thenReturn( false ); jdkAttributes = new JdkAttributes( jvmExecutable, jdkHome, true ); platform = new Platform().withJdkExecAttributesForTests( jdkAttributes ); assertThat( invokeMethod( mojo, "canExecuteProviderWithModularPath", platform, wrapper ) ) .isEqualTo( false ); } |
LegacyMasterProcessChannelDecoder implements MasterProcessChannelDecoder { @Override @Nonnull @SuppressWarnings( "checkstyle:innerassignment" ) public Command decode() throws IOException { List<String> tokens = new ArrayList<>( 3 ); StringBuilder token = new StringBuilder( MAGIC_NUMBER.length() ); ByteBuffer buffer = ByteBuffer.allocate( 1 ); start: do { boolean endOfStream; tokens.clear(); token.setLength( 0 ); FrameCompletion completion = null; for ( boolean frameStarted = false; !( endOfStream = channel.read( buffer ) == -1 ); completion = null ) { buffer.flip(); char c = (char) buffer.get(); buffer.clear(); if ( !frameStarted ) { if ( c == ':' ) { frameStarted = true; token.setLength( 0 ); tokens.clear(); } } else { if ( c == ':' ) { tokens.add( token.toString() ); token.setLength( 0 ); completion = frameCompleteness( tokens ); if ( completion == FrameCompletion.COMPLETE ) { break; } else if ( completion == FrameCompletion.MALFORMED ) { DumpErrorSingleton.getSingleton() .dumpStreamText( "Malformed frame with tokens " + tokens ); continue start; } } else { token.append( c ); } } } if ( completion == FrameCompletion.COMPLETE ) { MasterProcessCommand cmd = COMMAND_OPCODES.get( tokens.get( 1 ) ); if ( tokens.size() == 2 ) { return new Command( cmd ); } else if ( tokens.size() == 3 ) { return new Command( cmd, tokens.get( 2 ) ); } } if ( endOfStream ) { throw new EOFException(); } } while ( true ); } LegacyMasterProcessChannelDecoder( @Nonnull ReadableByteChannel channel ); @Override @Nonnull @SuppressWarnings( "checkstyle:innerassignment" ) Command decode(); @Override void close(); } | @Test public void testDecoderRunClass() throws IOException { assertEquals( String.class, RUN_CLASS.getDataType() ); byte[] encoded = ":maven-surefire-command:run-testclass:pkg.Test:\n".getBytes(); InputStream is = new ByteArrayInputStream( encoded ); LegacyMasterProcessChannelDecoder decoder = new LegacyMasterProcessChannelDecoder( newChannel( is ) ); Command command = decoder.decode(); assertThat( command.getCommandType() ).isSameAs( RUN_CLASS ); assertThat( command.getData() ).isEqualTo( "pkg.Test" ); }
@Test public void testDecoderTestsetFinished() throws IOException { Command command = Command.TEST_SET_FINISHED; assertThat( command.getCommandType() ).isSameAs( TEST_SET_FINISHED ); assertEquals( Void.class, TEST_SET_FINISHED.getDataType() ); byte[] encoded = ":maven-surefire-command:testset-finished:".getBytes(); ByteArrayInputStream is = new ByteArrayInputStream( encoded ); LegacyMasterProcessChannelDecoder decoder = new LegacyMasterProcessChannelDecoder( newChannel( is ) ); command = decoder.decode(); assertThat( command.getCommandType() ).isSameAs( TEST_SET_FINISHED ); assertNull( command.getData() ); }
@Test public void testDecoderSkipSinceNextTest() throws IOException { Command command = Command.SKIP_SINCE_NEXT_TEST; assertThat( command.getCommandType() ).isSameAs( SKIP_SINCE_NEXT_TEST ); assertEquals( Void.class, SKIP_SINCE_NEXT_TEST.getDataType() ); byte[] encoded = ":maven-surefire-command:skip-since-next-test:".getBytes(); ByteArrayInputStream is = new ByteArrayInputStream( encoded ); LegacyMasterProcessChannelDecoder decoder = new LegacyMasterProcessChannelDecoder( newChannel( is ) ); command = decoder.decode(); assertThat( command.getCommandType() ).isSameAs( SKIP_SINCE_NEXT_TEST ); assertNull( command.getData() ); }
@Test public void testDecoderShutdownWithExit() throws IOException { Shutdown shutdownType = EXIT; assertEquals( String.class, SHUTDOWN.getDataType() ); byte[] encoded = ( ":maven-surefire-command:shutdown:" + shutdownType + ":" ).getBytes(); ByteArrayInputStream is = new ByteArrayInputStream( encoded ); LegacyMasterProcessChannelDecoder decoder = new LegacyMasterProcessChannelDecoder( newChannel( is ) ); Command command = decoder.decode(); assertThat( command.getCommandType() ).isSameAs( SHUTDOWN ); assertThat( command.getData() ).isEqualTo( shutdownType.name() ); }
@Test public void testDecoderShutdownWithKill() throws IOException { Shutdown shutdownType = KILL; assertEquals( String.class, SHUTDOWN.getDataType() ); byte[] encoded = ( ":maven-surefire-command:shutdown:" + shutdownType + ":" ).getBytes(); ByteArrayInputStream is = new ByteArrayInputStream( encoded ); LegacyMasterProcessChannelDecoder decoder = new LegacyMasterProcessChannelDecoder( newChannel( is ) ); Command command = decoder.decode(); assertThat( command.getCommandType() ).isSameAs( SHUTDOWN ); assertThat( command.getData() ).isEqualTo( shutdownType.name() ); }
@Test public void testDecoderShutdownWithDefault() throws IOException { Shutdown shutdownType = DEFAULT; assertEquals( String.class, SHUTDOWN.getDataType() ); byte[] encoded = ( ":maven-surefire-command:shutdown:" + shutdownType + ":" ).getBytes(); ByteArrayInputStream is = new ByteArrayInputStream( encoded ); LegacyMasterProcessChannelDecoder decoder = new LegacyMasterProcessChannelDecoder( newChannel( is ) ); Command command = decoder.decode(); assertThat( command.getCommandType() ).isSameAs( SHUTDOWN ); assertThat( command.getData() ).isEqualTo( shutdownType.name() ); }
@Test public void testDecoderNoop() throws IOException { assertThat( NOOP ).isSameAs( Command.NOOP.getCommandType() ); assertEquals( Void.class, NOOP.getDataType() ); byte[] encoded = ":maven-surefire-command:noop:".getBytes(); ByteArrayInputStream is = new ByteArrayInputStream( encoded ); LegacyMasterProcessChannelDecoder decoder = new LegacyMasterProcessChannelDecoder( newChannel( is ) ); Command command = decoder.decode(); assertThat( command.getCommandType() ).isSameAs( NOOP ); assertNull( command.getData() ); }
@Test public void shouldIgnoreDamagedStream() throws IOException { assertThat( BYE_ACK ).isSameAs( Command.BYE_ACK.getCommandType() ); assertEquals( Void.class, BYE_ACK.getDataType() ); byte[] encoded = ":maven-surefire-command:bye-ack:".getBytes(); byte[] streamContent = ( "<something>" + new String( encoded ) + "<damaged>" ).getBytes(); ByteArrayInputStream is = new ByteArrayInputStream( streamContent ); LegacyMasterProcessChannelDecoder decoder = new LegacyMasterProcessChannelDecoder( newChannel( is ) ); Command command = decoder.decode(); assertThat( command.getCommandType() ).isSameAs( BYE_ACK ); assertNull( command.getData() ); }
@Test public void shouldIgnoreDamagedHeader() throws IOException { assertThat( BYE_ACK ).isSameAs( Command.BYE_ACK.getCommandType() ); assertEquals( Void.class, BYE_ACK.getDataType() ); byte[] encoded = ":maven-surefire-command:bye-ack:".getBytes(); byte[] streamContent = ( ":<damaged>:" + new String( encoded ) ).getBytes(); ByteArrayInputStream is = new ByteArrayInputStream( streamContent ); LegacyMasterProcessChannelDecoder decoder = new LegacyMasterProcessChannelDecoder( newChannel( is ) ); Command command = decoder.decode(); assertThat( command.getCommandType() ).isSameAs( BYE_ACK ); assertNull( command.getData() ); }
@Test public void testDecoderByeAck() throws IOException { assertThat( BYE_ACK ).isSameAs( Command.BYE_ACK.getCommandType() ); assertEquals( Void.class, BYE_ACK.getDataType() ); byte[] encoded = ":maven-surefire-command:bye-ack:".getBytes(); ByteArrayInputStream is = new ByteArrayInputStream( encoded ); LegacyMasterProcessChannelDecoder decoder = new LegacyMasterProcessChannelDecoder( newChannel( is ) ); Command command = decoder.decode(); assertThat( command.getCommandType() ).isSameAs( BYE_ACK ); assertNull( command.getData() ); }
@Test( expected = EOFException.class ) public void testIncompleteCommand() throws IOException { ByteArrayInputStream is = new ByteArrayInputStream( ":maven-surefire-command:".getBytes() ); LegacyMasterProcessChannelDecoder decoder = new LegacyMasterProcessChannelDecoder( newChannel( is ) ); decoder.decode(); fail(); }
@Test( expected = EOFException.class ) public void testIncompleteCommandStart() throws IOException { ByteArrayInputStream is = new ByteArrayInputStream( new byte[] {':', '\r'} ); LegacyMasterProcessChannelDecoder decoder = new LegacyMasterProcessChannelDecoder( newChannel( is ) ); decoder.decode(); fail(); }
@Test( expected = EOFException.class ) public void shouldNotDecodeCorruptedCommand() throws IOException { String cmd = ":maven-surefire-command:bye-ack ::maven-surefire-command:"; InputStream is = new ByteArrayInputStream( cmd.getBytes() ); LegacyMasterProcessChannelDecoder decoder = new LegacyMasterProcessChannelDecoder( newChannel( is ) ); decoder.decode(); }
@Test public void shouldSkipCorruptedCommand() throws IOException { String cmd = ":maven-surefire-command:bye-ack\r\n::maven-surefire-command:noop:"; InputStream is = new ByteArrayInputStream( cmd.getBytes() ); LegacyMasterProcessChannelDecoder decoder = new LegacyMasterProcessChannelDecoder( newChannel( is ) ); Command command = decoder.decode(); assertThat( command.getCommandType() ).isSameAs( NOOP ); assertNull( command.getData() ); } |
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 ); } | @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" ); } |
LegacyMasterProcessChannelEncoder implements MasterProcessChannelEncoder { static int estimateBufferLength( ForkedProcessEventType eventType, RunMode runMode, CharsetEncoder encoder, int integersCounter, String... strings ) { assert !( encoder == null && strings.length != 0 ); int lengthOfMetadata = 1 + MAGIC_NUMBER_BYTES.length + 1 + 1 + 1 + eventType.getOpcode().length() + 1; if ( runMode != null ) { lengthOfMetadata += 1 + 1 + runMode.geRunmode().length() + 1; } if ( encoder != null ) { lengthOfMetadata += 1 + 1 + encoder.charset().name().length() + 1; } int lengthOfData = ( 1 + 4 + 1 ) * integersCounter; for ( String string : strings ) { String s = string == null ? "\u0000" : string; lengthOfData += 4 + 1 + (int) ceil( encoder.maxBytesPerChar() * s.length() ) + 1; } return lengthOfMetadata + lengthOfData; } LegacyMasterProcessChannelEncoder( @Nonnull WritableBufferedByteChannel out ); protected LegacyMasterProcessChannelEncoder( @Nonnull WritableBufferedByteChannel out, @Nonnull RunMode runMode ); @Override MasterProcessChannelEncoder asRerunMode(); @Override MasterProcessChannelEncoder asNormalMode(); @Override boolean checkError(); @Override void onJvmExit(); @Override void sendSystemProperties( Map<String, String> sysProps ); @Override void testSetStarting( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testSetCompleted( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testStarting( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testSucceeded( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testFailed( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testSkipped( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testError( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testAssumptionFailure( ReportEntry reportEntry, boolean trimStackTraces ); @Override void stdOut( String msg, boolean newLine ); @Override void stdErr( String msg, boolean newLine ); @Override void consoleInfoLog( String message ); @Override void consoleErrorLog( String message ); @Override void consoleErrorLog( Throwable t ); @Override void consoleErrorLog( String message, Throwable t ); @Override void consoleErrorLog( StackTraceWriter stackTraceWriter, boolean trimStackTraces ); @Override void consoleDebugLog( String message ); @Override void consoleWarningLog( String message ); @Override void bye(); @Override void stopOnNextTest(); @Override void acquireNextTest(); @Override void sendExitError( StackTraceWriter stackTraceWriter, boolean trimStackTraces ); } | @Test public void shouldComputeStreamPreemptiveLength() { CharsetEncoder encoder = UTF_8.newEncoder(); assertThat( estimateBufferLength( BOOTERCODE_SYSPROPS, NORMAL_RUN, encoder, 0, "k", "v" ) ) .isEqualTo( 72 ); assertThat( estimateBufferLength( BOOTERCODE_TESTSET_STARTING, NORMAL_RUN, encoder, 1, "s", "s", "s", "s", "s", "s", "s", "s", "s" ) ) .isEqualTo( 149 ); assertThat( estimateBufferLength( BOOTERCODE_TESTSET_COMPLETED, NORMAL_RUN, encoder, 1, "s", "s", "s", "s", "s", "s", "s", "s", "s" ) ) .isEqualTo( 150 ); assertThat( estimateBufferLength( BOOTERCODE_TEST_STARTING, NORMAL_RUN, encoder, 1, "s", "s", "s", "s", "s", "s", "s", "s", "s" ) ) .isEqualTo( 146 ); assertThat( estimateBufferLength( BOOTERCODE_TEST_SUCCEEDED, NORMAL_RUN, encoder, 1, "s", "s", "s", "s", "s", "s", "s", "s", "s" ) ) .isEqualTo( 147 ); assertThat( estimateBufferLength( BOOTERCODE_TEST_FAILED, NORMAL_RUN, encoder, 1, "s", "s", "s", "s", "s", "s", "s", "s", "s" ) ) .isEqualTo( 144 ); assertThat( estimateBufferLength( BOOTERCODE_TEST_SKIPPED, NORMAL_RUN, encoder, 1, "s", "s", "s", "s", "s", "s", "s", "s", "s" ) ) .isEqualTo( 145 ); assertThat( estimateBufferLength( BOOTERCODE_TEST_ERROR, NORMAL_RUN, encoder, 1, "s", "s", "s", "s", "s", "s", "s", "s", "s" ) ) .isEqualTo( 143 ); assertThat( estimateBufferLength( BOOTERCODE_TEST_ASSUMPTIONFAILURE, NORMAL_RUN, encoder, 1, "s", "s", "s", "s", "s", "s", "s", "s", "s" ) ) .isEqualTo( 156 ); assertThat( estimateBufferLength( BOOTERCODE_STDOUT, NORMAL_RUN, encoder, 0, "s" ) ) .isEqualTo( 69 ); assertThat( estimateBufferLength( BOOTERCODE_STDOUT_NEW_LINE, NORMAL_RUN, encoder, 0, "s" ) ) .isEqualTo( 78 ); assertThat( estimateBufferLength( BOOTERCODE_STDERR, NORMAL_RUN, encoder, 0, "s" ) ) .isEqualTo( 69 ); assertThat( estimateBufferLength( BOOTERCODE_STDERR_NEW_LINE, NORMAL_RUN, encoder, 0, "s" ) ) .isEqualTo( 78 ); assertThat( estimateBufferLength( BOOTERCODE_CONSOLE_INFO, null, encoder, 0, "s" ) ) .isEqualTo( 58 ); assertThat( estimateBufferLength( BOOTERCODE_CONSOLE_DEBUG, null, encoder, 0, "s" ) ) .isEqualTo( 59 ); assertThat( estimateBufferLength( BOOTERCODE_CONSOLE_WARNING, null, encoder, 0, "s" ) ) .isEqualTo( 61 ); assertThat( estimateBufferLength( BOOTERCODE_CONSOLE_ERROR, null, encoder, 0, "s" ) ) .isEqualTo( 59 ); assertThat( estimateBufferLength( BOOTERCODE_BYE, null, null, 0 ) ) .isEqualTo( 28 ); assertThat( estimateBufferLength( BOOTERCODE_STOP_ON_NEXT_TEST, null, null, 0 ) ) .isEqualTo( 42 ); assertThat( estimateBufferLength( BOOTERCODE_NEXT_TEST, null, null, 0 ) ) .isEqualTo( 34 ); assertThat( estimateBufferLength( BOOTERCODE_JVM_EXIT_ERROR, null, null, 0 ) ) .isEqualTo( 39 ); } |
LegacyMasterProcessChannelEncoder implements MasterProcessChannelEncoder { @Override public void testSetCompleted( ReportEntry reportEntry, boolean trimStackTraces ) { encode( BOOTERCODE_TESTSET_COMPLETED, runMode, reportEntry, trimStackTraces, true ); } LegacyMasterProcessChannelEncoder( @Nonnull WritableBufferedByteChannel out ); protected LegacyMasterProcessChannelEncoder( @Nonnull WritableBufferedByteChannel out, @Nonnull RunMode runMode ); @Override MasterProcessChannelEncoder asRerunMode(); @Override MasterProcessChannelEncoder asNormalMode(); @Override boolean checkError(); @Override void onJvmExit(); @Override void sendSystemProperties( Map<String, String> sysProps ); @Override void testSetStarting( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testSetCompleted( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testStarting( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testSucceeded( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testFailed( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testSkipped( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testError( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testAssumptionFailure( ReportEntry reportEntry, boolean trimStackTraces ); @Override void stdOut( String msg, boolean newLine ); @Override void stdErr( String msg, boolean newLine ); @Override void consoleInfoLog( String message ); @Override void consoleErrorLog( String message ); @Override void consoleErrorLog( Throwable t ); @Override void consoleErrorLog( String message, Throwable t ); @Override void consoleErrorLog( StackTraceWriter stackTraceWriter, boolean trimStackTraces ); @Override void consoleDebugLog( String message ); @Override void consoleWarningLog( String message ); @Override void bye(); @Override void stopOnNextTest(); @Override void acquireNextTest(); @Override void sendExitError( StackTraceWriter stackTraceWriter, boolean trimStackTraces ); } | @Test public void testSetCompleted() throws IOException { String exceptionMessage = "msg"; String smartStackTrace = "MyTest:86 >> Error"; String stackTrace = "trace line 1\ntrace line 2"; String trimmedStackTrace = "trace line 1\ntrace line 2"; SafeThrowable safeThrowable = new SafeThrowable( new Exception( exceptionMessage ) ); StackTraceWriter stackTraceWriter = mock( StackTraceWriter.class ); when( stackTraceWriter.getThrowable() ).thenReturn( safeThrowable ); when( stackTraceWriter.smartTrimmedStackTrace() ).thenReturn( smartStackTrace ); when( stackTraceWriter.writeTrimmedTraceToString() ).thenReturn( trimmedStackTrace ); when( stackTraceWriter.writeTraceToString() ).thenReturn( stackTrace ); ReportEntry reportEntry = mock( ReportEntry.class ); when( reportEntry.getElapsed() ).thenReturn( ELAPSED_TIME ); when( reportEntry.getGroup() ).thenReturn( "this group" ); when( reportEntry.getMessage() ).thenReturn( "skipped test" ); when( reportEntry.getName() ).thenReturn( "my test" ); when( reportEntry.getNameWithGroup() ).thenReturn( "name with group" ); when( reportEntry.getSourceName() ).thenReturn( "pkg.MyTest" ); when( reportEntry.getStackTraceWriter() ).thenReturn( stackTraceWriter ); Stream out = Stream.newStream(); LegacyMasterProcessChannelEncoder encoder = new LegacyMasterProcessChannelEncoder( newBufferedChannel( out ) ); encoder.testSetCompleted( reportEntry, false ); ByteArrayOutputStream expectedFrame = new ByteArrayOutputStream(); expectedFrame.write( ":maven-surefire-event:".getBytes( UTF_8 ) ); expectedFrame.write( (byte) 17 ); expectedFrame.write( ":testset-completed:".getBytes( UTF_8 ) ); expectedFrame.write( (byte) 10 ); expectedFrame.write( ":normal-run:".getBytes( UTF_8 ) ); expectedFrame.write( (byte) 5 ); expectedFrame.write( ":UTF-8:".getBytes( UTF_8 ) ); expectedFrame.write( new byte[] {0, 0, 0, 10} ); expectedFrame.write( ':' ); expectedFrame.write( reportEntry.getSourceName().getBytes( UTF_8 ) ); expectedFrame.write( ':' ); expectedFrame.write( new byte[] {0, 0, 0, 1} ); expectedFrame.write( ':' ); expectedFrame.write( 0 ); expectedFrame.write( ':' ); expectedFrame.write( new byte[] {0, 0, 0, 7} ); expectedFrame.write( ':' ); expectedFrame.write( reportEntry.getName().getBytes( UTF_8 ) ); expectedFrame.write( ':' ); expectedFrame.write( new byte[] {0, 0, 0, 1} ); expectedFrame.write( ':' ); expectedFrame.write( 0 ); expectedFrame.write( ':' ); expectedFrame.write( new byte[] {0, 0, 0, 10} ); expectedFrame.write( ':' ); expectedFrame.write( reportEntry.getGroup().getBytes( UTF_8 ) ); expectedFrame.write( ':' ); expectedFrame.write( new byte[] {0, 0, 0, 12} ); expectedFrame.write( ':' ); expectedFrame.write( reportEntry.getMessage().getBytes( UTF_8 ) ); expectedFrame.write( ':' ); expectedFrame.write( 0xff ); expectedFrame.write( ELAPSED_TIME_HEXA ); expectedFrame.write( ':' ); expectedFrame.write( new byte[] {0, 0, 0, 3} ); expectedFrame.write( ':' ); expectedFrame.write( exceptionMessage.getBytes( UTF_8 ) ); expectedFrame.write( ':' ); expectedFrame.write( new byte[] {0, 0, 0, 18} ); expectedFrame.write( ':' ); expectedFrame.write( reportEntry.getStackTraceWriter().smartTrimmedStackTrace().getBytes( UTF_8 ) ); expectedFrame.write( ':' ); expectedFrame.write( new byte[] {0, 0, 0, 25} ); expectedFrame.write( ':' ); expectedFrame.write( stackTrace.getBytes( UTF_8 ) ); expectedFrame.write( ':' ); assertThat( out.toByteArray() ) .isEqualTo( expectedFrame.toByteArray() ); } |
LegacyMasterProcessChannelEncoder implements MasterProcessChannelEncoder { @Override public void testStarting( ReportEntry reportEntry, boolean trimStackTraces ) { encode( BOOTERCODE_TEST_STARTING, runMode, reportEntry, trimStackTraces, true ); } LegacyMasterProcessChannelEncoder( @Nonnull WritableBufferedByteChannel out ); protected LegacyMasterProcessChannelEncoder( @Nonnull WritableBufferedByteChannel out, @Nonnull RunMode runMode ); @Override MasterProcessChannelEncoder asRerunMode(); @Override MasterProcessChannelEncoder asNormalMode(); @Override boolean checkError(); @Override void onJvmExit(); @Override void sendSystemProperties( Map<String, String> sysProps ); @Override void testSetStarting( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testSetCompleted( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testStarting( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testSucceeded( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testFailed( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testSkipped( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testError( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testAssumptionFailure( ReportEntry reportEntry, boolean trimStackTraces ); @Override void stdOut( String msg, boolean newLine ); @Override void stdErr( String msg, boolean newLine ); @Override void consoleInfoLog( String message ); @Override void consoleErrorLog( String message ); @Override void consoleErrorLog( Throwable t ); @Override void consoleErrorLog( String message, Throwable t ); @Override void consoleErrorLog( StackTraceWriter stackTraceWriter, boolean trimStackTraces ); @Override void consoleDebugLog( String message ); @Override void consoleWarningLog( String message ); @Override void bye(); @Override void stopOnNextTest(); @Override void acquireNextTest(); @Override void sendExitError( StackTraceWriter stackTraceWriter, boolean trimStackTraces ); } | @Test public void testStarting() throws IOException { String exceptionMessage = "msg"; String smartStackTrace = "MyTest:86 >> Error"; String stackTrace = "trace line 1\ntrace line 2"; String trimmedStackTrace = "trace line 1\ntrace line 2"; SafeThrowable safeThrowable = new SafeThrowable( new Exception( exceptionMessage ) ); StackTraceWriter stackTraceWriter = mock( StackTraceWriter.class ); when( stackTraceWriter.getThrowable() ).thenReturn( safeThrowable ); when( stackTraceWriter.smartTrimmedStackTrace() ).thenReturn( smartStackTrace ); when( stackTraceWriter.writeTrimmedTraceToString() ).thenReturn( trimmedStackTrace ); when( stackTraceWriter.writeTraceToString() ).thenReturn( stackTrace ); ReportEntry reportEntry = mock( ReportEntry.class ); when( reportEntry.getElapsed() ).thenReturn( ELAPSED_TIME ); when( reportEntry.getGroup() ).thenReturn( "this group" ); when( reportEntry.getMessage() ).thenReturn( "skipped test" ); when( reportEntry.getName() ).thenReturn( "my test" ); when( reportEntry.getNameWithGroup() ).thenReturn( "name with group" ); when( reportEntry.getSourceName() ).thenReturn( "pkg.MyTest" ); when( reportEntry.getStackTraceWriter() ).thenReturn( stackTraceWriter ); Stream out = Stream.newStream(); LegacyMasterProcessChannelEncoder encoder = new LegacyMasterProcessChannelEncoder( newBufferedChannel( out ) ); encoder.testStarting( reportEntry, true ); ByteArrayOutputStream expectedFrame = new ByteArrayOutputStream(); expectedFrame.write( ":maven-surefire-event:".getBytes( UTF_8 ) ); expectedFrame.write( (byte) 13 ); expectedFrame.write( ":test-starting:".getBytes( UTF_8 ) ); expectedFrame.write( (byte) 10 ); expectedFrame.write( ":normal-run:".getBytes( UTF_8 ) ); expectedFrame.write( (byte) 5 ); expectedFrame.write( ":UTF-8:".getBytes( UTF_8 ) ); expectedFrame.write( new byte[] {0, 0, 0, 10} ); expectedFrame.write( ':' ); expectedFrame.write( reportEntry.getSourceName().getBytes( UTF_8 ) ); expectedFrame.write( ':' ); expectedFrame.write( new byte[] {0, 0, 0, 1} ); expectedFrame.write( ':' ); expectedFrame.write( 0 ); expectedFrame.write( ':' ); expectedFrame.write( new byte[] {0, 0, 0, 7} ); expectedFrame.write( ':' ); expectedFrame.write( reportEntry.getName().getBytes( UTF_8 ) ); expectedFrame.write( ':' ); expectedFrame.write( new byte[] {0, 0, 0, 1} ); expectedFrame.write( ':' ); expectedFrame.write( 0 ); expectedFrame.write( ':' ); expectedFrame.write( new byte[] {0, 0, 0, 10} ); expectedFrame.write( ':' ); expectedFrame.write( reportEntry.getGroup().getBytes( UTF_8 ) ); expectedFrame.write( ':' ); expectedFrame.write( new byte[] {0, 0, 0, 12} ); expectedFrame.write( ':' ); expectedFrame.write( reportEntry.getMessage().getBytes( UTF_8 ) ); expectedFrame.write( ':' ); expectedFrame.write( 0xff ); expectedFrame.write( ELAPSED_TIME_HEXA ); expectedFrame.write( ':' ); expectedFrame.write( new byte[] {0, 0, 0, 3} ); expectedFrame.write( ':' ); expectedFrame.write( exceptionMessage.getBytes( UTF_8 ) ); expectedFrame.write( ':' ); expectedFrame.write( new byte[] {0, 0, 0, 18} ); expectedFrame.write( ':' ); expectedFrame.write( reportEntry.getStackTraceWriter().smartTrimmedStackTrace().getBytes( UTF_8 ) ); expectedFrame.write( ':' ); expectedFrame.write( new byte[] {0, 0, 0, 25} ); expectedFrame.write( ':' ); expectedFrame.write( stackTrace.getBytes( UTF_8 ) ); expectedFrame.write( ':' ); assertThat( out.toByteArray() ) .isEqualTo( expectedFrame.toByteArray() ); } |
LegacyMasterProcessChannelEncoder implements MasterProcessChannelEncoder { @Override public void testSucceeded( ReportEntry reportEntry, boolean trimStackTraces ) { encode( BOOTERCODE_TEST_SUCCEEDED, runMode, reportEntry, trimStackTraces, true ); } LegacyMasterProcessChannelEncoder( @Nonnull WritableBufferedByteChannel out ); protected LegacyMasterProcessChannelEncoder( @Nonnull WritableBufferedByteChannel out, @Nonnull RunMode runMode ); @Override MasterProcessChannelEncoder asRerunMode(); @Override MasterProcessChannelEncoder asNormalMode(); @Override boolean checkError(); @Override void onJvmExit(); @Override void sendSystemProperties( Map<String, String> sysProps ); @Override void testSetStarting( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testSetCompleted( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testStarting( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testSucceeded( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testFailed( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testSkipped( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testError( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testAssumptionFailure( ReportEntry reportEntry, boolean trimStackTraces ); @Override void stdOut( String msg, boolean newLine ); @Override void stdErr( String msg, boolean newLine ); @Override void consoleInfoLog( String message ); @Override void consoleErrorLog( String message ); @Override void consoleErrorLog( Throwable t ); @Override void consoleErrorLog( String message, Throwable t ); @Override void consoleErrorLog( StackTraceWriter stackTraceWriter, boolean trimStackTraces ); @Override void consoleDebugLog( String message ); @Override void consoleWarningLog( String message ); @Override void bye(); @Override void stopOnNextTest(); @Override void acquireNextTest(); @Override void sendExitError( StackTraceWriter stackTraceWriter, boolean trimStackTraces ); } | @Test public void testSuccess() throws IOException { String exceptionMessage = "msg"; String smartStackTrace = "MyTest:86 >> Error"; String stackTrace = "trace line 1\ntrace line 2"; String trimmedStackTrace = "trace line 1\ntrace line 2"; SafeThrowable safeThrowable = new SafeThrowable( new Exception( exceptionMessage ) ); StackTraceWriter stackTraceWriter = mock( StackTraceWriter.class ); when( stackTraceWriter.getThrowable() ).thenReturn( safeThrowable ); when( stackTraceWriter.smartTrimmedStackTrace() ).thenReturn( smartStackTrace ); when( stackTraceWriter.writeTrimmedTraceToString() ).thenReturn( trimmedStackTrace ); when( stackTraceWriter.writeTraceToString() ).thenReturn( stackTrace ); ReportEntry reportEntry = mock( ReportEntry.class ); when( reportEntry.getElapsed() ).thenReturn( ELAPSED_TIME ); when( reportEntry.getGroup() ).thenReturn( "this group" ); when( reportEntry.getMessage() ).thenReturn( "skipped test" ); when( reportEntry.getName() ).thenReturn( "my test" ); when( reportEntry.getNameWithGroup() ).thenReturn( "name with group" ); when( reportEntry.getSourceName() ).thenReturn( "pkg.MyTest" ); when( reportEntry.getStackTraceWriter() ).thenReturn( stackTraceWriter ); Stream out = Stream.newStream(); LegacyMasterProcessChannelEncoder encoder = new LegacyMasterProcessChannelEncoder( newBufferedChannel( out ) ); encoder.testSucceeded( reportEntry, true ); ByteArrayOutputStream expectedFrame = new ByteArrayOutputStream(); expectedFrame.write( ":maven-surefire-event:".getBytes( UTF_8 ) ); expectedFrame.write( (byte) 14 ); expectedFrame.write( ":test-succeeded:".getBytes( UTF_8 ) ); expectedFrame.write( (byte) 10 ); expectedFrame.write( ":normal-run:".getBytes( UTF_8 ) ); expectedFrame.write( (byte) 5 ); expectedFrame.write( ":UTF-8:".getBytes( UTF_8 ) ); expectedFrame.write( new byte[] {0, 0, 0, 10} ); expectedFrame.write( ':' ); expectedFrame.write( reportEntry.getSourceName().getBytes( UTF_8 ) ); expectedFrame.write( ':' ); expectedFrame.write( new byte[] {0, 0, 0, 1} ); expectedFrame.write( ':' ); expectedFrame.write( 0 ); expectedFrame.write( ':' ); expectedFrame.write( new byte[] {0, 0, 0, 7} ); expectedFrame.write( ':' ); expectedFrame.write( reportEntry.getName().getBytes( UTF_8 ) ); expectedFrame.write( ':' ); expectedFrame.write( new byte[] {0, 0, 0, 1} ); expectedFrame.write( ':' ); expectedFrame.write( 0 ); expectedFrame.write( ':' ); expectedFrame.write( new byte[] {0, 0, 0, 10} ); expectedFrame.write( ':' ); expectedFrame.write( reportEntry.getGroup().getBytes( UTF_8 ) ); expectedFrame.write( ':' ); expectedFrame.write( new byte[] {0, 0, 0, 12} ); expectedFrame.write( ':' ); expectedFrame.write( reportEntry.getMessage().getBytes( UTF_8 ) ); expectedFrame.write( ':' ); expectedFrame.write( 0xff ); expectedFrame.write( ELAPSED_TIME_HEXA ); expectedFrame.write( ':' ); expectedFrame.write( new byte[] {0, 0, 0, 3} ); expectedFrame.write( ':' ); expectedFrame.write( exceptionMessage.getBytes( UTF_8 ) ); expectedFrame.write( ':' ); expectedFrame.write( new byte[] {0, 0, 0, 18} ); expectedFrame.write( ':' ); expectedFrame.write( reportEntry.getStackTraceWriter().smartTrimmedStackTrace().getBytes( UTF_8 ) ); expectedFrame.write( ':' ); expectedFrame.write( new byte[] {0, 0, 0, 25} ); expectedFrame.write( ':' ); expectedFrame.write( stackTrace.getBytes( UTF_8 ) ); expectedFrame.write( ':' ); assertThat( out.toByteArray() ) .isEqualTo( expectedFrame.toByteArray() ); } |
LegacyMasterProcessChannelEncoder implements MasterProcessChannelEncoder { @Override public void testFailed( ReportEntry reportEntry, boolean trimStackTraces ) { encode( BOOTERCODE_TEST_FAILED, runMode, reportEntry, trimStackTraces, true ); } LegacyMasterProcessChannelEncoder( @Nonnull WritableBufferedByteChannel out ); protected LegacyMasterProcessChannelEncoder( @Nonnull WritableBufferedByteChannel out, @Nonnull RunMode runMode ); @Override MasterProcessChannelEncoder asRerunMode(); @Override MasterProcessChannelEncoder asNormalMode(); @Override boolean checkError(); @Override void onJvmExit(); @Override void sendSystemProperties( Map<String, String> sysProps ); @Override void testSetStarting( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testSetCompleted( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testStarting( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testSucceeded( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testFailed( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testSkipped( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testError( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testAssumptionFailure( ReportEntry reportEntry, boolean trimStackTraces ); @Override void stdOut( String msg, boolean newLine ); @Override void stdErr( String msg, boolean newLine ); @Override void consoleInfoLog( String message ); @Override void consoleErrorLog( String message ); @Override void consoleErrorLog( Throwable t ); @Override void consoleErrorLog( String message, Throwable t ); @Override void consoleErrorLog( StackTraceWriter stackTraceWriter, boolean trimStackTraces ); @Override void consoleDebugLog( String message ); @Override void consoleWarningLog( String message ); @Override void bye(); @Override void stopOnNextTest(); @Override void acquireNextTest(); @Override void sendExitError( StackTraceWriter stackTraceWriter, boolean trimStackTraces ); } | @Test public void testFailed() throws IOException { String exceptionMessage = "msg"; String smartStackTrace = "MyTest:86 >> Error"; String stackTrace = "trace line 1\ntrace line 2"; String trimmedStackTrace = "trace line 1\ntrace line 2"; SafeThrowable safeThrowable = new SafeThrowable( new Exception( exceptionMessage ) ); StackTraceWriter stackTraceWriter = mock( StackTraceWriter.class ); when( stackTraceWriter.getThrowable() ).thenReturn( safeThrowable ); when( stackTraceWriter.smartTrimmedStackTrace() ).thenReturn( smartStackTrace ); when( stackTraceWriter.writeTrimmedTraceToString() ).thenReturn( trimmedStackTrace ); when( stackTraceWriter.writeTraceToString() ).thenReturn( stackTrace ); ReportEntry reportEntry = mock( ReportEntry.class ); when( reportEntry.getElapsed() ).thenReturn( ELAPSED_TIME ); when( reportEntry.getGroup() ).thenReturn( "this group" ); when( reportEntry.getMessage() ).thenReturn( "skipped test" ); when( reportEntry.getName() ).thenReturn( "my test" ); when( reportEntry.getNameWithGroup() ).thenReturn( "name with group" ); when( reportEntry.getSourceName() ).thenReturn( "pkg.MyTest" ); when( reportEntry.getStackTraceWriter() ).thenReturn( stackTraceWriter ); Stream out = Stream.newStream(); LegacyMasterProcessChannelEncoder encoder = new LegacyMasterProcessChannelEncoder( newBufferedChannel( out ) ); encoder.testFailed( reportEntry, false ); ByteArrayOutputStream expectedFrame = new ByteArrayOutputStream(); expectedFrame.write( ":maven-surefire-event:".getBytes( UTF_8 ) ); expectedFrame.write( (byte) 11 ); expectedFrame.write( ":test-failed:".getBytes( UTF_8 ) ); expectedFrame.write( (byte) 10 ); expectedFrame.write( ":normal-run:".getBytes( UTF_8 ) ); expectedFrame.write( (byte) 5 ); expectedFrame.write( ":UTF-8:".getBytes( UTF_8 ) ); expectedFrame.write( new byte[] {0, 0, 0, 10} ); expectedFrame.write( ':' ); expectedFrame.write( reportEntry.getSourceName().getBytes( UTF_8 ) ); expectedFrame.write( ':' ); expectedFrame.write( new byte[] {0, 0, 0, 1} ); expectedFrame.write( ':' ); expectedFrame.write( 0 ); expectedFrame.write( ':' ); expectedFrame.write( new byte[] {0, 0, 0, 7} ); expectedFrame.write( ':' ); expectedFrame.write( reportEntry.getName().getBytes( UTF_8 ) ); expectedFrame.write( ':' ); expectedFrame.write( new byte[] {0, 0, 0, 1} ); expectedFrame.write( ':' ); expectedFrame.write( 0 ); expectedFrame.write( ':' ); expectedFrame.write( new byte[] {0, 0, 0, 10} ); expectedFrame.write( ':' ); expectedFrame.write( reportEntry.getGroup().getBytes( UTF_8 ) ); expectedFrame.write( ':' ); expectedFrame.write( new byte[] {0, 0, 0, 12} ); expectedFrame.write( ':' ); expectedFrame.write( reportEntry.getMessage().getBytes( UTF_8 ) ); expectedFrame.write( ':' ); expectedFrame.write( 0xff ); expectedFrame.write( ELAPSED_TIME_HEXA ); expectedFrame.write( ':' ); expectedFrame.write( new byte[] {0, 0, 0, 3} ); expectedFrame.write( ':' ); expectedFrame.write( exceptionMessage.getBytes( UTF_8 ) ); expectedFrame.write( ':' ); expectedFrame.write( new byte[] {0, 0, 0, 18} ); expectedFrame.write( ':' ); expectedFrame.write( reportEntry.getStackTraceWriter().smartTrimmedStackTrace().getBytes( UTF_8 ) ); expectedFrame.write( ':' ); expectedFrame.write( new byte[] {0, 0, 0, 25} ); expectedFrame.write( ':' ); expectedFrame.write( stackTrace.getBytes( UTF_8 ) ); expectedFrame.write( ':' ); assertThat( out.toByteArray() ) .isEqualTo( expectedFrame.toByteArray() ); } |
LegacyMasterProcessChannelEncoder implements MasterProcessChannelEncoder { @Override public void testSkipped( ReportEntry reportEntry, boolean trimStackTraces ) { encode( BOOTERCODE_TEST_SKIPPED, runMode, reportEntry, trimStackTraces, true ); } LegacyMasterProcessChannelEncoder( @Nonnull WritableBufferedByteChannel out ); protected LegacyMasterProcessChannelEncoder( @Nonnull WritableBufferedByteChannel out, @Nonnull RunMode runMode ); @Override MasterProcessChannelEncoder asRerunMode(); @Override MasterProcessChannelEncoder asNormalMode(); @Override boolean checkError(); @Override void onJvmExit(); @Override void sendSystemProperties( Map<String, String> sysProps ); @Override void testSetStarting( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testSetCompleted( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testStarting( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testSucceeded( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testFailed( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testSkipped( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testError( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testAssumptionFailure( ReportEntry reportEntry, boolean trimStackTraces ); @Override void stdOut( String msg, boolean newLine ); @Override void stdErr( String msg, boolean newLine ); @Override void consoleInfoLog( String message ); @Override void consoleErrorLog( String message ); @Override void consoleErrorLog( Throwable t ); @Override void consoleErrorLog( String message, Throwable t ); @Override void consoleErrorLog( StackTraceWriter stackTraceWriter, boolean trimStackTraces ); @Override void consoleDebugLog( String message ); @Override void consoleWarningLog( String message ); @Override void bye(); @Override void stopOnNextTest(); @Override void acquireNextTest(); @Override void sendExitError( StackTraceWriter stackTraceWriter, boolean trimStackTraces ); } | @Test public void testSkipped() throws IOException { String smartStackTrace = "MyTest:86 >> Error"; String stackTrace = "trace line 1\ntrace line 2"; String trimmedStackTrace = "trace line 1\ntrace line 2"; SafeThrowable safeThrowable = new SafeThrowable( new Exception() ); StackTraceWriter stackTraceWriter = mock( StackTraceWriter.class ); when( stackTraceWriter.getThrowable() ).thenReturn( safeThrowable ); when( stackTraceWriter.smartTrimmedStackTrace() ).thenReturn( smartStackTrace ); when( stackTraceWriter.writeTrimmedTraceToString() ).thenReturn( trimmedStackTrace ); when( stackTraceWriter.writeTraceToString() ).thenReturn( stackTrace ); ReportEntry reportEntry = mock( ReportEntry.class ); when( reportEntry.getElapsed() ).thenReturn( ELAPSED_TIME ); when( reportEntry.getGroup() ).thenReturn( "this group" ); when( reportEntry.getMessage() ).thenReturn( "skipped test" ); when( reportEntry.getName() ).thenReturn( "my test" ); when( reportEntry.getNameWithGroup() ).thenReturn( "name with group" ); when( reportEntry.getSourceName() ).thenReturn( "pkg.MyTest" ); when( reportEntry.getStackTraceWriter() ).thenReturn( stackTraceWriter ); Stream out = Stream.newStream(); LegacyMasterProcessChannelEncoder encoder = new LegacyMasterProcessChannelEncoder( newBufferedChannel( out ) ); encoder.testSkipped( reportEntry, false ); ByteArrayOutputStream expectedFrame = new ByteArrayOutputStream(); expectedFrame.write( ":maven-surefire-event:".getBytes( UTF_8 ) ); expectedFrame.write( (byte) 12 ); expectedFrame.write( ":test-skipped:".getBytes( UTF_8 ) ); expectedFrame.write( (byte) 10 ); expectedFrame.write( ":normal-run:".getBytes( UTF_8 ) ); expectedFrame.write( (byte) 5 ); expectedFrame.write( ":UTF-8:".getBytes( UTF_8 ) ); expectedFrame.write( new byte[] {0, 0, 0, 10} ); expectedFrame.write( ':' ); expectedFrame.write( reportEntry.getSourceName().getBytes( UTF_8 ) ); expectedFrame.write( ':' ); expectedFrame.write( new byte[] {0, 0, 0, 1} ); expectedFrame.write( ':' ); expectedFrame.write( 0 ); expectedFrame.write( ':' ); expectedFrame.write( new byte[] {0, 0, 0, 7} ); expectedFrame.write( ':' ); expectedFrame.write( reportEntry.getName().getBytes( UTF_8 ) ); expectedFrame.write( ':' ); expectedFrame.write( new byte[] {0, 0, 0, 1} ); expectedFrame.write( ':' ); expectedFrame.write( 0 ); expectedFrame.write( ':' ); expectedFrame.write( new byte[] {0, 0, 0, 10} ); expectedFrame.write( ':' ); expectedFrame.write( reportEntry.getGroup().getBytes( UTF_8 ) ); expectedFrame.write( ':' ); expectedFrame.write( new byte[] {0, 0, 0, 12} ); expectedFrame.write( ':' ); expectedFrame.write( reportEntry.getMessage().getBytes( UTF_8 ) ); expectedFrame.write( ':' ); expectedFrame.write( 0xFF ); expectedFrame.write( ELAPSED_TIME_HEXA ); expectedFrame.write( ':' ); expectedFrame.write( new byte[] {0, 0, 0, 1} ); expectedFrame.write( ':' ); expectedFrame.write( 0 ); expectedFrame.write( ':' ); expectedFrame.write( new byte[] {0, 0, 0, 18} ); expectedFrame.write( ':' ); expectedFrame.write( reportEntry.getStackTraceWriter().smartTrimmedStackTrace().getBytes( UTF_8 ) ); expectedFrame.write( ':' ); expectedFrame.write( new byte[] {0, 0, 0, 25} ); expectedFrame.write( ':' ); expectedFrame.write( stackTrace.getBytes( UTF_8 ) ); expectedFrame.write( ':' ); assertThat( out.toByteArray() ) .isEqualTo( expectedFrame.toByteArray() ); } |
AbstractSurefireMojo extends AbstractMojo implements SurefireExecutionParameters { @Nonnull protected final PluginConsoleLogger getConsoleLogger() { if ( consoleLogger == null ) { synchronized ( this ) { if ( consoleLogger == null ) { consoleLogger = new PluginConsoleLogger( logger ); } } } return consoleLogger; } @Override abstract List<String> getIncludes(); abstract File getIncludesFile(); @Override abstract void setIncludes( List<String> includes ); abstract File getExcludesFile(); abstract File[] getSuiteXmlFiles(); abstract void setSuiteXmlFiles( File[] suiteXmlFiles ); abstract String getRunOrder(); abstract void setRunOrder( String runOrder ); abstract Long getRunOrderRandomSeed(); abstract void setRunOrderRandomSeed( Long runOrderRandomSeed ); @Override void execute(); static SurefireProperties createCopyAndReplaceForkNumPlaceholder(
SurefireProperties effectiveSystemProperties, int threadNumber ); RepositorySystem getRepositorySystem(); void setRepositorySystem( RepositorySystem repositorySystem ); DependencyResolver getDependencyResolver(); void setDependencyResolver( DependencyResolver dependencyResolver ); TestListResolver getSpecificTests(); @Override List<String> getExcludes(); @Override void setExcludes( List<String> excludes ); @Override ArtifactRepository getLocalRepository(); @Override void setLocalRepository( ArtifactRepository localRepository ); Properties getSystemProperties(); @SuppressWarnings( "UnusedDeclaration" ) void setSystemProperties( Properties systemProperties ); Map<String, String> getSystemPropertyVariables(); @SuppressWarnings( "UnusedDeclaration" ) void setSystemPropertyVariables( Map<String, String> systemPropertyVariables ); abstract File getSystemPropertiesFile(); @SuppressWarnings( "UnusedDeclaration" ) abstract void setSystemPropertiesFile( File systemPropertiesFile ); void setProperties( Properties properties ); Map<String, Artifact> getPluginArtifactMap(); @SuppressWarnings( "UnusedDeclaration" ) void setPluginArtifactMap( Map<String, Artifact> pluginArtifactMap ); Map<String, Artifact> getProjectArtifactMap(); @SuppressWarnings( "UnusedDeclaration" ) void setProjectArtifactMap( Map<String, Artifact> projectArtifactMap ); String getReportNameSuffix(); @SuppressWarnings( "UnusedDeclaration" ) void setReportNameSuffix( String reportNameSuffix ); boolean isRedirectTestOutputToFile(); @SuppressWarnings( "UnusedDeclaration" ) void setRedirectTestOutputToFile( boolean redirectTestOutputToFile ); Boolean getFailIfNoTests(); void setFailIfNoTests( boolean failIfNoTests ); String getForkMode(); @SuppressWarnings( "UnusedDeclaration" ) void setForkMode( String forkMode ); String getJvm(); String getArgLine(); @SuppressWarnings( "UnusedDeclaration" ) void setArgLine( String argLine ); Map<String, String> getEnvironmentVariables(); @SuppressWarnings( "UnusedDeclaration" ) void setEnvironmentVariables( Map<String, String> environmentVariables ); File getWorkingDirectory(); @SuppressWarnings( "UnusedDeclaration" ) void setWorkingDirectory( File workingDirectory ); boolean isChildDelegation(); @SuppressWarnings( "UnusedDeclaration" ) void setChildDelegation( boolean childDelegation ); String getGroups(); @SuppressWarnings( "UnusedDeclaration" ) void setGroups( String groups ); String getExcludedGroups(); @SuppressWarnings( "UnusedDeclaration" ) void setExcludedGroups( String excludedGroups ); String getJunitArtifactName(); @SuppressWarnings( "UnusedDeclaration" ) void setJunitArtifactName( String junitArtifactName ); String getTestNGArtifactName(); @SuppressWarnings( "UnusedDeclaration" ) void setTestNGArtifactName( String testNGArtifactName ); int getThreadCount(); @SuppressWarnings( "UnusedDeclaration" ) void setThreadCount( int threadCount ); boolean getPerCoreThreadCount(); @SuppressWarnings( "UnusedDeclaration" ) void setPerCoreThreadCount( boolean perCoreThreadCount ); boolean getUseUnlimitedThreads(); @SuppressWarnings( "UnusedDeclaration" ) void setUseUnlimitedThreads( boolean useUnlimitedThreads ); String getParallel(); @SuppressWarnings( "UnusedDeclaration" ) void setParallel( String parallel ); boolean isParallelOptimized(); @SuppressWarnings( "UnusedDeclaration" ) void setParallelOptimized( boolean parallelOptimized ); int getThreadCountSuites(); void setThreadCountSuites( int threadCountSuites ); int getThreadCountClasses(); void setThreadCountClasses( int threadCountClasses ); int getThreadCountMethods(); void setThreadCountMethods( int threadCountMethods ); boolean isTrimStackTrace(); @SuppressWarnings( "UnusedDeclaration" ) void setTrimStackTrace( boolean trimStackTrace ); List<ArtifactRepository> getProjectRemoteRepositories(); @SuppressWarnings( "UnusedDeclaration" ) void setProjectRemoteRepositories( List<ArtifactRepository> projectRemoteRepositories ); List<ArtifactRepository> getRemoteRepositories(); @SuppressWarnings( "UnusedDeclaration" ) void setRemoteRepositories( List<ArtifactRepository> remoteRepositories ); boolean isDisableXmlReport(); @SuppressWarnings( "UnusedDeclaration" ) void setDisableXmlReport( boolean disableXmlReport ); boolean isEnableAssertions(); boolean effectiveIsEnableAssertions(); @SuppressWarnings( "UnusedDeclaration" ) void setEnableAssertions( boolean enableAssertions ); MavenSession getSession(); @SuppressWarnings( "UnusedDeclaration" ) void setSession( MavenSession session ); String getObjectFactory(); @SuppressWarnings( "UnusedDeclaration" ) void setObjectFactory( String objectFactory ); ToolchainManager getToolchainManager(); @SuppressWarnings( "UnusedDeclaration" ) void setToolchainManager( ToolchainManager toolchainManager ); boolean isMavenParallel(); String[] getDependenciesToScan(); void setDependenciesToScan( String[] dependenciesToScan ); PluginDescriptor getPluginDescriptor(); MavenProject getProject(); @SuppressWarnings( "UnusedDeclaration" ) void setProject( MavenProject project ); @Override File getTestSourceDirectory(); @Override void setTestSourceDirectory( File testSourceDirectory ); String getForkCount(); boolean isReuseForks(); String[] getAdditionalClasspathElements(); void setAdditionalClasspathElements( String[] additionalClasspathElements ); String[] getClasspathDependencyExcludes(); void setClasspathDependencyExcludes( String[] classpathDependencyExcludes ); String getClasspathDependencyScopeExclude(); void setClasspathDependencyScopeExclude( String classpathDependencyScopeExclude ); File getProjectBuildDirectory(); void setProjectBuildDirectory( File projectBuildDirectory ); Map<String, String> getJdkToolchain(); void setJdkToolchain( Map<String, String> jdkToolchain ); String getTempDir(); void setTempDir( String tempDir ); } | @Test public void shouldShowArray() throws Exception { Logger logger = mock( Logger.class ); when( logger.isDebugEnabled() ).thenReturn( true ); doNothing().when( logger ).debug( anyString() ); AbstractSurefireMojo mojo = spy( this.mojo ); when( mojo.getConsoleLogger() ).thenReturn( new PluginConsoleLogger( logger ) ); Object[] array = { "ABC", "XYZ" }; invokeMethod( mojo, "showArray", array, "prefix" ); ArgumentCaptor<String> argument = ArgumentCaptor.forClass( String.class ); verify( logger, times( 2 ) ).debug( argument.capture() ); assertThat( argument.getAllValues() ) .containsExactly( "Setting prefix [ABC]", "Setting prefix [XYZ]" ); }
@Test public void shouldShowMap() throws Exception { Logger logger = mock( Logger.class ); when( logger.isDebugEnabled() ).thenReturn( true ); doNothing().when( logger ).debug( anyString() ); AbstractSurefireMojo mojo = spy( this.mojo ); when( mojo.getConsoleLogger() ).thenReturn( new PluginConsoleLogger( logger ) ); Map<String, String> map = new LinkedHashMap<>(); map.put( "ABC", "123" ); map.put( "XYZ", "987" ); invokeMethod( mojo, "showMap", map, "prefix" ); ArgumentCaptor<String> argument = ArgumentCaptor.forClass( String.class ); verify( logger, times( 2 ) ).debug( argument.capture() ); assertThat( argument.getAllValues() ) .containsExactly( "Setting prefix [ABC]=[123]", "Setting prefix [XYZ]=[987]" ); } |
LegacyMasterProcessChannelEncoder implements MasterProcessChannelEncoder { private void error( StackTraceWriter stackTraceWriter, boolean trimStackTraces, ForkedProcessEventType eventType, @SuppressWarnings( "SameParameterValue" ) boolean sendImmediately ) { CharsetEncoder encoder = DEFAULT_STREAM_ENCODING.newEncoder(); StackTrace stackTraceWrapper = new StackTrace( stackTraceWriter, trimStackTraces ); int bufferMaxLength = estimateBufferLength( eventType, null, encoder, 0, stackTraceWrapper.message, stackTraceWrapper.smartTrimmedStackTrace, stackTraceWrapper.stackTrace ); ByteBuffer result = ByteBuffer.allocate( bufferMaxLength ); encodeHeader( encoder, result, eventType, null ); encode( encoder, result, stackTraceWrapper ); encodeAndPrintEvent( result, sendImmediately ); } LegacyMasterProcessChannelEncoder( @Nonnull WritableBufferedByteChannel out ); protected LegacyMasterProcessChannelEncoder( @Nonnull WritableBufferedByteChannel out, @Nonnull RunMode runMode ); @Override MasterProcessChannelEncoder asRerunMode(); @Override MasterProcessChannelEncoder asNormalMode(); @Override boolean checkError(); @Override void onJvmExit(); @Override void sendSystemProperties( Map<String, String> sysProps ); @Override void testSetStarting( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testSetCompleted( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testStarting( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testSucceeded( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testFailed( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testSkipped( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testError( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testAssumptionFailure( ReportEntry reportEntry, boolean trimStackTraces ); @Override void stdOut( String msg, boolean newLine ); @Override void stdErr( String msg, boolean newLine ); @Override void consoleInfoLog( String message ); @Override void consoleErrorLog( String message ); @Override void consoleErrorLog( Throwable t ); @Override void consoleErrorLog( String message, Throwable t ); @Override void consoleErrorLog( StackTraceWriter stackTraceWriter, boolean trimStackTraces ); @Override void consoleDebugLog( String message ); @Override void consoleWarningLog( String message ); @Override void bye(); @Override void stopOnNextTest(); @Override void acquireNextTest(); @Override void sendExitError( StackTraceWriter stackTraceWriter, boolean trimStackTraces ); } | @Test public void testError() throws IOException { String stackTrace = "trace line 1\ntrace line 2"; String trimmedStackTrace = "trace line 1"; SafeThrowable safeThrowable = new SafeThrowable( new Exception() ); StackTraceWriter stackTraceWriter = mock( StackTraceWriter.class ); when( stackTraceWriter.getThrowable() ).thenReturn( safeThrowable ); when( stackTraceWriter.smartTrimmedStackTrace() ).thenReturn( null ); when( stackTraceWriter.writeTrimmedTraceToString() ).thenReturn( trimmedStackTrace ); when( stackTraceWriter.writeTraceToString() ).thenReturn( stackTrace ); ReportEntry reportEntry = mock( ReportEntry.class ); when( reportEntry.getElapsed() ).thenReturn( ELAPSED_TIME ); when( reportEntry.getGroup() ).thenReturn( "this group" ); when( reportEntry.getMessage() ).thenReturn( "skipped test" ); when( reportEntry.getName() ).thenReturn( "my test" ); when( reportEntry.getNameWithGroup() ).thenReturn( "name with group" ); when( reportEntry.getSourceName() ).thenReturn( "pkg.MyTest" ); when( reportEntry.getStackTraceWriter() ).thenReturn( stackTraceWriter ); Stream out = Stream.newStream(); LegacyMasterProcessChannelEncoder encoder = new LegacyMasterProcessChannelEncoder( newBufferedChannel( out ) ); encoder.testError( reportEntry, false ); ByteArrayOutputStream expectedFrame = new ByteArrayOutputStream(); expectedFrame.write( ":maven-surefire-event:".getBytes( UTF_8 ) ); expectedFrame.write( (byte) 10 ); expectedFrame.write( ":test-error:".getBytes( UTF_8 ) ); expectedFrame.write( (byte) 10 ); expectedFrame.write( ":normal-run:".getBytes( UTF_8 ) ); expectedFrame.write( (byte) 5 ); expectedFrame.write( ":UTF-8:".getBytes( UTF_8 ) ); expectedFrame.write( new byte[] {0, 0, 0, 10} ); expectedFrame.write( ':' ); expectedFrame.write( reportEntry.getSourceName().getBytes( UTF_8 ) ); expectedFrame.write( ':' ); expectedFrame.write( new byte[] {0, 0, 0, 1} ); expectedFrame.write( ':' ); expectedFrame.write( 0 ); expectedFrame.write( ':' ); expectedFrame.write( new byte[] {0, 0, 0, 7} ); expectedFrame.write( ':' ); expectedFrame.write( reportEntry.getName().getBytes( UTF_8 ) ); expectedFrame.write( ':' ); expectedFrame.write( new byte[] {0, 0, 0, 1} ); expectedFrame.write( ':' ); expectedFrame.write( 0 ); expectedFrame.write( ':' ); expectedFrame.write( new byte[] {0, 0, 0, 10} ); expectedFrame.write( ':' ); expectedFrame.write( reportEntry.getGroup().getBytes( UTF_8 ) ); expectedFrame.write( ':' ); expectedFrame.write( new byte[] {0, 0, 0, 12} ); expectedFrame.write( ':' ); expectedFrame.write( reportEntry.getMessage().getBytes( UTF_8 ) ); expectedFrame.write( ':' ); expectedFrame.write( 0xff ); expectedFrame.write( ELAPSED_TIME_HEXA ); expectedFrame.write( ':' ); expectedFrame.write( new byte[] {0, 0, 0, 1} ); expectedFrame.write( ':' ); expectedFrame.write( 0 ); expectedFrame.write( ':' ); expectedFrame.write( new byte[] {0, 0, 0, 1} ); expectedFrame.write( ':' ); expectedFrame.write( 0 ); expectedFrame.write( ':' ); expectedFrame.write( new byte[] {0, 0, 0, 25} ); expectedFrame.write( ':' ); expectedFrame.write( stackTrace.getBytes( UTF_8 ) ); expectedFrame.write( ':' ); assertThat( out.toByteArray() ) .isEqualTo( expectedFrame.toByteArray() ); } |
LegacyMasterProcessChannelEncoder implements MasterProcessChannelEncoder { @Override public void testAssumptionFailure( ReportEntry reportEntry, boolean trimStackTraces ) { encode( BOOTERCODE_TEST_ASSUMPTIONFAILURE, runMode, reportEntry, trimStackTraces, true ); } LegacyMasterProcessChannelEncoder( @Nonnull WritableBufferedByteChannel out ); protected LegacyMasterProcessChannelEncoder( @Nonnull WritableBufferedByteChannel out, @Nonnull RunMode runMode ); @Override MasterProcessChannelEncoder asRerunMode(); @Override MasterProcessChannelEncoder asNormalMode(); @Override boolean checkError(); @Override void onJvmExit(); @Override void sendSystemProperties( Map<String, String> sysProps ); @Override void testSetStarting( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testSetCompleted( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testStarting( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testSucceeded( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testFailed( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testSkipped( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testError( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testAssumptionFailure( ReportEntry reportEntry, boolean trimStackTraces ); @Override void stdOut( String msg, boolean newLine ); @Override void stdErr( String msg, boolean newLine ); @Override void consoleInfoLog( String message ); @Override void consoleErrorLog( String message ); @Override void consoleErrorLog( Throwable t ); @Override void consoleErrorLog( String message, Throwable t ); @Override void consoleErrorLog( StackTraceWriter stackTraceWriter, boolean trimStackTraces ); @Override void consoleDebugLog( String message ); @Override void consoleWarningLog( String message ); @Override void bye(); @Override void stopOnNextTest(); @Override void acquireNextTest(); @Override void sendExitError( StackTraceWriter stackTraceWriter, boolean trimStackTraces ); } | @Test public void testAssumptionFailure() throws IOException { String exceptionMessage = "msg"; String smartStackTrace = "MyTest:86 >> Error"; SafeThrowable safeThrowable = new SafeThrowable( new Exception( exceptionMessage ) ); StackTraceWriter stackTraceWriter = mock( StackTraceWriter.class ); when( stackTraceWriter.getThrowable() ).thenReturn( safeThrowable ); when( stackTraceWriter.smartTrimmedStackTrace() ).thenReturn( smartStackTrace ); when( stackTraceWriter.writeTrimmedTraceToString() ).thenReturn( null ); when( stackTraceWriter.writeTraceToString() ).thenReturn( null ); ReportEntry reportEntry = mock( ReportEntry.class ); when( reportEntry.getElapsed() ).thenReturn( null ); when( reportEntry.getGroup() ).thenReturn( "this group" ); when( reportEntry.getMessage() ).thenReturn( "skipped test" ); when( reportEntry.getName() ).thenReturn( "my test" ); when( reportEntry.getNameWithGroup() ).thenReturn( "name with group" ); when( reportEntry.getSourceName() ).thenReturn( "pkg.MyTest" ); when( reportEntry.getStackTraceWriter() ).thenReturn( stackTraceWriter ); Stream out = Stream.newStream(); LegacyMasterProcessChannelEncoder encoder = new LegacyMasterProcessChannelEncoder( newBufferedChannel( out ) ); encoder.testAssumptionFailure( reportEntry, false ); ByteArrayOutputStream expectedFrame = new ByteArrayOutputStream(); expectedFrame.write( ":maven-surefire-event:".getBytes( UTF_8 ) ); expectedFrame.write( (byte) 23 ); expectedFrame.write( ":test-assumption-failure:".getBytes( UTF_8 ) ); expectedFrame.write( (byte) 10 ); expectedFrame.write( ":normal-run:".getBytes( UTF_8 ) ); expectedFrame.write( (byte) 5 ); expectedFrame.write( ":UTF-8:".getBytes( UTF_8 ) ); expectedFrame.write( new byte[] {0, 0, 0, 10} ); expectedFrame.write( ':' ); expectedFrame.write( reportEntry.getSourceName().getBytes( UTF_8 ) ); expectedFrame.write( ':' ); expectedFrame.write( new byte[] {0, 0, 0, 1} ); expectedFrame.write( ':' ); expectedFrame.write( 0 ); expectedFrame.write( ':' ); expectedFrame.write( new byte[] {0, 0, 0, 7} ); expectedFrame.write( ':' ); expectedFrame.write( reportEntry.getName().getBytes( UTF_8 ) ); expectedFrame.write( ':' ); expectedFrame.write( new byte[] {0, 0, 0, 1} ); expectedFrame.write( ':' ); expectedFrame.write( 0 ); expectedFrame.write( ':' ); expectedFrame.write( new byte[] {0, 0, 0, 10} ); expectedFrame.write( ':' ); expectedFrame.write( reportEntry.getGroup().getBytes( UTF_8 ) ); expectedFrame.write( ':' ); expectedFrame.write( new byte[] {0, 0, 0, 12} ); expectedFrame.write( ':' ); expectedFrame.write( reportEntry.getMessage().getBytes( UTF_8 ) ); expectedFrame.write( ':' ); expectedFrame.write( 0 ); expectedFrame.write( ':' ); expectedFrame.write( new byte[] {0, 0, 0, 3} ); expectedFrame.write( ':' ); expectedFrame.write( exceptionMessage.getBytes( UTF_8 ) ); expectedFrame.write( ':' ); expectedFrame.write( new byte[] {0, 0, 0, 18} ); expectedFrame.write( ':' ); expectedFrame.write( smartStackTrace.getBytes( UTF_8 ) ); expectedFrame.write( ':' ); expectedFrame.write( new byte[] {0, 0, 0, 1} ); expectedFrame.write( ':' ); expectedFrame.write( 0 ); expectedFrame.write( ':' ); assertThat( out.toByteArray() ) .isEqualTo( expectedFrame.toByteArray() ); } |
LegacyMasterProcessChannelEncoder implements MasterProcessChannelEncoder { @Override public void bye() { encodeOpcode( BOOTERCODE_BYE, true ); } LegacyMasterProcessChannelEncoder( @Nonnull WritableBufferedByteChannel out ); protected LegacyMasterProcessChannelEncoder( @Nonnull WritableBufferedByteChannel out, @Nonnull RunMode runMode ); @Override MasterProcessChannelEncoder asRerunMode(); @Override MasterProcessChannelEncoder asNormalMode(); @Override boolean checkError(); @Override void onJvmExit(); @Override void sendSystemProperties( Map<String, String> sysProps ); @Override void testSetStarting( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testSetCompleted( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testStarting( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testSucceeded( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testFailed( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testSkipped( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testError( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testAssumptionFailure( ReportEntry reportEntry, boolean trimStackTraces ); @Override void stdOut( String msg, boolean newLine ); @Override void stdErr( String msg, boolean newLine ); @Override void consoleInfoLog( String message ); @Override void consoleErrorLog( String message ); @Override void consoleErrorLog( Throwable t ); @Override void consoleErrorLog( String message, Throwable t ); @Override void consoleErrorLog( StackTraceWriter stackTraceWriter, boolean trimStackTraces ); @Override void consoleDebugLog( String message ); @Override void consoleWarningLog( String message ); @Override void bye(); @Override void stopOnNextTest(); @Override void acquireNextTest(); @Override void sendExitError( StackTraceWriter stackTraceWriter, boolean trimStackTraces ); } | @Test public void testBye() { Stream out = Stream.newStream(); LegacyMasterProcessChannelEncoder encoder = new LegacyMasterProcessChannelEncoder( newBufferedChannel( out ) ); encoder.bye(); String encoded = new String( out.toByteArray(), UTF_8 ); assertThat( encoded ) .isEqualTo( ":maven-surefire-event:\u0003:bye:" ); } |
LegacyMasterProcessChannelEncoder implements MasterProcessChannelEncoder { @Override public void stopOnNextTest() { encodeOpcode( BOOTERCODE_STOP_ON_NEXT_TEST, true ); } LegacyMasterProcessChannelEncoder( @Nonnull WritableBufferedByteChannel out ); protected LegacyMasterProcessChannelEncoder( @Nonnull WritableBufferedByteChannel out, @Nonnull RunMode runMode ); @Override MasterProcessChannelEncoder asRerunMode(); @Override MasterProcessChannelEncoder asNormalMode(); @Override boolean checkError(); @Override void onJvmExit(); @Override void sendSystemProperties( Map<String, String> sysProps ); @Override void testSetStarting( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testSetCompleted( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testStarting( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testSucceeded( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testFailed( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testSkipped( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testError( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testAssumptionFailure( ReportEntry reportEntry, boolean trimStackTraces ); @Override void stdOut( String msg, boolean newLine ); @Override void stdErr( String msg, boolean newLine ); @Override void consoleInfoLog( String message ); @Override void consoleErrorLog( String message ); @Override void consoleErrorLog( Throwable t ); @Override void consoleErrorLog( String message, Throwable t ); @Override void consoleErrorLog( StackTraceWriter stackTraceWriter, boolean trimStackTraces ); @Override void consoleDebugLog( String message ); @Override void consoleWarningLog( String message ); @Override void bye(); @Override void stopOnNextTest(); @Override void acquireNextTest(); @Override void sendExitError( StackTraceWriter stackTraceWriter, boolean trimStackTraces ); } | @Test public void testStopOnNextTest() { Stream out = Stream.newStream(); LegacyMasterProcessChannelEncoder encoder = new LegacyMasterProcessChannelEncoder( newBufferedChannel( out ) ); encoder.stopOnNextTest(); String encoded = new String( out.toByteArray(), UTF_8 ); assertThat( encoded ) .isEqualTo( ":maven-surefire-event:\u0011:stop-on-next-test:" ); } |
LegacyMasterProcessChannelEncoder implements MasterProcessChannelEncoder { @Override public void acquireNextTest() { encodeOpcode( BOOTERCODE_NEXT_TEST, true ); } LegacyMasterProcessChannelEncoder( @Nonnull WritableBufferedByteChannel out ); protected LegacyMasterProcessChannelEncoder( @Nonnull WritableBufferedByteChannel out, @Nonnull RunMode runMode ); @Override MasterProcessChannelEncoder asRerunMode(); @Override MasterProcessChannelEncoder asNormalMode(); @Override boolean checkError(); @Override void onJvmExit(); @Override void sendSystemProperties( Map<String, String> sysProps ); @Override void testSetStarting( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testSetCompleted( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testStarting( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testSucceeded( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testFailed( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testSkipped( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testError( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testAssumptionFailure( ReportEntry reportEntry, boolean trimStackTraces ); @Override void stdOut( String msg, boolean newLine ); @Override void stdErr( String msg, boolean newLine ); @Override void consoleInfoLog( String message ); @Override void consoleErrorLog( String message ); @Override void consoleErrorLog( Throwable t ); @Override void consoleErrorLog( String message, Throwable t ); @Override void consoleErrorLog( StackTraceWriter stackTraceWriter, boolean trimStackTraces ); @Override void consoleDebugLog( String message ); @Override void consoleWarningLog( String message ); @Override void bye(); @Override void stopOnNextTest(); @Override void acquireNextTest(); @Override void sendExitError( StackTraceWriter stackTraceWriter, boolean trimStackTraces ); } | @Test public void testAcquireNextTest() { Stream out = Stream.newStream(); LegacyMasterProcessChannelEncoder encoder = new LegacyMasterProcessChannelEncoder( newBufferedChannel( out ) ); encoder.acquireNextTest(); String encoded = new String( out.toByteArray(), UTF_8 ); assertThat( encoded ) .isEqualTo( ":maven-surefire-event:\u0009:next-test:" ); } |
LegacyMasterProcessChannelEncoder implements MasterProcessChannelEncoder { @Override public void consoleInfoLog( String message ) { ByteBuffer result = encodeMessage( BOOTERCODE_CONSOLE_INFO, null, message ); encodeAndPrintEvent( result, true ); } LegacyMasterProcessChannelEncoder( @Nonnull WritableBufferedByteChannel out ); protected LegacyMasterProcessChannelEncoder( @Nonnull WritableBufferedByteChannel out, @Nonnull RunMode runMode ); @Override MasterProcessChannelEncoder asRerunMode(); @Override MasterProcessChannelEncoder asNormalMode(); @Override boolean checkError(); @Override void onJvmExit(); @Override void sendSystemProperties( Map<String, String> sysProps ); @Override void testSetStarting( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testSetCompleted( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testStarting( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testSucceeded( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testFailed( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testSkipped( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testError( ReportEntry reportEntry, boolean trimStackTraces ); @Override void testAssumptionFailure( ReportEntry reportEntry, boolean trimStackTraces ); @Override void stdOut( String msg, boolean newLine ); @Override void stdErr( String msg, boolean newLine ); @Override void consoleInfoLog( String message ); @Override void consoleErrorLog( String message ); @Override void consoleErrorLog( Throwable t ); @Override void consoleErrorLog( String message, Throwable t ); @Override void consoleErrorLog( StackTraceWriter stackTraceWriter, boolean trimStackTraces ); @Override void consoleDebugLog( String message ); @Override void consoleWarningLog( String message ); @Override void bye(); @Override void stopOnNextTest(); @Override void acquireNextTest(); @Override void sendExitError( StackTraceWriter stackTraceWriter, boolean trimStackTraces ); } | @Test public void testConsoleInfo() { Stream out = Stream.newStream(); LegacyMasterProcessChannelEncoder encoder = new LegacyMasterProcessChannelEncoder( newBufferedChannel( out ) ); encoder.consoleInfoLog( "msg" ); String encoded = new String( out.toByteArray(), UTF_8 ); String expected = ":maven-surefire-event:\u0010:console-info-log:\u0005:UTF-8:\u0000\u0000\u0000\u0003:msg:"; assertThat( encoded ) .isEqualTo( expected ); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.