This is an automated email from the ASF dual-hosted git repository. gnodet pushed a commit to branch maven-plugin-testing-3.x in repository https://gitbox.apache.org/repos/asf/maven-plugin-testing.git
commit ef22a776ad01fed838e1769a0f73c57c6c0e1a29 Author: Tamas Cservenak <ta...@cservenak.net> AuthorDate: Mon May 6 11:39:34 2024 +0200 Maven 3.x support --- .../{workflows/maven-verify.yml => dependabot.yml} | 23 +- .github/workflows/maven-verify.yml | 2 +- maven-plugin-testing-harness/pom.xml | 59 ++- .../api/plugin/testing/ConfigurationException.java | 51 --- .../maven/api/plugin/testing/InjectMojo.java | 35 -- .../maven/api/plugin/testing/MojoExtension.java | 431 --------------------- .../maven/api/plugin/testing/MojoParameter.java | 34 -- .../maven/api/plugin/testing/MojoParameters.java | 30 -- .../apache/maven/api/plugin/testing/MojoTest.java | 34 -- .../testing/ResolverExpressionEvaluatorStub.java | 120 ------ .../api/plugin/testing/stubs/ArtifactStub.java | 172 -------- .../plugin/testing/stubs/MojoExecutionStub.java | 66 ---- .../api/plugin/testing/stubs/ProjectStub.java | 193 --------- .../api/plugin/testing/stubs/SessionStub.java | 278 ------------- .../org/apache/maven/plugin/testing/MojoRule.java | 2 - .../maven/plugin/testing/junit5/MojoExtension.java | 9 +- .../plugin/testing/ExpressionEvaluatorTest.java | 125 ------ .../maven/plugin/testing/MojoTestCaseTest.java | 2 +- pom.xml | 8 +- 19 files changed, 74 insertions(+), 1600 deletions(-) diff --git a/.github/workflows/maven-verify.yml b/.github/dependabot.yml similarity index 72% copy from .github/workflows/maven-verify.yml copy to .github/dependabot.yml index 4d67fdc..ccf1b48 100644 --- a/.github/workflows/maven-verify.yml +++ b/.github/dependabot.yml @@ -15,13 +15,16 @@ # specific language governing permissions and limitations # under the License. -name: Verify - -on: - push: - pull_request: - -jobs: - build: - name: Verify - uses: apache/maven-gh-actions-shared/.github/workflows/maven-verify.yml@v3 +version: 2 +updates: + - package-ecosystem: "maven" + directory: "/" + schedule: + interval: "daily" + ignore: + # ignore Maven Core updates + - dependency-name: "org.apache.maven:*" + - package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "daily" diff --git a/.github/workflows/maven-verify.yml b/.github/workflows/maven-verify.yml index 4d67fdc..932827c 100644 --- a/.github/workflows/maven-verify.yml +++ b/.github/workflows/maven-verify.yml @@ -24,4 +24,4 @@ on: jobs: build: name: Verify - uses: apache/maven-gh-actions-shared/.github/workflows/maven-verify.yml@v3 + uses: apache/maven-gh-actions-shared/.github/workflows/maven-verify.yml@v4 diff --git a/maven-plugin-testing-harness/pom.xml b/maven-plugin-testing-harness/pom.xml index beaa39d..e32f630 100644 --- a/maven-plugin-testing-harness/pom.xml +++ b/maven-plugin-testing-harness/pom.xml @@ -23,19 +23,23 @@ under the License. <parent> <groupId>org.apache.maven.plugin-testing</groupId> <artifactId>maven-plugin-testing</artifactId> - <version>4.0.0-alpha-3-SNAPSHOT</version> + <version>3.4.0-SNAPSHOT</version> </parent> <artifactId>maven-plugin-testing-harness</artifactId> <name>Maven Plugin Testing Mechanism</name> <description>The Maven Plugin Testing Harness provides mechanisms to manage tests on Mojo.</description> + <properties> + <wagonVersion>3.5.3</wagonVersion> + </properties> + <dependencyManagement> <dependencies> <dependency> <groupId>org.junit</groupId> <artifactId>junit-bom</artifactId> - <version>5.10.0</version> + <version>5.10.2</version> <type>pom</type> <scope>import</scope> </dependency> @@ -46,7 +50,7 @@ under the License. <!-- maven --> <dependency> <groupId>org.apache.maven</groupId> - <artifactId>maven-api-core</artifactId> + <artifactId>maven-artifact</artifactId> <version>${mavenVersion}</version> <scope>provided</scope> </dependency> @@ -74,30 +78,69 @@ under the License. <version>${mavenVersion}</version> <scope>provided</scope> </dependency> + <dependency> + <groupId>org.apache.maven.wagon</groupId> + <artifactId>wagon-provider-api</artifactId> + <version>${wagonVersion}</version> + <scope>provided</scope> + </dependency> + <dependency> + <groupId>org.apache.maven.wagon</groupId> + <artifactId>wagon-file</artifactId> + <version>${wagonVersion}</version> + <scope>provided</scope> + </dependency> + <dependency> + <groupId>org.apache.maven.wagon</groupId> + <artifactId>wagon-http</artifactId> + <version>${wagonVersion}</version> + <scope>provided</scope> + </dependency> + <!-- + Keep this one as isolated as possible. + But has to be present, as Maven 3 object graph is incomplete without it + --> + <dependency> + <groupId>org.apache.maven</groupId> + <artifactId>maven-compat</artifactId> + <version>${mavenVersion}</version> + <scope>runtime</scope> + <exclusions> + <exclusion> + <groupId>*</groupId> + <artifactId>*</artifactId> + </exclusion> + </exclusions> + </dependency> <!-- plexus --> <dependency> <groupId>org.codehaus.plexus</groupId> <artifactId>plexus-utils</artifactId> - <version>4.0.0</version> + <version>4.0.1</version> </dependency> <dependency> <!-- correct version must be provided by project depends on Maven version --> <groupId>org.codehaus.plexus</groupId> <artifactId>plexus-xml</artifactId> - <version>4.0.0</version> + <version>4.0.3</version> <optional>true</optional> </dependency> <dependency> <groupId>org.codehaus.plexus</groupId> <artifactId>plexus-archiver</artifactId> - <version>4.8.0</version> + <version>4.9.2</version> + </dependency> + <dependency> + <groupId>org.apache.commons</groupId> + <artifactId>commons-compress</artifactId> + <version>1.26.1</version> </dependency> <dependency> <groupId>org.codehaus.plexus</groupId> <artifactId>plexus-testing</artifactId> - <version>1.1.0</version> + <version>1.3.0</version> <exclusions> <exclusion> <!-- we need as optional dependencies --> @@ -110,7 +153,7 @@ under the License. <!-- newer version is required by plexus-testing --> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> - <version>32.0.1-jre</version> + <version>33.2.0-jre</version> </dependency> <dependency> <groupId>junit</groupId> diff --git a/maven-plugin-testing-harness/src/main/java/org/apache/maven/api/plugin/testing/ConfigurationException.java b/maven-plugin-testing-harness/src/main/java/org/apache/maven/api/plugin/testing/ConfigurationException.java deleted file mode 100644 index dd13791..0000000 --- a/maven-plugin-testing-harness/src/main/java/org/apache/maven/api/plugin/testing/ConfigurationException.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.maven.api.plugin.testing; - -/** - * ConfigurationException - * - * @author jesse - */ -public class ConfigurationException extends Exception { - /** serialVersionUID */ - static final long serialVersionUID = -6180939638742159065L; - - /** - * @param message The detailed message. - */ - public ConfigurationException(String message) { - super(message); - } - - /** - * @param cause The detailed cause. - */ - public ConfigurationException(Throwable cause) { - super(cause); - } - - /** - * @param message The detailed message. - * @param cause The detailed cause. - */ - public ConfigurationException(String message, Throwable cause) { - super(message, cause); - } -} diff --git a/maven-plugin-testing-harness/src/main/java/org/apache/maven/api/plugin/testing/InjectMojo.java b/maven-plugin-testing-harness/src/main/java/org/apache/maven/api/plugin/testing/InjectMojo.java deleted file mode 100644 index e094d06..0000000 --- a/maven-plugin-testing-harness/src/main/java/org/apache/maven/api/plugin/testing/InjectMojo.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.maven.api.plugin.testing; - -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; - -/** - * - */ -@Retention(RetentionPolicy.RUNTIME) -public @interface InjectMojo { - - String goal(); - - String pom(); - - boolean empty() default false; -} diff --git a/maven-plugin-testing-harness/src/main/java/org/apache/maven/api/plugin/testing/MojoExtension.java b/maven-plugin-testing-harness/src/main/java/org/apache/maven/api/plugin/testing/MojoExtension.java deleted file mode 100644 index b217fab..0000000 --- a/maven-plugin-testing-harness/src/main/java/org/apache/maven/api/plugin/testing/MojoExtension.java +++ /dev/null @@ -1,431 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.maven.api.plugin.testing; - -import java.io.BufferedReader; -import java.io.File; -import java.io.InputStream; -import java.io.Reader; -import java.io.StringReader; -import java.lang.reflect.AccessibleObject; -import java.lang.reflect.Field; -import java.net.URL; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; -import java.util.Set; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -import com.google.inject.internal.ProviderMethodsModule; -import org.apache.maven.api.MojoExecution; -import org.apache.maven.api.Project; -import org.apache.maven.api.Session; -import org.apache.maven.api.plugin.Log; -import org.apache.maven.api.plugin.Mojo; -import org.apache.maven.api.xml.XmlNode; -import org.apache.maven.configuration.internal.EnhancedComponentConfigurator; -import org.apache.maven.internal.impl.DefaultLog; -import org.apache.maven.internal.xml.XmlNodeImpl; -import org.apache.maven.lifecycle.internal.MojoDescriptorCreator; -import org.apache.maven.plugin.PluginParameterExpressionEvaluatorV4; -import org.apache.maven.plugin.descriptor.MojoDescriptor; -import org.apache.maven.plugin.descriptor.Parameter; -import org.apache.maven.plugin.descriptor.PluginDescriptor; -import org.apache.maven.plugin.descriptor.PluginDescriptorBuilder; -import org.codehaus.plexus.DefaultPlexusContainer; -import org.codehaus.plexus.PlexusContainer; -import org.codehaus.plexus.component.configurator.ComponentConfigurator; -import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluationException; -import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluator; -import org.codehaus.plexus.component.configurator.expression.TypeAwareExpressionEvaluator; -import org.codehaus.plexus.component.repository.ComponentDescriptor; -import org.codehaus.plexus.component.repository.exception.ComponentLookupException; -import org.codehaus.plexus.configuration.xml.XmlPlexusConfiguration; -import org.codehaus.plexus.testing.PlexusExtension; -import org.codehaus.plexus.util.InterpolationFilterReader; -import org.codehaus.plexus.util.ReaderFactory; -import org.codehaus.plexus.util.ReflectionUtils; -import org.codehaus.plexus.util.xml.XmlStreamReader; -import org.codehaus.plexus.util.xml.Xpp3Dom; -import org.codehaus.plexus.util.xml.Xpp3DomBuilder; -import org.junit.jupiter.api.extension.ExtensionContext; -import org.junit.jupiter.api.extension.ParameterContext; -import org.junit.jupiter.api.extension.ParameterResolutionException; -import org.junit.jupiter.api.extension.ParameterResolver; -import org.slf4j.LoggerFactory; - -/** - * JUnit extension to help testing Mojos. The extension should be automatically registered - * by adding the {@link MojoTest} annotation on the test class. - * - * @see MojoTest - * @see InjectMojo - * @see MojoParameter - */ -public class MojoExtension extends PlexusExtension implements ParameterResolver { - - @Override - public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) - throws ParameterResolutionException { - return parameterContext.isAnnotated(InjectMojo.class) - || parameterContext.getDeclaringExecutable().isAnnotationPresent(InjectMojo.class); - } - - @Override - public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) - throws ParameterResolutionException { - try { - InjectMojo injectMojo = parameterContext - .findAnnotation(InjectMojo.class) - .orElseGet(() -> parameterContext.getDeclaringExecutable().getAnnotation(InjectMojo.class)); - - Set<MojoParameter> mojoParameters = - new HashSet<>(parameterContext.findRepeatableAnnotations(MojoParameter.class)); - - Optional.ofNullable(parameterContext.getDeclaringExecutable().getAnnotation(MojoParameter.class)) - .ifPresent(mojoParameters::add); - - Optional.ofNullable(parameterContext.getDeclaringExecutable().getAnnotation(MojoParameters.class)) - .map(MojoParameters::value) - .map(Arrays::asList) - .ifPresent(mojoParameters::addAll); - - Class<?> holder = parameterContext.getTarget().get().getClass(); - PluginDescriptor descriptor = extensionContext - .getStore(ExtensionContext.Namespace.GLOBAL) - .get(PluginDescriptor.class, PluginDescriptor.class); - return lookupMojo(holder, injectMojo, mojoParameters, descriptor); - } catch (Exception e) { - throw new ParameterResolutionException("Unable to resolve parameter", e); - } - } - - @Override - public void beforeEach(ExtensionContext context) throws Exception { - // TODO provide protected setters in PlexusExtension - Field field = PlexusExtension.class.getDeclaredField("basedir"); - field.setAccessible(true); - field.set(null, getBasedir()); - field = PlexusExtension.class.getDeclaredField("context"); - field.setAccessible(true); - field.set(this, context); - - getContainer().addComponent(getContainer(), PlexusContainer.class.getName()); - - ((DefaultPlexusContainer) getContainer()).addPlexusInjector(Collections.emptyList(), binder -> { - binder.install(ProviderMethodsModule.forObject(context.getRequiredTestInstance())); - binder.requestInjection(context.getRequiredTestInstance()); - binder.bind(Log.class).toInstance(new DefaultLog(LoggerFactory.getLogger("anonymous"))); - }); - - Map<Object, Object> map = getContainer().getContext().getContextData(); - - ClassLoader classLoader = context.getRequiredTestClass().getClassLoader(); - try (InputStream is = Objects.requireNonNull( - classLoader.getResourceAsStream(getPluginDescriptorLocation()), - "Unable to find plugin descriptor: " + getPluginDescriptorLocation()); - Reader reader = new BufferedReader(new XmlStreamReader(is)); - InterpolationFilterReader interpolationReader = new InterpolationFilterReader(reader, map, "${", "}")) { - - PluginDescriptor pluginDescriptor = new PluginDescriptorBuilder().build(interpolationReader); - - context.getStore(ExtensionContext.Namespace.GLOBAL).put(PluginDescriptor.class, pluginDescriptor); - - for (ComponentDescriptor<?> desc : pluginDescriptor.getComponents()) { - getContainer().addComponentDescriptor(desc); - } - } - } - - protected String getPluginDescriptorLocation() { - return "META-INF/maven/plugin.xml"; - } - - private Mojo lookupMojo( - Class<?> holder, - InjectMojo injectMojo, - Collection<MojoParameter> mojoParameters, - PluginDescriptor descriptor) - throws Exception { - String goal = injectMojo.goal(); - String pom = injectMojo.pom(); - String[] coord = mojoCoordinates(goal); - Xpp3Dom pomDom; - if (pom.startsWith("file:")) { - Path path = Paths.get(getBasedir()).resolve(pom.substring("file:".length())); - pomDom = Xpp3DomBuilder.build(ReaderFactory.newXmlReader(path.toFile())); - } else if (pom.startsWith("classpath:")) { - URL url = holder.getResource(pom.substring("classpath:".length())); - if (url == null) { - throw new IllegalStateException("Unable to find pom on classpath: " + pom); - } - pomDom = Xpp3DomBuilder.build(ReaderFactory.newXmlReader(url.openStream())); - } else if (pom.contains("<project>")) { - pomDom = Xpp3DomBuilder.build(new StringReader(pom)); - } else { - Path path = Paths.get(getBasedir()).resolve(pom); - pomDom = Xpp3DomBuilder.build(ReaderFactory.newXmlReader(path.toFile())); - } - XmlNode pluginConfiguration = extractPluginConfiguration(coord[1], pomDom); - if (!mojoParameters.isEmpty()) { - List<XmlNode> children = mojoParameters.stream() - .map(mp -> new XmlNodeImpl(mp.name(), mp.value())) - .collect(Collectors.toList()); - XmlNode config = new XmlNodeImpl("configuration", null, null, children, null); - pluginConfiguration = XmlNode.merge(config, pluginConfiguration); - } - Mojo mojo = lookupMojo(coord, pluginConfiguration, descriptor); - return mojo; - } - - protected String[] mojoCoordinates(String goal) throws Exception { - if (goal.matches(".*:.*:.*:.*")) { - return goal.split(":"); - } else { - Path pluginPom = Paths.get(getBasedir(), "pom.xml"); - Xpp3Dom pluginPomDom = Xpp3DomBuilder.build(ReaderFactory.newXmlReader(pluginPom.toFile())); - String artifactId = pluginPomDom.getChild("artifactId").getValue(); - String groupId = resolveFromRootThenParent(pluginPomDom, "groupId"); - String version = resolveFromRootThenParent(pluginPomDom, "version"); - return new String[] {groupId, artifactId, version, goal}; - } - } - - /** - * lookup the mojo while we have all the relevent information - */ - protected Mojo lookupMojo(String[] coord, XmlNode pluginConfiguration, PluginDescriptor descriptor) - throws Exception { - // pluginkey = groupId : artifactId : version : goal - Mojo mojo = lookup(Mojo.class, coord[0] + ":" + coord[1] + ":" + coord[2] + ":" + coord[3]); - for (MojoDescriptor mojoDescriptor : descriptor.getMojos()) { - if (Objects.equals( - mojoDescriptor.getImplementation(), mojo.getClass().getName())) { - if (pluginConfiguration != null) { - pluginConfiguration = finalizeConfig(pluginConfiguration, mojoDescriptor); - } - } - } - if (pluginConfiguration != null) { - Session session = getContainer().lookup(Session.class); - Project project; - try { - project = getContainer().lookup(Project.class); - } catch (ComponentLookupException e) { - project = null; - } - org.apache.maven.plugin.MojoExecution mojoExecution; - try { - MojoExecution me = getContainer().lookup(MojoExecution.class); - mojoExecution = new org.apache.maven.plugin.MojoExecution( - new org.apache.maven.model.Plugin(me.getPlugin()), me.getGoal(), me.getExecutionId()); - } catch (ComponentLookupException e) { - mojoExecution = null; - } - ExpressionEvaluator evaluator = new WrapEvaluator( - getContainer(), new PluginParameterExpressionEvaluatorV4(session, project, mojoExecution)); - ComponentConfigurator configurator = new EnhancedComponentConfigurator(); - configurator.configureComponent( - mojo, - new XmlPlexusConfiguration(new Xpp3Dom(pluginConfiguration)), - evaluator, - getContainer().getContainerRealm()); - } - - return mojo; - } - - private XmlNode finalizeConfig(XmlNode config, MojoDescriptor mojoDescriptor) { - List<XmlNode> children = new ArrayList<>(); - if (mojoDescriptor != null && mojoDescriptor.getParameters() != null) { - XmlNode defaultConfiguration = - MojoDescriptorCreator.convert(mojoDescriptor).getDom(); - for (Parameter parameter : mojoDescriptor.getParameters()) { - XmlNode parameterConfiguration = config.getChild(parameter.getName()); - if (parameterConfiguration == null) { - parameterConfiguration = config.getChild(parameter.getAlias()); - } - XmlNode parameterDefaults = defaultConfiguration.getChild(parameter.getName()); - parameterConfiguration = XmlNode.merge(parameterConfiguration, parameterDefaults, Boolean.TRUE); - if (parameterConfiguration != null) { - Map<String, String> attributes = new HashMap<>(parameterConfiguration.getAttributes()); - if (isEmpty(parameterConfiguration.getAttribute("implementation")) - && !isEmpty(parameter.getImplementation())) { - attributes.put("implementation", parameter.getImplementation()); - } - parameterConfiguration = new XmlNodeImpl( - parameter.getName(), - parameterConfiguration.getValue(), - attributes, - parameterConfiguration.getChildren(), - parameterConfiguration.getInputLocation()); - - children.add(parameterConfiguration); - } - } - } - return new XmlNodeImpl("configuration", null, null, children, null); - } - - private boolean isEmpty(String str) { - return str == null || str.isEmpty(); - } - - private static Optional<Xpp3Dom> child(Xpp3Dom element, String name) { - return Optional.ofNullable(element.getChild(name)); - } - - private static Stream<Xpp3Dom> children(Xpp3Dom element) { - return Stream.of(element.getChildren()); - } - - public static XmlNode extractPluginConfiguration(String artifactId, Xpp3Dom pomDom) throws Exception { - Xpp3Dom pluginConfigurationElement = child(pomDom, "build") - .flatMap(buildElement -> child(buildElement, "plugins")) - .map(MojoExtension::children) - .orElseGet(Stream::empty) - .filter(e -> e.getChild("artifactId").getValue().equals(artifactId)) - .findFirst() - .flatMap(buildElement -> child(buildElement, "configuration")) - .orElseThrow( - () -> new ConfigurationException("Cannot find a configuration element for a plugin with an " - + "artifactId of " + artifactId + ".")); - return pluginConfigurationElement.getDom(); - } - - /** - * sometimes the parent element might contain the correct value so generalize that access - * - * TODO find out where this is probably done elsewhere - */ - private static String resolveFromRootThenParent(Xpp3Dom pluginPomDom, String element) throws Exception { - return Optional.ofNullable(child(pluginPomDom, element).orElseGet(() -> child(pluginPomDom, "parent") - .flatMap(e -> child(e, element)) - .orElse(null))) - .map(Xpp3Dom::getValue) - .orElseThrow(() -> new Exception("unable to determine " + element)); - } - - /** - * Convenience method to obtain the value of a variable on a mojo that might not have a getter. - * <br> - * NOTE: the caller is responsible for casting to what the desired type is. - */ - public static Object getVariableValueFromObject(Object object, String variable) throws IllegalAccessException { - Field field = ReflectionUtils.getFieldByNameIncludingSuperclasses(variable, object.getClass()); - field.setAccessible(true); - return field.get(object); - } - - /** - * Convenience method to obtain all variables and values from the mojo (including its superclasses) - * <br> - * Note: the values in the map are of type Object so the caller is responsible for casting to desired types. - */ - public static Map<String, Object> getVariablesAndValuesFromObject(Object object) throws IllegalAccessException { - return getVariablesAndValuesFromObject(object.getClass(), object); - } - - /** - * Convenience method to obtain all variables and values from the mojo (including its superclasses) - * <br> - * Note: the values in the map are of type Object so the caller is responsible for casting to desired types. - * - * @return map of variable names and values - */ - public static Map<String, Object> getVariablesAndValuesFromObject(Class<?> clazz, Object object) - throws IllegalAccessException { - Map<String, Object> map = new HashMap<>(); - Field[] fields = clazz.getDeclaredFields(); - AccessibleObject.setAccessible(fields, true); - for (Field field : fields) { - map.put(field.getName(), field.get(object)); - } - Class<?> superclass = clazz.getSuperclass(); - if (!Object.class.equals(superclass)) { - map.putAll(getVariablesAndValuesFromObject(superclass, object)); - } - return map; - } - - /** - * Convenience method to set values to variables in objects that don't have setters - */ - public static void setVariableValueToObject(Object object, String variable, Object value) - throws IllegalAccessException { - Field field = ReflectionUtils.getFieldByNameIncludingSuperclasses(variable, object.getClass()); - Objects.requireNonNull(field, "Field " + variable + " not found"); - field.setAccessible(true); - field.set(object, value); - } - - static class WrapEvaluator implements TypeAwareExpressionEvaluator { - - private final PlexusContainer container; - private final TypeAwareExpressionEvaluator evaluator; - - WrapEvaluator(PlexusContainer container, TypeAwareExpressionEvaluator evaluator) { - this.container = container; - this.evaluator = evaluator; - } - - @Override - public Object evaluate(String expression) throws ExpressionEvaluationException { - return evaluate(expression, null); - } - - @Override - public Object evaluate(String expression, Class<?> type) throws ExpressionEvaluationException { - Object value = evaluator.evaluate(expression, type); - if (value == null) { - String expr = stripTokens(expression); - if (expr != null) { - try { - value = container.lookup(type, expr); - } catch (ComponentLookupException e) { - // nothing - } - } - } - return value; - } - - private String stripTokens(String expr) { - if (expr.startsWith("${") && expr.endsWith("}")) { - return expr.substring(2, expr.length() - 1); - } - return null; - } - - @Override - public File alignToBaseDirectory(File path) { - return evaluator.alignToBaseDirectory(path); - } - } -} diff --git a/maven-plugin-testing-harness/src/main/java/org/apache/maven/api/plugin/testing/MojoParameter.java b/maven-plugin-testing-harness/src/main/java/org/apache/maven/api/plugin/testing/MojoParameter.java deleted file mode 100644 index 2a28f48..0000000 --- a/maven-plugin-testing-harness/src/main/java/org/apache/maven/api/plugin/testing/MojoParameter.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.maven.api.plugin.testing; - -import java.lang.annotation.Repeatable; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; - -/** - * Mojo parameter - */ -@Retention(RetentionPolicy.RUNTIME) -@Repeatable(MojoParameters.class) -public @interface MojoParameter { - String name(); - - String value(); -} diff --git a/maven-plugin-testing-harness/src/main/java/org/apache/maven/api/plugin/testing/MojoParameters.java b/maven-plugin-testing-harness/src/main/java/org/apache/maven/api/plugin/testing/MojoParameters.java deleted file mode 100644 index 434abe1..0000000 --- a/maven-plugin-testing-harness/src/main/java/org/apache/maven/api/plugin/testing/MojoParameters.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.maven.api.plugin.testing; - -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; - -/** - * Mojo parameters container - */ -@Retention(RetentionPolicy.RUNTIME) -public @interface MojoParameters { - MojoParameter[] value(); -} diff --git a/maven-plugin-testing-harness/src/main/java/org/apache/maven/api/plugin/testing/MojoTest.java b/maven-plugin-testing-harness/src/main/java/org/apache/maven/api/plugin/testing/MojoTest.java deleted file mode 100644 index eb94c09..0000000 --- a/maven-plugin-testing-harness/src/main/java/org/apache/maven/api/plugin/testing/MojoTest.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.maven.api.plugin.testing; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -import org.junit.jupiter.api.extension.ExtendWith; - -/** - * - */ -@Retention(RetentionPolicy.RUNTIME) -@ExtendWith(MojoExtension.class) -@Target(ElementType.TYPE) -public @interface MojoTest {} diff --git a/maven-plugin-testing-harness/src/main/java/org/apache/maven/api/plugin/testing/ResolverExpressionEvaluatorStub.java b/maven-plugin-testing-harness/src/main/java/org/apache/maven/api/plugin/testing/ResolverExpressionEvaluatorStub.java deleted file mode 100644 index 4461071..0000000 --- a/maven-plugin-testing-harness/src/main/java/org/apache/maven/api/plugin/testing/ResolverExpressionEvaluatorStub.java +++ /dev/null @@ -1,120 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.maven.api.plugin.testing; - -import java.io.File; -import java.util.Map; - -import org.codehaus.plexus.PlexusTestCase; -import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluationException; -import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluator; -import org.codehaus.plexus.component.configurator.expression.TypeAwareExpressionEvaluator; -import org.codehaus.plexus.testing.PlexusExtension; -import org.eclipse.aether.repository.LocalRepository; - -/** - * Stub for {@link ExpressionEvaluator} - * - * @author jesse - */ -public class ResolverExpressionEvaluatorStub implements TypeAwareExpressionEvaluator { - - private final Map<String, Object> properties; - - public ResolverExpressionEvaluatorStub(Map<String, Object> properties) { - this.properties = properties; - } - - /** {@inheritDoc} */ - @Override - public Object evaluate(String expr) throws ExpressionEvaluationException { - return evaluate(expr, null); - } - - /** {@inheritDoc} */ - @Override - public Object evaluate(String expr, Class<?> type) throws ExpressionEvaluationException { - - Object value = null; - - if (expr == null) { - return null; - } - - String expression = stripTokens(expr); - - if (expression.equals(expr)) { - int index = expr.indexOf("${"); - if (index >= 0) { - int lastIndex = expr.indexOf("}", index); - if (lastIndex >= 0) { - String retVal = expr.substring(0, index); - - if (index > 0 && expr.charAt(index - 1) == '$') { - retVal += expr.substring(index + 1, lastIndex + 1); - } else { - retVal += evaluate(expr.substring(index, lastIndex + 1)); - } - - retVal += evaluate(expr.substring(lastIndex + 1)); - return retVal; - } - } - - // Was not an expression - return expression.contains("$$") ? expression.replaceAll("\\$\\$", "\\$") : expression; - } else { - if ("basedir".equals(expression) || "project.basedir".equals(expression)) { - value = PlexusExtension.getBasedir(); - } else if (expression.startsWith("basedir") || expression.startsWith("project.basedir")) { - int pathSeparator = expression.indexOf("/"); - if (pathSeparator > 0) { - value = PlexusTestCase.getBasedir() + expression.substring(pathSeparator); - } - } else if ("localRepository".equals(expression)) { - File localRepo = new File(PlexusTestCase.getBasedir(), "target/local-repo"); - return new LocalRepository("file://" + localRepo.getAbsolutePath()); - } - if (value == null && properties != null && properties.containsKey(expression)) { - value = properties.get(expression); - } - return value; - } - } - - private String stripTokens(String expr) { - if (expr.startsWith("${") && expr.indexOf("}") == expr.length() - 1) { - expr = expr.substring(2, expr.length() - 1); - } - - return expr; - } - - /** {@inheritDoc} */ - @Override - public File alignToBaseDirectory(File file) { - if (file.getAbsolutePath().startsWith(PlexusExtension.getBasedir())) { - return file; - } else if (file.isAbsolute()) { - return file; - } else { - return new File(PlexusExtension.getBasedir(), file.getPath()); - } - } -} diff --git a/maven-plugin-testing-harness/src/main/java/org/apache/maven/api/plugin/testing/stubs/ArtifactStub.java b/maven-plugin-testing-harness/src/main/java/org/apache/maven/api/plugin/testing/stubs/ArtifactStub.java deleted file mode 100644 index 59be14f..0000000 --- a/maven-plugin-testing-harness/src/main/java/org/apache/maven/api/plugin/testing/stubs/ArtifactStub.java +++ /dev/null @@ -1,172 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.maven.api.plugin.testing.stubs; - -import java.util.Objects; - -import org.apache.maven.api.Artifact; -import org.apache.maven.api.ArtifactCoordinate; -import org.apache.maven.api.Version; -import org.apache.maven.api.VersionRange; -import org.apache.maven.api.annotations.Nonnull; -import org.apache.maven.internal.impl.DefaultVersionParser; - -/** - * - */ -public class ArtifactStub implements Artifact { - private String groupId; - private String artifactId; - private String classifier; - private String version; - private String extension; - - public ArtifactStub() { - groupId = ""; - artifactId = ""; - version = ""; - classifier = ""; - extension = ""; - } - - public ArtifactStub(String groupId, String artifactId, String classifier, String version, String extension) { - this.groupId = groupId; - this.artifactId = artifactId; - this.classifier = classifier; - this.version = version; - this.extension = extension; - } - - @Nonnull - @Override - public String getGroupId() { - return groupId; - } - - public void setGroupId(String groupId) { - this.groupId = groupId; - } - - @Nonnull - @Override - public String getArtifactId() { - return artifactId; - } - - public void setArtifactId(String artifactId) { - this.artifactId = artifactId; - } - - @Nonnull - @Override - public String getClassifier() { - return classifier; - } - - public void setClassifier(String classifier) { - this.classifier = classifier; - } - - @Nonnull - @Override - public Version getVersion() { - return new DefaultVersionParser().parseVersion(version); - } - - public void setVersion(String version) { - this.version = version; - } - - @Nonnull - @Override - public String getExtension() { - return extension; - } - - public void setExtension(String extension) { - this.extension = extension; - } - - @Override - public boolean isSnapshot() { - return false; - } - - @Override - public ArtifactCoordinate toCoordinate() { - return new ArtifactCoordinate() { - @Override - public String getGroupId() { - return groupId; - } - - @Override - public String getArtifactId() { - return artifactId; - } - - @Override - public String getClassifier() { - return classifier; - } - - @Override - public VersionRange getVersion() { - return new DefaultVersionParser().parseVersionRange(version); - } - - @Override - public String getExtension() { - return extension; - } - }; - } - - @Override - public String toString() { - return "ArtifactStub[" - + "groupId='" + groupId + '\'' - + ", artifactId='" + artifactId + '\'' - + ", classifier='" + classifier + '\'' - + ", version='" + version + '\'' - + ", extension='" + extension + '\'' - + ']'; - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (!(o instanceof ArtifactStub)) { - return false; - } - ArtifactStub that = (ArtifactStub) o; - return Objects.equals(groupId, that.groupId) - && Objects.equals(artifactId, that.artifactId) - && Objects.equals(classifier, that.classifier) - && Objects.equals(version, that.version) - && Objects.equals(extension, that.extension); - } - - @Override - public int hashCode() { - return Objects.hash(groupId, artifactId, classifier, version, extension); - } -} diff --git a/maven-plugin-testing-harness/src/main/java/org/apache/maven/api/plugin/testing/stubs/MojoExecutionStub.java b/maven-plugin-testing-harness/src/main/java/org/apache/maven/api/plugin/testing/stubs/MojoExecutionStub.java deleted file mode 100644 index a2d2b5b..0000000 --- a/maven-plugin-testing-harness/src/main/java/org/apache/maven/api/plugin/testing/stubs/MojoExecutionStub.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.maven.api.plugin.testing.stubs; - -import java.util.Optional; - -import org.apache.maven.api.MojoExecution; -import org.apache.maven.api.model.Plugin; -import org.apache.maven.api.xml.XmlNode; - -/** - * Stub for {@link MojoExecution}. - */ -public class MojoExecutionStub implements MojoExecution { - private final String artifactId; - private final String executionId; - private final String goal; - private final XmlNode dom; - - public MojoExecutionStub(String artifactId, String executionId, String goal) { - this(artifactId, executionId, goal, null); - } - - public MojoExecutionStub(String artifactId, String executionId, String goal, XmlNode dom) { - this.artifactId = artifactId; - this.executionId = executionId; - this.goal = goal; - this.dom = dom; - } - - @Override - public Plugin getPlugin() { - return Plugin.newBuilder().artifactId(artifactId).build(); - } - - @Override - public String getExecutionId() { - return executionId; - } - - @Override - public String getGoal() { - return goal; - } - - @Override - public Optional<XmlNode> getConfiguration() { - return Optional.ofNullable(dom); - } -} diff --git a/maven-plugin-testing-harness/src/main/java/org/apache/maven/api/plugin/testing/stubs/ProjectStub.java b/maven-plugin-testing-harness/src/main/java/org/apache/maven/api/plugin/testing/stubs/ProjectStub.java deleted file mode 100644 index b3624cf..0000000 --- a/maven-plugin-testing-harness/src/main/java/org/apache/maven/api/plugin/testing/stubs/ProjectStub.java +++ /dev/null @@ -1,193 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.maven.api.plugin.testing.stubs; - -import java.io.File; -import java.nio.file.Path; -import java.util.Collections; -import java.util.List; -import java.util.Optional; - -import org.apache.maven.api.Artifact; -import org.apache.maven.api.DependencyCoordinate; -import org.apache.maven.api.Project; -import org.apache.maven.api.RemoteRepository; -import org.apache.maven.api.annotations.Nonnull; -import org.apache.maven.api.model.Model; - -/** - * @author Olivier Lamy - * @since 1.0-beta-1 - * - */ -public class ProjectStub implements Project { - - private Model model = Model.newInstance(); - private Path basedir; - private File pomPath; - private boolean topProject; - private Artifact artifact; - private Path rootDirectory; - - public void setModel(Model model) { - this.model = model; - } - - @Nonnull - @Override - public String getGroupId() { - return model.getGroupId(); - } - - @Nonnull - @Override - public String getArtifactId() { - return model.getArtifactId(); - } - - @Nonnull - @Override - public String getVersion() { - return model.getVersion(); - } - - public String getName() { - return model.getName(); - } - - @Nonnull - @Override - public String getPackaging() { - return model.getPackaging(); - } - - @Nonnull - @Override - public Artifact getArtifact() { - return artifact; - } - - @Nonnull - @Override - public Model getModel() { - return model; - } - - @Nonnull - @Override - public Optional<Path> getPomPath() { - return Optional.ofNullable(pomPath).map(File::toPath); - } - - @Nonnull - @Override - public List<DependencyCoordinate> getDependencies() { - return null; - } - - @Nonnull - @Override - public List<DependencyCoordinate> getManagedDependencies() { - return null; - } - - @Override - public Optional<Path> getBasedir() { - return Optional.ofNullable(basedir); - } - - public void setBasedir(Path basedir) { - this.basedir = basedir; - } - - @Override - public boolean isExecutionRoot() { - return isTopProject(); - } - - @Override - public Optional<Project> getParent() { - return Optional.empty(); - } - - @Override - public List<RemoteRepository> getRemoteProjectRepositories() { - return Collections.emptyList(); - } - - @Override - public List<RemoteRepository> getRemotePluginRepositories() { - return Collections.emptyList(); - } - - @Override - public boolean isTopProject() { - return topProject; - } - - @Override - public boolean isRootProject() { - return model.isRoot(); - } - - @Override - public Path getRootDirectory() { - return rootDirectory; - } - - public void setGroupId(String groupId) { - model = model.withGroupId(groupId); - } - - public void setArtifactId(String artifactId) { - model = model.withArtifactId(artifactId); - } - - public void setVersion(String version) { - model = model.withVersion(version); - } - - public void setName(String name) { - model = model.withName(name); - } - - public void setPackaging(String packaging) { - model = model.withPackaging(packaging); - } - - public void setArtifact(Artifact artifact) { - this.artifact = artifact; - } - - public void setPomPath(File pomPath) { - this.pomPath = pomPath; - } - - public void setTopProject(boolean topProject) { - this.topProject = topProject; - } - - public void setMavenModel(org.apache.maven.model.Model model) { - this.model = model.getDelegate(); - } - - public void setRootDirectory(Path rootDirectory) { - this.rootDirectory = rootDirectory; - } -} diff --git a/maven-plugin-testing-harness/src/main/java/org/apache/maven/api/plugin/testing/stubs/SessionStub.java b/maven-plugin-testing-harness/src/main/java/org/apache/maven/api/plugin/testing/stubs/SessionStub.java deleted file mode 100644 index 2b05567..0000000 --- a/maven-plugin-testing-harness/src/main/java/org/apache/maven/api/plugin/testing/stubs/SessionStub.java +++ /dev/null @@ -1,278 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.maven.api.plugin.testing.stubs; - -import java.net.URI; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.Map; -import java.util.Optional; -import java.util.Properties; - -import org.apache.maven.api.Artifact; -import org.apache.maven.api.LocalRepository; -import org.apache.maven.api.Project; -import org.apache.maven.api.RemoteRepository; -import org.apache.maven.api.Session; -import org.apache.maven.api.model.Model; -import org.apache.maven.api.model.Repository; -import org.apache.maven.api.services.ArtifactDeployer; -import org.apache.maven.api.services.ArtifactDeployerRequest; -import org.apache.maven.api.services.ArtifactFactory; -import org.apache.maven.api.services.ArtifactFactoryRequest; -import org.apache.maven.api.services.ArtifactInstaller; -import org.apache.maven.api.services.ArtifactInstallerRequest; -import org.apache.maven.api.services.ArtifactManager; -import org.apache.maven.api.services.LocalRepositoryManager; -import org.apache.maven.api.services.ProjectBuilder; -import org.apache.maven.api.services.ProjectBuilderRequest; -import org.apache.maven.api.services.ProjectBuilderResult; -import org.apache.maven.api.services.ProjectManager; -import org.apache.maven.api.services.RepositoryFactory; -import org.apache.maven.api.services.xml.ModelXmlFactory; -import org.apache.maven.internal.impl.DefaultModelXmlFactory; -import org.apache.maven.model.v4.MavenStaxReader; -import org.mockito.ArgumentMatchers; - -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.ArgumentMatchers.same; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; -import static org.mockito.Mockito.withSettings; - -/** - * - */ -public class SessionStub { - - public static Session getMockSession(String localRepo) { - LocalRepository localRepository = mock(LocalRepository.class); - when(localRepository.getId()).thenReturn("local"); - when(localRepository.getPath()).thenReturn(Paths.get(localRepo)); - return getMockSession(localRepository); - } - - public static Session getMockSession(LocalRepository localRepository) { - Session session = mock(Session.class); - - RepositoryFactory repositoryFactory = mock(RepositoryFactory.class); - when(repositoryFactory.createRemote(any(Repository.class))).thenAnswer(iom -> { - Repository repository = iom.getArgument(0, Repository.class); - return repositoryFactory.createRemote(repository.getId(), repository.getUrl()); - }); - when(repositoryFactory.createRemote(anyString(), anyString())).thenAnswer(iom -> { - String id = iom.getArgument(0, String.class); - String url = iom.getArgument(1, String.class); - RemoteRepository remoteRepository = - mock(RemoteRepository.class, withSettings().lenient()); - when(remoteRepository.getId()).thenReturn(id); - when(remoteRepository.getUrl()).thenReturn(url); - when(remoteRepository.getProtocol()).thenReturn(URI.create(url).getScheme()); - return remoteRepository; - }); - - LocalRepositoryManager localRepositoryManager = mock(LocalRepositoryManager.class); - when(localRepositoryManager.getPathForLocalArtifact(any(), any(), any())) - .thenAnswer(iom -> { - LocalRepository localRepo = iom.getArgument(1, LocalRepository.class); - Artifact artifact = iom.getArgument(2, Artifact.class); - return localRepo.getPath().resolve(getPathForArtifact(artifact, true)); - }); - - ArtifactInstaller artifactInstaller = mock(ArtifactInstaller.class); - doAnswer(iom -> { - artifactInstaller.install(ArtifactInstallerRequest.build( - iom.getArgument(0, Session.class), iom.getArgument(1, Collection.class))); - return null; - }) - .when(artifactInstaller) - .install(any(Session.class), ArgumentMatchers.<Collection<Artifact>>any()); - - ArtifactDeployer artifactDeployer = mock(ArtifactDeployer.class); - doAnswer(iom -> { - artifactDeployer.deploy(ArtifactDeployerRequest.build( - iom.getArgument(0, Session.class), - iom.getArgument(1, RemoteRepository.class), - iom.getArgument(2, Collection.class))); - return null; - }) - .when(artifactDeployer) - .deploy(any(), any(), any()); - - ArtifactManager artifactManager = mock(ArtifactManager.class); - Map<Artifact, Path> paths = new HashMap<>(); - doAnswer(iom -> { - paths.put(iom.getArgument(0), iom.getArgument(1)); - return null; - }) - .when(artifactManager) - .setPath(any(), any()); - doAnswer(iom -> Optional.ofNullable(paths.get(iom.getArgument(0, Artifact.class)))) - .when(artifactManager) - .getPath(any()); - - ProjectManager projectManager = mock(ProjectManager.class); - Map<Project, Collection<Artifact>> attachedArtifacts = new HashMap<>(); - doAnswer(iom -> { - Project project = iom.getArgument(1, Project.class); - String type = iom.getArgument(2, String.class); - Path path = iom.getArgument(3, Path.class); - Artifact artifact = session.createArtifact( - project.getGroupId(), project.getArtifactId(), project.getVersion(), null, null, type); - artifactManager.setPath(artifact, path); - attachedArtifacts - .computeIfAbsent(project, p -> new ArrayList<>()) - .add(artifact); - return null; - }) - .when(projectManager) - .attachArtifact(same(session), any(Project.class), any(), any()); - doAnswer(iom -> { - Project project = iom.getArgument(0, Project.class); - Artifact artifact = iom.getArgument(1, Artifact.class); - Path path = iom.getArgument(2, Path.class); - artifactManager.setPath(artifact, path); - attachedArtifacts - .computeIfAbsent(project, p -> new ArrayList<>()) - .add(artifact); - return null; - }) - .when(projectManager) - .attachArtifact(any(Project.class), any(Artifact.class), any(Path.class)); - when(projectManager.getAttachedArtifacts(any())) - .then(iom -> - attachedArtifacts.computeIfAbsent(iom.getArgument(0, Project.class), p -> new ArrayList<>())); - - ArtifactFactory artifactFactory = mock(ArtifactFactory.class); - when(artifactFactory.create(any())).then(iom -> { - ArtifactFactoryRequest request = iom.getArgument(0, ArtifactFactoryRequest.class); - String classifier = request.getClassifier(); - String extension = request.getExtension(); - String type = request.getType(); - if (classifier == null) { - classifier = ""; - } - if (extension == null) { - extension = type != null ? type : ""; - } - return new ArtifactStub( - request.getGroupId(), request.getArtifactId(), classifier, request.getVersion(), extension); - }); - - ProjectBuilder projectBuilder = mock(ProjectBuilder.class); - when(projectBuilder.build(any(ProjectBuilderRequest.class))).then(iom -> { - ProjectBuilderRequest request = iom.getArgument(0, ProjectBuilderRequest.class); - ProjectBuilderResult result = mock(ProjectBuilderResult.class); - Model model = new MavenStaxReader().read(request.getSource().get().openStream()); - ProjectStub projectStub = new ProjectStub(); - projectStub.setModel(model); - ArtifactStub artifactStub = new ArtifactStub( - model.getGroupId(), model.getArtifactId(), "", model.getVersion(), model.getPackaging()); - projectStub.setArtifact(artifactStub); - when(result.getProject()).thenReturn(Optional.of(projectStub)); - return result; - }); - - Properties sysProps = new Properties(); - Properties usrProps = new Properties(); - doReturn(sysProps).when(session).getSystemProperties(); - doReturn(usrProps).when(session).getUserProperties(); - - when(session.getLocalRepository()).thenReturn(localRepository); - when(session.getService(RepositoryFactory.class)).thenReturn(repositoryFactory); - when(session.getService(ProjectBuilder.class)).thenReturn(projectBuilder); - when(session.getService(LocalRepositoryManager.class)).thenReturn(localRepositoryManager); - when(session.getService(ProjectManager.class)).thenReturn(projectManager); - when(session.getService(ArtifactManager.class)).thenReturn(artifactManager); - when(session.getService(ArtifactInstaller.class)).thenReturn(artifactInstaller); - when(session.getService(ArtifactDeployer.class)).thenReturn(artifactDeployer); - when(session.getService(ArtifactFactory.class)).thenReturn(artifactFactory); - when(session.getService(ModelXmlFactory.class)).thenReturn(new DefaultModelXmlFactory()); - - when(session.getPathForLocalArtifact(any(Artifact.class))) - .then(iom -> localRepositoryManager.getPathForLocalArtifact( - session, session.getLocalRepository(), iom.getArgument(0, Artifact.class))); - when(session.createArtifact(any(), any(), any(), any(), any(), any())).thenAnswer(iom -> { - String groupId = iom.getArgument(0, String.class); - String artifactId = iom.getArgument(1, String.class); - String version = iom.getArgument(2, String.class); - String classifier = iom.getArgument(3, String.class); - String extension = iom.getArgument(4, String.class); - String type = iom.getArgument(5, String.class); - return session.getService(ArtifactFactory.class) - .create(ArtifactFactoryRequest.builder() - .session(session) - .groupId(groupId) - .artifactId(artifactId) - .version(version) - .classifier(classifier) - .extension(extension) - .type(type) - .build()); - }); - when(session.createArtifact(any(), any(), any(), any())).thenAnswer(iom -> { - String groupId = iom.getArgument(0, String.class); - String artifactId = iom.getArgument(1, String.class); - String version = iom.getArgument(2, String.class); - String extension = iom.getArgument(3, String.class); - return session.getService(ArtifactFactory.class) - .create(ArtifactFactoryRequest.builder() - .session(session) - .groupId(groupId) - .artifactId(artifactId) - .version(version) - .extension(extension) - .build()); - }); - when(session.createRemoteRepository(anyString(), anyString())).thenAnswer(iom -> { - String id = iom.getArgument(0, String.class); - String url = iom.getArgument(1, String.class); - return session.getService(RepositoryFactory.class).createRemote(id, url); - }); - doAnswer(iom -> artifactManager.getPath(iom.getArgument(0, Artifact.class))) - .when(session) - .getArtifactPath(any()); - - when(session.withLocalRepository(any())) - .thenAnswer(iom -> getMockSession(iom.getArgument(0, LocalRepository.class))); - return session; - } - - static String getPathForArtifact(Artifact artifact, boolean local) { - StringBuilder path = new StringBuilder(128); - path.append(artifact.getGroupId().replace('.', '/')).append('/'); - path.append(artifact.getArtifactId()).append('/'); - path.append(artifact.getVersion()).append('/'); - path.append(artifact.getArtifactId()).append('-'); - path.append(artifact.getVersion()); - if (artifact.getClassifier().length() > 0) { - path.append('-').append(artifact.getClassifier()); - } - if (artifact.getExtension().length() > 0) { - path.append('.').append(artifact.getExtension()); - } - return path.toString(); - } -} diff --git a/maven-plugin-testing-harness/src/main/java/org/apache/maven/plugin/testing/MojoRule.java b/maven-plugin-testing-harness/src/main/java/org/apache/maven/plugin/testing/MojoRule.java index 878d750..bbc882e 100644 --- a/maven-plugin-testing-harness/src/main/java/org/apache/maven/plugin/testing/MojoRule.java +++ b/maven-plugin-testing-harness/src/main/java/org/apache/maven/plugin/testing/MojoRule.java @@ -22,7 +22,6 @@ import java.io.File; import java.io.InputStream; import java.util.Map; -import org.apache.maven.api.Session; import org.apache.maven.execution.DefaultMavenExecutionRequest; import org.apache.maven.execution.MavenExecutionRequest; import org.apache.maven.execution.MavenSession; @@ -337,7 +336,6 @@ public class MojoRule implements TestRule { try { sessionScope.enter(); sessionScope.seed(MavenSession.class, session); - sessionScope.seed(Session.class, session.getSession()); MojoExecutionScope executionScope = lookup(MojoExecutionScope.class); try { diff --git a/maven-plugin-testing-harness/src/main/java/org/apache/maven/plugin/testing/junit5/MojoExtension.java b/maven-plugin-testing-harness/src/main/java/org/apache/maven/plugin/testing/junit5/MojoExtension.java index c7746c2..247b7f9 100644 --- a/maven-plugin-testing-harness/src/main/java/org/apache/maven/plugin/testing/junit5/MojoExtension.java +++ b/maven-plugin-testing-harness/src/main/java/org/apache/maven/plugin/testing/junit5/MojoExtension.java @@ -44,7 +44,6 @@ import java.util.stream.Collectors; import java.util.stream.Stream; import com.google.inject.internal.ProviderMethodsModule; -import org.apache.maven.api.plugin.testing.MojoTest; import org.apache.maven.execution.MavenSession; import org.apache.maven.lifecycle.internal.MojoDescriptorCreator; import org.apache.maven.plugin.Mojo; @@ -83,12 +82,12 @@ import org.mockito.Mockito; import org.slf4j.LoggerFactory; /** - * JUnit extension to help testing Mojos. The extension should be automatically registered - * by adding the {@link org.apache.maven.api.plugin.testing.MojoTest} annotation on the test class. + * JUnit's extension to help testing Mojos. The extension should be automatically registered + * by adding the {@link MojoTest} annotation on the test class. * * @see MojoTest - * @see org.apache.maven.api.plugin.testing.InjectMojo - * @see org.apache.maven.api.plugin.testing.MojoParameter + * @see InjectMojo + * @see MojoParameter */ public class MojoExtension extends PlexusExtension implements ParameterResolver { diff --git a/maven-plugin-testing-harness/src/test/java/org/apache/maven/api/plugin/testing/ExpressionEvaluatorTest.java b/maven-plugin-testing-harness/src/test/java/org/apache/maven/api/plugin/testing/ExpressionEvaluatorTest.java deleted file mode 100644 index b287bbf..0000000 --- a/maven-plugin-testing-harness/src/test/java/org/apache/maven/api/plugin/testing/ExpressionEvaluatorTest.java +++ /dev/null @@ -1,125 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.maven.api.plugin.testing; - -import javax.inject.Named; - -import java.nio.file.Paths; -import java.util.Properties; - -import com.google.inject.Provides; -import org.apache.maven.api.Session; -import org.apache.maven.api.plugin.MojoException; -import org.apache.maven.api.plugin.testing.stubs.SessionStub; -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.doReturn; - -/** - * @author Edwin Punzalan - */ -@MojoTest -public class ExpressionEvaluatorTest { - - private static final String LOCAL_REPO = "target/local-repo/"; - private static final String ARTIFACT_ID = "maven-test-mojo"; - private static final String COORDINATES = "groupId:" + ARTIFACT_ID + ":version:goal"; - private static final String CONFIG = "<project>\n" - + " <build>\n" - + " <plugins>\n" - + " <plugin>\n" - + " <artifactId>" + ARTIFACT_ID + "</artifactId>\n" - + " <configuration>\n" - + " <basedir>${basedir}</basedir>\n" - + " <workdir>${basedir}/workDirectory</workdir>\n" - + " </configuration>\n" - + " </plugin>\n" - + " </plugins>\n" - + " </build>\n" - + "</project>\n"; - - @Test - @InjectMojo(goal = COORDINATES, pom = CONFIG) - public void testInjection(ExpressionEvaluatorMojo mojo) { - assertNotNull(mojo.basedir); - assertNotNull(mojo.workdir); - assertDoesNotThrow(mojo::execute); - } - - @Test - @InjectMojo(goal = COORDINATES, pom = CONFIG) - @MojoParameter(name = "param", value = "paramValue") - public void testParam(ExpressionEvaluatorMojo mojo) { - assertNotNull(mojo.basedir); - assertNotNull(mojo.workdir); - assertEquals("paramValue", mojo.param); - assertDoesNotThrow(mojo::execute); - } - - @Test - @InjectMojo(goal = COORDINATES, pom = CONFIG) - @MojoParameter(name = "param", value = "paramValue") - @MojoParameter(name = "param2", value = "param2Value") - public void testParams(ExpressionEvaluatorMojo mojo) { - assertNotNull(mojo.basedir); - assertNotNull(mojo.workdir); - assertEquals("paramValue", mojo.param); - assertEquals("param2Value", mojo.param2); - assertDoesNotThrow(mojo::execute); - } - - @Named(COORDINATES) - public static class ExpressionEvaluatorMojo implements org.apache.maven.api.plugin.Mojo { - private String basedir; - - private String workdir; - - private String param; - - private String param2; - - /** {@inheritDoc} */ - @Override - public void execute() throws MojoException { - if (basedir == null || basedir.isEmpty()) { - throw new MojoException("basedir was not injected."); - } - - if (workdir == null || workdir.isEmpty()) { - throw new MojoException("workdir was not injected."); - } else if (!workdir.startsWith(basedir)) { - throw new MojoException("workdir does not start with basedir."); - } - } - } - - @Provides - @SuppressWarnings("unused") - Session session() { - Session session = SessionStub.getMockSession(LOCAL_REPO); - doReturn(new Properties()).when(session).getSystemProperties(); - doReturn(new Properties()).when(session).getUserProperties(); - doAnswer(iom -> Paths.get(MojoExtension.getBasedir())).when(session).getRootDirectory(); - return session; - } -} diff --git a/maven-plugin-testing-harness/src/test/java/org/apache/maven/plugin/testing/MojoTestCaseTest.java b/maven-plugin-testing-harness/src/test/java/org/apache/maven/plugin/testing/MojoTestCaseTest.java index 1fa8947..e1ab92d 100644 --- a/maven-plugin-testing-harness/src/test/java/org/apache/maven/plugin/testing/MojoTestCaseTest.java +++ b/maven-plugin-testing-harness/src/test/java/org/apache/maven/plugin/testing/MojoTestCaseTest.java @@ -21,7 +21,7 @@ package org.apache.maven.plugin.testing; import java.io.StringReader; import java.util.Map; -import org.apache.maven.api.plugin.testing.MojoTest; +import org.apache.maven.plugin.testing.junit5.MojoTest; import org.codehaus.plexus.configuration.PlexusConfiguration; import org.codehaus.plexus.util.xml.Xpp3Dom; import org.codehaus.plexus.util.xml.Xpp3DomBuilder; diff --git a/pom.xml b/pom.xml index 4cea8e8..e1a25e2 100644 --- a/pom.xml +++ b/pom.xml @@ -23,13 +23,13 @@ under the License. <parent> <groupId>org.apache.maven</groupId> <artifactId>maven-parent</artifactId> - <version>40</version> + <version>42</version> <relativePath /> </parent> <groupId>org.apache.maven.plugin-testing</groupId> <artifactId>maven-plugin-testing</artifactId> - <version>4.0.0-alpha-3-SNAPSHOT</version> + <version>3.4.0-SNAPSHOT</version> <packaging>pom</packaging> <name>Maven Plugin Testing</name> @@ -64,8 +64,8 @@ under the License. </distributionManagement> <properties> - <surefire.version>3.2.1</surefire.version> - <mavenVersion>4.0.0-alpha-8</mavenVersion> + <surefire.version>3.2.5</surefire.version> + <mavenVersion>3.9.6</mavenVersion> <maven.site.path>plugin-testing-archives/LATEST</maven.site.path> <javaVersion>8</javaVersion> <project.build.outputTimestamp>2023-11-07T21:58:12Z</project.build.outputTimestamp>