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/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-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/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); - } - -}