From 41e85743092aa6dab582577af7abd8656ed81f4c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Christoph=20L=C3=A4ubrich?= Date: Mon, 9 Sep 2024 18:25:49 +0200 Subject: [PATCH] Remove Mojo test cases Tycho currently contains some so called "Mojo Testcases" that are ones that (partly) simulate the execution of a mojo, but these have some problems: 1) They currently depend on heavy outdated (and deprecated) maven-plugin-testharness 2) They often do not have a full test setup so we need to have some quirks in the code (e.g components are null) 3) They are often hard to understand as they are a mixture of (incomplete) maven setups with things setup in the code 4) We even have some constructors only used to support these cases 5) As they often test very specific internal behavior they often need adjustments. 6) For the Maven 4 transition one needs to adjust them to new maven4 api and components and executions. On the other hand we have a very good integration suite that is made of actual executable examples and test, changing internal implementation details does not affect these or show clear use-cases that break. Because of this and to prepare for the Maven 4 transition these tests are now deleted. --- .../osgicompiler/test/OsgiCompilerTest.java | 620 ------------------ .../core/ee/ExecutionEnvironmentTest.java | 40 -- .../core/osgitools/EquinoxResolverTest.java | 142 ---- ...TargetPlatformConfigurationReaderTest.java | 157 ----- .../core/test/DependencyComputerTest.java | 330 ---------- .../test/MavenDependencyCollectorTest.java | 195 ------ .../org/eclipse/tycho/core/test/P2IUTest.java | 48 -- .../eclipse/tycho/core/test/TychoTest.java | 281 -------- .../extras/eclipserun/EclipseRunMojoTest.java | 169 ----- .../plugins/p2/extras/MirrorMojoTest.java | 195 ------ .../PublishFeaturesAndBundlesMojoTest.java | 130 ---- .../test/PackageFeatureMojoTest.java | 127 ---- .../buildnumber/test/PackageIUMojoTest.java | 95 --- .../test/PackagePluginMojoTest.java | 154 ----- .../buildnumber/test/ValidateVersionTest.java | 94 --- .../buildversion/BuildQualifierTest.java | 303 --------- .../tycho/buildversion/ValidateIdTest.java | 88 --- .../tycho/source/OsgiSourceMojoTest.java | 178 ----- .../testing/AbstractTychoMojoTestCase.java | 260 -------- 19 files changed, 3606 deletions(-) delete mode 100644 tycho-compiler-plugin/src/test/java/org/eclipse/tycho/osgicompiler/test/OsgiCompilerTest.java delete mode 100644 tycho-core/src/test/java/org/eclipse/tycho/core/ee/ExecutionEnvironmentTest.java delete mode 100644 tycho-core/src/test/java/org/eclipse/tycho/core/osgitools/EquinoxResolverTest.java delete mode 100644 tycho-core/src/test/java/org/eclipse/tycho/core/resolver/DefaultTargetPlatformConfigurationReaderTest.java delete mode 100644 tycho-core/src/test/java/org/eclipse/tycho/core/test/DependencyComputerTest.java delete mode 100644 tycho-core/src/test/java/org/eclipse/tycho/core/test/MavenDependencyCollectorTest.java delete mode 100644 tycho-core/src/test/java/org/eclipse/tycho/core/test/P2IUTest.java delete mode 100644 tycho-core/src/test/java/org/eclipse/tycho/core/test/TychoTest.java delete mode 100644 tycho-eclipse-plugin/src/test/java/org/eclipse/tycho/extras/eclipserun/EclipseRunMojoTest.java delete mode 100644 tycho-extras/tycho-p2-extras-plugin/src/test/java/org/eclipse/tycho/plugins/p2/extras/MirrorMojoTest.java delete mode 100644 tycho-extras/tycho-p2-extras-plugin/src/test/java/org/eclipse/tycho/plugins/p2/extras/PublishFeaturesAndBundlesMojoTest.java delete mode 100644 tycho-packaging-plugin/src/test/java/org/eclipse/tycho/buildnumber/test/PackageFeatureMojoTest.java delete mode 100644 tycho-packaging-plugin/src/test/java/org/eclipse/tycho/buildnumber/test/PackageIUMojoTest.java delete mode 100644 tycho-packaging-plugin/src/test/java/org/eclipse/tycho/buildnumber/test/PackagePluginMojoTest.java delete mode 100644 tycho-packaging-plugin/src/test/java/org/eclipse/tycho/buildnumber/test/ValidateVersionTest.java delete mode 100644 tycho-packaging-plugin/src/test/java/org/eclipse/tycho/buildversion/BuildQualifierTest.java delete mode 100644 tycho-packaging-plugin/src/test/java/org/eclipse/tycho/buildversion/ValidateIdTest.java delete mode 100644 tycho-source-plugin/src/test/java/org/eclipse/tycho/source/OsgiSourceMojoTest.java delete mode 100644 tycho-testing-harness/src/main/java/org/eclipse/tycho/testing/AbstractTychoMojoTestCase.java diff --git a/tycho-compiler-plugin/src/test/java/org/eclipse/tycho/osgicompiler/test/OsgiCompilerTest.java b/tycho-compiler-plugin/src/test/java/org/eclipse/tycho/osgicompiler/test/OsgiCompilerTest.java deleted file mode 100644 index ce3e7bb386..0000000000 --- a/tycho-compiler-plugin/src/test/java/org/eclipse/tycho/osgicompiler/test/OsgiCompilerTest.java +++ /dev/null @@ -1,620 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008, 2018 Sonatype Inc. and others. - * This program and the accompanying materials - * are made available under the terms of the Eclipse Public License 2.0 - * which accompanies this distribution, and is available at - * https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Sonatype Inc. - initial API and implementation - *******************************************************************************/ -package org.eclipse.tycho.osgicompiler.test; - -import static java.util.Arrays.asList; -import static org.hamcrest.CoreMatchers.containsString; -import static org.hamcrest.CoreMatchers.not; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.Assert.assertThrows; - -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.Properties; -import java.util.Set; -import java.util.stream.Collectors; - -import org.apache.bcel.classfile.ClassFormatException; -import org.apache.bcel.classfile.ClassParser; -import org.apache.bcel.classfile.JavaClass; -import org.apache.maven.plugin.MojoExecutionException; -import org.apache.maven.plugin.MojoFailureException; -import org.apache.maven.plugin.logging.SystemStreamLog; -import org.apache.maven.project.MavenProject; -import org.codehaus.plexus.util.FileUtils; -import org.eclipse.tycho.SourcepathEntry; -import org.eclipse.tycho.compiler.AbstractOsgiCompilerMojo; -import org.eclipse.tycho.core.ee.StandardExecutionEnvironment; -import org.eclipse.tycho.testing.AbstractTychoMojoTestCase; -import org.eclipse.tycho.version.TychoVersion; -import org.hamcrest.Matchers; -import org.hamcrest.core.StringContains; - -import copied.org.apache.maven.plugin.CompilationFailureException; - -public class OsgiCompilerTest extends AbstractTychoMojoTestCase { - - private static final int TARGET_1_4 = 48; - private static final int TARGET_1_8 = 52; - - protected File storage; - private Properties properties; - - @Override - protected void setUp() throws Exception { - super.setUp(); - storage = new File(getBasedir(), "target/storage"); - FileUtils.deleteDirectory(storage); - properties = new Properties(); - properties.setProperty("tycho-version", TychoVersion.getTychoVersion()); - } - - private AbstractOsgiCompilerMojo getMojo(List projects, MavenProject project) throws Exception { - AbstractOsgiCompilerMojo mojo = (AbstractOsgiCompilerMojo) lookupConfiguredMojo(project, "compile"); - for (MavenProject mavenProject : projects) { - new File(mavenProject.getBasedir(), "target/classes").mkdirs(); - } -// setVariableValueToObject(mojo, "project", project); -// setVariableValueToObject(mojo, "session", newMavenSession(project, projects)); - - // tycho-compiler-jdt does not support forked compilation -// setVariableValueToObject(mojo, "fork", fork? Boolean.TRUE: Boolean.FALSE); - return mojo; - } - - public void testAccessRestrictionCompilationError() throws Exception { - File basedir = getBasedir("projects/accessrules"); - List projects = getSortedProjects(basedir); - - try { - for (MavenProject project : projects) { - if (!"pom".equals(project.getPackaging())) { - getMojo(projects, project).execute(); - } - } - fail("Restricted package access"); - } catch (MojoFailureException e) { - assertTrue(e.getLongMessage().contains("The type 'P001Impl' is not API")); - } - } - - public void testAccessRulesClasspath() throws Exception { - File basedir = getBasedir("projects/accessrules"); - List projects = getSortedProjects(basedir); - - getMojo(projects, projects.get(1)).execute(); - getMojo(projects, projects.get(2)).execute(); - getMojo(projects, projects.get(3)).execute(); - - MavenProject project = projects.get(4); - AbstractOsgiCompilerMojo mojo = getMojo(projects, project); - List cp = mojo.getClasspathElements(); - assertEquals(4, cp.size()); - assertEquals(getClasspathElement(new File(getBasedir()), "target/projects/accessrules/p001/target/classes", - "[+p001/*:?**/*]"), cp.get(0)); - // note that PDE sorts dependencies coming via imported-package by symbolicName_version - assertEquals(getClasspathElement(new File(getBasedir()), "target/projects/accessrules/p003/target/classes", - "[+p003/*:?**/*]"), cp.get(1)); - assertEquals(getClasspathElement(new File(getBasedir()), "target/projects/accessrules/p004/target/classes", - "[+p004/*:?**/*]"), cp.get(2)); - assertEquals(getClasspathElement(project.getBasedir(), "target/classes", ""), cp.get(3)); - - } - - public void testClasspath() throws Exception { - File basedir = getBasedir("projects/classpath"); - List projects = getSortedProjects(basedir, properties); - - MavenProject project; - List cp; - - // simple project - project = projects.get(1); - AbstractOsgiCompilerMojo mojo = getMojo(projects, project); - cp = mojo.getClasspathElements(); - assertEquals(1, cp.size()); - assertEquals(getClasspathElement(project.getBasedir(), "target/classes", ""), cp.get(0)); - - // project with nested lib - project = projects.get(2); - mojo = getMojo(projects, project); - cp = mojo.getClasspathElements(); - assertEquals(2, cp.size()); - assertEquals(getClasspathElement(project.getBasedir(), "target/classes", ""), cp.get(0)); - assertEquals(getClasspathElement(project.getBasedir(), "lib/lib.jar", ""), cp.get(1)); - - // project with external dependency with nested jar - project = projects.get(3); - mojo = getMojo(projects, project); - cp = mojo.getClasspathElements(); - assertEquals(3, cp.size()); - final String plainJarPath = "target/projects/classpath/platform/plugins/p003_0.0.1.jar"; - final String nestedJarPath = "target/local-repo/.cache/tycho/p003_0.0.1.jar/lib/lib.jar"; - assertEquals(getClasspathElement(new File(getBasedir()), plainJarPath, "[?**/*]"), cp.get(0)); - assertEquals(getClasspathElement(new File(getBasedir()), nestedJarPath, "[?**/*]"), cp.get(1)); - assertEquals(getClasspathElement(project.getBasedir(), "target/classes", ""), cp.get(2)); - - // project with a (not yet) existing nested jar that would be copied later during build - // (wrapper scenario with copy-pom-dependencies) -// project = projects.get(4); -// mojo = getMojo(projects, project); -// mojo.execute(); -// cp = mojo.getClasspathElements(); -// assertEquals(3, cp.size()); -// assertEquals(getClasspathElement(project.getBasedir(), "target/classes", ""), cp.get(0)); -// assertEquals(getClasspathElement(project.getBasedir(), "lib/not_existing_yet.jar", ""), cp.get(1)); -// assertEquals(getClasspathElement(project.getBasedir(), "lib/not_existing_yet_dir/", ""), cp.get(2)); - } - - private String getClasspathElement(File base, String path, String accessRules) throws IOException { - String file = new File(base, path).getAbsolutePath(); - return file + accessRules.replace(":", AbstractOsgiCompilerMojo.RULE_SEPARATOR); - } - - public void test_multisourceP001_viaMojoConfiguration() throws Exception { - File basedir = getBasedir("projects/multisource/p001"); - List projects = getSortedProjects(basedir); - - MavenProject project = projects.get(0); - getMojo(projects, project).execute(); - - assertTrue(new File(project.getBasedir(), "target/classes/p001/p1/P1.class").canRead()); - assertTrue(new File(project.getBasedir(), "target/classes/p001/p2/P2.class").canRead()); - } - - public void test_multisourceP002_viaBuildProperties() throws Exception { - File basedir = getBasedir("projects/multisource/p002"); - List projects = getSortedProjects(basedir); - - MavenProject project = projects.get(0); - getMojo(projects, project).execute(); - - assertTrue(new File(project.getBasedir(), "target/classes/p002/p1/P1.class").canRead()); - assertTrue(new File(project.getBasedir(), "target/classes/p002/p2/P2.class").canRead()); - } - - public void test_multipleOutputJars() throws Exception { - File basedir = getBasedir("projects/multijar"); - List projects = getSortedProjects(basedir); - - MavenProject project = projects.get(0); - getMojo(projects, project).execute(); - - assertTrue(new File(project.getBasedir(), "target/classes/src/Src.class").canRead()); - assertTrue(new File(project.getBasedir(), "target/library.jar-classes/src2/Src2.class").canRead()); - - List sourcepath = getMojo(projects, project).getSourcepath(); - assertEquals(2, sourcepath.size()); - } - - public void test_multipleOutputJars_getSourcepath() throws Exception { - File basedir = getBasedir("projects/multijar"); - List projects = getSortedProjects(basedir); - - MavenProject project = projects.get(0); - - List sourcepath = getMojo(projects, project).getSourcepath(); - assertEquals(2, sourcepath.size()); - assertSameFile(new File(project.getBasedir(), "target/classes"), sourcepath.get(0).getOutputDirectory()); - assertSameFile(new File(project.getBasedir(), "src"), sourcepath.get(0).getSourcesRoot()); - assertSameFile(new File(project.getBasedir(), "target/library.jar-classes"), - sourcepath.get(1).getOutputDirectory()); - assertSameFile(new File(project.getBasedir(), "src2"), sourcepath.get(1).getSourcesRoot()); - } - - private void assertSameFile(File expected, File actual) throws IOException { - assertEquals(expected.getCanonicalFile(), actual.getCanonicalFile()); - } - - public void testCopyResources() throws Exception { - File basedir = getBasedir("projects/resources/p001"); - List projects = getSortedProjects(basedir); - MavenProject project = projects.get(0); - getMojo(projects, project).execute(); - assertTrue(new File(project.getBasedir(), "target/classes/testresources/Test.class").canRead()); - assertTrue(new File(project.getBasedir(), "target/classes/testresources/test.properties").canRead()); - } - - public void testCopyResourcesWithNestedJar() throws Exception { - File basedir = getBasedir("projects/resources/p004"); - List projects = getSortedProjects(basedir); - MavenProject project = projects.get(0); - getMojo(projects, project).execute(); - assertTrue(new File(project.getBasedir(), "target/classes/testresources/Test.class").canRead()); - assertTrue(new File(project.getBasedir(), "target/classes/testresources/test.properties").canRead()); - } - - public void testExcludeCopyResources() throws Exception { - File basedir = getBasedir("projects/resources/p002"); - List projects = getSortedProjects(basedir); - MavenProject project = projects.get(0); - getMojo(projects, project).execute(); - assertTrue(new File(project.getBasedir(), "target/classes/testresources/Test.class").canRead()); - assertFalse(new File(project.getBasedir(), "target/classes/testresources/Test.aj").canRead()); - } - - public void testCopyResourcesWithResourceCopyingSetToOff() throws Exception { - File basedir = getBasedir("projects/resources/p003"); - List projects = getSortedProjects(basedir); - MavenProject project = projects.get(0); - getMojo(projects, project).execute(); - assertTrue(new File(project.getBasedir(), "target/classes/testresources/Test.class").exists()); - assertFalse(new File(project.getBasedir(), "target/classes/testresources/test.properties").exists()); - } - - public void testSourceCompileLevel() throws Exception { - File basedir = getBasedir("projects/executionEnvironment"); - List projects = getSortedProjects(basedir); - MavenProject project; - // project with neither POM nor MANIFEST configuration => must fallback to - // source/target level of the JVM - project = projects.get(1); - getMojo(projects, project).execute(); - // Java 17 -> 61, Java 21 -> 65 - assertBytecodeMajorLevel(Runtime.version().feature() + 44, - new File(project.getBasedir(), "target/classes/Generic.class")); - - // project with multiple execution envs. - // Minimum source and target level must be taken - project = projects.get(2); - AbstractOsgiCompilerMojo mojo = getMojo(projects, project); - assertEquals("1.3", mojo.getSourceLevel()); - try { - mojo.execute(); - fail("compilation failure due to assert keyword expected"); - } catch (CompilationFailureException e) { - // expected - } - // project with both explicit compiler configuration in pom.xml and Bundle-RequiredExecutionEnvironment. - // explicit compiler configuration in the pom should win. see https://issues.sonatype.org/browse/TYCHO-476 - project = projects.get(3); - mojo = getMojo(projects, project); - assertEquals("jsr14", mojo.getTargetLevel()); - assertEquals("1.5", mojo.getSourceLevel()); - mojo.execute(); - assertBytecodeMajorLevel(TARGET_1_4, new File(project.getBasedir(), "target/classes/Generic.class")); - // project with both explicit EE configuration in pom.xml and Bundle-RequiredExecutionEnvironment. - // explicit configuration in the pom.xml win - project = projects.get(4); - mojo = getMojo(projects, project); - mojo.execute(); - assertEquals("1.3", mojo.getSourceLevel()); - // project with both explicit compiler configuration in build.properties and Bundle-RequiredExecutionEnvironment. - // build.properties should win. - project = projects.get(5); - mojo = getMojo(projects, project); - mojo.execute(); - assertEquals("jsr14", mojo.getTargetLevel()); - assertEquals("1.5", mojo.getSourceLevel()); - assertBytecodeMajorLevel(TARGET_1_4, new File(project.getBasedir(), "target/classes/Generic.class")); - } - - public void testNewerEEthanBREE() throws Exception { - File basedir = getBasedir("projects/executionEnvironment/p006-newerEEthanBREE"); - List projects = getSortedProjects(basedir); - MavenProject project = projects.get(0); - AbstractOsgiCompilerMojo mojo = getMojo(projects, project); - mojo.execute(); - assertTrue(Integer.parseInt(mojo.getExecutionEnvironment().substring("JavaSE-".length())) >= 11); - assertEquals("1.8", mojo.getSourceLevel()); - assertEquals("1.8", mojo.getTargetLevel()); - assertEquals("8", mojo.getReleaseLevel()); - assertBytecodeMajorLevel(TARGET_1_8, new File(project.getBasedir(), "target/classes/Noop.class")); - } - - public void testNoBREEButEERequirement() throws Exception { - File basedir = getBasedir("projects/executionEnvironment/eeAsRequirement"); - List projects = getSortedProjects(basedir); - MavenProject project = projects.get(0); - AbstractOsgiCompilerMojo mojo = getMojo(projects, project); - StandardExecutionEnvironment[] ees = mojo.getBREE(); - assertEquals(Set.of("JavaSE-1.8", "JavaSE/compact1-1.8"), - Arrays.stream(ees).map(StandardExecutionEnvironment::getProfileName).collect(Collectors.toSet())); - } - - public void testAutomaticReleaseCompilerArgumentDeterminationDisabled() throws Exception { - File basedir = getBasedir( - "projects/executionEnvironment/p007-automaticReleaseCommpilerArgumentDeterminationDisabled"); - List projects = getSortedProjects(basedir); - MavenProject project = projects.get(0); - AbstractOsgiCompilerMojo mojo = getMojo(projects, project); - mojo.execute(); - assertTrue(Integer.parseInt(mojo.getExecutionEnvironment().substring("JavaSE-".length())) >= 11); - assertEquals("1.8", mojo.getSourceLevel()); - assertEquals("1.8", mojo.getTargetLevel()); - assertNull(mojo.getReleaseLevel()); - assertBytecodeMajorLevel(TARGET_1_8, new File(project.getBasedir(), "target/classes/Noop.class")); - } - - private void assertBytecodeMajorLevel(int majorLevel, File classFile) throws ClassFormatException, IOException { - assertTrue(classFile.canRead()); - JavaClass javaClass = new ClassParser(classFile.getAbsolutePath()).parse(); - assertEquals(majorLevel, javaClass.getMajor()); - } - - public void test_TYCHO0400indirectDependencies() throws Exception { - File basedir = getBasedir("projects/indirectDependencies"); - List projects = getSortedProjects(basedir); - - assertEquals("C", projects.get(1).getArtifactId()); - getMojo(projects, projects.get(1)).execute(); - - assertEquals("B", projects.get(2).getArtifactId()); - getMojo(projects, projects.get(2)).execute(); - - assertEquals("A", projects.get(3).getArtifactId()); - AbstractOsgiCompilerMojo mojo = getMojo(projects, projects.get(3)); - List cp = mojo.getClasspathElements(); - assertEquals(getClasspathElement(projects.get(1).getBasedir(), "target/classes", "[?**/*]"), cp.get(1)); - - mojo.execute(); - assertTrue(new File(projects.get(3).getBasedir(), "target/classes/a/A.class").canRead()); - } - - public void test_embeddedNonClasspath() throws Exception { - File basedir = getBasedir("projects/embedednonclasspath"); - List projects = getSortedProjects(basedir); - - MavenProject project = projects.get(0); - getMojo(projects, project).execute(); - - assertTrue(new File(project.getBasedir(), "target/classes/src/Src.class").canRead()); - assertTrue(new File(project.getBasedir(), "target/library.jar-classes/src2/Src2.class").canRead()); - - List sourcepath = getMojo(projects, project).getSourcepath(); - assertEquals(2, sourcepath.size()); - } - - public void test_bootclasspathAccessRules() throws Exception { - File basedir = getBasedir("projects/bootclasspath-accessrules"); - List projects = getSortedProjects(basedir); - - MavenProject project = projects.get(0); - getMojo(projects, project).execute(); - } - - public void testWarningAndErrorMessages() throws Exception { - File basedir = getBasedir("projects/compilermessages"); - List projects = getSortedProjects(basedir); - MavenProject project = projects.get(0); - AbstractOsgiCompilerMojo mojo = getMojo(projects, project); - final List warnings = new ArrayList<>(); - mojo.setLog(new SystemStreamLog() { - - @Override - public void warn(CharSequence content) { - warnings.add(content); - } - - }); - try { - mojo.execute(); - fail("compilation failure expected"); - } catch (CompilationFailureException e) { - String message = e.getLongMessage(); - assertThat(message, containsString("3 problems (1 error, 2 warnings)")); - // 1 error - assertThat(message, containsString("Test.java:[25")); - assertThat(message, containsString("System.foo();")); - } - // 2 warnings - List expectedWarnings = asList("Test.java:[21", // - "Test.java:[23"); - assertEquals(expectedWarnings.size(), warnings.size()); - for (int i = 0; i < warnings.size(); i++) { - String warning = (String) warnings.get(i); - String expectedWarning = expectedWarnings.get(i); - assertThat(warning, containsString(expectedWarning)); - } - } - - public void testCompilerArgs() throws Exception { - File basedir = getBasedir("projects/compiler-args"); - List projects = getSortedProjects(basedir); - MavenProject project = projects.get(0); - AbstractOsgiCompilerMojo mojo = getMojo(projects, project); - - setVariableValueToObject(mojo, "showWarnings", Boolean.TRUE); - - final List warnings = new ArrayList<>(); - mojo.setLog(new SystemStreamLog() { - - @Override - public void warn(CharSequence content) { - warnings.add(content); - } - - }); - try { - mojo.execute(); - fail("compilation failure expected"); - } catch (CompilationFailureException e) { - String message = e.getLongMessage(); - assertThat(message, containsString("2 problems (1 error, 1 warning)")); - // 1 error - assertThat(message, containsString("unused")); - } - // 1 warning - assertThat((String) warnings.iterator().next(), containsString("is boxed")); - } - - public void testUseProjectSettingsSetToTrue() throws Exception { - // the code in the project does use boxing and the settings file - // turns on warning for auto boxing so we expect here a warning - File basedir = getBasedir("projects/projectSettings/p001"); - List projects = getSortedProjects(basedir); - MavenProject project = projects.get(0); - AbstractOsgiCompilerMojo mojo = getMojo(projects, project); - setVariableValueToObject(mojo, "useProjectSettings", Boolean.TRUE); - setVariableValueToObject(mojo, "showWarnings", Boolean.TRUE); - final List warnings = new ArrayList<>(); - mojo.setLog(new SystemStreamLog() { - - @Override - public void warn(CharSequence content) { - warnings.add(content); - } - - }); - mojo.execute(); - assertThat((String) warnings.iterator().next(), containsString("is boxed")); - } - - public void testUseProjectSettingsSetToFalse() throws Exception { - File basedir = getBasedir("projects/projectSettings/p001"); - List projects = getSortedProjects(basedir); - MavenProject project = projects.get(0); - AbstractOsgiCompilerMojo mojo = getMojo(projects, project); - setVariableValueToObject(mojo, "useProjectSettings", Boolean.FALSE); - final List warnings = new ArrayList<>(); - mojo.setLog(new SystemStreamLog() { - - @Override - public void warn(CharSequence content) { - warnings.add(content); - } - - }); - mojo.execute(); - assertTrue(warnings.isEmpty()); - } - - public void testUseProjectSettingsSetToTrueWithMissingPrefsFile() throws Exception { - File basedir = getBasedir("projects/projectSettings/p002"); - List projects = getSortedProjects(basedir); - MavenProject project = projects.get(0); - AbstractOsgiCompilerMojo mojo = getMojo(projects, project); - setVariableValueToObject(mojo, "useProjectSettings", Boolean.TRUE); - final List debug = new ArrayList<>(); - mojo.setLog(new SystemStreamLog() { - - @Override - public void debug(CharSequence content) { - debug.add(content.toString()); - } - - }); - mojo.execute(); - assertTrue(debug.stream() - .anyMatch(msg -> msg.contains("Parameter 'useProjectSettings' is set to true, but preferences file"))); - } - - public void test367431_frameworkExtensionCompileAccessRules() throws Exception { - // This test assumes that the internal class com.sun.crypto.provider.SunJCE exists and its package is not exported. - // This is the case for all supported JDKs to date (1.8, 11, 14). - // Note: The bundle uses BREE 1.8 here, because apparently this kind of framework-extension does not - // correctly work with modular API (Java9+). - File basedir = getBasedir("projects/367431_frameworkExtensionCompileAccessRules/"); - List projects = getSortedProjects(new File(basedir, "bundle"), properties); - - MavenProject project = projects.get(0); - getMojo(projects, project).execute(); - } - - public void testBreeCompilerTargetCompatibilityIsChecked() throws Exception { - File basedir = getBasedir("projects/bree-target-compatibility"); - List projects = getSortedProjects(basedir); - - MavenProject project = projects.get(0); - MojoExecutionException e = assertThrows(MojoExecutionException.class, - () -> getMojo(projects, project).execute()); - // assert that the compiler mojo checks the target levels of all BREEs (and not just the first or "minimal" one) - assertThat(e.getMessage(), containsString( - "The effective compiler target level 1.5 is incompatible with the following OSGi execution environments")); - assertThat(e.getMessage(), containsString("J2SE-1.2")); - assertThat(e.getMessage(), containsString("CDC-1.0/Foundation-1.0")); - assertThat(e.getMessage(), containsString("OSGi/Minimum-1.2")); - assertThat(e.getMessage(), not(containsString("JavaSE-1.6"))); - } - - public void test386210_compilerConfigurationCrosstalk() throws Exception { - File basedir = getBasedir("projects/crosstalk"); - List projects = getSortedProjects(basedir); - - getMojo(projects, projects.get(1)).execute(); - getMojo(projects, projects.get(2)).execute(); - } - - public void testCompilerLogWithMultiJarInSingleDirectory() throws Exception { - File basedir = getBasedir("projects/logs/multiJarSingleDir"); - List projects = getSortedProjects(basedir); - MavenProject project = projects.get(0); - lookupConfiguredMojo(project, "compile").execute(); - assertTrue(new File(basedir, "target/log-dir/@dot.log").canRead()); - assertTrue(new File(basedir, "target/log-dir/library.jar.log").canRead()); - } - - public void testCompilerLogWithMultiJarInSubDirectory() throws Exception { - File basedir = getBasedir("projects/logs/multiJarMultiDir"); - List projects = getSortedProjects(basedir); - MavenProject project = projects.get(0); - lookupConfiguredMojo(project, "compile").execute(); - assertTrue(new File(basedir, "target/log-dir/@dot.log").canRead()); - assertTrue(new File(basedir, "target/log-dir/lib_library.jar.log").canRead()); - } - - public void testCompilerLogWithSingleJar() throws Exception { - File basedir = getBasedir("projects/logs/singleJar"); - List projects = getSortedProjects(basedir); - MavenProject project = projects.get(0); - lookupConfiguredMojo(project, "compile").execute(); - assertTrue(new File(basedir, "target/log-dir/@dot.xml").canRead()); - } - - public void testCompilerLogWithCustomComilerArgs() throws Exception { - File basedir = getBasedir("projects/logs/customCompilerArgs"); - List projects = getSortedProjects(basedir); - MavenProject project = projects.get(0); - lookupConfiguredMojo(project, "compile").execute(); - assertTrue(new File(basedir, "target/@dot.xml").canRead()); - } - - public void testCompilerLogWithCustomComilerArgsAndLog() throws Exception { - File basedir = getBasedir("projects/logs/customCompilerArgsAndLog"); - List projects = getSortedProjects(basedir); - MavenProject project = projects.get(0); - MojoFailureException e = assertThrows(MojoFailureException.class, - () -> lookupConfiguredMojo(project, "compile").execute()); - assertThat(e.getMessage(), containsString("Compiler logging is configured by the 'log' compiler" - + " plugin parameter and the custom compiler argument '-log'. Only either of them is allowed.")); - } - - public void testJreCompilationProfile() throws Exception { - File basedir = getBasedir("projects/jreCompilationProfile"); - List projects = getSortedProjects(basedir); - MavenProject project = projects.get(0); - AbstractOsgiCompilerMojo mojo = getMojo(Collections.singletonList(project), project); - mojo.execute(); - assertEquals("1.8", mojo.getSourceLevel()); - assertEquals("1.8", mojo.getTargetLevel()); - assertBytecodeMajorLevel(TARGET_1_8, new File(project.getBasedir(), "target/classes/Test.class")); - } - - public void testUseJDKBREE() throws Exception { - File basedir = getBasedir("projects/useJDKBREE"); - List projects = getSortedProjects(basedir); - MavenProject project = projects.get(0); - AbstractOsgiCompilerMojo mojo = getMojo(Collections.singletonList(project), project); - try { - mojo.execute(); - fail("Mojo should fail because of missing toolchains"); - } catch (MojoExecutionException ex) { - assertThat(ex.getMessage(), Matchers.allOf(StringContains.containsStringIgnoringCase("toolchain"), - StringContains.containsString("JavaSE-1.8"))); - } - } -} diff --git a/tycho-core/src/test/java/org/eclipse/tycho/core/ee/ExecutionEnvironmentTest.java b/tycho-core/src/test/java/org/eclipse/tycho/core/ee/ExecutionEnvironmentTest.java deleted file mode 100644 index ee323331ec..0000000000 --- a/tycho-core/src/test/java/org/eclipse/tycho/core/ee/ExecutionEnvironmentTest.java +++ /dev/null @@ -1,40 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2020 Red Hat Inc., and others. - * This program and the accompanying materials - * are made available under the terms of the Eclipse Public License 2.0 - * which accompanies this distribution, and is available at - * https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - *******************************************************************************/ -package org.eclipse.tycho.core.ee; - -import java.io.File; -import java.util.Optional; - -import org.apache.maven.project.MavenProject; -import org.eclipse.tycho.ExecutionEnvironmentConfiguration; -import org.eclipse.tycho.ReactorProject; -import org.eclipse.tycho.TychoConstants; -import org.eclipse.tycho.core.osgitools.DefaultReactorProject; -import org.eclipse.tycho.testing.AbstractTychoMojoTestCase; - -public class ExecutionEnvironmentTest extends AbstractTychoMojoTestCase { - - public void testTargetJRE() throws Exception { - File basedir = getBasedir("projects/targetJRE"); - Optional project = getSortedProjects(basedir).stream().filter(p -> p.getName().equals("bundle")) - .findAny(); - assertEquals("JavaSE-1.7", - getExecutionEnvironmentConfiguration(DefaultReactorProject.adapt(project.get())).getProfileName()); - } - - public static ExecutionEnvironmentConfiguration getExecutionEnvironmentConfiguration(ReactorProject project) { - ExecutionEnvironmentConfiguration storedConfig = (ExecutionEnvironmentConfiguration) project - .getContextValue(TychoConstants.CTX_EXECUTION_ENVIRONMENT_CONFIGURATION); - if (storedConfig == null) { - throw new IllegalStateException(project.toString()); - } - return storedConfig; - } -} diff --git a/tycho-core/src/test/java/org/eclipse/tycho/core/osgitools/EquinoxResolverTest.java b/tycho-core/src/test/java/org/eclipse/tycho/core/osgitools/EquinoxResolverTest.java deleted file mode 100644 index f8f43b9edf..0000000000 --- a/tycho-core/src/test/java/org/eclipse/tycho/core/osgitools/EquinoxResolverTest.java +++ /dev/null @@ -1,142 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012, 2022 Sonatype Inc. and others. - * This program and the accompanying materials - * are made available under the terms of the Eclipse Public License 2.0 - * which accompanies this distribution, and is available at - * https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Sonatype Inc. - initial API and implementation - * Christoph Läubrich - adjust to new API - *******************************************************************************/ -package org.eclipse.tycho.core.osgitools; - -import java.io.File; -import java.io.IOException; -import java.util.List; -import java.util.Properties; - -import org.apache.maven.plugin.testing.SilentLog; -import org.apache.maven.project.MavenProject; -import org.eclipse.osgi.container.Module; -import org.eclipse.osgi.container.ModuleContainer; -import org.eclipse.tycho.ExecutionEnvironment; -import org.eclipse.tycho.ExecutionEnvironmentConfiguration; -import org.eclipse.tycho.ReactorProject; -import org.eclipse.tycho.TychoConstants; -import org.eclipse.tycho.core.ee.ExecutionEnvironmentUtils; -import org.eclipse.tycho.core.osgitools.targetplatform.DefaultDependencyArtifacts; -import org.eclipse.tycho.testing.AbstractTychoMojoTestCase; -import org.eclipse.tycho.version.TychoVersion; -import org.osgi.framework.BundleException; -import org.osgi.framework.Constants; -import org.osgi.framework.wiring.BundleRevision; - -public class EquinoxResolverTest extends AbstractTychoMojoTestCase { - private static final ExecutionEnvironment DUMMY_EE = ExecutionEnvironmentUtils.getExecutionEnvironment("J2SE-1.5", - null, null, new SilentLog()); - - private EquinoxResolver subject; - - @Override - protected void setUp() throws Exception { - super.setUp(); - - subject = (EquinoxResolver) lookup(DependenciesResolver.class, EquinoxResolver.HINT); - } - - @Override - protected void tearDown() throws Exception { - subject = null; - - super.tearDown(); - } - - public void test_noSystemBundle() throws BundleException { - Properties properties = subject.getPlatformProperties(new Properties(), null, null, DUMMY_EE); - ModuleContainer container = subject.newState(new DefaultDependencyArtifacts(), properties, null, null, - new EquinoxResolverConfiguration()); - assertEquals(1, container.getModules().stream().map(Module::getCurrentRevision) - .map(BundleRevision::getSymbolicName).filter(Constants.SYSTEM_BUNDLE_SYMBOLICNAME::equals).count()); - } - - public void testBREEJavaSE11() throws Exception { - MavenProject javaSE10Project = getProject("projects/javase-11"); - assertEquals("executionenvironment.javase11", javaSE10Project.getArtifactId()); - ReactorProject reactorProject = DefaultReactorProject.adapt(javaSE10Project); - ExecutionEnvironment ee = getExecutionEnvironmentConfiguration(reactorProject).getFullSpecification(); - assertEquals("JavaSE-" + Runtime.version().feature(), ee.getProfileName()); - Properties platformProperties = subject.getPlatformProperties(reactorProject, null, - new DefaultDependencyArtifacts(), ee); - String executionEnvironments = platformProperties.getProperty("org.osgi.framework.executionenvironment"); - assertTrue(executionEnvironments.contains("JavaSE-10")); - String capabilities = platformProperties.getProperty("org.osgi.framework.system.capabilities"); - assertTrue(capabilities.contains( - "osgi.ee=\"JavaSE\"; version:List=\"1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 9.0, 10.0, 11.0")); - } - - public void testBuildFrameworkBundle() throws Exception { - MavenProject javaSE10Project = getProject("projects/frameworkBundle/org.eclipse.osgi"); - assertEquals("org.eclipse.osgi", javaSE10Project.getArtifactId()); -// ReactorProject reactorProject = DefaultReactorProject.adapt(javaSE10Project); -// ExecutionEnvironment ee = TychoProjectUtils.getExecutionEnvironmentConfiguration(reactorProject) -// .getFullSpecification(); -// assertEquals("JavaSE-11", ee.getProfileName()); -// Properties platformProperties = subject.getPlatformProperties(reactorProject, null, -// new DefaultDependencyArtifacts(), ee); -// String executionEnvironments = platformProperties.getProperty("org.osgi.framework.executionenvironment"); -// assertTrue(executionEnvironments.contains("JavaSE-10")); -// String capabilities = platformProperties.getProperty("org.osgi.framework.system.capabilities"); -// assertTrue(capabilities.contains( -// "osgi.ee=\"JavaSE\"; version:List=\"1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 9.0, 10.0, 11.0\"")); - } - - public static ExecutionEnvironmentConfiguration getExecutionEnvironmentConfiguration(ReactorProject project) { - ExecutionEnvironmentConfiguration storedConfig = (ExecutionEnvironmentConfiguration) project - .getContextValue(TychoConstants.CTX_EXECUTION_ENVIRONMENT_CONFIGURATION); - if (storedConfig == null) { - throw new IllegalStateException(project.toString()); - } - return storedConfig; - } - - public void testBundleNativeCode() throws IOException, Exception { - MavenProject project = getProject("projects/bundleNativeCode/bundleWithNativeCode"); - assertEquals("test.bundleNativeCode", project.getArtifactId()); - } - - public void testBundleNativeCode_usingAliases() throws IOException, Exception { - // This project uses the alias "Win10" for the "Windows10" osname, and "amd64" as alias for the "x86-64" processor. - // The processor-alias "x86_64" is probably more common but the difference between hyphen and underscore is hard to spot. - MavenProject project = getProject("projects/bundleNativeCode/bundleWithNativeCodeUsingAliases"); - assertEquals("test.bundleNativeCode.using.aliases", project.getArtifactId()); - } - - //currently do not work anymore! - public void testBundleNativeCode_usingInvalidAliases() throws IOException, Exception { - // Negative test to check that a project with invalid aliases fails to resolve -// try { -// getProject("projects/bundleNativeCode/bundleWithNativeCodeUsingInvalidAliases"); -// fail("Project must not resolve"); -// } catch (CompoundRuntimeException e) { -// assertThat(e.getMessage(), containsString( -// "Unresolved requirement: Require-Capability: osgi.native; native.paths:List=\"/lib/dummyLib.dll\"; filter:=\"(&(osgi.native.osname~=theBestOS)(osgi.native.processor~=x43))\"")); -// } - } - - // --- uility methods --- - - private MavenProject getProject(String path) throws IOException, Exception { - File basedir = getBasedir(path); - - Properties properties = new Properties(); - properties.put("tycho-version", TychoVersion.getTychoVersion()); - - List projects = getSortedProjects(basedir, properties); - assertEquals(1, projects.size()); - - return projects.get(0); - } -} diff --git a/tycho-core/src/test/java/org/eclipse/tycho/core/resolver/DefaultTargetPlatformConfigurationReaderTest.java b/tycho-core/src/test/java/org/eclipse/tycho/core/resolver/DefaultTargetPlatformConfigurationReaderTest.java deleted file mode 100644 index d87fad8ca3..0000000000 --- a/tycho-core/src/test/java/org/eclipse/tycho/core/resolver/DefaultTargetPlatformConfigurationReaderTest.java +++ /dev/null @@ -1,157 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014, 2021 Bachmann electronics GmbH and others. - * This program and the accompanying materials - * are made available under the terms of the Eclipse Public License 2.0 - * which accompanies this distribution, and is available at - * https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Bachmann electronics GmbH - initial API and implementation - * Christoph Läubrich - Adjust to changed API - *******************************************************************************/ -package org.eclipse.tycho.core.resolver; - -import static org.junit.Assert.assertThrows; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import java.io.File; -import java.util.Arrays; - -import org.apache.maven.execution.MavenSession; -import org.apache.maven.plugin.MojoExecutionException; -import org.apache.maven.project.MavenProject; -import org.codehaus.plexus.util.xml.Xpp3Dom; -import org.eclipse.tycho.BuildFailureException; -import org.eclipse.tycho.core.TargetPlatformConfiguration; -import org.eclipse.tycho.testing.AbstractTychoMojoTestCase; -import org.junit.Test; - -public class DefaultTargetPlatformConfigurationReaderTest extends AbstractTychoMojoTestCase { - - private DefaultTargetPlatformConfigurationReader configurationReader; - - @Override - protected void setUp() throws Exception { - super.setUp(); - configurationReader = lookup(DefaultTargetPlatformConfigurationReader.class); - } - - @Override - protected void tearDown() throws Exception { - configurationReader = null; - super.tearDown(); - } - - @Test - public void testExtraRequirementMissingVersionRange() throws Exception { - Xpp3Dom dom = createConfigurationDom("type", "id"); - BuildFailureException e = assertThrows(BuildFailureException.class, - () -> configurationReader.readExtraRequirements(new TargetPlatformConfiguration(), dom)); - assertTrue(e.getMessage() - .contains("Element is missing in section.")); - } - - @Test - public void testExtraRequirementMissingType() throws Exception { - Xpp3Dom dom = createConfigurationDom("id", "versionRange"); - BuildFailureException e = assertThrows(BuildFailureException.class, - () -> configurationReader.readExtraRequirements(new TargetPlatformConfiguration(), dom)); - assertTrue(e.getMessage().contains("Element is missing in section.")); - } - - @Test - public void testExtraRequirementId() throws Exception { - Xpp3Dom dom = createConfigurationDom("type", "versionRange"); - BuildFailureException e = assertThrows(BuildFailureException.class, - () -> configurationReader.readExtraRequirements(new TargetPlatformConfiguration(), dom)); - assertTrue(e.getMessage().contains("Element is missing in section.")); - } - - @Test - public void testAddTargetWithMissingVersionInTargetDefinition() throws MojoExecutionException { - Xpp3Dom dom = createGavConfiguration("myGroupId", "myArtifactId", null); - MavenSession session = setupMockSession(); - TargetPlatformConfiguration configuration = new TargetPlatformConfiguration(); - TargetPlatformConfigurationException e = assertThrows(TargetPlatformConfigurationException.class, - () -> configurationReader.addTargetArtifact(configuration, session, null, dom)); - assertTrue(e.getMessage().contains("The target artifact configuration is invalid")); - } - - @Test - public void testAddTargetWithMissingGroupInTargetDefinition() throws MojoExecutionException { - Xpp3Dom dom = createGavConfiguration(null, "myArtifactId", "myVersion"); - MavenSession session = setupMockSession(); - TargetPlatformConfiguration configuration = new TargetPlatformConfiguration(); - TargetPlatformConfigurationException e = assertThrows(TargetPlatformConfigurationException.class, - () -> configurationReader.addTargetArtifact(configuration, session, null, dom)); - assertTrue(e.getMessage().contains("The target artifact configuration is invalid")); - } - - @Test - public void testAddTargetWithMissingArtifactIdInTargetDefinition() throws MojoExecutionException { - Xpp3Dom dom = createGavConfiguration("myGroupId", null, "myVersion"); - MavenSession session = setupMockSession(); - TargetPlatformConfiguration configuration = new TargetPlatformConfiguration(); - TargetPlatformConfigurationException e = assertThrows(TargetPlatformConfigurationException.class, - () -> configurationReader.addTargetArtifact(configuration, session, null, dom)); - assertTrue(e.getMessage().contains("The target artifact configuration is invalid")); - } - - @Test - public void testOptionalResolution() throws MojoExecutionException { - Xpp3Dom dom = createConfigurationDom(); - Xpp3Dom res = new Xpp3Dom(DefaultTargetPlatformConfigurationReader.DEPENDENCY_RESOLUTION); - Xpp3Dom opt = new Xpp3Dom(DefaultTargetPlatformConfigurationReader.OPTIONAL_DEPENDENCIES); - opt.setValue("optional"); - res.addChild(opt); - dom.addChild(res); - configurationReader.readDependencyResolutionConfiguration(new TargetPlatformConfiguration(), dom, null); - } - - private MavenSession setupMockSession() { - MavenSession session = mock(MavenSession.class); - MavenProject project = mock(MavenProject.class); - when(session.getProjects()).thenReturn(Arrays.asList(project)); - when(project.getGroupId()).thenReturn("myGroupId"); - when(project.getArtifactId()).thenReturn("myArtifactId"); - when(project.getVersion()).thenReturn("myVersion"); - when(project.getBasedir()).thenReturn(new File("/basedir/")); - return session; - } - - private Xpp3Dom createGavConfiguration(String groupId, String artifactId, String version) { - Xpp3Dom dom = new Xpp3Dom("artifact"); - if (groupId != null) { - Xpp3Dom group = new Xpp3Dom("groupId"); - group.setValue(groupId); - dom.addChild(group); - } - if (artifactId != null) { - Xpp3Dom artifact = new Xpp3Dom("artifactId"); - artifact.setValue(artifactId); - dom.addChild(artifact); - } - if (version != null) { - Xpp3Dom ver = new Xpp3Dom("version"); - ver.setValue(version); - dom.addChild(ver); - } - return dom; - } - - private Xpp3Dom createConfigurationDom(String... requirementChildren) { - Xpp3Dom dom = new Xpp3Dom("configuration"); - Xpp3Dom extraRequirements = new Xpp3Dom("extraRequirements"); - Xpp3Dom requirement = new Xpp3Dom("requirement"); - extraRequirements.addChild(requirement); - dom.addChild(extraRequirements); - for (String requirementChild : requirementChildren) { - requirement.addChild(new Xpp3Dom(requirementChild)); - } - return dom; - } - -} diff --git a/tycho-core/src/test/java/org/eclipse/tycho/core/test/DependencyComputerTest.java b/tycho-core/src/test/java/org/eclipse/tycho/core/test/DependencyComputerTest.java deleted file mode 100644 index 5e7a9eac07..0000000000 --- a/tycho-core/src/test/java/org/eclipse/tycho/core/test/DependencyComputerTest.java +++ /dev/null @@ -1,330 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008, 2021 Sonatype Inc. and others. - * This program and the accompanying materials - * are made available under the terms of the Eclipse Public License 2.0 - * which accompanies this distribution, and is available at - * https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Sonatype Inc. - initial API and implementation - *******************************************************************************/ -package org.eclipse.tycho.core.test; - -import static java.util.Arrays.asList; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.hasItem; -import static org.junit.Assert.assertArrayEquals; - -import java.io.File; -import java.util.Arrays; -import java.util.Collection; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Properties; -import java.util.Set; -import java.util.stream.Collectors; - -import org.apache.maven.execution.MavenExecutionRequest; -import org.apache.maven.execution.MavenExecutionResult; -import org.apache.maven.plugin.testing.SilentLog; -import org.apache.maven.project.MavenProject; -import org.eclipse.osgi.container.ModuleContainer; -import org.eclipse.osgi.container.ModuleRevision; -import org.eclipse.tycho.ClasspathEntry.AccessRule; -import org.eclipse.tycho.SystemCapability.Type; -import org.eclipse.tycho.DependencyArtifacts; -import org.eclipse.tycho.ExecutionEnvironment; -import org.eclipse.tycho.ExecutionEnvironmentConfiguration; -import org.eclipse.tycho.ReactorProject; -import org.eclipse.tycho.SystemCapability; -import org.eclipse.tycho.TychoConstants; -import org.eclipse.tycho.core.ee.CustomExecutionEnvironment; -import org.eclipse.tycho.core.ee.ExecutionEnvironmentUtils; -import org.eclipse.tycho.core.osgitools.DefaultReactorProject; -import org.eclipse.tycho.core.osgitools.DependenciesResolver; -import org.eclipse.tycho.core.osgitools.DependencyComputer; -import org.eclipse.tycho.core.osgitools.DependencyComputer.DependencyEntry; -import org.eclipse.tycho.test.util.MavenSessionUtils; -import org.eclipse.tycho.core.osgitools.EquinoxResolver; -import org.eclipse.tycho.testing.AbstractTychoMojoTestCase; -import org.eclipse.tycho.version.TychoVersion; -import org.junit.Assert; -import org.junit.Test; -import org.osgi.framework.BundleException; -import org.osgi.framework.Constants; - -public class DependencyComputerTest extends AbstractTychoMojoTestCase { - private DependencyComputer dependencyComputer; - private EquinoxResolver resolver; - - @Override - protected void setUp() throws Exception { - super.setUp(); - dependencyComputer = lookup(DependencyComputer.class); - resolver = (EquinoxResolver) lookup(DependenciesResolver.class, EquinoxResolver.HINT); - } - - @Override - protected void tearDown() throws Exception { - dependencyComputer = null; - super.tearDown(); - } - - @Test - public void testExportPackage() throws Exception { - File basedir = getBasedir("projects/exportpackage"); - - Map basedirMap = MavenSessionUtils.getBasedirMap(getSortedProjects(basedir)); - - MavenProject project = basedirMap.get(new File(basedir, "bundle")); - ReactorProject reactorProject = DefaultReactorProject.adapt(project); - DependencyArtifacts platform = (DependencyArtifacts) reactorProject - .getContextValue(TychoConstants.CTX_DEPENDENCY_ARTIFACTS); - - ExecutionEnvironment executionEnvironment = getExecutionEnvironmentConfiguration(reactorProject) - .getFullSpecification(); - ModuleContainer state = resolver.newResolvedState(reactorProject, null, executionEnvironment, platform); - ModuleRevision bundle = state.getModule(project.getBasedir().getAbsolutePath()).getCurrentRevision(); - - List dependencies = dependencyComputer.computeDependencies(bundle); - Assert.assertEquals(3, dependencies.size()); - Assert.assertEquals("dep", dependencies.get(0).getSymbolicName()); - Assert.assertEquals("dep2", dependencies.get(1).getSymbolicName()); - Assert.assertEquals("dep3", dependencies.get(2).getSymbolicName()); - Assert.assertTrue(dependencies.get(2).rules.isEmpty()); - } - - public static ExecutionEnvironmentConfiguration getExecutionEnvironmentConfiguration(ReactorProject project) { - ExecutionEnvironmentConfiguration storedConfig = (ExecutionEnvironmentConfiguration) project - .getContextValue(TychoConstants.CTX_EXECUTION_ENVIRONMENT_CONFIGURATION); - if (storedConfig == null) { - throw new IllegalStateException(project.toString()); - } - return storedConfig; - } - - @Test - public void testTYCHO0378unwantedSelfDependency() throws Exception { - File basedir = getBasedir("projects/TYCHO0378unwantedSelfDependency"); - File pom = new File(basedir, "pom.xml"); - MavenExecutionRequest request = newMavenExecutionRequest(pom); - request.getProjectBuildingRequest().setProcessPlugins(false); - MavenExecutionResult result = maven.execute(request); - - Assert.assertEquals(0, result.getProject().getDependencies().size()); - } - - // TODO code reuse - @Test - public void testWiringToPackageFromCustomProfile() throws Exception { - File basedir = getBasedir("projects/customProfile"); - - Map basedirMap = MavenSessionUtils.getBasedirMap(getSortedProjects(basedir)); - - MavenProject project = basedirMap.get(new File(basedir, "bundle")); - ReactorProject reactorProject = DefaultReactorProject.adapt(project); - DependencyArtifacts platform = (DependencyArtifacts) reactorProject - .getContextValue(TychoConstants.CTX_DEPENDENCY_ARTIFACTS); - - CustomExecutionEnvironment customProfile = new CustomExecutionEnvironment("custom", - Arrays.asList(new SystemCapability(Type.JAVA_PACKAGE, "package.historically.not.in.jdk", "1.2.1"), // - new SystemCapability(Type.OSGI_EE, "OSGi/Minimum", "1.0.0"), // - new SystemCapability(Type.OSGI_EE, "JavaSE", "1.0.0"), // - new SystemCapability(Type.OSGI_EE, "JavaSE", "1.1.0"), // - new SystemCapability(Type.OSGI_EE, "JavaSE", "1.2.0"))); - - ModuleContainer state = resolver.newResolvedState(reactorProject, null, customProfile, platform); - ModuleRevision bundle = state.getModule(project.getBasedir().getAbsolutePath()).getCurrentRevision(); - - List dependencies = dependencyComputer.computeDependencies(bundle); - - if (dependencies.size() > 0) { - assertEquals(1, dependencies.size()); - assertEquals(Constants.SYSTEM_BUNDLE_SYMBOLICNAME, dependencies.get(0).getSymbolicName()); - } - } - - @Test - public void testStrictBootClasspathAccessRules() throws Exception { - Properties properties = new Properties(); - properties.setProperty("tycho-version", TychoVersion.getTychoVersion()); - File basedir = getBasedir("projects/bootclasspath"); - Map basedirMap = MavenSessionUtils.getBasedirMap(getSortedProjects(basedir, properties)); - // 1. bundle importing a JRE package only - MavenProject bundle1Project = basedirMap.get(new File(basedir, "bundle1")); - List bundle1Dependencies = computeDependencies(bundle1Project); - assertEquals(1, bundle1Dependencies.size()); - DependencyEntry dependency = bundle1Dependencies.get(0); - assertEquals(1, dependency.rules.size()); - assertEquals("javax/net/ssl/*", dependency.rules.iterator().next().getPattern()); - - // 2. bundle importing both a JRE package and an OSGi framework package - MavenProject bundle2Project = basedirMap.get(new File(basedir, "bundle2")); - List bundle2Dependencies = computeDependencies(bundle2Project); - assertEquals(1, bundle2Dependencies.size()); - DependencyEntry dependencyBundle2 = bundle2Dependencies.get(0); - Set accessRules = new HashSet<>(); - for (AccessRule rule : dependencyBundle2.rules) { - accessRules.add(rule.getPattern()); - } - assertEquals(new HashSet<>(asList("javax/net/ssl/*", "org/osgi/framework/*")), accessRules); - } - - private List computeDependencies(MavenProject project) throws BundleException { - DependencyArtifacts platform = (DependencyArtifacts) DefaultReactorProject.adapt(project) - .getContextValue(TychoConstants.CTX_DEPENDENCY_ARTIFACTS); - ModuleContainer state = resolver.newResolvedState(DefaultReactorProject.adapt(project), null, - ExecutionEnvironmentUtils.getExecutionEnvironment("J2SE-1.4", null, null, new SilentLog()), platform); - ModuleRevision bundle = state.getModule(project.getBasedir().getAbsolutePath()).getCurrentRevision(); - return dependencyComputer.computeDependencies(bundle); - } - - private List computeDependenciesIgnoringEE(MavenProject project) throws BundleException { - DependencyArtifacts platform = (DependencyArtifacts) DefaultReactorProject.adapt(project) - .getContextValue(TychoConstants.CTX_DEPENDENCY_ARTIFACTS); - ModuleContainer state = resolver.newResolvedState(DefaultReactorProject.adapt(project), null, null, platform); - ModuleRevision bundle = state.getModule(project.getBasedir().getAbsolutePath()).getCurrentRevision(); - return dependencyComputer.computeDependencies(bundle); - } - - @Test - public void testAccessRules() throws Exception { - File basedir = getBasedir("projects/accessrules"); - MavenProject project = getProjectWithName(getSortedProjects(basedir), "p002"); - List dependencies = computeDependencies(project); - assertEquals(3, dependencies.size()); - assertArrayEquals(new String[] { "p001/*" }, getAccessRulePatterns(dependencies, "p001")); - assertArrayEquals(new String[] { "p003/*" }, getAccessRulePatterns(dependencies, "p003")); - assertArrayEquals(new String[] { "p004/*" }, getAccessRulePatterns(dependencies, "p004")); - } - - @Test - public void testReexportAccessRules() throws Exception { - File basedir = getBasedir("projects/reexport"); - MavenProject project = getProjectWithName(getSortedProjects(basedir), "p002"); - List dependencies = computeDependencies(project); - assertEquals(3, dependencies.size()); - assertArrayEquals(new String[] { "p001/*" }, getAccessRulePatterns(dependencies, "p001")); - // next one should be accessible because p001 reexports - assertArrayEquals(new String[] { "p003/*" }, getAccessRulePatterns(dependencies, "p003")); - assertArrayEquals(new String[] { "p004/*" }, getAccessRulePatterns(dependencies, "p004")); - } - - @Test -// @Ignore("currently that code do not work anymore in Tycho") - public void testFragments() throws Exception { -// File basedir = getBasedir("projects/eeProfile.resolution.fragments"); -// MavenProject jface = getProjectWithArtifactId(getSortedProjects(basedir), "org.eclipse.jface.databinding"); -// assertEquals("org.eclipse.jface.databinding", jface.getArtifactId()); -// Collection deps = computeDependenciesIgnoringEE(jface); -// assertTrue(deps.stream().filter(entry -> entry.module.getSymbolicName().equals("org.eclipse.swt.gtk.linux.x86")) // -// .flatMap(entry -> entry.rules.stream()) // -// .filter(accessRule -> !accessRule.isDiscouraged()) // -// .filter(accessRule -> accessRule.getPattern().startsWith("org/eclipse/swt/graphics")) // -// .findAny() // -// .isPresent()); - } - - @Test - public void testFragmentsImportClassProvidedByFragmentFromPackageExportedByHost() throws Exception { - File basedir = getBasedir("projects/fragment-import-class-provided-by-fragment-from-package-exported-by-host"); - MavenProject bundle2 = getProjectWithArtifactId(getSortedProjects(basedir), "bundle2"); - Collection deps = computeDependenciesIgnoringEE(bundle2); - assertThat(deps.stream().filter(entry -> entry.getSymbolicName().equals("bundle1.fragment")) // - .flatMap(entry -> entry.rules.stream()) // - .map(rule -> rule.getPattern()) // - .toList(), // - hasItem("bundle1/*")); - } - - @Test -// @Ignore("currently that code do not work anymore in Tycho") - public void testFragmentSplitPackage() throws Exception { -// File basedir = getBasedir("projects/fragment-split-package"); -// MavenProject bundleTest = getProjectWithArtifactId(getSortedProjects(basedir), "bundle.tests"); -// Collection deps = computeDependencies(bundleTest); -// assertTrue(deps.stream().filter(entry -> entry.module.getSymbolicName().equals("bundle")) // -// .flatMap(entry -> entry.rules.stream()) // -// .filter(accessRule -> !accessRule.isDiscouraged()) // -// .filter(accessRule -> accessRule.getPattern().startsWith("split")) // -// .findAny() // -// .isPresent()); -// assertTrue(deps.stream().filter(entry -> entry.module.getSymbolicName().equals("fragment")) // -// .flatMap(entry -> entry.rules.stream()) // -// .filter(accessRule -> !accessRule.isDiscouraged()) // -// .filter(accessRule -> accessRule.getPattern().startsWith("split")) // -// .findAny() // -// .isPresent()); - } - - @Test - public void testFragmentSplitPackageMandatory() throws Exception { - File basedir = getBasedir("projects/fragment-split-mandatory"); - MavenProject bundleTest = getProjectWithArtifactId(getSortedProjects(basedir), "bundle.tests"); - Collection deps = computeDependencies(bundleTest); - assertTrue(deps.stream().filter(entry -> entry.getSymbolicName().equals("bundle")) // - .flatMap(entry -> entry.rules.stream()) // - .filter(accessRule -> !accessRule.isDiscouraged()) // - .filter(accessRule -> accessRule.getPattern().startsWith("split")) // - .findAny() // - .isPresent()); - assertTrue(deps.stream().filter(entry -> entry.getSymbolicName().equals("fragment")) // - .flatMap(entry -> entry.rules.stream()) // - .filter(accessRule -> !accessRule.isDiscouraged()) // - .filter(accessRule -> accessRule.getPattern().startsWith("split")) // - .findAny() // - .isPresent()); - } - - @Test - public void testImportVsRequire() throws Exception { - File basedir = getBasedir("projects/importVsRequire"); - MavenProject bundleTest = getProjectWithArtifactId(getSortedProjects(basedir), "A"); - Collection deps = computeDependencies(bundleTest); - Collection patterns = deps.stream().filter(entry -> entry.getSymbolicName().equals("B")) // - .flatMap(entry -> entry.rules.stream()) // - .filter(accessRule -> !accessRule.isDiscouraged()) // - .map(AccessRule::getPattern) // - .collect(Collectors.toSet()); - assertTrue(patterns.stream().anyMatch(pattern -> pattern.startsWith("b1"))); - assertTrue(patterns.stream().anyMatch(pattern -> pattern.startsWith("b2"))); - } - - @Test - public void testDeepReexportBundle() throws Exception { - File basedir = getBasedir("projects/deepReexport"); - MavenProject bundleTest = getProjectWithArtifactId(getSortedProjects(basedir), "D"); - Collection deps = computeDependencies(bundleTest); - Collection patterns = deps.stream() // - .flatMap(entry -> entry.rules.stream()) // - .filter(accessRule -> !accessRule.isDiscouraged()) // - .map(AccessRule::getPattern) // - .collect(Collectors.toSet()); - assertTrue(patterns.stream().anyMatch(pattern -> pattern.startsWith("a"))); - assertTrue(patterns.stream().anyMatch(pattern -> pattern.startsWith("b"))); - assertTrue(patterns.stream().anyMatch(pattern -> pattern.startsWith("c"))); - } - - private String[] getAccessRulePatterns(List dependencies, String moduleName) { - String[] p001accessRulesPatterns = dependencies.stream().filter(dep -> dep.getSymbolicName().equals(moduleName)) // - .flatMap(dep -> dep.rules.stream()) // - .map(AccessRule::getPattern) // - .toArray(String[]::new); - return p001accessRulesPatterns; - } - - @Test - public void testFragmentRequiredBundle() throws Exception { - File basedir = getBasedir("projects/fragment"); - MavenProject fragment = getProjectWithArtifactId(getSortedProjects(basedir), "fragment"); - Collection deps = computeDependencies(fragment); - assertTrue(deps.stream().filter(dep -> dep.getSymbolicName().equals("dep")) // - .flatMap(dep -> dep.rules.stream()) // - .filter(rule -> !rule.isDiscouraged()) // - .map(AccessRule::getPattern) // - .anyMatch(pack -> pack.startsWith("pack/"))); - } -} diff --git a/tycho-core/src/test/java/org/eclipse/tycho/core/test/MavenDependencyCollectorTest.java b/tycho-core/src/test/java/org/eclipse/tycho/core/test/MavenDependencyCollectorTest.java deleted file mode 100644 index 1eefc74a00..0000000000 --- a/tycho-core/src/test/java/org/eclipse/tycho/core/test/MavenDependencyCollectorTest.java +++ /dev/null @@ -1,195 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2010, 2011 SAP AG and others. - * This program and the accompanying materials - * are made available under the terms of the Eclipse Public License 2.0 - * which accompanies this distribution, and is available at - * https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * SAP AG - initial API and implementation - *******************************************************************************/ -package org.eclipse.tycho.core.test; - -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Properties; - -import org.apache.maven.artifact.Artifact; -import org.apache.maven.execution.MavenExecutionRequest; -import org.apache.maven.execution.MavenExecutionResult; -import org.apache.maven.model.Dependency; -import org.apache.maven.project.MavenProject; -import org.eclipse.tycho.testing.AbstractTychoMojoTestCase; -import org.eclipse.tycho.testing.CompoundRuntimeException; -import org.eclipse.tycho.version.TychoVersion; -import org.junit.Assert; - -public class MavenDependencyCollectorTest extends AbstractTychoMojoTestCase { - - @Override - protected void setUp() throws Exception { - super.setUp(); - } - - public void testNestedJars() throws Exception { - getBasedir("targetplatforms/nestedJar"); - Properties properties = new Properties(); - properties.setProperty("tycho-version", TychoVersion.getTychoVersion()); - List projects = getSortedProjects(getBasedir("projects/mavendeps"), properties); - String expectedType = "eclipse-plugin"; - { - // 1. project with dependency to external bundle with nested jar - MavenProject project = projects.get(1); - final String plainJarPath = "target/targetplatforms/nestedJar/plugins/nested_1.0.0.jar"; - final String nestedJarPath = "target/local-repo/.cache/tycho/nested_1.0.0.jar/lib/lib.jar"; - List mavenDependencies = project.getModel().getDependencies(); - Assert.assertEquals(2, mavenDependencies.size()); - final String expectedGroupId = "p2.eclipse.plugin"; - final String expectedArtifactId = "nested"; - final String expectedVersion = "1.0.0"; - final String expectedScope = Artifact.SCOPE_SYSTEM; - // assert that dependencies to both plain jar and nested jar are injected back into maven model - assertDependenciesContains(mavenDependencies, expectedGroupId, expectedArtifactId, expectedVersion, null, - expectedType, expectedScope, new File(getBasedir(), plainJarPath)); - assertDependenciesContains(mavenDependencies, expectedGroupId, expectedArtifactId, expectedVersion, - "lib/lib.jar", expectedType, expectedScope, new File(getBasedir(), nestedJarPath)); - } - { - // 2. project with checked-in nested jar - MavenProject project = projects.get(2); - List mavenDependencies = project.getModel().getDependencies(); - assertEquals(1, mavenDependencies.size()); - assertDependenciesContains(mavenDependencies, "mavenDependencies", "p002", "1.0.0", "lib/lib.jar", - expectedType, Artifact.SCOPE_SYSTEM, - new File(getBasedir("projects/mavendeps"), "p002/lib/lib.jar")); - } - { - // 3. project with dependency to bundle with nested jar within the same reactor - MavenProject project = projects.get(3); - List mavenDependencies = project.getModel().getDependencies(); - // assert that dependencies to both reactor module and checked-in nested jar are injected back into maven - // model. - // Also, dependency to missing nested jar must *not* be injected (would throw - // MavenDependencyResolutionException otherwise) - Assert.assertEquals(2, mavenDependencies.size()); - final String expectedGroupId = "mavenDependencies"; - final String expectedArtifactId = "p002"; - final String expectedVersion = "1.0.0"; - assertDependenciesContains(mavenDependencies, expectedGroupId, expectedArtifactId, expectedVersion, null, - "eclipse-plugin", Artifact.SCOPE_COMPILE, null); - assertDependenciesContains(mavenDependencies, expectedGroupId, expectedArtifactId, expectedVersion, - "lib/lib.jar", expectedType, Artifact.SCOPE_SYSTEM, - new File(getBasedir("projects/mavendeps"), "p002/lib/lib.jar")); - } - } - - public void testModuleOrderNoDotOnClasspath() throws Exception { - File pom = new File(getBasedir("projects/nodotonclasspath"), "pom.xml"); - List projects = getSortedProjects(newMavenExecutionRequest(pom)); - assertEquals(3, projects.size()); - MavenProject project1 = projects.get(1); - MavenProject project2 = projects.get(2); - Assert.assertEquals("provider", project1.getArtifactId()); - Assert.assertEquals("consumer", project2.getArtifactId()); - } - - public void testInjectDuplicateSourceFolders() throws Exception { - File pom = new File(getBasedir("projects/sourceFolders"), "pom.xml"); - List projects = getSortedProjects(newMavenExecutionRequest(pom)); - MavenProject project = projects.get(0); - List sourceRootFiles = new ArrayList<>(); - for (String compileRoot : project.getCompileSourceRoots()) { - sourceRootFiles.add(new File(compileRoot)); - } - List testRootFiles = new ArrayList<>(); - for (String testCompileRoot : project.getTestCompileSourceRoots()) { - testRootFiles.add(new File(testCompileRoot)); - } - assertTrue(Collections.disjoint(sourceRootFiles, testRootFiles)); - } - - private void assertDependenciesContains(List mavenDependencies, String groupId, String artifactId, - String version, String classifier, String type, String scope, File systemLocation) throws IOException { - for (Dependency dependency : mavenDependencies) { - boolean systemLocationEquals = true; - if (systemLocation != null) { - systemLocationEquals = dependency.getSystemPath() != null - && systemLocation.getCanonicalFile().getAbsolutePath() - .equals(new File(dependency.getSystemPath()).getCanonicalFile().getAbsolutePath()); - } - if (systemLocationEquals // - && groupId.equals(dependency.getGroupId()) // - && artifactId.equals(dependency.getArtifactId())// - && version.equals(dependency.getVersion()) // - && type.equals(dependency.getType())// - && scope.equals(dependency.getScope()) // - ) { - if (classifier == null) { - if (dependency.getClassifier() == null) { - return; - } - } else { - if (classifier.equals(dependency.getClassifier())) { - return; - } - } - } - } - Dependency dependency = new Dependency(); - dependency.setArtifactId(artifactId); - dependency.setGroupId(groupId); - dependency.setClassifier(classifier); - dependency.setVersion(version); - dependency.setType(type); - dependency.setScope(scope); - if (systemLocation != null) { - dependency.setSystemPath(systemLocation.getCanonicalPath()); - } - fail("Expected dependency \r\n" + toDebugString(dependency) + " not found in actual dependencies: \r\n" - + toDebugString(mavenDependencies)); - } - - private static String toDebugString(List mavenDependencies) { - StringBuilder sb = new StringBuilder(); - for (Dependency dependency : mavenDependencies) { - sb.append(toDebugString(dependency)); - sb.append("\r\n"); - } - return sb.toString(); - } - - private static String toDebugString(Dependency dependency) { - StringBuilder sb = new StringBuilder(); - sb.append('['); - sb.append(dependency.getGroupId()); - sb.append(':'); - sb.append(dependency.getArtifactId()); - sb.append(':'); - sb.append(dependency.getVersion()); - sb.append(':'); - sb.append(dependency.getClassifier()); - sb.append(':'); - sb.append(dependency.getType()); - sb.append(", scope: "); - sb.append(dependency.getScope()); - sb.append(", systemPath: "); - sb.append(dependency.getSystemPath()); - sb.append(']'); - return sb.toString(); - } - - private List getSortedProjects(MavenExecutionRequest request) { - request.getProjectBuildingRequest().setProcessPlugins(false); - MavenExecutionResult result = maven.execute(request); - if (result.hasExceptions()) { - throw new CompoundRuntimeException(result.getExceptions()); - } - return result.getTopologicallySortedProjects(); - } - -} diff --git a/tycho-core/src/test/java/org/eclipse/tycho/core/test/P2IUTest.java b/tycho-core/src/test/java/org/eclipse/tycho/core/test/P2IUTest.java deleted file mode 100644 index ac85c5de0d..0000000000 --- a/tycho-core/src/test/java/org/eclipse/tycho/core/test/P2IUTest.java +++ /dev/null @@ -1,48 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2015 Rapicorp, Inc. and others. - * This program and the accompanying materials - * are made available under the terms of the Eclipse Public License 2.0 - * which accompanies this distribution, and is available at - * https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Rapicorp, Inc. - initial API and implementation - *******************************************************************************/ -package org.eclipse.tycho.core.test; - -import java.io.File; -import java.util.List; - -import org.apache.maven.project.MavenProject; -import org.eclipse.tycho.testing.AbstractTychoMojoTestCase; - -// TODO 353889 make ordering work - the deprecated LocalDependencyResolver doesn't order p2-installable-unit modules -public class P2IUTest extends AbstractTychoMojoTestCase { - - public void testIUDependencies() throws Exception { - File basedir = getBasedir("iuBuildOrder/justIUs"); - List projects = getSortedProjects(basedir); - assertEquals("parent", projects.get(0).getArtifactId()); -// assertEquals("iuA", projects.get(1).getArtifactId()); -// assertEquals("iuB", projects.get(2).getArtifactId()); - } - - public void testFeatureToIUDependency() throws Exception { - File basedir = getBasedir("iuBuildOrder/featureToIU"); - List projects = getSortedProjects(basedir); - assertEquals("parent", projects.get(0).getArtifactId()); -// assertEquals("anIU", projects.get(1).getArtifactId()); -// assertEquals("featureWithIUDeps", projects.get(2).getArtifactId()); - } - - public void testIUToFeature() throws Exception { - File basedir = getBasedir("iuBuildOrder/iuToFeature"); - List projects = getSortedProjects(basedir); - assertEquals("parent", projects.get(0).getArtifactId()); -// assertEquals("aFeature", projects.get(1).getArtifactId()); -// assertEquals("anIU", projects.get(2).getArtifactId()); - } - -} diff --git a/tycho-core/src/test/java/org/eclipse/tycho/core/test/TychoTest.java b/tycho-core/src/test/java/org/eclipse/tycho/core/test/TychoTest.java deleted file mode 100644 index e4a0fba98f..0000000000 --- a/tycho-core/src/test/java/org/eclipse/tycho/core/test/TychoTest.java +++ /dev/null @@ -1,281 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008, 2020 Sonatype Inc. and others. - * This program and the accompanying materials - * are made available under the terms of the Eclipse Public License 2.0 - * which accompanies this distribution, and is available at - * https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Sonatype Inc. - initial API and implementation - *******************************************************************************/ -package org.eclipse.tycho.core.test; - -import static org.junit.Assert.assertThrows; - -import java.io.File; -import java.io.IOException; -import java.util.List; -import java.util.Properties; - -import org.apache.maven.execution.MavenSession; -import org.apache.maven.model.Dependency; -import org.apache.maven.plugin.testing.SilentLog; -import org.apache.maven.project.MavenProject; -import org.codehaus.plexus.logging.Logger; -import org.eclipse.tycho.ClasspathEntry; -import org.eclipse.tycho.TargetEnvironment; -import org.eclipse.tycho.core.TargetPlatformConfiguration; -import org.eclipse.tycho.core.TychoProject; -import org.eclipse.tycho.core.osgitools.DefaultReactorProject; -import org.eclipse.tycho.core.osgitools.OsgiBundleProject; -import org.eclipse.tycho.core.resolver.DefaultTargetPlatformConfigurationReader; -import org.eclipse.tycho.core.resolver.TargetPlatformConfigurationException; -import org.eclipse.tycho.p2.resolver.ResolverException; -import org.eclipse.tycho.testing.AbstractTychoMojoTestCase; -import org.eclipse.tycho.version.TychoVersion; - -public class TychoTest extends AbstractTychoMojoTestCase { - - protected Logger logger; - private Properties properties; - - @Override - protected void setUp() throws Exception { - super.setUp(); - logger = new SilentLog(); - properties = new Properties(); - properties.setProperty("tycho-version", TychoVersion.getTychoVersion()); - } - - @Override - protected void tearDown() throws Exception { - logger = null; - super.tearDown(); - } - - public void testModuleOrder() throws Exception { - File basedir = getBasedir("projects/moduleorder"); - - List projects = getSortedProjects(basedir); - assertEquals(5, projects.size()); - - MavenProject p002 = projects.get(1); - MavenProject p001 = projects.get(2); - MavenProject p004 = projects.get(3); // feature - MavenProject p003 = projects.get(4); // site - - assertEquals("moduleorder.p001", p001.getArtifactId()); - assertEquals("moduleorder.p002", p002.getArtifactId()); - assertEquals("moduleorder.p003", p003.getArtifactId()); - assertEquals("moduleorder.p004", p004.getArtifactId()); - } - - public void testResolutionError() throws Exception { - File basedir = getBasedir("projects/resolutionerror/p001"); - - Exception e = assertThrows(Exception.class, () -> getSortedProjects(basedir)); - assertResolveError(e, - "Missing requirement: moduleorder.p001 0.0.1 requires 'java.package; moduleorder.p002 0.0.0' but it could not be found"); - } - - private void assertResolveError(Throwable e, String string) { - if (e instanceof ResolverException re) { - String details = re.getDetails(); - assertTrue(string + " not found in details: " + details, details.contains(string)); - return; - } - if (e.getCause() != null) { - assertResolveError(e.getCause(), string); - return; - } - fail("Resolve error was not found: " + string); - } - - public void testFeatureMissingFeature() throws Exception { - File basedir = getBasedir("projects/resolutionerror/feature_missing_feature"); - Exception e = assertThrows(Exception.class, () -> getSortedProjects(basedir)); - assertResolveError(e, - "feature_missing_feature.feature.group 1.0.0 requires 'org.eclipse.equinox.p2.iu; feature.not.found.feature.group 0.0.0' but it could not be found"); - } - - public void testFeatureMissingPlugin() throws Exception { - File basedir = getBasedir("projects/resolutionerror/feature_missing_plugin"); - Exception e = assertThrows(Exception.class, () -> getSortedProjects(basedir)); - assertResolveError(e, - "feature_missing_feature.feature.group 1.0.0 requires 'org.eclipse.equinox.p2.iu; plugin.not.found 0.0.0' but it could not be found"); - } - - public void testProjectPriority() throws Exception { - File basedir = getBasedir("projects/projectpriority"); - List projects = getSortedProjects(basedir, properties); - - MavenProject p002 = projects.get(2); - - List dependencies = p002.getModel().getDependencies(); - Dependency dependency = dependencies.get(0); - assertEquals("0.0.1", dependency.getVersion()); - } - - public void testMissingClasspathEntries() throws Exception { - File basedir = getBasedir("projects/missingentry"); - MavenProject project = getSortedProjects(basedir, properties).get(0); - - OsgiBundleProject projectType = (OsgiBundleProject) lookup(TychoProject.class, project.getPackaging()); - - List classpath = projectType.getClasspath(DefaultReactorProject.adapt(project)); - - assertEquals(3, classpath.size()); - assertEquals(1, classpath.get(0).getLocations().size()); - assertEquals(canonicalFile("src/test/resources/targetplatforms/missingentry/plugins/dirbundle_0.0.1"), - classpath.get(0).getLocations().get(0).getCanonicalFile()); - assertEquals(1, classpath.get(1).getLocations().size()); - assertEquals(canonicalFile("src/test/resources/targetplatforms/missingentry/plugins/jarbundle_0.0.1.jar"), - classpath.get(1).getLocations().get(0).getCanonicalFile()); - } - - private File canonicalFile(String path) throws IOException { - return new File(path).getCanonicalFile(); - } - - public void testBundleExtraClasspath() throws Exception { - File basedir = getBasedir("projects/extraclasspath"); - List projects = getSortedProjects(basedir, properties); - assertEquals(3, projects.size()); - - MavenProject b02 = projects.get(2); - - OsgiBundleProject projectType = (OsgiBundleProject) lookup(TychoProject.class, b02.getPackaging()); - - List classpath = projectType.getClasspath(DefaultReactorProject.adapt(b02)); - - assertClasspathContains(classpath, canonicalFile( - "target/local-repo/.cache/tycho/org.eclipse.equinox.launcher_1.0.101.R34x_v20081125.jar/launcher.properties")); - assertClasspathContains(classpath, - canonicalFile("target/projects/extraclasspath/b01/target/lib/nested.jar-classes")); - assertClasspathContains(classpath, canonicalFile( - "src/test/resources/targetplatforms/basic/plugins/org.eclipse.equinox.launcher_1.0.101.R34x_v20081125.jar")); - assertClasspathContains(classpath, new File(basedir, "b02/classes")); - assertClasspathContains(classpath, canonicalFile("target/projects/extraclasspath/b02/target/classes")); - } - - private void assertClasspathContains(List classpath, File file) throws IOException { - for (ClasspathEntry cpe : classpath) { - for (File cpfile : cpe.getLocations()) { - if (cpfile.getCanonicalFile().equals(file.getCanonicalFile())) { - return; - } - } - } - - fail("File " + file + " not found on the classpath"); - - } - - public void testImplicitTargetEnvironment() throws Exception { - File basedir = getBasedir("projects/implicitenvironment/simple"); - - List projects = getSortedProjects(basedir); - assertEquals(1, projects.size()); - -// assertEquals("ambiguous", projects.get(0).getArtifactId()); -// assertEquals("none", projects.get(0).getArtifactId()); - assertEquals("simple", projects.get(0).getArtifactId()); - - DefaultTargetPlatformConfigurationReader resolver = lookup(DefaultTargetPlatformConfigurationReader.class); - - MavenSession session; - TargetPlatformConfiguration configuration; - List environments; - - // ambiguous -// session = newMavenSession(projects.get(0), projects); -// configuration = resolver.getTargetPlatformConfiguration(session, session.getCurrentProject()); -// environments = configuration.getEnvironments(); -// assertEquals(0, environments.size()); - - // none -// session = newMavenSession(projects.get(0), projects); -// configuration = resolver.getTargetPlatformConfiguration(session, session.getCurrentProject()); -// environments = configuration.getEnvironments(); -// assertEquals(0, environments.size()); - - // simple - session = newMavenSession(projects.get(0), projects); - configuration = resolver.getTargetPlatformConfiguration(session, session.getCurrentProject()); - environments = configuration.getEnvironments(); - assertEquals(1, environments.size()); - TargetEnvironment env = environments.get(0); - assertEquals("foo", env.getOs()); - assertEquals("bar", env.getWs()); - assertEquals("munchy", env.getArch()); - } - - public void testWithValidExplicitTargetEnvironment() throws Exception { - File basedir = getBasedir("projects/explicitenvironment/valid"); - - List projects = getSortedProjects(basedir); - assertEquals(1, projects.size()); - - assertEquals("valid", projects.get(0).getArtifactId()); - - DefaultTargetPlatformConfigurationReader resolver = lookup(DefaultTargetPlatformConfigurationReader.class); - - MavenSession session = newMavenSession(projects.get(0), projects); - - TargetPlatformConfiguration configuration; - List environments; - - configuration = resolver.getTargetPlatformConfiguration(session, session.getCurrentProject()); - environments = configuration.getEnvironments(); - assertEquals(1, environments.size()); - TargetEnvironment env = environments.get(0); - assertEquals("linux", env.getOs()); - assertEquals("gtk", env.getWs()); - assertEquals("arm", env.getArch()); - } - - public void testWithMissingOsInExplicitTargetEnvironment() throws Exception { - File basedir = getBasedir("projects/explicitenvironment/missingOs"); - RuntimeException e = assertThrows(RuntimeException.class, () -> getSortedProjects(basedir)); - assertTrue(e.getMessage().contains( - "target-platform-configuration error in project explicitenvironment:missingos:eclipse-plugin")); - Throwable cause = e; - while (cause.getCause() != null) { - cause = cause.getCause(); - } - assertTrue(cause instanceof TargetPlatformConfigurationException); - assertEquals(" element is missing within target-platform-configuration (element )", - cause.getMessage()); - } - - public void testWithMissingWsInExplicitTargetEnvironment() throws Exception { - File basedir = getBasedir("projects/explicitenvironment/missingWs"); - RuntimeException e = assertThrows(RuntimeException.class, () -> getSortedProjects(basedir)); - assertTrue(e.getMessage().contains( - "target-platform-configuration error in project explicitenvironment:missingws:eclipse-plugin")); - Throwable cause = e; - while (cause.getCause() != null) { - cause = cause.getCause(); - } - assertTrue(cause instanceof TargetPlatformConfigurationException); - assertEquals(" element is missing within target-platform-configuration (element )", - cause.getMessage()); - } - - public void testWithMissingArchInExplicitTargetEnvironment() throws Exception { - File basedir = getBasedir("projects/explicitenvironment/missingArch"); - RuntimeException e = assertThrows(RuntimeException.class, () -> getSortedProjects(basedir)); - assertTrue(e.getMessage().contains( - "target-platform-configuration error in project explicitenvironment:missingarch:eclipse-plugin")); - Throwable cause = e; - while (cause.getCause() != null) { - cause = cause.getCause(); - } - assertTrue(cause instanceof TargetPlatformConfigurationException); - assertEquals(" element is missing within target-platform-configuration (element )", - cause.getMessage()); - } - -} diff --git a/tycho-eclipse-plugin/src/test/java/org/eclipse/tycho/extras/eclipserun/EclipseRunMojoTest.java b/tycho-eclipse-plugin/src/test/java/org/eclipse/tycho/extras/eclipserun/EclipseRunMojoTest.java deleted file mode 100644 index f09ecccf26..0000000000 --- a/tycho-eclipse-plugin/src/test/java/org/eclipse/tycho/extras/eclipserun/EclipseRunMojoTest.java +++ /dev/null @@ -1,169 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016 Bachmann electronic GmbH and others. - * This program and the accompanying materials - * are made available under the terms of the Eclipse Public License 2.0 - * which accompanies this distribution, and is available at - * https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Bachmann electronic GmbH - initial API and implementation - ******************************************************************************/ -package org.eclipse.tycho.extras.eclipserun; - -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import java.io.File; -import java.io.IOException; -import java.util.Arrays; -import java.util.List; -import java.util.concurrent.atomic.AtomicReference; - -import org.apache.maven.execution.MavenSession; -import org.apache.maven.plugin.MojoExecutionException; -import org.apache.maven.plugin.testing.SilentLog; -import org.apache.maven.project.MavenProject; -import org.apache.maven.toolchain.java.JavaToolchainImpl; -import org.eclipse.sisu.equinox.launching.EquinoxInstallation; -import org.eclipse.sisu.equinox.launching.EquinoxLauncher; -import org.eclipse.sisu.equinox.launching.LaunchConfiguration; -import org.eclipse.tycho.ExecutionEnvironmentConfiguration; -import org.eclipse.tycho.TargetPlatform; -import org.eclipse.tycho.core.maven.ToolchainProvider; -import org.eclipse.tycho.core.resolver.P2Resolver; -import org.eclipse.tycho.core.resolver.P2ResolverFactory; -import org.eclipse.tycho.eclipserun.EclipseRunMojo; -import org.eclipse.tycho.p2.target.facade.TargetPlatformFactory; -import org.eclipse.tycho.testing.AbstractTychoMojoTestCase; -import org.eclipse.tycho.version.TychoVersion; -import org.junit.rules.TemporaryFolder; - -public class EclipseRunMojoTest extends AbstractTychoMojoTestCase { - - private EclipseRunMojo runMojo; - private EquinoxInstallation installation; - private TemporaryFolder temporaryFolder; - private File workFolder; - private ToolchainProvider toolchainProvider; - - @Override - public void setUp() throws Exception { - super.setUp(); - - runMojo = (EclipseRunMojo) lookupMojo("org.eclipse.tycho", "tycho-eclipse-plugin", - TychoVersion.getTychoVersion(), "eclipse-run", null); - runMojo.setLog(new SilentLog()); - MavenSession mavenSession = newMavenSession(mock(MavenProject.class)); - configureMojoWithDefaultConfiguration(runMojo, mavenSession, "eclipse-run"); - - installation = mock(EquinoxInstallation.class); - temporaryFolder = new TemporaryFolder(); - temporaryFolder.create(); - MavenProject project = mock(MavenProject.class); - setVariableValueToObject(runMojo, "project", project); - toolchainProvider = mock(ToolchainProvider.class); - setVariableValueToObject(runMojo, "toolchainProvider", toolchainProvider); - workFolder = new File(temporaryFolder.getRoot(), "work"); - setVariableValueToObject(runMojo, "work", workFolder); - setVariableValueToObject(runMojo, "launcher", mock(EquinoxLauncher.class)); - setVariableValueToObject(runMojo, "repositories", List.of()); - when(installation.getLocation()).thenReturn(new File("installpath")); - } - - @Override - protected void tearDown() throws Exception { - temporaryFolder.delete(); - super.tearDown(); - } - - public void testCreateCommandlineWithJvmArgs() throws IllegalAccessException, MojoExecutionException { - List args = Arrays.asList("-Xdebug", "-DanotherOptionWithValue=theValue", - "-DoptionWith=\"A space in the value\""); - setVariableValueToObject(runMojo, "jvmArgs", args); - setVariableValueToObject(runMojo, "argLine", "-DoldArgLineOption"); - LaunchConfiguration commandLine = runMojo.createCommandLine(installation); - List vmArgs = Arrays.asList(commandLine.getVMArguments()); - assertTrue(vmArgs.contains("-Xdebug")); - assertTrue(vmArgs.contains("-DanotherOptionWithValue=theValue")); - assertTrue(vmArgs.contains("-DoldArgLineOption")); - assertTrue(vmArgs.contains("-DoptionWith=\"A space in the value\"")); - } - - public void testCreateCommandlineWithApplicationArgs() throws IllegalAccessException, MojoExecutionException { - List args = Arrays.asList("arg1", "literal arg with spaces", "argument'with'literalquotes"); - setVariableValueToObject(runMojo, "appArgLine", "appArg1 \"literal appArg with spaces\""); - setVariableValueToObject(runMojo, "applicationArgs", args); - LaunchConfiguration commandLine = runMojo.createCommandLine(installation); - List programArgs = Arrays.asList(commandLine.getProgramArguments()); - assertTrue(programArgs.contains("arg1")); - assertTrue(programArgs.contains("appArg1")); - assertTrue(programArgs.contains("literal arg with spaces")); - assertTrue(programArgs.contains("literal appArg with spaces")); - assertTrue(programArgs.contains("argument'with'literalquotes")); - } - - public void testCreateCommandLineWithNullJvmArgs() throws MojoExecutionException { - LaunchConfiguration commandLine = runMojo.createCommandLine(installation); - assertEquals(0, commandLine.getVMArguments().length); - } - - public void testCreateCommandLineProgramArgs() throws MojoExecutionException { - LaunchConfiguration commandLine = runMojo.createCommandLine(installation); - List programArgs = Arrays.asList(commandLine.getProgramArguments()); - assertTrue(programArgs.containsAll(List.of("-install", installation.getLocation().getAbsolutePath(), // - "-configuration", new File(workFolder, "configuration").getAbsolutePath(), // - "-data", new File(workFolder, "data").getAbsolutePath() // - ))); - } - - public void testDataDirectoryIsClearedBeforeLaunching() throws IOException, MojoExecutionException { - File markerFile = new File(workFolder, "data/markerfile").getAbsoluteFile(); - markerFile.getParentFile().mkdirs(); - markerFile.createNewFile(); - assertTrue(markerFile.exists()); - runMojo.runEclipse(installation); - assertFalse(markerFile.exists()); - } - - public void testExecutionEnvironmentIsRespectedDuringDependencyResolution() throws Exception { - AtomicReference recordedExecutionEnvironmentConfiguration = new AtomicReference<>(); - - TargetPlatform mockTargetPlatform = mock(TargetPlatform.class); - TargetPlatformFactory mockTargetPlatformFactory = mock(TargetPlatformFactory.class); - when(mockTargetPlatformFactory.createTargetPlatform(any(), any(), any())).thenAnswer(invocation -> { - recordedExecutionEnvironmentConfiguration.set(invocation.getArgument(1)); - return mockTargetPlatform; - }); - - P2Resolver mockP2Resolver = mock(P2Resolver.class); - - P2ResolverFactory mockP2ResolverFactory = mock(P2ResolverFactory.class); - when(mockP2ResolverFactory.createResolver(any())).thenReturn(mockP2Resolver); - - setVariableValueToObject(runMojo, "resolverFactory", mockP2ResolverFactory); - setVariableValueToObject(runMojo, "platformFactory", mockTargetPlatformFactory); - - setVariableValueToObject(runMojo, "executionEnvironment", "custom-ee"); - - runMojo.execute(); - - assertEquals("custom-ee", recordedExecutionEnvironmentConfiguration.get().getProfileName()); - } - - public void testExecutionEnvironmentIsRespectedDuringEclipseExecution() throws Exception { - JavaToolchainImpl mockToolchainForCustomEE = mock(JavaToolchainImpl.class); - when(mockToolchainForCustomEE.findTool("java")).thenReturn("/path/to/custom-ee-jdk/bin/java"); - when(toolchainProvider.findMatchingJavaToolChain(any(), eq("custom-ee"))).thenReturn(mockToolchainForCustomEE); - - setVariableValueToObject(runMojo, "executionEnvironment", "custom-ee"); - - LaunchConfiguration commandLine = runMojo.createCommandLine(installation); - - assertEquals("/path/to/custom-ee-jdk/bin/java", commandLine.getJvmExecutable()); - } - -} diff --git a/tycho-extras/tycho-p2-extras-plugin/src/test/java/org/eclipse/tycho/plugins/p2/extras/MirrorMojoTest.java b/tycho-extras/tycho-p2-extras-plugin/src/test/java/org/eclipse/tycho/plugins/p2/extras/MirrorMojoTest.java deleted file mode 100644 index 55084f0c74..0000000000 --- a/tycho-extras/tycho-p2-extras-plugin/src/test/java/org/eclipse/tycho/plugins/p2/extras/MirrorMojoTest.java +++ /dev/null @@ -1,195 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2010, 2022 SAP AG and others. - * This program and the accompanying materials - * are made available under the terms of the Eclipse Public License 2.0 - * which accompanies this distribution, and is available at - * https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Jan Sievers - initial API and implementation - *******************************************************************************/ -package org.eclipse.tycho.plugins.p2.extras; - -import static org.junit.Assert.assertThrows; - -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.nio.file.FileVisitResult; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.SimpleFileVisitor; -import java.nio.file.attribute.BasicFileAttributes; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Properties; - -import org.apache.maven.artifact.repository.ArtifactRepository; -import org.apache.maven.execution.MavenSession; -import org.apache.maven.plugin.LegacySupport; -import org.apache.maven.plugin.Mojo; -import org.apache.maven.plugin.MojoExecutionException; -import org.apache.maven.project.MavenProject; -import org.apache.maven.repository.RepositorySystem; -import org.eclipse.core.runtime.adaptor.EclipseStarter; -import org.eclipse.tycho.testing.AbstractTychoMojoTestCase; -import org.junit.Assert; - -public class MirrorMojoTest extends AbstractTychoMojoTestCase { - - private File mirrorDestinationDir; - private Mojo mirrorMojo; - - @Override - protected void setUp() throws Exception { - super.setUp(); - File basedir = getBasedir("mirroring/testProject"); - List projects = getSortedProjects(basedir); - MavenProject project = projects.get(0); - initLegacySupport(projects, project); - mirrorDestinationDir = new File(project.getFile().getParent(), "target/repository").getCanonicalFile(); - if (mirrorDestinationDir.exists()) { - deleteFolder(mirrorDestinationDir.toPath()); - } - mirrorMojo = lookupMojo("mirror", project.getFile()); - setVariableValueToObject(mirrorMojo, "destination", mirrorDestinationDir); - setVariableValueToObject(mirrorMojo, "project", project); - } - - private static void deleteFolder(final Path path) throws IOException { - Files.walkFileTree(path, new SimpleFileVisitor() { - @Override - public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException { - Files.delete(file); - return FileVisitResult.CONTINUE; - } - - @Override - public FileVisitResult visitFileFailed(final Path file, final IOException e) { - return FileVisitResult.TERMINATE; - } - - @Override - public FileVisitResult postVisitDirectory(final Path dir, final IOException e) throws IOException { - if (e != null) { - return FileVisitResult.TERMINATE; - } - Files.delete(dir); - return FileVisitResult.CONTINUE; - } - }); - } - - @Override - protected void tearDown() throws Exception { - // this is needed because the DefaultEquinoxEmbedder plexus component - // is not disposed - EclipseStarter.shutdown(); - System.clearProperty("org.osgi.framework.vendor"); - } - - public void testMirrorSpecificIUFromP2Repo() throws Exception { - File sourceRepository = new File("src/test/resources/mirroring/sourceP2Repo").getCanonicalFile(); - setVariableValueToObject(mirrorMojo, "source", - Collections.singletonList(new Repository(sourceRepository.toURI()))); - Iu testBundleIu = new Iu(); - testBundleIu.id = "test.bundle1"; - setVariableValueToObject(mirrorMojo, "ius", Collections.singletonList(testBundleIu)); - mirrorMojo.execute(); - assertTrue(mirrorDestinationDir.isDirectory()); - assertEquals(1, new File(mirrorDestinationDir, "plugins").listFiles().length); - assertMirroredBundle(mirrorDestinationDir, "test.bundle1", "1.0.0.201108100850"); - } - - public void testMirrorProduct() throws Exception { - File sourceRepository = new File("src/test/resources/mirroring/sourceP2RepoWithProduct").getCanonicalFile(); - setVariableValueToObject(mirrorMojo, "source", - Collections.singletonList(new Repository(sourceRepository.toURI()))); - Iu testBundleIu = new Iu(); - testBundleIu.id = "dummy"; - setVariableValueToObject(mirrorMojo, "ius", Collections.singletonList(testBundleIu)); - mirrorMojo.execute(); - assertTrue(mirrorDestinationDir.isDirectory()); - assertTrue(Arrays.stream(new File(mirrorDestinationDir, "binary").listFiles()).map(File::getName) - .anyMatch(name -> name.startsWith("dummy"))); - } - - public void testMirrorWithPlatformFilter() throws Exception { - File sourceRepository = new File("src/test/resources/mirroring/sourceP2Repo").getCanonicalFile(); - setVariableValueToObject(mirrorMojo, "source", - Collections.singletonList(new Repository(sourceRepository.toURI()))); - Iu featureIU = new Iu(); - featureIU.id = "test.feature.feature.group"; - setVariableValueToObject(mirrorMojo, "ius", Collections.singletonList(featureIU)); - Map filter = new HashMap<>(); - filter.put("osgi.os", "linux"); - filter.put("osgi.ws", "gtk"); - filter.put("osgi.arch", "x86_64"); - setVariableValueToObject(mirrorMojo, "filter", filter); - mirrorMojo.execute(); - assertTrue(mirrorDestinationDir.isDirectory()); - // win32 fragment must not mirrored because platform filter does not match - assertEquals(2, new File(mirrorDestinationDir, "plugins").listFiles().length); - assertMirroredBundle(mirrorDestinationDir, "test.bundle1", "1.0.0.201108100850"); - assertMirroredBundle(mirrorDestinationDir, "test.bundle2", "1.0.0.201108100850"); - } - - public void testTargetPlatformAsSource() throws Exception { - Iu featureIU = new Iu(); - featureIU.id = "test.feature.feature.group"; - setVariableValueToObject(mirrorMojo, "ius", Collections.singletonList(featureIU)); - setVariableValueToObject(mirrorMojo, "targetPlatformAsSource", Boolean.TRUE); - // Source is allowed to be empty, for example when targetPlatformAsSource is set, but in this test - // project we have no target platform so it should fail gracefully instead of throwing a NPE - MojoExecutionException e = assertThrows(MojoExecutionException.class, () -> mirrorMojo.execute()); - assertEquals(e.getMessage(), "No repository provided as 'source'"); - } - - private static void assertMirroredBundle(File publishedContentDir, String bundleID, String version) { - assertMirroredArtifact(publishedContentDir, bundleID, version, "plugins"); - } - - private static void assertMirroredArtifact(File publishedContentDir, String id, String version, String folder) { - String pluginArtifactNamePrefix = id + "_" + version; // without qualifier - for (File bundle : new File(publishedContentDir, folder).listFiles()) { - if (bundle.getName().startsWith(pluginArtifactNamePrefix)) - return; - } - - Assert.fail("Published artifact not found: " + pluginArtifactNamePrefix); - } - - private void initLegacySupport(List projects, MavenProject currentProject) throws Exception { - MavenSession session = newMavenSession(currentProject, projects); - LegacySupport buildContext = lookup(LegacySupport.class); - buildContext.setSession(session); - } - - // use the normal local Maven repository (called by newMavenSession) - @Override - protected ArtifactRepository getLocalRepository() throws Exception { - RepositorySystem repoSystem = lookup(RepositorySystem.class); - File path = getLocalMavenRepository().getCanonicalFile(); - ArtifactRepository r = repoSystem.createLocalRepository(path); - return r; - } - - private File getLocalMavenRepository() { - /* - * The build (more specifically, the maven-properties-plugin) writes the local Maven - * repository location to a file. Here, we read this file. (Approach copied from tycho-its.) - */ - Properties buildProperties = new Properties(); - try (InputStream is = this.getClassLoader().getResourceAsStream("baseTest.properties")) { - buildProperties.load(is); - } catch (IOException e) { - throw new RuntimeException(e); - } - return new File(buildProperties.getProperty("local-repo")); - } -} diff --git a/tycho-extras/tycho-p2-extras-plugin/src/test/java/org/eclipse/tycho/plugins/p2/extras/PublishFeaturesAndBundlesMojoTest.java b/tycho-extras/tycho-p2-extras-plugin/src/test/java/org/eclipse/tycho/plugins/p2/extras/PublishFeaturesAndBundlesMojoTest.java deleted file mode 100644 index 7a5ba475cd..0000000000 --- a/tycho-extras/tycho-p2-extras-plugin/src/test/java/org/eclipse/tycho/plugins/p2/extras/PublishFeaturesAndBundlesMojoTest.java +++ /dev/null @@ -1,130 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2010, 2021 SAP AG and others. - * This program and the accompanying materials - * are made available under the terms of the Eclipse Public License 2.0 - * which accompanies this distribution, and is available at - * https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Tobias Oberlies - initial API and implementation - *******************************************************************************/ -package org.eclipse.tycho.plugins.p2.extras; - -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.net.URL; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.nio.file.StandardCopyOption; -import java.util.List; -import java.util.Properties; - -import org.apache.maven.artifact.repository.ArtifactRepository; -import org.apache.maven.execution.MavenSession; -import org.apache.maven.plugin.LegacySupport; -import org.apache.maven.plugin.Mojo; -import org.apache.maven.project.MavenProject; -import org.apache.maven.repository.RepositorySystem; -import org.eclipse.tycho.testing.AbstractTychoMojoTestCase; -import org.junit.Assert; - -import de.pdark.decentxml.Document; -import de.pdark.decentxml.Element; -import de.pdark.decentxml.XMLIOSource; -import de.pdark.decentxml.XMLParser; - -public class PublishFeaturesAndBundlesMojoTest extends AbstractTychoMojoTestCase { - - public void testPublisher() throws Exception { - File basedir = getBasedir("publisher/testProject"); - List projects = getSortedProjects(basedir); - MavenProject project = projects.get(0); - - initLegacySupport(projects, project); - - // simulate that content to be published has already been extracted to the target folder - Path sourceRepositoryDir = Paths.get(project.getFile().getParent(), "target/sourceRepository"); - generateContentToBePublished(sourceRepositoryDir); - - File publishedContentDir = new File(project.getFile().getParent(), "target/repository with spaces") - .getAbsoluteFile(); - - // call publisher mojo - Mojo publishMojo = lookupMojo("publish-features-and-bundles", project.getFile()); - setVariableValueToObject(publishMojo, "project", project); - setVariableValueToObject(publishMojo, "sourceLocation", sourceRepositoryDir.toString()); - setVariableValueToObject(publishMojo, "artifactRepositoryLocation", publishedContentDir.toString()); - setVariableValueToObject(publishMojo, "metadataRepositoryLocation", publishedContentDir.toString()); - setVariableValueToObject(publishMojo, "publishArtifacts", Boolean.TRUE); - - publishMojo.execute(); - - assertPublishedIU(publishedContentDir, "org.eclipse.tycho.extras.testdata"); - assertPublishedArtifact(publishedContentDir, "org.eclipse.tycho.extras.testdata", "1.0.0"); - } - - private static void assertPublishedArtifact(File publishedContentDir, String bundleID, String version) { - String pluginArtifactNamePrefix = bundleID + "_" + version; // without qualifier - for (File bundle : new File(publishedContentDir, "plugins").listFiles()) { - if (bundle.getName().startsWith(pluginArtifactNamePrefix)) - return; - } - - Assert.fail("Published artifact not found: " + pluginArtifactNamePrefix); - } - - private static void assertPublishedIU(File publishedContentDir, String iuID) throws IOException { - XMLParser parser = new XMLParser(); - Document document = parser.parse(new XMLIOSource(new File(publishedContentDir, "content.xml"))); - Element unitElement = document.getChild("repository/units"); - List children = unitElement.getChildren("unit"); - for (Element element : children) { - if (iuID.equals(element.getAttribute("id").getValue())) { - return; - } - } - Assert.fail("IU not found: " + iuID); - } - - private void initLegacySupport(List projects, MavenProject currentProject) throws Exception { - MavenSession session = newMavenSession(currentProject, projects); - System.out.println(session.getLocalRepository()); - LegacySupport buildContext = lookup(LegacySupport.class); - buildContext.setSession(session); - } - - private void generateContentToBePublished(Path repositoryFolder) throws IOException { - String bundleFileName = "testdata-1.0.0-SNAPSHOT.jar"; - URL source = getClassLoader().getResource(bundleFileName); - Path path = repositoryFolder.resolve("plugins/" + bundleFileName); - Files.createDirectories(path); - Files.copy(source.openStream(), path, StandardCopyOption.REPLACE_EXISTING); - } - - // use the normal local Maven repository (called by newMavenSession) - @Override - protected ArtifactRepository getLocalRepository() throws Exception { - RepositorySystem repoSystem = lookup(RepositorySystem.class); - File path = getLocalMavenRepository().getCanonicalFile(); - ArtifactRepository r = repoSystem.createLocalRepository(path); - return r; - } - - private File getLocalMavenRepository() { - /* - * The build (more specifically, the maven-properties-plugin) writes the local Maven - * repository location to a file. Here, we read this file. (Approach copied from tycho-its.) - */ - Properties buildProperties = new Properties(); - try (InputStream is = this.getClassLoader().getResourceAsStream("baseTest.properties")) { - buildProperties.load(is); - } catch (IOException e) { - throw new RuntimeException(e); - } - return new File(buildProperties.getProperty("local-repo")); - } -} diff --git a/tycho-packaging-plugin/src/test/java/org/eclipse/tycho/buildnumber/test/PackageFeatureMojoTest.java b/tycho-packaging-plugin/src/test/java/org/eclipse/tycho/buildnumber/test/PackageFeatureMojoTest.java deleted file mode 100644 index 880236730c..0000000000 --- a/tycho-packaging-plugin/src/test/java/org/eclipse/tycho/buildnumber/test/PackageFeatureMojoTest.java +++ /dev/null @@ -1,127 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008, 2021 Sonatype Inc. and others. - * This program and the accompanying materials - * are made available under the terms of the Eclipse Public License 2.0 - * which accompanies this distribution, and is available at - * https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Sonatype Inc. - initial API and implementation - *******************************************************************************/ -package org.eclipse.tycho.buildnumber.test; - -import java.io.File; -import java.nio.charset.Charset; -import java.util.List; -import java.util.Properties; -import java.util.zip.ZipEntry; -import java.util.zip.ZipFile; - -import org.apache.commons.io.IOUtils; -import org.apache.maven.execution.MavenSession; -import org.apache.maven.project.MavenProject; -import org.eclipse.tycho.model.Feature; -import org.eclipse.tycho.packaging.PackageFeatureMojo; -import org.eclipse.tycho.testing.AbstractTychoMojoTestCase; -import org.eclipse.tycho.version.TychoVersion; - -public class PackageFeatureMojoTest extends AbstractTychoMojoTestCase { - - Properties properties = new Properties(); - - public PackageFeatureMojoTest() { - properties.setProperty("tycho-version", TychoVersion.getTychoVersion()); - } - - public void testLicenseFeature() throws Exception { - File basedir = new File(getBasedir("projects/licenseFeature"), "feature"); - List projects = getSortedProjects(basedir, properties); - - MavenProject project = getProject(projects, "licenseFeature.feature"); - MavenSession session = newMavenSession(project, projects); - // set build qualifier - lookupMojoWithDefaultConfiguration(project, session, "build-qualifier").execute(); - - PackageFeatureMojo mojo = (PackageFeatureMojo) lookupMojo("package-feature", project.getFile()); - setVariableValueToObject(mojo, "project", project); - setVariableValueToObject(mojo, "session", session); - setVariableValueToObject(mojo, "finalName", "feature"); - setVariableValueToObject(mojo, "featureFile", new File(project.getBasedir(), "feature.xml")); - - mojo.execute(); - - try (ZipFile zip = new ZipFile(new File(basedir, "target/feature.jar"))) { - // igorf: input streams are closed by zip.close() at the end, sloppy but should work - - // all bin.includes files from license features are included - assertNotNull(zip.getEntry("file-license.txt")); - assertNull(zip.getEntry("file-unlicense.txt")); - - // do not leak build.properties into 'this' feature - assertNull(zip.getEntry("build.properties")); - - // license feature id/version are stripped off - Feature feature = Feature.read(zip.getInputStream(zip.getEntry(Feature.FEATURE_XML))); - assertNull(feature.getLicenseFeature()); - assertNull(feature.getLicenseFeatureVersion()); - assertEquals("http://www.foo.bar", feature.getLicenseURL()); - assertEquals("This is the license", feature.getLicense().trim()); - - // feature.properties merged - Properties p = new Properties(); - p.load(zip.getInputStream(zip.getEntry("feature.properties"))); - assertEquals("test property value", p.getProperty("test")); - assertEquals("license test property value", p.getProperty("license-test")); - - // when present both in 'this' and license feature, files from 'this' feature are included - assertEquals("file.txt contents", - IOUtils.toString(zip.getInputStream(zip.getEntry("file.txt")), Charset.defaultCharset())); - } - } - - public void testAddMavenDescriptorNotAddedPerDefault() throws Exception { - File basedir = getBasedir("projects/addMavenDescriptor/featureDefault/"); - List projects = getSortedProjects(basedir, properties); - - MavenProject project = getProject(projects, "featureDefault"); - MavenSession session = newMavenSession(project, projects); - // set build qualifier - lookupMojoWithDefaultConfiguration(project, session, "build-qualifier").execute(); - - PackageFeatureMojo mojo = (PackageFeatureMojo) lookupMojo("package-feature", project.getFile()); - setVariableValueToObject(mojo, "project", project); - setVariableValueToObject(mojo, "session", session); - setVariableValueToObject(mojo, "featureFile", new File(project.getBasedir(), "feature.xml")); - - mojo.execute(); - - try (ZipFile zip = new ZipFile(new File(basedir, "target/featureDefault.jar"))) { - ZipEntry entry = zip.getEntry("META-INF/maven"); - assertNull("No 'META-INF/maven/' entry must be in the feature.jar!", entry); - } - } - - public void testAddMavenDescriptorSetToTrue() throws Exception { - File basedir = getBasedir("projects/addMavenDescriptor/featureForcedToTrue"); - List projects = getSortedProjects(basedir, properties); - - MavenProject project = getProject(projects, "featureForcedToTrue"); - MavenSession session = newMavenSession(project, projects); - // set build qualifier - lookupMojoWithDefaultConfiguration(project, session, "build-qualifier").execute(); - - PackageFeatureMojo mojo = (PackageFeatureMojo) lookupMojo("package-feature", project.getFile()); - setVariableValueToObject(mojo, "project", project); - setVariableValueToObject(mojo, "session", session); - setVariableValueToObject(mojo, "featureFile", new File(project.getBasedir(), "feature.xml")); - - mojo.execute(); - - try (ZipFile zip = new ZipFile(new File(basedir, "target/featureForcedToTrue.jar"))) { - ZipEntry entry = zip.getEntry("META-INF/maven"); - assertNotNull("There must be a 'META-INF/maven/' entry in the feature.jar!", entry); - } - } -} diff --git a/tycho-packaging-plugin/src/test/java/org/eclipse/tycho/buildnumber/test/PackageIUMojoTest.java b/tycho-packaging-plugin/src/test/java/org/eclipse/tycho/buildnumber/test/PackageIUMojoTest.java deleted file mode 100644 index e09b3da04d..0000000000 --- a/tycho-packaging-plugin/src/test/java/org/eclipse/tycho/buildnumber/test/PackageIUMojoTest.java +++ /dev/null @@ -1,95 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2015, 2023 Rapicorp, Inc. and others. - * This program and the accompanying materials - * are made available under the terms of the Eclipse Public License 2.0 - * which accompanies this distribution, and is available at - * https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Rapicorp, Inc. - initial API and implementation - *******************************************************************************/ -package org.eclipse.tycho.buildnumber.test; - -import static org.eclipse.tycho.test.util.ArchiveContentUtil.getFilesInZip; - -import java.io.File; -import java.util.List; -import java.util.Properties; - -import org.apache.maven.execution.MavenSession; -import org.apache.maven.project.MavenProject; -import org.eclipse.tycho.model.IU; -import org.eclipse.tycho.packaging.PackageIUMojo; -import org.eclipse.tycho.testing.AbstractTychoMojoTestCase; -import org.eclipse.tycho.version.TychoVersion; - -import de.pdark.decentxml.Element; - -public class PackageIUMojoTest extends AbstractTychoMojoTestCase { - - Properties properties = new Properties(); - - public PackageIUMojoTest() { - properties.setProperty("tycho-version", TychoVersion.getTychoVersion()); - } - - public void testThatArtifactPayloadIsCorrect() throws Exception { - File basedir = getBasedir("projects/iuWithPayload/"); - List projects = getSortedProjects(basedir, properties); - - MavenProject project = getProject(projects, "iuWithPayload"); - MavenSession session = newMavenSession(project, projects); - // set build qualifier - lookupMojoWithDefaultConfiguration(project, session, "build-qualifier").execute(); - - PackageIUMojo mojo = (PackageIUMojo) lookupConfiguredMojo(project, "package-iu"); - setVariableValueToObject(mojo, "artifactContentFolder", - new File(basedir, "src/main/resources").getAbsolutePath()); - mojo.execute(); - - assertTrue(getFilesInZip(new File(basedir, "target/iuWithPayload-1.0.0.zip")).contains("file.txt")); - } - - public void testArtifactWithoutPayload() throws Exception { - File basedir = getBasedir("projects/iuWithoutPayload"); - List projects = getSortedProjects(basedir, properties); - - MavenProject project = getProject(projects, "iuWithoutPayload"); - MavenSession session = newMavenSession(project, projects); - // set build qualifier - lookupMojoWithDefaultConfiguration(project, session, "build-qualifier").execute(); - - PackageIUMojo mojo = (PackageIUMojo) lookupConfiguredMojo(project, "package-iu"); - mojo.execute(); - - IU iu = IU.loadIU(new File(basedir, "target")); - Element artifact = iu.getSelfArtifact(); - assertNull(artifact); - - assertTrue(new File(basedir, "target/iuWithoutPayload-1.0.0.zip").exists()); - } - - public void testInjectArtifactReference() throws Exception { - File basedir = getBasedir("projects/iuWithPayloadButNoArtifactReference"); - List projects = getSortedProjects(basedir, properties); - - MavenProject project = getProject(projects, "iuWithPayloadButNoArtifactReference"); - MavenSession session = newMavenSession(project, projects); - // set build qualifier - lookupMojoWithDefaultConfiguration(project, session, "build-qualifier").execute(); - - PackageIUMojo mojo = (PackageIUMojo) lookupConfiguredMojo(project, "package-iu"); - setVariableValueToObject(mojo, "artifactContentFolder", - new File(basedir, "src/main/resources").getAbsolutePath()); - mojo.execute(); - - IU iu = IU.loadIU(new File(basedir, "target")); - Element artifact = iu.getSelfArtifact(); - assertNotNull(artifact); - assertEquals("binary", artifact.getAttributeValue("classifier")); - assertEquals("iuWithPayloadButNoArtifactReference", artifact.getAttributeValue("id")); - assertEquals("1.0.0", artifact.getAttributeValue("version")); - } -} diff --git a/tycho-packaging-plugin/src/test/java/org/eclipse/tycho/buildnumber/test/PackagePluginMojoTest.java b/tycho-packaging-plugin/src/test/java/org/eclipse/tycho/buildnumber/test/PackagePluginMojoTest.java deleted file mode 100644 index fc49d119de..0000000000 --- a/tycho-packaging-plugin/src/test/java/org/eclipse/tycho/buildnumber/test/PackagePluginMojoTest.java +++ /dev/null @@ -1,154 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2010, 2020 SAP AG and others. - * This program and the accompanying materials - * are made available under the terms of the Eclipse Public License 2.0 - * which accompanies this distribution, and is available at - * https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * SAP AG - initial API and implementation - *******************************************************************************/ -package org.eclipse.tycho.buildnumber.test; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.nio.file.Files; -import java.util.List; -import java.util.jar.JarFile; -import java.util.jar.Manifest; - -import org.apache.maven.execution.MavenSession; -import org.apache.maven.project.MavenProject; -import org.codehaus.plexus.util.FileUtils; -import org.eclipse.tycho.packaging.PackagePluginMojo; -import org.eclipse.tycho.testing.AbstractTychoMojoTestCase; - -public class PackagePluginMojoTest extends AbstractTychoMojoTestCase { - - public void testBinIncludesNoDot() throws Exception { - File basedir = getBasedir("projects/binIncludesNoDot"); - basedir = new File(basedir, "p001"); - PackagePluginMojo mojo = execMaven(basedir); - createDummyClassFile(basedir); - mojo.execute(); - try (JarFile pluginJar = new JarFile(new File(basedir, "target/test.jar"))) { - assertNull("class files from target/classes must not be included in plugin jar if no '.' in bin.includes", - pluginJar.getEntry("TestNoDot.class")); - } - } - - public void testOutputClassesInANestedFolder() throws Exception { - File basedir = getBasedir("projects/outputClassesInANestedFolder"); - //Copy the hello.properties to simulate the compiler and resource mojos - File classes = new File(basedir, "target/classes/"); - FileUtils.copyFileToDirectory(new File(basedir, "src/main/resources/hello.properties"), classes); - PackagePluginMojo mojo = execMaven(basedir); - createDummyClassFile(basedir); - mojo.execute(); - try (JarFile pluginJar = new JarFile(new File(basedir, "target/test.jar"))) { - //make sure we can find the WEB-INF/classes/hello.properties - //and no hello.properties in the root. - assertNotNull(pluginJar.getEntry("WEB-INF/classes/hello.properties")); - assertNull(pluginJar.getEntry("hello.properties")); - //make sure we can find the WEB-INF/classes/TestNoDot.class - //and no TestNoDot.class in the root. - assertNotNull(pluginJar.getEntry("WEB-INF/classes/TestNoDot.class")); - assertNull(pluginJar.getEntry("TestNoDot.class")); - } - } - - public void testBinIncludesSpaces() throws Exception { - File basedir = getBasedir("projects/binIncludesSpaces"); - File classes = new File(basedir, "target/classes"); - classes.mkdirs(); - Files.writeString(new File(classes, "foo.bar").toPath(), "foobar"); - PackagePluginMojo mojo = execMaven(basedir); - mojo.execute(); - - try (JarFile pluginJar = new JarFile(new File(basedir, "target/test.jar"))) { - assertNotNull(pluginJar.getEntry("foo.bar")); - } - } - - public void testCustomManifestNestedJar() throws Exception { - File basedir = getBasedir("projects/customManifestNestedJar"); - File classes = new File(basedir, "target/classes"); - classes.mkdirs(); - PackagePluginMojo mojo = execMaven(basedir); - mojo.execute(); - - try (JarFile nestedJar = new JarFile(new File(basedir, "nested.jar"))) { - assertEquals("nested", nestedJar.getManifest().getMainAttributes().getValue("Bundle-SymbolicName")); - } - } - - public void testNoManifestVersion() throws Exception { - File basedir = getBasedir("projects/noManifestVersion"); - PackagePluginMojo mojo = execMaven(basedir); - mojo.execute(); - - Manifest mf; - try (InputStream is = new FileInputStream(new File(basedir, "target/MANIFEST.MF"))) { - mf = new Manifest(is); - } - - String symbolicName = mf.getMainAttributes().getValue("Bundle-SymbolicName"); - - assertEquals("bundle;singleton:=true", symbolicName); - } - - public void testMavenDescriptorNotAddedToJarIfSetToFalse() throws Exception { - File basedir = getBasedir("projects/addMavenDescriptor/pluginForcedToFalse"); - File classes = new File(basedir, "target/classes"); - classes.mkdirs(); - PackagePluginMojo mojo = execMaven(basedir); - mojo.execute(); - - try (JarFile nestedJar = new JarFile(new File(basedir, "target/pluginForcedToFalse.jar"))) { - assertNull("Jar must not contain the maven descriptor if forced to not include it!", - nestedJar.getEntry("META-INF/maven")); - } - } - - public void testMavenDescriptorAddedToJarPerDefault() throws Exception { - File basedir = getBasedir("projects/addMavenDescriptor/pluginDefault"); - File classes = new File(basedir, "target/classes"); - classes.mkdirs(); - PackagePluginMojo mojo = execMaven(basedir); - mojo.execute(); - - try (JarFile nestedJar = new JarFile(new File(basedir, "target/pluginDefault.jar"))) { - assertNotNull("Jar must contain the maven descriptor per default!", nestedJar.getEntry("META-INF/maven")); - } - } - - private PackagePluginMojo execMaven(File basedir) throws Exception { - List projects = getSortedProjects(basedir); - MavenProject project = projects.get(0); - MavenSession session = newMavenSession(project, projects); - - // set build qualifier - lookupMojoWithDefaultConfiguration(project, session, "build-qualifier").execute(); - - return getMojo("package-plugin", PackagePluginMojo.class, project, session); - } - - private void createDummyClassFile(File basedir) throws IOException { - File classFile = new File(basedir, "target/classes/TestNoDot.class"); - classFile.getParentFile().mkdirs(); - classFile.createNewFile(); - } - - private T getMojo(String goal, Class mojoClass, MavenProject project, MavenSession session) - throws Exception { - T mojo = mojoClass.cast(lookupMojo(goal, project.getFile())); - setVariableValueToObject(mojo, "project", project); - setVariableValueToObject(mojo, "session", session); - return mojo; - } - -} diff --git a/tycho-packaging-plugin/src/test/java/org/eclipse/tycho/buildnumber/test/ValidateVersionTest.java b/tycho-packaging-plugin/src/test/java/org/eclipse/tycho/buildnumber/test/ValidateVersionTest.java deleted file mode 100644 index 2ea057106b..0000000000 --- a/tycho-packaging-plugin/src/test/java/org/eclipse/tycho/buildnumber/test/ValidateVersionTest.java +++ /dev/null @@ -1,94 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008, 2015 Sonatype Inc. and others. - * This program and the accompanying materials - * are made available under the terms of the Eclipse Public License 2.0 - * which accompanies this distribution, and is available at - * https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Sonatype Inc. - initial API and implementation - *******************************************************************************/ -package org.eclipse.tycho.buildnumber.test; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; - -import org.apache.maven.plugin.MojoExecutionException; -import org.apache.maven.plugin.logging.Log; -import org.eclipse.tycho.buildversion.ValidateVersionMojo; -import org.eclipse.tycho.testing.AbstractTychoMojoTestCase; -import org.junit.Assert; -import org.junit.Test; - -public class ValidateVersionTest extends AbstractTychoMojoTestCase { - - private ValidateVersionMojo mojo; - private Log log; - - @Override - protected void setUp() throws Exception { - super.setUp(); - - mojo = new ValidateVersionMojo(); - log = mock(Log.class); - mojo.setLog(log); - } - - @Test - public void testValidateVersionWithVersionMatches() throws MojoExecutionException { - mojo.validateReleaseVersion("1.2.3", "1.2.3"); - mojo.validateSnapshotVersion("1.2.3-SNAPSHOT", "1.2.3.qualifier"); - } - - @Test - public void testValidateSnapshotVersionWithInvalidVersionsUsingStrictVersions() - throws MojoExecutionException, IllegalAccessException { - testValidateSnapshotVersionWithInvalidVersions(true); - } - - @Test - public void testValidateSnapshotVersionWithInvalidVersionsUsingNonStrictVersions() - throws MojoExecutionException, IllegalAccessException { - testValidateSnapshotVersionWithInvalidVersions(false); - } - - private void testValidateSnapshotVersionWithInvalidVersions(Boolean strictVersions) - throws MojoExecutionException, IllegalAccessException { - setVariableValueToObject(mojo, "strictVersions", strictVersions); - assertInvalidSnapshotVersion("1.2.3-SNAPSHOT", "1.2.3", - "OSGi version 1.2.3 must have .qualifier qualifier for SNAPSHOT builds", strictVersions); - - assertInvalidSnapshotVersion("1.2.3", "1.2.3.qualifier", - "Maven version 1.2.3 must have -SNAPSHOT qualifier for SNAPSHOT builds", strictVersions); - - assertInvalidSnapshotVersion("1.2.3-SNAPSHOT", "1.2.0.qualifier", - "Unqualified OSGi version 1.2.0.qualifier must match unqualified Maven version 1.2.3-SNAPSHOT for SNAPSHOT builds", - strictVersions); - - assertInvalidSnapshotVersion("1.2.3.qualifier", "1.2.3.qualifier", - "Maven version 1.2.3.qualifier must have -SNAPSHOT qualifier for SNAPSHOT builds", strictVersions); - - assertInvalidSnapshotVersion("1.2.3-SNAPSHOT", "1.2.3.SNAPSHOT", - "OSGi version 1.2.3.SNAPSHOT must have .qualifier qualifier for SNAPSHOT builds", strictVersions); - } - - private void assertInvalidSnapshotVersion(String maven, String osgi, String expectedMessage, boolean strictVersions) - throws MojoExecutionException { - try { - mojo.validateSnapshotVersion(maven, osgi); - if (strictVersions) { - fail(); - } else { - verify(log).warn(expectedMessage); - } - } catch (MojoExecutionException e) { - if (strictVersions) { - Assert.assertEquals(expectedMessage, e.getMessage()); - } else { - throw e; - } - } - } -} diff --git a/tycho-packaging-plugin/src/test/java/org/eclipse/tycho/buildversion/BuildQualifierTest.java b/tycho-packaging-plugin/src/test/java/org/eclipse/tycho/buildversion/BuildQualifierTest.java deleted file mode 100644 index b09bfda89e..0000000000 --- a/tycho-packaging-plugin/src/test/java/org/eclipse/tycho/buildversion/BuildQualifierTest.java +++ /dev/null @@ -1,303 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008, 2015 Sonatype Inc. and others. - * This program and the accompanying materials - * are made available under the terms of the Eclipse Public License 2.0 - * which accompanies this distribution, and is available at - * https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Sonatype Inc. - initial API and implementation - *******************************************************************************/ -package org.eclipse.tycho.buildversion; - -import static org.junit.Assert.assertThrows; - -import java.io.File; -import java.io.IOException; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; -import java.util.Properties; -import java.util.TimeZone; - -import org.apache.maven.execution.MavenExecutionRequest; -import org.apache.maven.execution.MavenExecutionResult; -import org.apache.maven.execution.MavenSession; -import org.apache.maven.plugin.MojoExecutionException; -import org.apache.maven.plugin.MojoFailureException; -import org.apache.maven.project.MavenProject; -import org.codehaus.plexus.component.configurator.ComponentConfigurationException; -import org.eclipse.tycho.ArtifactDescriptor; -import org.eclipse.tycho.ArtifactType; -import org.eclipse.tycho.DependencyArtifacts; -import org.eclipse.tycho.ReactorProject; -import org.eclipse.tycho.TychoConstants; -import org.eclipse.tycho.core.osgitools.DefaultReactorProject; -import org.eclipse.tycho.core.osgitools.targetplatform.DefaultDependencyArtifacts; -import org.eclipse.tycho.testing.AbstractTychoMojoTestCase; -import org.eclipse.tycho.version.TychoVersion; - -public class BuildQualifierTest extends AbstractTychoMojoTestCase { - - private static final String BUILD_QUALIFIER_PROPERTY = "buildQualifier"; - private static final String UNQUALIFIED_VERSION_PROPERTY = "unqualifiedVersion"; - private static final String QUALIFIED_VERSION_PROPERTY = "qualifiedVersion"; - - public void testForceContextQualifier() throws Exception { - /* - * This test covers all scenarios that involve forceContextQualifier mojo parameter, i.e. - * setting -DforceContextQualifier=... on cli, specifying forceContextQualifier project - * property and setting forceContextQualifier using explicit mojo configuration. - */ - - MavenProject project = getProject("projects/buildqualifier", "p001/pom.xml"); - project.getProperties().put(BUILD_QUALIFIER_PROPERTY, "garbage"); - BuildQualifierMojo mojo = createMojoWithProject(project); - - setVariableValueToObject(mojo, "forceContextQualifier", "foo-bar"); - - mojo.execute(); - - assertEquals("foo-bar", project.getProperties().get(BUILD_QUALIFIER_PROPERTY)); - } - - public void testBuildProperties() throws Exception { - MavenProject project = getProject("projects/buildqualifier", "p002/pom.xml"); - project.getProperties().put(BUILD_QUALIFIER_PROPERTY, "garbage"); - BuildQualifierMojo mojo = createMojoWithProject(project); - - mojo.execute(); - - assertEquals("blah", project.getProperties().get(BUILD_QUALIFIER_PROPERTY)); - } - - public void testTimestamp() throws Exception { - - MavenProject project = getProject("projects/buildqualifier", "p001/pom.xml"); - project.getProperties().put(BUILD_QUALIFIER_PROPERTY, "garbage"); - - ArrayList projects = new ArrayList<>(); - projects.add(project); - - BuildQualifierMojo mojo = createMojoWithProject(project); - - mojo.execute(); - - String firstTimestamp = (String) project.getProperties().get(BUILD_QUALIFIER_PROPERTY); - - // lets do it again - Thread.sleep(500L); - - project = getProject("projects/buildqualifier", "p001/pom.xml"); - assertNull(project.getProperties().get(BUILD_QUALIFIER_PROPERTY)); - mojo = createMojoWithProject(project); - mojo.execute(); - - String secondTimestamp = (String) project.getProperties().get(BUILD_QUALIFIER_PROPERTY); - SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmm"); - Date firstDate = dateFormat.parse(firstTimestamp); - Date secondDate = dateFormat.parse(secondTimestamp); - - // 2nd build time must be the same (within the same minute) - // or higher than the 1st build time - assertTrue(secondDate.compareTo(firstDate) >= 0); - } - - public void testUnqualifiedVersion() throws Exception { - MavenProject project = getProject("projects/buildqualifier", "p002/pom.xml"); - BuildQualifierMojo mojo = createMojoWithProject(project); - - mojo.execute(); - - assertEquals("0.0.1", project.getProperties().get(UNQUALIFIED_VERSION_PROPERTY)); - } - - public void testFullyQualifiedVersion() throws Exception { - MavenProject project = getProject("projects/buildqualifier/fullyqualified", "pom.xml"); - BuildQualifierMojo mojo = createMojoWithProject(project); - - mojo.execute(); - - assertEquals("0.0.1", project.getProperties().get(UNQUALIFIED_VERSION_PROPERTY)); - assertEquals("123456", project.getProperties().get(BUILD_QUALIFIER_PROPERTY)); - assertEquals("0.0.1.123456", project.getProperties().get(QUALIFIED_VERSION_PROPERTY)); - } - - public void testNoQualifiedVersion() throws Exception { - MavenProject project = getProject("projects/buildqualifier/noqualifier", "pom.xml"); - BuildQualifierMojo mojo = createMojoWithProject(project); - - mojo.execute(); - - assertEquals("0.0.1", project.getProperties().get(UNQUALIFIED_VERSION_PROPERTY)); - assertEquals("", project.getProperties().get(BUILD_QUALIFIER_PROPERTY)); - assertEquals("0.0.1", project.getProperties().get(QUALIFIED_VERSION_PROPERTY)); - } - - public void testTimeZone() { - final TimeZone oldTimeZone = TimeZone.getDefault(); - try { - final Date date = new Date(0L); - String qualiferCreatedInGMTTimeZone = createTimeStampInTimeZone("GMT", date); - String qualiferCreatedInGMTPlus2TimeZone = createTimeStampInTimeZone("GMT+02:00", date); - assertEquals(qualiferCreatedInGMTPlus2TimeZone, qualiferCreatedInGMTTimeZone); - } finally { - TimeZone.setDefault(oldTimeZone); - } - } - - public void testStableQualifier() throws Exception { - File basedir = getBasedir("projects/stablebuildqualifier/basic"); - - List projects = getSortedProjects(basedir); - MavenSession session = newMavenSession(projects.get(0), projects); - - executeMojo(session, getProject(projects, "bundle01")); - executeMojo(session, getProject(projects, "bundle02")); - executeMojo(session, getProject(projects, "feature02"), "build-qualifier-aggregator"); - executeMojo(session, getProject(projects, "feature"), "build-qualifier-aggregator"); - executeMojo(session, getProject(projects, "product"), "build-qualifier-aggregator"); - - assertQualifier("201205192000", projects, "bundle02"); - // feature02 includes bundle02, but its qualifier is hard-coded via the manifest - assertQualifier("201205191300", projects, "feature02"); - // product includes feature02, and hence transitively also bundle02, but qualifier is only the max. of direct inclusions - assertQualifier("201205191300", projects, "product"); - - assertQualifier("201205191500", projects, "bundle01"); - // feature has direct inclusions bundle01 and feature02 -> bundle01's 1500 time-stamp is the max. - assertQualifier("201205191500", projects, "feature"); - - } - - public void testUnparsableIncludedArtifactQualifier() throws Exception { - File basedir = getBasedir("projects/stablebuildqualifier/unpasablequalifier"); - - List projects = getSortedProjects(basedir); - MavenSession session = newMavenSession(projects.get(0), projects); - - executeMojo(session, getProject(projects, "bundle")); - executeMojo(session, getProject(projects, "feature")); - - assertQualifier("201205191300", projects, "feature"); - } - - public void testAggregateAttachedFeatureQualifier() throws Exception { - File basedir = getBasedir("projects/stablebuildqualifier/attachedfeature"); - Properties properties = new Properties(); - properties.setProperty("tycho-version", TychoVersion.getTychoVersion()); - List projects = getSortedProjects(basedir, properties); - MavenProject project = getProject(projects, "attachedfeature"); - ReactorProject reactorProject = DefaultReactorProject.adapt(project); - - DefaultDependencyArtifacts dependencyArtifacts = (DefaultDependencyArtifacts) getDependencyArtifacts( - reactorProject); - - // replace target platform dependencies with fake attached feature and bundle - // artifacts - ArtifactDescriptor attachedFeature = dependencyArtifacts.getArtifact(ArtifactType.TYPE_ECLIPSE_FEATURE, - "attachedfeature.attached.feature", null); - dependencyArtifacts.removeAll(attachedFeature.getKey().getType(), attachedFeature.getKey().getId()); - - dependencyArtifacts.addReactorArtifact(attachedFeature.getKey(), reactorProject, - "attached-feature", - attachedFeature.getInstallableUnits()); - ArtifactDescriptor attachedBundle = dependencyArtifacts.getArtifact(ArtifactType.TYPE_ECLIPSE_PLUGIN, - "attachedfeature.attached.bundle", null); - dependencyArtifacts.removeAll(attachedBundle.getKey().getType(), attachedBundle.getKey().getId()); - dependencyArtifacts.addReactorArtifact(attachedBundle.getKey(), reactorProject, "attached-bundle", - attachedBundle.getInstallableUnits()); - - MavenSession session = newMavenSession(projects.get(0), projects); - - executeMojo(session, project, "build-qualifier-aggregator"); - - assertQualifier("201206180600", projects, "attachedfeature"); - } - - public static DependencyArtifacts getDependencyArtifacts(ReactorProject project) throws IllegalStateException { - DependencyArtifacts resolvedDependencies = (DependencyArtifacts) project - .getContextValue(TychoConstants.CTX_DEPENDENCY_ARTIFACTS); - if (resolvedDependencies == null) { - throw new IllegalStateException(); - } - return resolvedDependencies; - } - - public void testWithInvalidQualifierFormat() throws Exception { - MavenProject project = getProject("projects/buildqualifier", "p001/pom.xml"); - BuildQualifierMojo mojo = createMojoWithProject(project); - mojo.setFormat("yyyyMMdd HHmm"); - MojoFailureException e = assertThrows(MojoFailureException.class, () -> mojo.execute()); - assertTrue(e.getMessage().contains("Invalid build qualifier")); - } - - public void testWithInvalidForcedQualifier() throws Exception { - MavenProject project = getProject("projects/buildqualifier", "p001/pom.xml"); - BuildQualifierMojo mojo = createMojoWithProject(project); - setVariableValueToObject(mojo, "forceContextQualifier", "invalid:Qualifier"); - MojoFailureException e = assertThrows(MojoFailureException.class, () -> mojo.execute()); - assertTrue(e.getMessage().contains("Invalid build qualifier")); - } - - public void testInvalidQualifierDisplaysInErrorMessage() throws Exception { - MavenProject project = getProject("projects/buildqualifier", "p001/pom.xml"); - BuildQualifierMojo mojo = createMojoWithProject(project); - mojo.setFormat("'This qualifier should be in error message'"); - MojoFailureException e = assertThrows(MojoFailureException.class, () -> mojo.execute()); - assertTrue(e.getMessage().contains("This qualifier should be in error message")); - } - - private BuildQualifierMojo createMojoWithProject(MavenProject project) throws IOException, Exception { - ArrayList projects = new ArrayList<>(); - projects.add(project); - MavenSession session = newMavenSession(projects.get(0), projects); - BuildQualifierMojo mojo = getMojo(project, session); - return mojo; - } - - private void assertQualifier(String expected, List projects, String artifactId) { - MavenProject project = getProject(projects, artifactId); - assertEquals(expected, project.getProperties().getProperty(BUILD_QUALIFIER_PROPERTY)); - } - - private void executeMojo(MavenSession session, MavenProject project) throws Exception { - executeMojo(session, project, "build-qualifier"); - } - - protected void executeMojo(MavenSession session, MavenProject project, String goal) - throws Exception, ComponentConfigurationException, MojoExecutionException, MojoFailureException { - session.setCurrentProject(project); - BuildQualifierMojo mojo = (BuildQualifierMojo) lookupConfiguredMojo(session, newMojoExecution(goal)); - mojo.execute(); - } - - private String createTimeStampInTimeZone(String timeZone, Date date) { - TimeZone.setDefault(TimeZone.getTimeZone(timeZone)); - BuildQualifierMojo mojo = new BuildQualifierMojo(); - mojo.setFormat("yyyyMMddHHmm"); - return mojo.getQualifier(date); - } - - private MavenProject getProject(String baseDir, String pom) throws Exception { - File basedirFile = getBasedir(baseDir); - File pomFile = new File(basedirFile, pom); - MavenExecutionRequest request = newMavenExecutionRequest(pomFile); - request.getProjectBuildingRequest().setProcessPlugins(false); - MavenExecutionResult result = maven.execute(request); - return result.getProject(); - } - - private BuildQualifierMojo getMojo(MavenProject project, MavenSession session) throws Exception { - BuildQualifierMojo mojo = (BuildQualifierMojo) lookupMojo("build-qualifier", project.getFile()); - setVariableValueToObject(mojo, "project", project); - - setVariableValueToObject(mojo, "session", session); - - return mojo; - } - -} diff --git a/tycho-packaging-plugin/src/test/java/org/eclipse/tycho/buildversion/ValidateIdTest.java b/tycho-packaging-plugin/src/test/java/org/eclipse/tycho/buildversion/ValidateIdTest.java deleted file mode 100644 index ff81e6bad5..0000000000 --- a/tycho-packaging-plugin/src/test/java/org/eclipse/tycho/buildversion/ValidateIdTest.java +++ /dev/null @@ -1,88 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008, 2022 Sonatype Inc. and others. - * This program and the accompanying materials - * are made available under the terms of the Eclipse Public License 2.0 - * which accompanies this distribution, and is available at - * https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Sonatype Inc. - initial API and implementation - * Rapicorp, Inc. - add support for IU type (428310) - *******************************************************************************/ -package org.eclipse.tycho.buildversion; - -import static org.junit.Assert.assertThrows; - -import java.io.File; - -import org.apache.maven.execution.MavenExecutionRequest; -import org.apache.maven.execution.MavenExecutionResult; -import org.apache.maven.plugin.MojoExecutionException; -import org.apache.maven.project.MavenProject; -import org.eclipse.tycho.testing.AbstractTychoMojoTestCase; - -public class ValidateIdTest extends AbstractTychoMojoTestCase { - - public void testValidateMatchingIdBundle() throws MojoExecutionException, Exception { - File basedir = getBasedir("projects/matchingIds/bundle"); - ValidateIdMojo mojo = getMojo(basedir); - mojo.execute(); - } - - public void testValidateMatchingIdTestPlugin() throws MojoExecutionException, Exception { - File basedir = getBasedir("projects/matchingIds/test-plugin"); - ValidateIdMojo mojo = getMojo(basedir); - mojo.execute(); - } - - public void testValidateMatchingIdFeature() throws MojoExecutionException, Exception { - File basedir = getBasedir("projects/matchingIds/feature"); - ValidateIdMojo mojo = getMojo(basedir); - mojo.execute(); - } - - public void testValidateMatchingIdIU() throws MojoExecutionException, Exception { - File basedir = getBasedir("projects/matchingIds/iu"); - ValidateIdMojo mojo = getMojo(basedir); - mojo.execute(); - } - - public void testFailIfNonMatchingIdBundle() throws MojoExecutionException, Exception { - File basedir = getBasedir("projects/nonMatchingIds/bundle"); - ValidateIdMojo mojo = getMojo(basedir); - assertThrows(MojoExecutionException.class, () -> mojo.execute()); - } - - public void testFailIfNonMatchingIdTestPlugin() throws MojoExecutionException, Exception { - File basedir = getBasedir("projects/nonMatchingIds/test-plugin"); - ValidateIdMojo mojo = getMojo(basedir); - assertThrows(MojoExecutionException.class, () -> mojo.execute()); - } - - public void testFailIfNonMatchingIdFeature() throws MojoExecutionException, Exception { - File basedir = getBasedir("projects/nonMatchingIds/feature"); - ValidateIdMojo mojo = getMojo(basedir); - assertThrows(MojoExecutionException.class, () -> mojo.execute()); - } - - public void testFailIfNonMatchingIdIU() throws MojoExecutionException, Exception { - File basedir = getBasedir("projects/nonMatchingIds/iu"); - ValidateIdMojo mojo = getMojo(basedir); - assertThrows(MojoExecutionException.class, () -> mojo.execute()); - } - - private ValidateIdMojo getMojo(File basedir) throws Exception { - File pom = new File(basedir, "pom.xml"); - MavenExecutionRequest request = newMavenExecutionRequest(pom); - request.getProjectBuildingRequest().setProcessPlugins(false); - MavenExecutionResult result = maven.execute(request); - MavenProject project = result.getProject(); - ValidateIdMojo mojo = (ValidateIdMojo) lookupMojo("validate-id", project.getFile()); - setVariableValueToObject(mojo, "project", project); - setVariableValueToObject(mojo, "packaging", project.getPackaging()); - return mojo; - } - -} diff --git a/tycho-source-plugin/src/test/java/org/eclipse/tycho/source/OsgiSourceMojoTest.java b/tycho-source-plugin/src/test/java/org/eclipse/tycho/source/OsgiSourceMojoTest.java deleted file mode 100644 index 92e3bcd4f0..0000000000 --- a/tycho-source-plugin/src/test/java/org/eclipse/tycho/source/OsgiSourceMojoTest.java +++ /dev/null @@ -1,178 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2015, 2021 SAP AG and others. - * This program and the accompanying materials - * are made available under the terms of the Eclipse Public License 2.0 - * which accompanies this distribution, and is available at - * https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * SAP AG - initial API and implementation - *******************************************************************************/ - -package org.eclipse.tycho.source; - -import static java.util.Arrays.asList; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import java.io.File; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Properties; - -import org.apache.maven.execution.MavenSession; -import org.apache.maven.model.Build; -import org.apache.maven.model.Plugin; -import org.apache.maven.model.PluginExecution; -import org.apache.maven.plugin.logging.Log; -import org.apache.maven.project.MavenProject; -import org.codehaus.plexus.component.repository.exception.ComponentLookupException; -import org.codehaus.plexus.util.xml.Xpp3Dom; -import org.eclipse.tycho.BuildPropertiesParser; -import org.eclipse.tycho.ReactorProject; -import org.eclipse.tycho.core.osgitools.OsgiManifest; -import org.eclipse.tycho.testing.AbstractTychoMojoTestCase; -import org.eclipse.tycho.version.TychoVersion; -import org.osgi.framework.Constants; - -public class OsgiSourceMojoTest extends AbstractTychoMojoTestCase { - - private OsgiSourceMojo mojo; - - @Override - protected void setUp() throws Exception { - super.setUp(); - mojo = new OsgiSourceMojo(); - mojo.setBuildPropertiesParser(lookup(BuildPropertiesParser.class)); - } - - public void testIsRelevantProjectPackagingType() throws Exception { - assertTrue(mojo.isRelevantProject(createStubProjectWithSourceFolder("eclipse-plugin"))); - assertTrue(mojo.isRelevantProject(createStubProjectWithSourceFolder("eclipse-test-plugin"))); - assertFalse(mojo.isRelevantProject(createStubProjectWithSourceFolder("foo"))); - } - - public void testIsRelevantProjectSourcePluginEnabled() throws Exception { - assertTrue(mojo.isRelevantProject(createStubProjectWithSourceFolder(true))); - assertFalse(mojo.isRelevantProject(createStubProjectWithSourceFolder(false))); - } - - public void testIsRelevantProjectWithSourceIncludesOnly() throws Exception { - MavenProject stubProject = createStubProject("eclipse-plugin", "srcIncludesOnly", true); - assertTrue(mojo.isRelevantProject(stubProject)); - } - - public void testIsRelevantProjectNoSources() throws Exception { - MavenProject stubProject = createStubProject("eclipse-plugin", "noSources", true); - assertFalse(mojo.isRelevantProject(stubProject)); - } - - public void testIsRelevantProjectRequireSourceRootsConfigured() throws Exception { - MavenProject stubProject = createStubProject("eclipse-plugin", "noSources", true, true); - assertTrue(mojo.isRelevantProject(stubProject)); - } - - public void testDefaultClassifier() throws Exception { - File basedir = getBasedir("bundle01"); - List projects = getSortedProjects(basedir); - - MavenSession session = newMavenSession(projects.get(0)); - OsgiSourceMojo sourceMojo = (OsgiSourceMojo) lookupMojoWithDefaultConfiguration(projects.get(0), session, - "plugin-source"); - - assertEquals(ReactorProject.SOURCE_ARTIFACT_CLASSIFIER, sourceMojo.getClassifier()); - } - - public void testCustomClassifier() throws Exception { - Map config = new HashMap<>(); - config.put("classifier", "otherclassifier"); - OsgiSourceMojo sourceMojo = (OsgiSourceMojo) lookupMojo("org.eclipse.tycho", "tycho-source-plugin", - TychoVersion.getTychoVersion(), "plugin-source", null); - setVariableValueToObject(sourceMojo, "classifier", "customclassifier"); - assertEquals("customclassifier", sourceMojo.getClassifier()); - } - - public void testReadL10nPropsWithExistingL10nFile() throws Exception { - readL10nPropsSetup(); - OsgiManifest manifest = mock(OsgiManifest.class); - when(manifest.getValue(Constants.BUNDLE_LOCALIZATION)).thenReturn("l10n"); - Properties properties = mojo.readL10nProps(manifest); - verify(mojo.getLog(), never()).warn(anyString()); - assertNotNull(properties); - } - - public void testReadL10nPropsShouldPrintWarningForNonExistingL10NFile() throws Exception { - readL10nPropsSetup(); - OsgiManifest manifest = mock(OsgiManifest.class); - when(manifest.getValue(Constants.BUNDLE_LOCALIZATION)).thenReturn("nonexisting"); - Properties properties = mojo.readL10nProps(manifest); - verify(mojo.getLog(), times(1)).warn(anyString()); - assertNull(properties); - } - - public void testReadL10nPropsShouldNotWarnIfBundleIsNotL10Ned() throws Exception { - readL10nPropsSetup(); - OsgiManifest manifest = mock(OsgiManifest.class); - when(manifest.getValue(Constants.BUNDLE_LOCALIZATION)).thenReturn(null); - Properties properties = mojo.readL10nProps(manifest); - verify(mojo.getLog(), never()).warn(anyString()); - assertNull(properties); - } - - public void readL10nPropsSetup() throws Exception { - File basedir = getBasedir("bundleWithL10N"); - MavenProject mavenProject = new MavenProject(); - mavenProject.setFile(new File(basedir, "pom.xml")); - mojo.project = mavenProject; - Log log = mock(Log.class); - mojo.setLog(log); - } - - private MavenProject createStubProjectWithSourceFolder(String packaging) throws ComponentLookupException { - return createStubProject(packaging, "srcFolder", true); - } - - private MavenProject createStubProjectWithSourceFolder(boolean sourcePluginEnabled) - throws ComponentLookupException { - return createStubProject("eclipse-plugin", "srcFolder", sourcePluginEnabled); - } - - private MavenProject createStubProject(String packaging, String testResourceFolder, boolean enableSourePlugin) - throws ComponentLookupException { - return createStubProject(packaging, testResourceFolder, enableSourePlugin, false); - } - - private MavenProject createStubProject(String packaging, String testResourceFolder, boolean enableSourePlugin, - boolean requireSourceRoots) throws ComponentLookupException { - MavenProject stubProject = new MavenProject(); - stubProject.setPackaging(packaging); - if (enableSourePlugin) { - Build build = new Build(); - stubProject.setBuild(build); - Plugin tychoSourcePlugin = new Plugin(); - tychoSourcePlugin.setGroupId("org.eclipse.tycho"); - tychoSourcePlugin.setArtifactId("tycho-source-plugin"); - PluginExecution execution = new PluginExecution(); - execution.setGoals(asList("plugin-source")); - if (requireSourceRoots) { - Xpp3Dom config = new Xpp3Dom("configuration"); - Xpp3Dom requireSourceRootsDom = new Xpp3Dom("requireSourceRoots"); - requireSourceRootsDom.setValue("true"); - config.addChild(requireSourceRootsDom); - execution.setConfiguration(config); - } - tychoSourcePlugin.setExecutions(asList(execution)); - build.setPlugins(asList(tychoSourcePlugin)); - } - stubProject.setFile(new File("src/test/resources/sourceMojo/" + testResourceFolder + "/pom.xml")); - return stubProject; - } - -} diff --git a/tycho-testing-harness/src/main/java/org/eclipse/tycho/testing/AbstractTychoMojoTestCase.java b/tycho-testing-harness/src/main/java/org/eclipse/tycho/testing/AbstractTychoMojoTestCase.java deleted file mode 100644 index 399009d06d..0000000000 --- a/tycho-testing-harness/src/main/java/org/eclipse/tycho/testing/AbstractTychoMojoTestCase.java +++ /dev/null @@ -1,260 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008, 2016 Sonatype Inc. and others. - * This program and the accompanying materials - * are made available under the terms of the Eclipse Public License 2.0 - * which accompanies this distribution, and is available at - * https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Sonatype Inc. - initial API and implementation - *******************************************************************************/ -package org.eclipse.tycho.testing; - -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.util.Arrays; -import java.util.Date; -import java.util.List; -import java.util.Properties; -import java.util.stream.Collectors; - -import org.apache.maven.Maven; -import org.apache.maven.artifact.repository.ArtifactRepository; -import org.apache.maven.execution.DefaultMavenExecutionRequest; -import org.apache.maven.execution.DefaultMavenExecutionResult; -import org.apache.maven.execution.MavenExecutionRequest; -import org.apache.maven.execution.MavenExecutionRequestPopulator; -import org.apache.maven.execution.MavenExecutionResult; -import org.apache.maven.execution.MavenSession; -import org.apache.maven.internal.aether.DefaultRepositorySystemSessionFactory; -import org.apache.maven.plugin.LegacySupport; -import org.apache.maven.plugin.Mojo; -import org.apache.maven.plugin.MojoExecution; -import org.apache.maven.plugin.PluginParameterExpressionEvaluator; -import org.apache.maven.plugin.descriptor.Parameter; -import org.apache.maven.plugin.testing.AbstractMojoTestCase; -import org.apache.maven.project.MavenProject; -import org.apache.maven.project.ProjectBuildingRequest; -import org.apache.maven.repository.RepositorySystem; -import org.apache.maven.session.scope.internal.SessionScope; -import org.apache.maven.settings.MavenSettingsBuilder; -import org.apache.maven.settings.Settings; -import org.codehaus.plexus.PlexusContainer; -import org.codehaus.plexus.component.configurator.ComponentConfigurator; -import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluator; -import org.codehaus.plexus.configuration.xml.XmlPlexusConfiguration; -import org.codehaus.plexus.util.xml.Xpp3Dom; -import org.eclipse.aether.DefaultRepositorySystemSession; -import org.eclipse.tycho.resolver.TychoResolver; - -public class AbstractTychoMojoTestCase extends AbstractMojoTestCase { - - protected Maven maven; - private MavenSettingsBuilder settingsBuilder; - private MavenExecutionRequestPopulator requestPopulator; - private TychoResolver tychoResolver; - - @Override - protected void setUp() throws Exception { - super.setUp(); - SessionScope sessionScope = lookup(SessionScope.class); - MavenSession session = newMavenSession(new MavenProject()); - sessionScope.enter(); - sessionScope.seed(MavenSession.class, session); - maven = lookup(Maven.class); - settingsBuilder = lookup(MavenSettingsBuilder.class); - requestPopulator = lookup(MavenExecutionRequestPopulator.class); - tychoResolver = lookup(TychoResolver.class); - } - - @Override - protected void tearDown() throws Exception { - SessionScope sessionScope = lookup(SessionScope.class); - sessionScope.exit(); - maven = null; - super.tearDown(); - } - - @Override - protected String getCustomConfigurationName() { - return AbstractTychoMojoTestCase.class.getName().replace('.', '/') + ".xml"; - } - - @Override - protected Mojo lookupMojo(String goal, File pom) throws Exception { - return super.lookupMojo(goal, pom); - } - - protected ArtifactRepository getLocalRepository() throws Exception { - RepositorySystem repoSystem = lookup(RepositorySystem.class); - - File path = new File("target/local-repo").getAbsoluteFile(); - - return repoSystem.createLocalRepository(path); - } - - protected MavenExecutionRequest newMavenExecutionRequest(File pom) throws Exception { - Properties systemProps = new Properties(); - systemProps.putAll(System.getProperties()); - - Properties userProps = new Properties(); - userProps.put("tycho-version", "0.0.0"); - - MavenExecutionRequest request = new DefaultMavenExecutionRequest(); - request.setBaseDirectory(pom.getParentFile()); - request.setPom(pom); - request.setSystemProperties(systemProps); - request.setUserProperties(userProps); - request.setLocalRepository(getLocalRepository()); - request.setStartTime(new Date()); - File settingsFile = getUserSettingsFile(); - if (settingsFile.isFile()) { - request.setUserSettingsFile(settingsFile); - } - Settings settings = settingsBuilder.buildSettings(request); - requestPopulator.populateFromSettings(request, settings); - request.setGoals(Arrays.asList("validate")); - request.setLocalRepositoryPath(getLocalRepository().getBasedir()); - return request; - } - - private File getUserSettingsFile() throws IOException { - String systemValue = System.getProperty("tycho.testSettings"); - if (systemValue != null) { - return new File(systemValue); - } - Properties props = new Properties(); - try (InputStream stream = AbstractTychoMojoTestCase.class.getResourceAsStream("settings.properties")) { - props.load(stream); - } - String settingsFilePath = props.getProperty("settings.file"); - return new File(settingsFilePath); - } - - protected List getSortedProjects(File basedir) throws Exception { - return getSortedProjects(basedir, null); - } - - protected List getSortedProjects(File basedir, Properties userProperties) throws Exception { - File pom = new File(basedir, "pom.xml"); - MavenExecutionRequest request = newMavenExecutionRequest(pom); - ProjectBuildingRequest projectBuildingRequest = request.getProjectBuildingRequest(); - projectBuildingRequest.setProcessPlugins(false); - request.setLocalRepository(getLocalRepository()); - if (userProperties != null) { - request.getUserProperties().putAll(userProperties); - } - MavenExecutionResult result = maven.execute(request); - if (result.hasExceptions()) { - throw new CompoundRuntimeException(result.getExceptions()); - } - List projects = result.getTopologicallySortedProjects(); - for (MavenProject mavenProject : projects) { - PlexusContainer container = getContainer(); - DefaultRepositorySystemSessionFactory repositorySystemSessionFactory = container - .lookup(DefaultRepositorySystemSessionFactory.class); - DefaultRepositorySystemSession repositorySession = repositorySystemSessionFactory - .newRepositorySession(request); - MavenSession session = new MavenSession(container, repositorySession, request, result); - LegacySupport lookup = container.lookup(LegacySupport.class); - session.setProjects(projects); - MavenSession oldSession = lookup.getSession(); - try { - lookup.setSession(session); - tychoResolver.resolveProject(session, mavenProject); - } catch (RuntimeException e) { - result.addException(e); - } finally { - lookup.setSession(oldSession); - } - } - if (result.hasExceptions()) { - throw new CompoundRuntimeException(result.getExceptions()); - } - return projects; - } - - protected MavenSession newMavenSession(MavenProject project, List projects) throws Exception { - MavenExecutionRequest request = newMavenExecutionRequest(new File(project.getBasedir(), "pom.xml")); - MavenExecutionResult result = new DefaultMavenExecutionResult(); - DefaultRepositorySystemSession repositorySession = new DefaultRepositorySystemSession(); - MavenSession session = new MavenSession(getContainer(), repositorySession, request, result); - session.setProjects(projects); - session.setCurrentProject(project); - return session; - } - - protected MavenProject getProject(List projects, String artifactId) { - for (MavenProject project : projects) { - if (artifactId.equals(project.getArtifactId())) { - return project; - } - } - - throw new IllegalArgumentException("No project with artifactId " + artifactId); - } - - protected MavenProject getProjectWithArtifactId(List projects, String artifactId) - throws AssertionError, Exception { - return projects.stream().filter(p -> artifactId.equals(p.getArtifactId())).findFirst() - .orElseThrow(() -> new AssertionError("Project with artifactId " + artifactId - + " not found, projects discovered are: " - + projects.stream().map(MavenProject::getArtifactId).collect(Collectors.joining(", ")))); - } - - protected MavenProject getProjectWithName(List projects, String name) - throws AssertionError, Exception { - return projects.stream().filter(p -> name.equals(p.getName())).findFirst().orElseThrow( - () -> new AssertionError("Project with name " + name + " not found, projects discovered are: " - + projects.stream().map(MavenProject::getName).collect(Collectors.joining(", ")))); - } - - /** - * Returns a mojo configured with the mojo's default configuration. - */ - // workaround for MPLUGINTESTING-46 - see https://jira.codehaus.org/browse/MPLUGINTESTING-46 - protected Mojo lookupMojoWithDefaultConfiguration(MavenProject project, MavenSession session, String goal) - throws Exception { - Mojo mojo = lookupEmptyMojo(goal, project.getFile()); - configureMojoWithDefaultConfiguration(mojo, session, goal); - return mojo; - } - - /** - * Configures the given mojo according to the specified goal of the given session. - *

- * Especially this also initializes each {@link Parameter} of the mojo with its default values. - *

- */ - protected void configureMojoWithDefaultConfiguration(Mojo mojo, MavenSession session, String goal) - throws Exception { - MojoExecution mojoExecution = newMojoExecution(goal); - configureMojoWithDefaultConfiguration(mojo, session, mojoExecution); - } - - /** - * Configures the given mojo according to the specified session and mojo-exectuion. - *

- * Especially this also initializes each {@link Parameter} of the mojo with its default values. - *

- */ - private void configureMojoWithDefaultConfiguration(Mojo mojo, MavenSession session, MojoExecution mojoExecution) - throws Exception { - Xpp3Dom defaultConfiguration = mojoExecution.getConfiguration(); - - // the ResolverExpressionEvaluatorStub of lookupMojo is not sufficient to evaluate the variables in the default configuration - ExpressionEvaluator expressionEvaluator = new PluginParameterExpressionEvaluator(session, mojoExecution); - ComponentConfigurator configurator = getContainer().lookup(ComponentConfigurator.class, "basic"); - - configurator.configureComponent(mojo, new XmlPlexusConfiguration(defaultConfiguration), expressionEvaluator, - getContainer().getContainerRealm(), null); - } - - protected static File getBasedir(String name) throws IOException { - return TestUtil.getBasedir(name); - } - -}