diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..ccf1b48 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,30 @@ +# 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. + +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..d5ebe25 100644 --- a/maven-plugin-testing-harness/pom.xml +++ b/maven-plugin-testing-harness/pom.xml @@ -23,19 +23,23 @@ under the License. org.apache.maven.plugin-testing maven-plugin-testing - 4.0.0-alpha-3-SNAPSHOT + 3.4.0-SNAPSHOT maven-plugin-testing-harness Maven Plugin Testing Mechanism The Maven Plugin Testing Harness provides mechanisms to manage tests on Mojo. + + 3.5.3 + + org.junit junit-bom - 5.10.0 + 5.11.0 pom import @@ -46,7 +50,7 @@ under the License. org.apache.maven - maven-api-core + maven-artifact ${mavenVersion} provided @@ -74,30 +78,60 @@ under the License. ${mavenVersion} provided + + org.apache.maven.wagon + wagon-provider-api + ${wagonVersion} + provided + + + org.apache.maven.wagon + wagon-file + ${wagonVersion} + provided + + + org.apache.maven.wagon + wagon-http + ${wagonVersion} + provided + + + + org.apache.maven + maven-compat + ${mavenVersion} + runtime + + + * + * + + + - org.codehaus.plexus plexus-utils - 4.0.0 - org.codehaus.plexus - plexus-xml - 4.0.0 - true + plexus-archiver + 4.9.2 - org.codehaus.plexus - plexus-archiver - 4.8.0 + org.apache.commons + commons-compress + 1.26.1 org.codehaus.plexus plexus-testing - 1.1.0 + 1.3.0 @@ -110,7 +144,7 @@ under the License. com.google.guava guava - 32.0.1-jre + 33.2.0-jre junit 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 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 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 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("")) { - 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 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 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 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 child(Xpp3Dom element, String name) { - return Optional.ofNullable(element.getChild(name)); - } - - private static Stream 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. - *
- * 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) - *
- * Note: the values in the map are of type Object so the caller is responsible for casting to desired types. - */ - public static Map getVariablesAndValuesFromObject(Object object) throws IllegalAccessException { - return getVariablesAndValuesFromObject(object.getClass(), object); - } - - /** - * Convenience method to obtain all variables and values from the mojo (including its superclasses) - *
- * 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 getVariablesAndValuesFromObject(Class clazz, Object object) - throws IllegalAccessException { - Map 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 properties; - - public ResolverExpressionEvaluatorStub(Map 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 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 getPomPath() { - return Optional.ofNullable(pomPath).map(File::toPath); - } - - @Nonnull - @Override - public List getDependencies() { - return null; - } - - @Nonnull - @Override - public List getManagedDependencies() { - return null; - } - - @Override - public Optional getBasedir() { - return Optional.ofNullable(basedir); - } - - public void setBasedir(Path basedir) { - this.basedir = basedir; - } - - @Override - public boolean isExecutionRoot() { - return isTopProject(); - } - - @Override - public Optional getParent() { - return Optional.empty(); - } - - @Override - public List getRemoteProjectRepositories() { - return Collections.emptyList(); - } - - @Override - public List 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.>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 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> 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/AbstractMojoTestCase.java b/maven-plugin-testing-harness/src/main/java/org/apache/maven/plugin/testing/AbstractMojoTestCase.java index c2b2309..8c11a8f 100644 --- a/maven-plugin-testing-harness/src/main/java/org/apache/maven/plugin/testing/AbstractMojoTestCase.java +++ b/maven-plugin-testing-harness/src/main/java/org/apache/maven/plugin/testing/AbstractMojoTestCase.java @@ -72,7 +72,6 @@ import org.codehaus.plexus.configuration.xml.XmlPlexusConfiguration; import org.codehaus.plexus.context.Context; import org.codehaus.plexus.util.InterpolationFilterReader; -import org.codehaus.plexus.util.ReaderFactory; import org.codehaus.plexus.util.ReflectionUtils; import org.codehaus.plexus.util.StringUtils; import org.codehaus.plexus.util.xml.XmlStreamReader; @@ -297,7 +296,7 @@ protected T lookupEmptyMojo(String goal, String pluginPom) thro protected T lookupMojo(String goal, File pom) throws Exception { File pluginPom = new File(getBasedir(), "pom.xml"); - Xpp3Dom pluginPomDom = Xpp3DomBuilder.build(ReaderFactory.newXmlReader(pluginPom)); + Xpp3Dom pluginPomDom = Xpp3DomBuilder.build(new XmlStreamReader(pluginPom)); String artifactId = pluginPomDom.getChild("artifactId").getValue(); @@ -321,7 +320,7 @@ protected T lookupMojo(String goal, File pom) throws Exception protected T lookupEmptyMojo(String goal, File pom) throws Exception { File pluginPom = new File(getBasedir(), "pom.xml"); - Xpp3Dom pluginPomDom = Xpp3DomBuilder.build(ReaderFactory.newXmlReader(pluginPom)); + Xpp3Dom pluginPomDom = Xpp3DomBuilder.build(new XmlStreamReader(pluginPom)); String artifactId = pluginPomDom.getChild("artifactId").getValue(); @@ -507,7 +506,7 @@ private void finalizeMojoConfiguration(MojoExecution mojoExecution) { */ protected PlexusConfiguration extractPluginConfiguration(String artifactId, File pom) throws Exception { - try (Reader reader = ReaderFactory.newXmlReader(pom)) { + try (Reader reader = new XmlStreamReader(pom)) { Xpp3Dom pomDom = Xpp3DomBuilder.build(reader); return extractPluginConfiguration(artifactId, pomDom); } 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.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 void executeMojo(MavenSession session, MavenProject project, MojoExecutio 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..fc6746b 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.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; @@ -55,7 +54,6 @@ import org.apache.maven.plugin.descriptor.PluginDescriptor; import org.apache.maven.plugin.descriptor.PluginDescriptorBuilder; import org.apache.maven.plugin.logging.Log; -import org.apache.maven.plugin.testing.ConfigurationException; import org.apache.maven.plugin.testing.MojoLogWrapper; import org.apache.maven.project.MavenProject; import org.codehaus.plexus.DefaultPlexusContainer; @@ -70,7 +68,6 @@ 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; @@ -83,12 +80,12 @@ 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 { @@ -204,18 +201,18 @@ private Mojo lookupMojo( Xpp3Dom pomDom; if (pom.startsWith("file:")) { Path path = Paths.get(getBasedir()).resolve(pom.substring("file:".length())); - pomDom = Xpp3DomBuilder.build(ReaderFactory.newXmlReader(path.toFile())); + pomDom = Xpp3DomBuilder.build(new XmlStreamReader(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())); + pomDom = Xpp3DomBuilder.build(new XmlStreamReader(url.openStream())); } else if (pom.contains("")) { pomDom = Xpp3DomBuilder.build(new StringReader(pom)); } else { Path path = Paths.get(getBasedir()).resolve(pom); - pomDom = Xpp3DomBuilder.build(ReaderFactory.newXmlReader(path.toFile())); + pomDom = Xpp3DomBuilder.build(new XmlStreamReader(path.toFile())); } Xpp3Dom pluginConfiguration = extractPluginConfiguration(coord[1], pomDom); if (!mojoParameters.isEmpty()) { @@ -239,7 +236,7 @@ protected String[] mojoCoordinates(String goal) throws Exception { return goal.split(":"); } else { Path pluginPom = Paths.get(getBasedir(), "pom.xml"); - Xpp3Dom pluginPomDom = Xpp3DomBuilder.build(ReaderFactory.newXmlReader(pluginPom.toFile())); + Xpp3Dom pluginPomDom = Xpp3DomBuilder.build(new XmlStreamReader(pluginPom.toFile())); String artifactId = pluginPomDom.getChild("artifactId").getValue(); String groupId = resolveFromRootThenParent(pluginPomDom, "groupId"); String version = resolveFromRootThenParent(pluginPomDom, "version"); @@ -264,11 +261,10 @@ protected Mojo lookupMojo(String[] coord, Xpp3Dom pluginConfiguration, PluginDes } if (pluginConfiguration != null) { MavenSession session = getContainer().lookup(MavenSession.class); - MavenProject project; try { - project = getContainer().lookup(MavenProject.class); - } catch (ComponentLookupException e) { - project = null; + getContainer().lookup(MavenProject.class); + } catch (ComponentLookupException ignore) { + // nothing } MojoExecution mojoExecution; try { @@ -336,9 +332,7 @@ public static Xpp3Dom extractPluginConfiguration(String artifactId, Xpp3Dom pomD .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 + ".")); + .orElse(Xpp3DomBuilder.build(new StringReader(""))); return pluginConfigurationElement; } diff --git a/maven-plugin-testing-harness/src/main/java/org/apache/maven/plugin/testing/stubs/MavenProjectStub.java b/maven-plugin-testing-harness/src/main/java/org/apache/maven/plugin/testing/stubs/MavenProjectStub.java index 513629b..ab2e517 100644 --- a/maven-plugin-testing-harness/src/main/java/org/apache/maven/plugin/testing/stubs/MavenProjectStub.java +++ b/maven-plugin-testing-harness/src/main/java/org/apache/maven/plugin/testing/stubs/MavenProjectStub.java @@ -58,7 +58,7 @@ import org.apache.maven.model.io.xpp3.MavenXpp3Reader; import org.apache.maven.project.MavenProject; import org.codehaus.plexus.PlexusTestCase; -import org.codehaus.plexus.util.ReaderFactory; +import org.codehaus.plexus.util.xml.XmlStreamReader; import org.codehaus.plexus.util.xml.Xpp3Dom; import org.codehaus.plexus.util.xml.pull.XmlPullParserException; @@ -186,7 +186,7 @@ protected void readModel(File pomFile) { pomFile = new File(getBasedir(), pomFile.getPath()); } try { - setModel(new MavenXpp3Reader().read(ReaderFactory.newXmlReader(pomFile))); + setModel(new MavenXpp3Reader().read(new XmlStreamReader(pomFile))); } catch (IOException e) { throw new RuntimeException("Failed to read POM file: " + pomFile, e); } catch (XmlPullParserException e) { 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 = "\n" - + " \n" - + " \n" - + " \n" - + " " + ARTIFACT_ID + "\n" - + " \n" - + " ${basedir}\n" - + " ${basedir}/workDirectory\n" - + " \n" - + " \n" - + " \n" - + " \n" - + "\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 @@ 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..14a9a9d 100644 --- a/pom.xml +++ b/pom.xml @@ -23,13 +23,13 @@ under the License. org.apache.maven maven-parent - 40 + 43 org.apache.maven.plugin-testing maven-plugin-testing - 4.0.0-alpha-3-SNAPSHOT + 3.4.0-SNAPSHOT pom Maven Plugin Testing @@ -64,8 +64,7 @@ under the License. - 3.2.1 - 4.0.0-alpha-8 + 3.9.9 plugin-testing-archives/LATEST 8 2023-11-07T21:58:12Z