diff options
author | SimonBrandhof <simon.brandhof@gmail.com> | 2013-04-04 14:22:09 +0200 |
---|---|---|
committer | SimonBrandhof <simon.brandhof@gmail.com> | 2013-04-04 14:23:51 +0200 |
commit | bbea938a2f1baab23570e8bc659ab17794af436e (patch) | |
tree | 7de89a00aacee873fc9e49f9aeb3b4591ba7fca8 /sonar-runner-api/src/test/java | |
parent | ba11419ac9bc98398f478b73520c24da5f65547c (diff) | |
download | sonar-scanner-cli-bbea938a2f1baab23570e8bc659ab17794af436e.tar.gz sonar-scanner-cli-bbea938a2f1baab23570e8bc659ab17794af436e.zip |
SONAR-2574 new API + ability to fork
Diffstat (limited to 'sonar-runner-api/src/test/java')
12 files changed, 375 insertions, 703 deletions
diff --git a/sonar-runner-api/src/test/java/org/sonar/runner/BootstrapClassLoaderTest.java b/sonar-runner-api/src/test/java/org/sonar/runner/BootstrapClassLoaderTest.java deleted file mode 100644 index 7917d2d..0000000 --- a/sonar-runner-api/src/test/java/org/sonar/runner/BootstrapClassLoaderTest.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Sonar Runner - API - * Copyright (C) 2011 SonarSource - * dev@sonar.codehaus.org - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 - */ -package org.sonar.runner; - -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; - -import static org.fest.assertions.Assertions.assertThat; - -public class BootstrapClassLoaderTest { - - @Rule - public ExpectedException thrown = ExpectedException.none(); - - @Test - public void should_restrict_loading_from_parent() throws Exception { - BootstrapClassLoader classLoader = new BootstrapClassLoader(getClass().getClassLoader(), "org.apache.ant"); - assertThat(classLoader.canLoadFromParent("org.sonar.runner.internal.batch.Launcher")).isFalse(); - assertThat(classLoader.canLoadFromParent("org.sonar.runner.Runner")).isTrue(); - assertThat(classLoader.canLoadFromParent("org.objectweb.asm.ClassVisitor")).isFalse(); - assertThat(classLoader.canLoadFromParent("org.apache.ant.project.Project")).isTrue(); - } - - @Test - public void should_use_isolated_system_classloader_when_parent_is_excluded() throws ClassNotFoundException { - thrown.expect(ClassNotFoundException.class); - thrown.expectMessage("org.junit.Test"); - ClassLoader parent = getClass().getClassLoader(); - BootstrapClassLoader classLoader = new BootstrapClassLoader(parent); - - // JUnit is available in the parent classloader (classpath used to execute this test) but not in the core JVM - assertThat(classLoader.loadClass("java.lang.String", false)).isNotNull(); - classLoader.loadClass("org.junit.Test", false); - } - - @Test - public void should_find_in_parent_when_matches_unmasked_packages() throws ClassNotFoundException { - ClassLoader parent = getClass().getClassLoader(); - BootstrapClassLoader classLoader = new BootstrapClassLoader(parent, "org.junit"); - - // JUnit is available in the parent classloader (classpath used to execute this test) but not in the core JVM - assertThat(classLoader.loadClass("org.junit.Test", false)).isNotNull(); - } -} diff --git a/sonar-runner-api/src/test/java/org/sonar/runner/BootstrapperTest.java b/sonar-runner-api/src/test/java/org/sonar/runner/BootstrapperTest.java deleted file mode 100644 index 37a5425..0000000 --- a/sonar-runner-api/src/test/java/org/sonar/runner/BootstrapperTest.java +++ /dev/null @@ -1,178 +0,0 @@ -/* - * Sonar Runner - API - * Copyright (C) 2011 SonarSource - * dev@sonar.codehaus.org - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 - */ -package org.sonar.runner; - -import org.apache.commons.io.IOUtils; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; - -import java.io.File; -import java.io.IOException; -import java.net.HttpURLConnection; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.HashMap; -import java.util.Map; - -import static org.fest.assertions.Assertions.assertThat; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -public class BootstrapperTest { - - @Rule - public TemporaryFolder tempFolder = new TemporaryFolder(); - - @Test - public void shouldRemoveLastUrlSlash() { - Bootstrapper bootstrapper = new Bootstrapper("", "http://test/", new File("target/tmp"), null); - assertThat(bootstrapper.getServerUrl()).isEqualTo("http://test"); - } - - @Test(expected = Exception.class) - public void shouldFailIfCanNotConnectServer() { - Bootstrapper bootstrapper = new Bootstrapper("", "http://unknown.foo", new File("target/tmp"), null); - bootstrapper.getServerVersion(); - } - - @Test - public void shouldReturnUserAgent() { - Bootstrapper bootstrapper = new Bootstrapper("test/0.1", "http://unknown.foo", new File("target/tmp"), null); - String userAgent = bootstrapper.getUserAgent(); - - assertThat(userAgent.length()).isGreaterThan(0); - assertThat(userAgent).startsWith("sonar-bootstrapper/"); - assertThat(userAgent).endsWith(" test/0.1"); - } - - @Test - public void shouldReturnValidVersion() { - Bootstrapper bootstrapper = new Bootstrapper("", "http://test", new File("target/tmp"), null) { - @Override - String remoteContent(String path) throws IOException { - return "2.6"; - } - }; - assertThat(bootstrapper.getServerVersion()).isEqualTo("2.6"); - } - - @Test - public void shouldParseEncodingFromContentType() { - assertThat(Bootstrapper.getCharsetFromContentType("text/html; charset=EUC-JP")).isEqualTo("EUC-JP"); - assertThat(Bootstrapper.getCharsetFromContentType("text/html")).isNull(); - } - - @Test - public void shouldCheckVersionForCache() { - assertThat(Bootstrapper.isUnsupportedVersionForCache("1.0")).isTrue(); - assertThat(Bootstrapper.isUnsupportedVersionForCache("2.0")).isTrue(); - assertThat(Bootstrapper.isUnsupportedVersionForCache("2.1")).isTrue(); - assertThat(Bootstrapper.isUnsupportedVersionForCache("2.2")).isTrue(); - assertThat(Bootstrapper.isUnsupportedVersionForCache("2.3")).isTrue(); - assertThat(Bootstrapper.isUnsupportedVersionForCache("2.4")).isTrue(); - assertThat(Bootstrapper.isUnsupportedVersionForCache("2.4.1")).isTrue(); - assertThat(Bootstrapper.isUnsupportedVersionForCache("2.5")).isTrue(); - assertThat(Bootstrapper.isUnsupportedVersionForCache("2.11")).isTrue(); - assertThat(Bootstrapper.isUnsupportedVersionForCache("3.0")).isTrue(); - assertThat(Bootstrapper.isUnsupportedVersionForCache("3.1")).isTrue(); - assertThat(Bootstrapper.isUnsupportedVersionForCache("3.2")).isTrue(); - assertThat(Bootstrapper.isUnsupportedVersionForCache("3.3")).isTrue(); - assertThat(Bootstrapper.isUnsupportedVersionForCache("3.4")).isTrue(); - assertThat(Bootstrapper.isUnsupportedVersionForCache("3.5")).isFalse(); - } - - @Test - public void shouldCacheWhenNecessary() throws Exception { - File sonarUserHome = tempFolder.newFolder(); - SonarCache cache = SonarCache.create(sonarUserHome).build(); - final MockedConnectionFactory connections = new MockedConnectionFactory("http://test"); - connections.register("/api/server/version", "3.5"); - connections.register("/batch_bootstrap/index", "foo.jar|922afef30ca31573d7131347d01b76c4\nbar.jar|69155f65900fbabbf21e28abb33dd06a"); - connections.register("/batch/foo.jar", "fakecontent1"); - connections.register("/batch/bar.jar", "fakecontent2"); - Bootstrapper bootstrapper = new Bootstrapper("", "http://test", new File("target/tmp"), cache) { - @Override - HttpURLConnection newHttpConnection(URL url) throws IOException { - return connections.get(url); - } - }; - bootstrapper.createClassLoader(new URL[] {}, this.getClass().getClassLoader()); - assertThat(new File(new File(cache.getCacheLocation(), "922afef30ca31573d7131347d01b76c4"), "foo.jar")).exists(); - assertThat(new File(new File(cache.getCacheLocation(), "69155f65900fbabbf21e28abb33dd06a"), "bar.jar")).exists(); - - // Should not download during the second execution - final MockedConnectionFactory connections2 = new MockedConnectionFactory("http://test"); - connections2.register("/api/server/version", "3.5"); - connections2.register("/batch_bootstrap/index", "foo.jar|922afef30ca31573d7131347d01b76c4\nbar.jar|69155f65900fbabbf21e28abb33dd06a"); - Bootstrapper bootstrapper2 = new Bootstrapper("", "http://test", new File("target/tmp"), cache) { - @Override - HttpURLConnection newHttpConnection(URL url) throws IOException { - return connections2.get(url); - } - }; - bootstrapper2.createClassLoader(new URL[] {}, this.getClass().getClassLoader()); - } - - @Test - public void shouldDownloadFromOldURL() throws Exception { - File sonarUserHome = tempFolder.newFolder(); - final MockedConnectionFactory connections = new MockedConnectionFactory("http://test"); - connections.register("/api/server/version", "3.4"); - connections.register("/batch/", "foo.jar,bar.jar"); - connections.register("/batch/foo.jar", "fakecontent1"); - connections.register("/batch/bar.jar", "fakecontent2"); - Bootstrapper bootstrapper = new Bootstrapper("", "http://test", new File("target/tmp"), SonarCache.create(sonarUserHome).build()) { - @Override - HttpURLConnection newHttpConnection(URL url) throws IOException { - return connections.get(url); - } - }; - bootstrapper.createClassLoader(new URL[] {}, this.getClass().getClassLoader()); - verify(connections.get("/batch/foo.jar")).getInputStream(); - verify(connections.get("/batch/bar.jar")).getInputStream(); - } - - private class MockedConnectionFactory { - private Map<URL, HttpURLConnection> mockedConnections = new HashMap<URL, HttpURLConnection>(); - private String serverUrl; - - public MockedConnectionFactory(String serverUrl) { - this.serverUrl = serverUrl; - } - - public void register(String path, String content) throws Exception { - HttpURLConnection mockConnection = mock(HttpURLConnection.class); - when(mockConnection.getInputStream()).thenReturn(IOUtils.toInputStream(content)); - when(mockConnection.getResponseCode()).thenReturn(HttpURLConnection.HTTP_OK); - mockedConnections.put(new URL(serverUrl + path), mockConnection); - } - - public HttpURLConnection get(URL url) { - return mockedConnections.get(url); - } - - public HttpURLConnection get(String path) throws MalformedURLException { - return mockedConnections.get(new URL(serverUrl + path)); - } - - } -} diff --git a/sonar-runner-api/src/test/java/org/sonar/runner/LogsTest.java b/sonar-runner-api/src/test/java/org/sonar/runner/LogsTest.java deleted file mode 100644 index 1131300..0000000 --- a/sonar-runner-api/src/test/java/org/sonar/runner/LogsTest.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Sonar Runner - API - * Copyright (C) 2011 SonarSource - * dev@sonar.codehaus.org - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 - */ -package org.sonar.runner; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import java.io.ByteArrayOutputStream; -import java.io.PrintStream; - -import static org.fest.assertions.Assertions.assertThat; - -public class LogsTest { - - private PrintStream oldSysout; - private PrintStream oldSyserr; - - private ByteArrayOutputStream baosOut; - private ByteArrayOutputStream baosErr; - - @Before - public void prepare() { - oldSysout = System.out; - oldSyserr = System.err; - baosOut = new ByteArrayOutputStream(); - System.setOut(new PrintStream(baosOut)); - baosErr = new ByteArrayOutputStream(); - System.setErr(new PrintStream(baosErr)); - } - - @After - public void restore() { - System.setOut(oldSysout); - System.setErr(oldSyserr); - } - - @Test - public void shouldLogInfo() { - Logs.info("info"); - assertThat(baosOut.toString()).contains("INFO: info"); - assertThat(baosErr.toString()).isEmpty(); - } - - @Test - public void shouldLogError() { - Logs.error("error"); - assertThat(baosOut.toString()).isEmpty(); - assertThat(baosErr.toString()).contains("ERROR: error"); - } - - @Test - public void shouldLogErrorWithoutThrowable() { - Logs.error("error", null); - assertThat(baosOut.toString()).isEmpty(); - assertThat(baosErr.toString()).contains("ERROR: error"); - } - - @Test - public void shouldLogErrorWithThrowable() { - Logs.error("error", new RuntimeException()); - assertThat(baosOut.toString()).isEmpty(); - assertThat(baosErr.toString()).contains("ERROR: error").contains("RuntimeException"); - } - -} diff --git a/sonar-runner-api/src/test/java/org/sonar/runner/MainTest.java b/sonar-runner-api/src/test/java/org/sonar/runner/MainTest.java deleted file mode 100644 index de7f17c..0000000 --- a/sonar-runner-api/src/test/java/org/sonar/runner/MainTest.java +++ /dev/null @@ -1,131 +0,0 @@ -/* - * Sonar Runner - API - * Copyright (C) 2011 SonarSource - * dev@sonar.codehaus.org - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 - */ -package org.sonar.runner; - -import org.junit.Before; -import org.junit.Test; - -import java.io.File; -import java.util.Properties; - -import static org.fest.assertions.Assertions.assertThat; - -public class MainTest { - - private Main main; - - @Before - public void prepare() { - main = new Main(); - } - - @Test - public void shouldParseEmptyArguments() { - Properties props = main.parseArguments(new String[] {}); - assertThat(props).isEmpty(); - } - - @Test - public void shouldParseArguments() { - Properties props = main.parseArguments(new String[] {"-D", "foo=bar", "--define", "hello=world", "-Dboolean"}); - assertThat(props).hasSize(3); - assertThat(props.getProperty("foo")).isEqualTo("bar"); - assertThat(props.getProperty("hello")).isEqualTo("world"); - assertThat(props.getProperty("boolean")).isEqualTo("true"); - } - - @Test - public void shouldParseCommand() { - - Properties props = main.parseArguments(new String[] {"cmd", "-D", "foo=bar", "--define", "hello=world", "-Dboolean"}); - assertThat(main.command).isEqualTo("cmd"); - assertThat(props).hasSize(3); - } - - @Test - public void shouldEnableDebugMode() { - Properties props = main.parseArguments(new String[] {"-X"}); - assertThat(main.debugMode).isTrue(); - assertThat(main.displayStackTrace).isTrue(); - assertThat(props.getProperty(Runner.PROPERTY_VERBOSE)).isEqualTo("true"); - } - - @Test - public void shouldEnableError() { - Properties props = main.parseArguments(new String[] {"-e"}); - assertThat(main.debugMode).isFalse(); - assertThat(main.displayStackTrace).isTrue(); - assertThat(props.getProperty(Runner.PROPERTY_VERBOSE)).isNull(); - } - - @Test - public void shouldDisableDebugModeAndStackByDefault() { - Properties props = main.parseArguments(new String[] {}); - assertThat(main.debugMode).isFalse(); - assertThat(main.displayStackTrace).isFalse(); - assertThat(props.getProperty(Runner.PROPERTY_VERBOSE)).isNull(); - } - - @Test - public void shouldLoadRunnerSettingsByHome() throws Exception { - File home = new File(getClass().getResource("/org/sonar/runner/MainTest/shouldLoadRunnerSettingsByHome/").toURI()); - Properties args = new Properties(); - args.setProperty("runner.home", home.getCanonicalPath()); - - Properties props = new Main().loadRunnerConfiguration(args); - - assertThat(props.getProperty("sonar.host.url")).isEqualTo("http://moon/sonar"); - } - - @Test - public void shouldNotFailIfNoHome() throws Exception { - Properties args = new Properties(); - Properties props = new Main().loadRunnerConfiguration(args); - - assertThat(props).isEmpty(); - } - - @Test - public void shouldLoadRunnerSettingsByDirectPath() throws Exception { - File settings = new File(getClass().getResource("/org/sonar/runner/MainTest/shouldLoadRunnerSettingsByDirectPath/other-conf.properties").toURI()); - Properties args = new Properties(); - args.setProperty("runner.settings", settings.getCanonicalPath()); - Properties props = new Main().loadRunnerConfiguration(args); - - assertThat(props.getProperty("sonar.host.url")).isEqualTo("http://other/sonar"); - } - - @Test - public void shouldLoadCompleteConfiguration() throws Exception { - File runnerHome = new File(getClass().getResource("/org/sonar/runner/MainTest/shouldLoadCompleteConfiguration/runner").toURI()); - File projectHome = new File(getClass().getResource("/org/sonar/runner/MainTest/shouldLoadCompleteConfiguration/project").toURI()); - Main main = new Main(); - Properties args = main.parseArguments(new String[] { - "-D", "runner.home=" + runnerHome.getCanonicalPath(), - "-D", "project.home=" + projectHome.getCanonicalPath() - }); - main.loadProperties(args); - - assertThat(main.projectProperties.getProperty("project.prop")).isEqualTo("foo"); - assertThat(main.projectProperties.getProperty("overridden.prop")).isEqualTo("project scope"); - assertThat(main.globalProperties.getProperty("global.prop")).isEqualTo("jdbc:mysql:localhost/sonar"); - } - -} diff --git a/sonar-runner-api/src/test/java/org/sonar/runner/RunnerTest.java b/sonar-runner-api/src/test/java/org/sonar/runner/RunnerTest.java deleted file mode 100644 index 545565f..0000000 --- a/sonar-runner-api/src/test/java/org/sonar/runner/RunnerTest.java +++ /dev/null @@ -1,227 +0,0 @@ -/* - * Sonar Runner - API - * Copyright (C) 2011 SonarSource - * dev@sonar.codehaus.org - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 - */ -package org.sonar.runner; - -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.rules.TemporaryFolder; - -import java.io.File; -import java.nio.charset.Charset; -import java.util.Properties; - -import static org.fest.assertions.Assertions.assertThat; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -public class RunnerTest { - - @Rule - public TemporaryFolder tempFolder = new TemporaryFolder(); - - @Rule - public ExpectedException thrown = ExpectedException.none(); - - @Test - public void shouldHaveDefaultEncodingIfNotForce() { - Runner runner = Runner.create(new Properties()); - assertThat(runner.getSourceCodeEncoding()).isEqualTo(Charset.defaultCharset().name()); - assertThat(runner.isEncodingPlatformDependant()).isTrue(); - } - - @Test - public void shouldKeepEncodingIfSpecified() { - Properties props = new Properties(); - // Yeah, windows charset! - props.setProperty("sonar.sourceEncoding", "cp1252"); - Runner runner = Runner.create(props); - assertThat(runner.getSourceCodeEncoding()).isEqualTo("cp1252"); - assertThat(runner.isEncodingPlatformDependant()).isFalse(); - } - - @Test - public void shouldHaveDefaultEnvironmentInformationValues() { - Runner runner = Runner.create(new Properties()); - assertThat(runner.getProperties().getProperty(Runner.PROPERTY_ENVIRONMENT_INFORMATION_KEY)).isEqualTo("Runner"); - assertThat(runner.getProperties().getProperty(Runner.PROPERTY_ENVIRONMENT_INFORMATION_VERSION)).contains("."); - assertThat(runner.getProperties().getProperty(Runner.PROPERTY_ENVIRONMENT_INFORMATION_VERSION)).doesNotContain("$"); - } - - @Test - public void shouldOverwriteDefaultEnvironmentInformationValues() { - Runner runner = Runner.create(new Properties()); - runner.setEnvironmentInformation("Ant", "1.2.3"); - assertThat(runner.getProperties().getProperty(Runner.PROPERTY_ENVIRONMENT_INFORMATION_KEY)).isEqualTo("Ant"); - assertThat(runner.getProperties().getProperty(Runner.PROPERTY_ENVIRONMENT_INFORMATION_VERSION)).isEqualTo("1.2.3"); - } - - @Test - public void shouldCheckVersion() { - assertThat(Runner.isUnsupportedVersion("1.0")).isTrue(); - assertThat(Runner.isUnsupportedVersion("2.0")).isTrue(); - assertThat(Runner.isUnsupportedVersion("2.1")).isTrue(); - assertThat(Runner.isUnsupportedVersion("2.2")).isTrue(); - assertThat(Runner.isUnsupportedVersion("2.3")).isTrue(); - assertThat(Runner.isUnsupportedVersion("2.4")).isTrue(); - assertThat(Runner.isUnsupportedVersion("2.4.1")).isTrue(); - assertThat(Runner.isUnsupportedVersion("2.5")).isTrue(); - assertThat(Runner.isUnsupportedVersion("2.11")).isFalse(); - assertThat(Runner.isUnsupportedVersion("3.0")).isFalse(); - assertThat(Runner.isUnsupportedVersion("3.1")).isFalse(); - assertThat(Runner.isUnsupportedVersion("3.2")).isFalse(); - assertThat(Runner.isUnsupportedVersion("3.3")).isFalse(); - assertThat(Runner.isUnsupportedVersion("3.4")).isFalse(); - assertThat(Runner.isUnsupportedVersion("3.5")).isFalse(); - } - - @Test - public void shouldCheckVersionForTasks() { - assertThat(Runner.isUnsupportedVersionForTasks("1.0")).isTrue(); - assertThat(Runner.isUnsupportedVersionForTasks("2.0")).isTrue(); - assertThat(Runner.isUnsupportedVersionForTasks("2.1")).isTrue(); - assertThat(Runner.isUnsupportedVersionForTasks("2.2")).isTrue(); - assertThat(Runner.isUnsupportedVersionForTasks("2.3")).isTrue(); - assertThat(Runner.isUnsupportedVersionForTasks("2.4")).isTrue(); - assertThat(Runner.isUnsupportedVersionForTasks("2.4.1")).isTrue(); - assertThat(Runner.isUnsupportedVersionForTasks("2.5")).isTrue(); - assertThat(Runner.isUnsupportedVersionForTasks("2.11")).isTrue(); - assertThat(Runner.isUnsupportedVersionForTasks("3.0")).isTrue(); - assertThat(Runner.isUnsupportedVersionForTasks("3.1")).isTrue(); - assertThat(Runner.isUnsupportedVersionForTasks("3.2")).isTrue(); - assertThat(Runner.isUnsupportedVersionForTasks("3.3")).isTrue(); - assertThat(Runner.isUnsupportedVersionForTasks("3.4")).isTrue(); - assertThat(Runner.isUnsupportedVersionForTasks("3.5")).isFalse(); - } - - @Test - public void shouldGetServerUrl() { - Properties properties = new Properties(); - Runner runner = Runner.create(properties); - assertThat(runner.getSonarServerURL()).isEqualTo("http://localhost:9000"); - properties.setProperty("sonar.host.url", "foo"); - assertThat(runner.getSonarServerURL()).isEqualTo("foo"); - } - - @Test - public void shouldInitDirs() throws Exception { - Properties props = new Properties(); - File home = tempFolder.newFolder("shouldInitDirs").getCanonicalFile(); - props.setProperty(Runner.PROPERTY_SONAR_PROJECT_BASEDIR, home.getCanonicalPath()); - Runner runner = Runner.create(props); - assertThat(runner.getProperties().get(Runner.PROPERTY_SONAR_PROJECT_BASEDIR)).isEqualTo(home.getCanonicalPath()); - - assertThat(runner.getProjectDir().getCanonicalFile()).isEqualTo(home); - assertThat(runner.getWorkDir().getCanonicalFile()).isEqualTo(new File(home, ".sonar")); - } - - @Test - public void shouldInitProjectDirWithCurrentDir() throws Exception { - Runner runner = Runner.create(new Properties()); - - assertThat(runner.getProjectDir().isDirectory()).isTrue(); - assertThat(runner.getProjectDir().exists()).isTrue(); - } - - @Test - public void shouldSetValidBaseDirOnConstructor() { - File baseDir = tempFolder.newFolder("shouldInitDirs"); - Runner runner = Runner.create(new Properties(), baseDir); - assertThat(runner.getProjectDir()).isEqualTo(baseDir); - } - - @Test - public void shouldFailIfBaseDirDoesNotExist() { - File fakeBasedir = new File("fake"); - - thrown.expect(RunnerException.class); - thrown.expectMessage("Project home must be an existing directory: " + fakeBasedir.getAbsolutePath()); - - Runner.create(new Properties(), fakeBasedir); - } - - @Test - public void shouldSpecifyWorkingDirectory() { - Properties properties = new Properties(); - Runner runner = Runner.create(properties); - assertThat(runner.getWorkDir()).isEqualTo(new File(".", ".sonar")); - - // empty string - properties.setProperty(Runner.PROPERTY_WORK_DIRECTORY, " "); - runner = Runner.create(properties); - assertThat(runner.getWorkDir()).isEqualTo(new File(".", ".sonar").getAbsoluteFile()); - - // real relative path - properties.setProperty(Runner.PROPERTY_WORK_DIRECTORY, "temp-dir"); - runner = Runner.create(properties); - assertThat(runner.getWorkDir()).isEqualTo(new File(".", "temp-dir").getAbsoluteFile()); - - // real absolute path - properties.setProperty(Runner.PROPERTY_WORK_DIRECTORY, new File("target", "temp-dir2").getAbsolutePath()); - runner = Runner.create(properties); - assertThat(runner.getWorkDir()).isEqualTo(new File("target", "temp-dir2").getAbsoluteFile()); - } - - @Test - public void shouldDeleteWorkingDirectory() { - Properties properties = new Properties(); - File workDir = new File("target", "temp-dir-should-be-deleted"); - workDir.mkdirs(); - assertThat(workDir.exists()).isTrue(); - // real absolute path - properties.setProperty(Runner.PROPERTY_WORK_DIRECTORY, workDir.getAbsolutePath()); - Runner.create(properties); - assertThat(workDir.exists()).isFalse(); - } - - @Test - public void shouldCheckSonarVersion() { - Properties properties = new Properties(); - Runner runner = Runner.create(properties); - Bootstrapper bootstrapper = mock(Bootstrapper.class); - - // nothing happens, OK - when(bootstrapper.getServerVersion()).thenReturn("3.0"); - runner.checkSonarVersion(bootstrapper); - - // but fails with older versions - when(bootstrapper.getServerVersion()).thenReturn("2.1"); - thrown.expect(RunnerException.class); - thrown.expectMessage("Sonar 2.1 is not supported. Please upgrade Sonar to version 2.11 or more."); - runner.checkSonarVersion(bootstrapper); - } - - @Test - public void shouldCheckSonarVersionForTasks() { - Properties properties = new Properties(); - Runner runner = Runner.create("foo-cmd", properties, properties); - Bootstrapper bootstrapper = mock(Bootstrapper.class); - - // nothing happens, OK - when(bootstrapper.getServerVersion()).thenReturn("3.5"); - runner.checkSonarVersion(bootstrapper); - - // but fails with older versions - when(bootstrapper.getServerVersion()).thenReturn("3.4"); - thrown.expect(RunnerException.class); - thrown.expectMessage("Sonar 3.4 doesn't support tasks. Please upgrade Sonar to version 3.5 or more."); - runner.checkSonarVersion(bootstrapper); - } -} diff --git a/sonar-runner-api/src/test/java/org/sonar/runner/api/CommandExecutorTest.java b/sonar-runner-api/src/test/java/org/sonar/runner/api/CommandExecutorTest.java new file mode 100644 index 0000000..d63a6a3 --- /dev/null +++ b/sonar-runner-api/src/test/java/org/sonar/runner/api/CommandExecutorTest.java @@ -0,0 +1,157 @@ +/* + * Sonar Runner - API + * Copyright (C) 2011 SonarSource + * dev@sonar.codehaus.org + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 + */ +package org.sonar.runner.api; + +import org.apache.commons.io.FileUtils; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.junit.rules.TemporaryFolder; +import org.junit.rules.TestName; + +import java.io.File; +import java.io.IOException; + +import static org.fest.assertions.Assertions.assertThat; +import static org.junit.Assert.fail; + +public class CommandExecutorTest { + + @Rule + public TemporaryFolder tempFolder = new TemporaryFolder(); + + @Rule + public TestName testName = new TestName(); + + @Rule + public ExpectedException thrown = ExpectedException.none(); + + private File workDir; + + @Before + public void setUp() throws IOException { + workDir = tempFolder.newFolder(testName.getMethodName()); + } + + @Test + public void should_consume_StdOut_and_StdErr() throws Exception { + final StringBuilder stdOutBuilder = new StringBuilder(); + CommandExecutor.StreamConsumer stdOutConsumer = new CommandExecutor.StreamConsumer() { + public void consumeLine(String line) { + stdOutBuilder.append(line).append(System.getProperty("line.separator")); + } + }; + final StringBuilder stdErrBuilder = new StringBuilder(); + CommandExecutor.StreamConsumer stdErrConsumer = new CommandExecutor.StreamConsumer() { + public void consumeLine(String line) { + stdErrBuilder.append(line).append(System.getProperty("line.separator")); + } + }; + Command command = Command.builder().setExecutable(getScript("output")).setDirectory(workDir).build(); + int exitCode = CommandExecutor.create().execute(command, stdOutConsumer, stdErrConsumer, 1000L); + assertThat(exitCode).isEqualTo(0); + + String stdOut = stdOutBuilder.toString(); + String stdErr = stdErrBuilder.toString(); + assertThat(stdOut).contains("stdOut: first line"); + assertThat(stdOut).contains("stdOut: second line"); + assertThat(stdErr).contains("stdErr: first line"); + assertThat(stdErr).contains("stdErr: second line"); + } + + @Test + public void stdOut_consumer_can_throw_exception() throws Exception { + Command command = Command.builder().setExecutable(getScript("output")).setDirectory(workDir).build(); + thrown.expect(CommandException.class); + thrown.expectMessage("Error inside stdOut stream"); + CommandExecutor.create().execute(command, BAD_CONSUMER, NOP_CONSUMER, 1000L); + } + + @Test + public void stdErr_consumer_can_throw_exception() throws Exception { + Command command = Command.builder().setExecutable(getScript("output")).setDirectory(workDir).build(); + thrown.expect(CommandException.class); + thrown.expectMessage("Error inside stdErr stream"); + CommandExecutor.create().execute(command, NOP_CONSUMER, BAD_CONSUMER, 1000L); + } + + private static final CommandExecutor.StreamConsumer NOP_CONSUMER = new CommandExecutor.StreamConsumer() { + public void consumeLine(String line) { + // nop + } + }; + + private static final CommandExecutor.StreamConsumer BAD_CONSUMER = new CommandExecutor.StreamConsumer() { + public void consumeLine(String line) { + throw new RuntimeException(); + } + }; + + @Test + public void should_use_working_directory_to_store_argument_and_environment_variable() throws Exception { + Command command = Command.builder() + .setDirectory(workDir) + .setExecutable(getScript("echo")) + .addArguments("1") + .setEnvVariable("ENVVAR", "2") + .build(); + int exitCode = CommandExecutor.create().execute(command, 1000L); + assertThat(exitCode).isEqualTo(0); + File logFile = new File(workDir, "echo.log"); + assertThat(logFile).exists(); + String log = FileUtils.readFileToString(logFile); + assertThat(log).contains(workDir.getAbsolutePath()); + assertThat(log).contains("Parameter: 1"); + assertThat(log).contains("Environment variable: 2"); + } + + @Test + public void should_stop_after_timeout() throws IOException { + String executable = getScript("forever"); + long start = System.currentTimeMillis(); + try { + CommandExecutor.create().execute(Command.builder().setExecutable(executable).setDirectory(workDir).build(), 300L); + fail(); + } catch (CommandException e) { + long duration = System.currentTimeMillis() - start; + // should test >= 300 but it strangly fails during build on windows. + // The timeout is raised after 297ms (??) + assertThat(duration).as(e.getMessage()).isGreaterThan(290L); + } + } + + @Test + public void should_fail_if_script_not_found() { + thrown.expect(CommandException.class); + CommandExecutor.create().execute(Command.builder().setExecutable("notfound").setDirectory(workDir).build(), 1000L); + } + + private static String getScript(String name) throws IOException { + String filename; + if (new Os().isWindows()) { + filename = name + ".bat"; + } else { + filename = name + ".sh"; + } + return new File("src/test/scripts/" + filename).getCanonicalPath(); + } + +} diff --git a/sonar-runner-api/src/test/java/org/sonar/runner/api/CommandTest.java b/sonar-runner-api/src/test/java/org/sonar/runner/api/CommandTest.java new file mode 100644 index 0000000..259d1c6 --- /dev/null +++ b/sonar-runner-api/src/test/java/org/sonar/runner/api/CommandTest.java @@ -0,0 +1,75 @@ +/* + * Sonar Runner - API + * Copyright (C) 2011 SonarSource + * dev@sonar.codehaus.org + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 + */ +package org.sonar.runner.api; + +import org.junit.Test; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; + +import static org.fest.assertions.Assertions.assertThat; +import static org.fest.assertions.Fail.fail; +import static org.fest.assertions.MapAssert.entry; + +public class CommandTest { + @Test + public void test_simple_build() throws Exception { + Command command = Command.builder().setExecutable("java").build(); + assertThat(command.executable()).isEqualTo("java"); + assertThat(command.envVariables()).isEmpty(); + assertThat(command.arguments()).isEmpty(); + assertThat(command.toStrings()).containsOnly("java"); + assertThat(command.toString()).isEqualTo("java"); + } + + @Test + public void test_arguments_and_env_variables() throws Exception { + Map<String, String> env = new HashMap<String, String>(); + env.put("USER_HOME", "/user"); + + Command command = Command.builder() + .setExecutable("java") + .addArguments("-Dfoo=bar", "-Djava.io.tmpdir=/tmp") + .addArguments(Arrays.asList("-Xmx512m")) + .setEnvVariable("JAVA_HOME", "/path/to/jdk") + .addEnvVariables(env) + .build(); + + assertThat(command.executable()).isEqualTo("java"); + assertThat(command.envVariables()).hasSize(2).includes( + entry("JAVA_HOME", "/path/to/jdk"), + entry("USER_HOME", "/user") + ); + assertThat(command.arguments()).containsSequence("-Dfoo=bar", "-Djava.io.tmpdir=/tmp", "-Xmx512m"); + assertThat(command.toStrings()).containsOnly("java", "-Dfoo=bar", "-Djava.io.tmpdir=/tmp", "-Xmx512m"); + assertThat(command.toString()).isEqualTo("java -Dfoo=bar -Djava.io.tmpdir=/tmp -Xmx512m"); + } + + @Test + public void executable_should_be_required() { + try { + Command.builder().build(); + fail(); + } catch (IllegalArgumentException e) { + // success + } + } +} diff --git a/sonar-runner-api/src/test/java/org/sonar/runner/api/EmbeddedRunnerTest.java b/sonar-runner-api/src/test/java/org/sonar/runner/api/EmbeddedRunnerTest.java new file mode 100644 index 0000000..d3d2ca2 --- /dev/null +++ b/sonar-runner-api/src/test/java/org/sonar/runner/api/EmbeddedRunnerTest.java @@ -0,0 +1,54 @@ +/* + * Sonar Runner - API + * Copyright (C) 2011 SonarSource + * dev@sonar.codehaus.org + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 + */ +package org.sonar.runner.api; + +import org.junit.Test; +import org.sonar.runner.impl.Constants; + +import static org.fest.assertions.Assertions.assertThat; + +public class EmbeddedRunnerTest { + @Test + public void should_create() { + assertThat(EmbeddedRunner.create()).isNotNull().isInstanceOf(EmbeddedRunner.class); + } + + @Test + public void should_set_unmasked_packages() { + EmbeddedRunner runner = EmbeddedRunner.create(); + assertThat(runner.property(Constants.UNMASKED_PACKAGES, null)).isNull(); + + runner = EmbeddedRunner.create().setUnmaskedPackages("org.apache.ant", "org.ant"); + assertThat(runner.property(Constants.UNMASKED_PACKAGES, null)).isEqualTo("org.apache.ant,org.ant"); + } + + @Test + public void should_add_extensions() { + EmbeddedRunner runner = EmbeddedRunner.create(); + assertThat(runner.extensions()).isEmpty(); + + FakeExtension fakeExtension = new FakeExtension(); + runner.addExtensions(fakeExtension); + assertThat(runner.extensions()).containsExactly(fakeExtension); + } + + static class FakeExtension { + } +} diff --git a/sonar-runner-api/src/test/java/org/sonar/runner/StatsTest.java b/sonar-runner-api/src/test/java/org/sonar/runner/api/ForkedRunnerTest.java index 7ea5d84..5c8767b 100644 --- a/sonar-runner-api/src/test/java/org/sonar/runner/StatsTest.java +++ b/sonar-runner-api/src/test/java/org/sonar/runner/api/ForkedRunnerTest.java @@ -17,26 +17,15 @@ * License along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 */ -package org.sonar.runner; +package org.sonar.runner.api; import org.junit.Test; import static org.fest.assertions.Assertions.assertThat; - -public class StatsTest { - - @Test - public void shouldPrintStats() { - new Stats().start().stop(); - //TODO mock Logs - } - +public class ForkedRunnerTest { @Test - public void shouldFormatTime() { - assertThat(Stats.formatTime(1 * 60 * 60 * 1000 + 2 * 60 * 1000 + 3 * 1000 + 400)).isEqualTo("1:02:03.400s"); - assertThat(Stats.formatTime(2 * 60 * 1000 + 3 * 1000 + 400)).isEqualTo("2:03.400s"); - assertThat(Stats.formatTime(3 * 1000 + 400)).isEqualTo("3.400s"); - assertThat(Stats.formatTime(400)).isEqualTo("0.400s"); + public void should_create() { + assertThat(ForkedRunner.create()).isNotNull().isInstanceOf(ForkedRunner.class); } } diff --git a/sonar-runner-api/src/test/java/org/sonar/runner/api/OsTest.java b/sonar-runner-api/src/test/java/org/sonar/runner/api/OsTest.java new file mode 100644 index 0000000..20c4a91 --- /dev/null +++ b/sonar-runner-api/src/test/java/org/sonar/runner/api/OsTest.java @@ -0,0 +1,47 @@ +/* + * Sonar Runner - API + * Copyright (C) 2011 SonarSource + * dev@sonar.codehaus.org + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 + */ +package org.sonar.runner.api; + +import org.apache.commons.lang.SystemUtils; +import org.junit.Test; + +import java.io.File; + +import static org.fest.assertions.Assertions.assertThat; + +public class OsTest { + @Test + public void testIsWindows() throws Exception { + assertThat(new Os().isWindows()).isEqualTo(SystemUtils.IS_OS_WINDOWS); + } + + @Test + public void testUsedJavaHome() throws Exception { + File javaHome = new Os().usedJavaHome(); + assertThat(javaHome).isNotNull().exists().isDirectory(); + } + + @Test + public void testUsedJavaExe() throws Exception { + File javaExe = new Os().usedJavaExe(); + assertThat(javaExe).isNotNull().isFile().exists(); + assertThat(javaExe.getName()).contains("java"); + } +} diff --git a/sonar-runner-api/src/test/java/org/sonar/runner/VersionTest.java b/sonar-runner-api/src/test/java/org/sonar/runner/api/RunnerVersionTest.java index 2280195..65d13c5 100644 --- a/sonar-runner-api/src/test/java/org/sonar/runner/VersionTest.java +++ b/sonar-runner-api/src/test/java/org/sonar/runner/api/RunnerVersionTest.java @@ -17,20 +17,18 @@ * License along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 */ -package org.sonar.runner; +package org.sonar.runner.api; import org.junit.Test; -import org.sonar.runner.Version; import static org.fest.assertions.Assertions.assertThat; -public class VersionTest { +public class RunnerVersionTest { @Test - public void shouldLoadVersion() { - String version = Version.getVersion(); - assertThat(version).contains("."); - assertThat(version).doesNotContain("$"); + public void should_load_version() { + String version = RunnerVersion.version(); + assertThat(version).isNotEmpty().contains(".").endsWith("-SNAPSHOT").doesNotContain("$"); } } diff --git a/sonar-runner-api/src/test/java/org/sonar/runner/api/UtilsTest.java b/sonar-runner-api/src/test/java/org/sonar/runner/api/UtilsTest.java new file mode 100644 index 0000000..f956c75 --- /dev/null +++ b/sonar-runner-api/src/test/java/org/sonar/runner/api/UtilsTest.java @@ -0,0 +1,33 @@ +/* + * Sonar Runner - API + * Copyright (C) 2011 SonarSource + * dev@sonar.codehaus.org + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 + */ +package org.sonar.runner.api; + +import org.junit.Test; + +import static org.fest.assertions.Assertions.assertThat; + +public class UtilsTest { + @Test + public void should_join_strings() { + assertThat(Utils.join(new String[]{}, ",")).isEqualTo(""); + assertThat(Utils.join(new String[]{"foo"}, ",")).isEqualTo("foo"); + assertThat(Utils.join(new String[]{"foo", "bar"}, ",")).isEqualTo("foo,bar"); + } +} |