Skip to content

Commits on Source 4

......@@ -6,4 +6,5 @@ target
#idea
*.iml
.idea
.java-version
.svn
#!/bin/sh
#
# 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.
#
mvn -Preporting site site:stage $@
mvn scm-publish:publish-scm $@
......@@ -25,19 +25,13 @@ under the License.
<parent>
<groupId>org.apache.maven.plugin-testing</groupId>
<artifactId>maven-plugin-testing</artifactId>
<version>2.1</version>
<version>3.3.0</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>
<scm>
<connection>scm:svn:http://svn.apache.org/repos/asf/maven/plugin-testing/tags/maven-plugin-testing-2.1/maven-plugin-testing-harness</connection>
<developerConnection>scm:svn:https://svn.apache.org/repos/asf/maven/plugin-testing/tags/maven-plugin-testing-2.1/maven-plugin-testing-harness</developerConnection>
<url>http://svn.apache.org/viewvc/maven/plugin-testing/tags/maven-plugin-testing-2.1/maven-plugin-testing-harness</url>
</scm>
<dependencies>
<!-- maven -->
<dependency>
......@@ -66,6 +60,11 @@ under the License.
<groupId>org.codehaus.plexus</groupId>
<artifactId>plexus-utils</artifactId>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>org.codehaus.plexus</groupId>
<artifactId>plexus-archiver</artifactId>
......
......@@ -22,15 +22,23 @@ package org.apache.maven.plugin.testing;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Field;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.apache.commons.io.input.XmlStreamReader;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.versioning.DefaultArtifactVersion;
import org.apache.maven.execution.DefaultMavenExecutionRequest;
import org.apache.maven.execution.DefaultMavenExecutionResult;
import org.apache.maven.execution.MavenExecutionRequest;
......@@ -49,10 +57,11 @@ import org.apache.maven.plugin.descriptor.PluginDescriptorBuilder;
import org.apache.maven.plugin.logging.Log;
import org.apache.maven.project.MavenProject;
import org.apache.maven.repository.RepositorySystem;
import org.apache.maven.repository.internal.MavenRepositorySystemSession;
import org.apache.maven.repository.internal.MavenRepositorySystemUtils;
import org.codehaus.plexus.ContainerConfiguration;
import org.codehaus.plexus.DefaultContainerConfiguration;
import org.codehaus.plexus.DefaultPlexusContainer;
import org.codehaus.plexus.PlexusConstants;
import org.codehaus.plexus.PlexusContainer;
import org.codehaus.plexus.PlexusContainerException;
import org.codehaus.plexus.PlexusTestCase;
......@@ -64,14 +73,16 @@ import org.codehaus.plexus.component.repository.ComponentDescriptor;
import org.codehaus.plexus.configuration.PlexusConfiguration;
import org.codehaus.plexus.configuration.xml.XmlPlexusConfiguration;
import org.codehaus.plexus.logging.LoggerManager;
import org.codehaus.plexus.util.IOUtil;
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;
import org.codehaus.plexus.util.xml.Xpp3Dom;
import org.codehaus.plexus.util.xml.Xpp3DomBuilder;
import com.google.inject.Module;
/**
* TODO: add a way to use the plugin POM for the lookup so that the user doesn't have to provide the a:g:v:goal
* as the role hint for the mojo lookup.
......@@ -83,11 +94,42 @@ import org.codehaus.plexus.util.xml.Xpp3DomBuilder;
* descriptor and make this entirely declarative!
*
* @author jesse
* @version $Id: AbstractMojoTestCase.java 1345446 2012-06-02 05:52:30Z hboutemy $
* @version $Id$
*/
public abstract class AbstractMojoTestCase
extends PlexusTestCase
{
private static final DefaultArtifactVersion MAVEN_VERSION;
static
{
DefaultArtifactVersion version = null;
String path = "/META-INF/maven/org.apache.maven/maven-core/pom.properties";
InputStream is = AbstractMojoTestCase.class.getResourceAsStream( path );
try
{
Properties properties = new Properties();
if ( is != null )
{
properties.load( is );
}
String property = properties.getProperty( "version" );
if ( property != null )
{
version = new DefaultArtifactVersion( property );
}
}
catch ( IOException e )
{
// odd, where did this come from
}
finally
{
IOUtil.close( is );
}
MAVEN_VERSION = version;
}
private ComponentConfigurator configurator;
private PlexusContainer container;
......@@ -104,11 +146,14 @@ public abstract class AbstractMojoTestCase
protected void setUp()
throws Exception
{
assertTrue( "Maven 3.2.4 or better is required",
MAVEN_VERSION == null || new DefaultArtifactVersion( "3.2.3" ).compareTo( MAVEN_VERSION ) < 0 );
configurator = getContainer().lookup( ComponentConfigurator.class, "basic" );
InputStream is = getClass().getResourceAsStream( "/" + getPluginDescriptorLocation() );
XmlStreamReader reader = ReaderFactory.newXmlReader( is );
XmlStreamReader reader = new XmlStreamReader( is );
InterpolationFilterReader interpolationFilterReader =
new InterpolationFilterReader( new BufferedReader( reader ), container.getContext().getContextData() );
......@@ -119,7 +164,8 @@ public abstract class AbstractMojoTestCase
lookup( RepositorySystem.class ).createArtifact( pluginDescriptor.getGroupId(),
pluginDescriptor.getArtifactId(),
pluginDescriptor.getVersion(), ".jar" );
artifact.setFile( new File( getBasedir() ).getCanonicalFile() );
artifact.setFile( getPluginArtifactFile() );
pluginDescriptor.setPluginArtifact( artifact );
pluginDescriptor.setArtifacts( Arrays.asList( artifact ) );
......@@ -135,6 +181,63 @@ public abstract class AbstractMojoTestCase
}
}
/**
* Returns best-effort plugin artifact file.
* <p>
* First, attempts to determine parent directory of META-INF directory holding the plugin descriptor. If META-INF
* parent directory cannot be determined, falls back to test basedir.
*/
private File getPluginArtifactFile()
throws IOException
{
final String pluginDescriptorLocation = getPluginDescriptorLocation();
final URL resource = getClass().getResource( "/" + pluginDescriptorLocation );
File file = null;
// attempt to resolve relative to META-INF/maven/plugin.xml first
if ( resource != null )
{
if ( "file".equalsIgnoreCase( resource.getProtocol() ) )
{
String path = resource.getPath();
if ( path.endsWith( pluginDescriptorLocation ) )
{
file = new File( path.substring( 0, path.length() - pluginDescriptorLocation.length() ) );
}
}
else if ( "jar".equalsIgnoreCase( resource.getProtocol() ) )
{
// TODO is there a helper for this somewhere?
try
{
URL jarfile = new URL( resource.getPath() );
if ( "file".equalsIgnoreCase( jarfile.getProtocol() ) )
{
String path = jarfile.getPath();
if ( path.endsWith( pluginDescriptorLocation ) )
{
file =
new File( path.substring( 0, path.length() - pluginDescriptorLocation.length() - 2 ) );
}
}
}
catch ( MalformedURLException e )
{
// not jar:file:/ URL, too bad
}
}
}
// fallback to test project basedir if couldn't resolve relative to META-INF/maven/plugin.xml
if ( file == null || ! file.exists() )
{
file = new File( getBasedir() );
}
return file.getCanonicalFile();
}
protected InputStream getPublicDescriptorStream()
throws Exception
{
......@@ -156,7 +259,9 @@ public abstract class AbstractMojoTestCase
ContainerConfiguration cc = setupContainerConfiguration();
try
{
container = new DefaultPlexusContainer( cc );
List<Module> modules = new ArrayList<Module>();
addGuiceModules( modules );
container = new DefaultPlexusContainer( cc, modules.toArray( new Module[modules.size()] ) );
}
catch ( PlexusContainerException e )
{
......@@ -165,11 +270,25 @@ public abstract class AbstractMojoTestCase
}
}
/**
* @since 3.0.0
*/
protected void addGuiceModules( List<Module> modules )
{
// no custom guice modules by default
}
protected ContainerConfiguration setupContainerConfiguration()
{
ClassWorld classWorld = new ClassWorld( "plexus.core", Thread.currentThread().getContextClassLoader() );
return new DefaultContainerConfiguration().setClassWorld( classWorld ).setName( "embedder" );
ContainerConfiguration cc = new DefaultContainerConfiguration()
.setClassWorld( classWorld )
.setClassPathScanning( PlexusConstants.SCANNING_INDEX )
.setAutoWiring( true )
.setName( "maven" );
return cc;
}
protected PlexusContainer getContainer()
......@@ -353,10 +472,15 @@ public abstract class AbstractMojoTestCase
{
configuration = new Xpp3Dom( "configuration" );
}
configuration = Xpp3Dom.mergeXpp3Dom( execution.getConfiguration(), configuration );
configuration = Xpp3Dom.mergeXpp3Dom( configuration, execution.getConfiguration() );
PlexusConfiguration pluginConfiguration = new XmlPlexusConfiguration( configuration );
if ( mojoDescriptor.getComponentConfigurator() != null )
{
configurator = getContainer().lookup( ComponentConfigurator.class, mojoDescriptor.getComponentConfigurator() );
}
configurator.configureComponent( mojo, pluginConfiguration, evaluator, getContainer().getContainerRealm() );
return mojo;
......@@ -373,7 +497,7 @@ public abstract class AbstractMojoTestCase
MavenExecutionRequest request = new DefaultMavenExecutionRequest();
MavenExecutionResult result = new DefaultMavenExecutionResult();
MavenSession session = new MavenSession( container, new MavenRepositorySystemSession(), request, result );
MavenSession session = new MavenSession( container, MavenRepositorySystemUtils.newSession(), request, result );
session.setCurrentProject( project );
session.setProjects( Arrays.asList( project ) );
return session;
......@@ -388,7 +512,7 @@ public abstract class AbstractMojoTestCase
protected MojoExecution newMojoExecution( String goal )
{
MojoDescriptor mojoDescriptor = mojoDescriptors.get( goal );
assertNotNull( mojoDescriptor );
assertNotNull(String.format("The MojoDescriptor for the goal %s cannot be null.", goal), mojoDescriptor );
MojoExecution execution = new MojoExecution( mojoDescriptor );
finalizeMojoConfiguration( execution );
return execution;
......
......@@ -47,7 +47,7 @@ import org.codehaus.plexus.util.StringUtils;
* plugins that need to simulate artifacts for unit tests.
*
* @author <a href="mailto:brianf@apache.org">Brian Fox</a>
* @version $Id: ArtifactStubFactory.java 1340745 2012-05-20 14:48:44Z hboutemy $
* @version $Id$
*/
public class ArtifactStubFactory
{
......
......@@ -23,7 +23,7 @@ package org.apache.maven.plugin.testing;
* ConfigurationException
*
* @author jesse
* @version $Id: ConfigurationException.java 638332 2008-03-18 11:39:00Z bentmann $
* @version $Id$
*/
public class ConfigurationException
extends Exception
......
package org.apache.maven.plugin.testing;
import org.codehaus.plexus.util.xml.Xpp3Dom;
/*
* 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.
*/
/**
* Static helpers to create and manipulate mojo execution configuration parameters
*
* @since 3.2.0
*/
public class MojoParameters
{
public static Xpp3Dom newParameter( String name, String value )
{
Xpp3Dom child = new Xpp3Dom( name );
child.setValue( value );
return child;
}
}
package org.apache.maven.plugin.testing;
/*
* 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.
*/
import java.io.File;
import java.io.InputStream;
import java.util.Map;
import org.apache.maven.execution.DefaultMavenExecutionRequest;
import org.apache.maven.execution.MavenExecutionRequest;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.execution.MojoExecutionEvent;
import org.apache.maven.execution.MojoExecutionListener;
import org.apache.maven.execution.scope.internal.MojoExecutionScope;
import org.apache.maven.plugin.Mojo;
import org.apache.maven.plugin.MojoExecution;
import org.apache.maven.project.MavenProject;
import org.apache.maven.project.ProjectBuilder;
import org.apache.maven.project.ProjectBuildingRequest;
import org.apache.maven.session.scope.internal.SessionScope;
import org.codehaus.plexus.ContainerConfiguration;
import org.codehaus.plexus.PlexusContainer;
import org.codehaus.plexus.component.configurator.ComponentConfigurationException;
import org.codehaus.plexus.component.repository.exception.ComponentLookupException;
import org.codehaus.plexus.configuration.PlexusConfiguration;
import org.codehaus.plexus.util.xml.Xpp3Dom;
import org.eclipse.aether.DefaultRepositorySystemSession;
import org.junit.Assert;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
/**
* {@link TestRule} for usage with Junit-4.10ff. This is just a wrapper for an embedded
* {@link AbstractMojoTestCase}, so all <tt>protected</tt> methods of the TestCase are
* exhibited as <tt>public</tt> in the rule. You may annotate single tests methods with
* {@link WithoutMojo} to prevent the rule from firing.
*
* @author Mirko Friedenhagen
* @version $Id$
* @since 2.2
*/
public class MojoRule
implements TestRule
{
private final AbstractMojoTestCase testCase;
public MojoRule()
{
this( new AbstractMojoTestCase() {} );
}
public MojoRule(AbstractMojoTestCase testCase)
{
this.testCase = testCase;
}
/**
* May be overridden in the implementation to do stuff <em>after</em> the embedded test case
* is set up but <em>before</em> the current test is actually run.
*
* @throws Throwable
*/
protected void before() throws Throwable
{
}
/**
* May be overridden in the implementation to do stuff after the current test was run.
*/
protected void after()
{
}
public InputStream getPublicDescriptorStream()
throws Exception
{
return testCase.getPublicDescriptorStream();
}
public String getPluginDescriptorPath()
{
return testCase.getPluginDescriptorPath();
}
public String getPluginDescriptorLocation()
{
return testCase.getPluginDescriptorLocation();
}
public void setupContainer()
{
testCase.setupContainer();
}
public ContainerConfiguration setupContainerConfiguration()
{
return testCase.setupContainerConfiguration();
}
public PlexusContainer getContainer()
{
return testCase.getContainer();
}
/**
* Lookup the mojo leveraging the subproject pom
*
* @param goal
* @param pluginPom
* @return a Mojo instance
* @throws Exception
*/
public Mojo lookupMojo( String goal, String pluginPom )
throws Exception
{
return testCase.lookupMojo( goal, pluginPom );
}
/**
* Lookup an empty mojo
*
* @param goal
* @param pluginPom
* @return a Mojo instance
* @throws Exception
*/
public Mojo lookupEmptyMojo( String goal, String pluginPom )
throws Exception
{
return testCase.lookupEmptyMojo( goal, new File( pluginPom ) );
}
/**
* Lookup the mojo leveraging the actual subprojects pom
*
* @param goal
* @param pom
* @return a Mojo instance
* @throws Exception
*/
public Mojo lookupMojo( String goal, File pom )
throws Exception
{
return testCase.lookupMojo( goal, pom );
}
/**
* Lookup the mojo leveraging the actual subprojects pom
*
* @param goal
* @param pom
* @return a Mojo instance
* @throws Exception
*/
public Mojo lookupEmptyMojo( String goal, File pom )
throws Exception
{
return testCase.lookupEmptyMojo( goal, pom );
}
public Mojo lookupMojo( String groupId, String artifactId, String version, String goal,
PlexusConfiguration pluginConfiguration )
throws Exception
{
return testCase.lookupMojo( groupId, artifactId, version, goal, pluginConfiguration );
}
public Mojo lookupConfiguredMojo( MavenProject project, String goal )
throws Exception
{
return testCase.lookupConfiguredMojo( project, goal );
}
public Mojo lookupConfiguredMojo( MavenSession session, MojoExecution execution )
throws Exception, ComponentConfigurationException
{
return testCase.lookupConfiguredMojo( session, execution );
}
public MavenSession newMavenSession( MavenProject project )
{
return testCase.newMavenSession( project );
}
public MojoExecution newMojoExecution( String goal )
{
return testCase.newMojoExecution( goal );
}
public PlexusConfiguration extractPluginConfiguration( String artifactId, File pom )
throws Exception
{
return testCase.extractPluginConfiguration( artifactId, pom );
}
public PlexusConfiguration extractPluginConfiguration( String artifactId, Xpp3Dom pomDom )
throws Exception
{
return testCase.extractPluginConfiguration( artifactId, pomDom );
}
public Mojo configureMojo( Mojo mojo, String artifactId, File pom )
throws Exception
{
return testCase.configureMojo( mojo, artifactId, pom );
}
public Mojo configureMojo( Mojo mojo, PlexusConfiguration pluginConfiguration )
throws Exception
{
return testCase.configureMojo( mojo, pluginConfiguration );
}
/**
* 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 to what the desired type is.
*
* @param object
* @param variable
* @return object value of variable
* @throws IllegalArgumentException
*/
public Object getVariableValueFromObject( Object object, String variable )
throws IllegalAccessException
{
return testCase.getVariableValueFromObject( object, variable );
}
/**
* 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.
*
* @param object
* @return map of variable names and values
*/
public Map<String, Object> getVariablesAndValuesFromObject( Object object )
throws IllegalAccessException
{
return testCase.getVariablesAndValuesFromObject( 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.
*
* @param clazz
* @param object
* @return map of variable names and values
*/
public Map<String, Object> getVariablesAndValuesFromObject( Class<?> clazz, Object object )
throws IllegalAccessException
{
return testCase.getVariablesAndValuesFromObject( clazz, object );
}
/**
* Convenience method to set values to variables in objects that don't have setters
*
* @param object
* @param variable
* @param value
* @throws IllegalAccessException
*/
public void setVariableValueToObject( Object object, String variable, Object value )
throws IllegalAccessException
{
testCase.setVariableValueToObject( object, variable, value );
}
@Override
public Statement apply(final Statement base, Description description) {
if (description.getAnnotation(WithoutMojo.class) != null) // skip.
{
return base;
}
return new Statement()
{
@Override
public void evaluate() throws Throwable
{
testCase.setUp();
before();
try
{
base.evaluate();
}
finally
{
after();
}
}
};
}
/**
* @since 3.1.0
*/
public MavenProject readMavenProject( File basedir )
throws Exception
{
File pom = new File( basedir, "pom.xml" );
MavenExecutionRequest request = new DefaultMavenExecutionRequest();
request.setBaseDirectory( basedir );
ProjectBuildingRequest configuration = request.getProjectBuildingRequest();
configuration.setRepositorySession( new DefaultRepositorySystemSession() );
MavenProject project = lookup( ProjectBuilder.class ).build( pom, configuration ).getProject();
Assert.assertNotNull( project );
return project;
}
/**
* @since 3.1.0
*/
public void executeMojo( File basedir, String goal )
throws Exception
{
MavenProject project = readMavenProject( basedir );
MavenSession session = newMavenSession( project );
MojoExecution execution = newMojoExecution( goal );
executeMojo( session, project, execution );
}
/**
* @since 3.1.0
*/
public Mojo lookupConfiguredMojo( File basedir, String goal )
throws Exception, ComponentConfigurationException
{
MavenProject project = readMavenProject( basedir );
MavenSession session = newMavenSession( project );
MojoExecution execution = newMojoExecution( goal );
return lookupConfiguredMojo( session, execution );
}
/**
* @since 3.1.0
*/
public final <T> T lookup( final Class<T> role )
throws ComponentLookupException
{
return getContainer().lookup( role );
}
/**
* @since 3.2.0
*/
public void executeMojo( MavenProject project, String goal, Xpp3Dom... parameters )
throws Exception
{
MavenSession session = newMavenSession( project );
executeMojo( session, project, goal, parameters );
}
/**
* @since 3.2.0
*/
public void executeMojo( MavenSession session, MavenProject project, String goal, Xpp3Dom... parameters )
throws Exception
{
MojoExecution execution = newMojoExecution( goal );
if ( parameters != null )
{
Xpp3Dom configuration = execution.getConfiguration();
for ( Xpp3Dom parameter : parameters )
{
configuration.addChild( parameter );
}
}
executeMojo( session, project, execution );
}
/**
* @since 3.2.0
*/
public void executeMojo( MavenSession session, MavenProject project, MojoExecution execution )
throws Exception
{
SessionScope sessionScope = lookup( SessionScope.class );
try
{
sessionScope.enter();
sessionScope.seed( MavenSession.class, session );
MojoExecutionScope executionScope = lookup( MojoExecutionScope.class );
try
{
executionScope.enter();
executionScope.seed( MavenProject.class, project );
executionScope.seed( MojoExecution.class, execution );
Mojo mojo = lookupConfiguredMojo( session, execution );
mojo.execute();
MojoExecutionEvent event = new MojoExecutionEvent( session, project, execution, mojo );
for ( MojoExecutionListener listener : getContainer().lookupList( MojoExecutionListener.class ) )
{
listener.afterMojoExecutionSuccess( event );
}
}
finally
{
executionScope.exit();
}
}
finally
{
sessionScope.exit();
}
}
}
......@@ -31,7 +31,7 @@ import org.apache.maven.artifact.repository.layout.DefaultRepositoryLayout;
* Stub for {@link ExpressionEvaluator}
*
* @author jesse
* @version $Id: ResolverExpressionEvaluatorStub.java 638332 2008-03-18 11:39:00Z bentmann $
* @version $Id$
*/
public class ResolverExpressionEvaluatorStub
implements ExpressionEvaluator
......
......@@ -27,7 +27,7 @@ import org.codehaus.plexus.logging.Logger;
* to turn off logs during testing where they aren't desired.
*
* @author <a href="mailto:brianf@apache.org">Brian Fox</a>
* @version $Id: SilentLog.java 785452 2009-06-17 00:00:18Z olamy $
* @version $Id$
*/
public class SilentLog
implements Log, Logger
......
package org.apache.maven.plugin.testing;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
/*
* 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.
*/
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Target;
/**
*
* An annotation for test methods that do not require the {@link MojoRule} to create and tear down the instance.
*
* @author Mirko Friedenhagen
*/
@Retention(RUNTIME)
@Documented
@Target(METHOD)
public @interface WithoutMojo {
}
package org.apache.maven.plugin.testing.resources;
/*
* 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.
*/
import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.Set;
import java.util.TreeSet;
import org.codehaus.plexus.util.DirectoryScanner;
import org.codehaus.plexus.util.FileUtils;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.rules.TestWatcher;
import org.junit.runner.Description;
/**
* Junit4 test {@link Rule} to extract and assert test resources.
*
* @since 3.1.0
*/
public class TestResources
extends TestWatcher
{
private final String projectsDir;
private final String workDir;
public TestResources()
{
this( "src/test/projects", "target/test-projects" );
}
public TestResources( String projectsDir, String workDir )
{
this.projectsDir = projectsDir;
this.workDir = workDir;
}
private String name;
@Override
protected void starting( Description d )
{
String methodName = d.getMethodName();
if ( methodName != null )
{
methodName = methodName.replace( '/', '_' ).replace( '\\', '_' );
}
name = d.getTestClass().getSimpleName() + "_" + methodName;
}
/**
* Creates new clean copy of test project directory structure. The copy is named after both the test being executed
* and test project name, which allows the same test project can be used by multiple tests and by different
* instances of the same parametrized tests.<br/>
* TODO Provide alternative working directory naming for Windows, which still limits path names to ~250 charecters
*/
public File getBasedir( String project )
throws IOException
{
if ( name == null )
{
throw new IllegalStateException( getClass().getSimpleName()
+ " must be a test class field annotated with org.junit.Rule" );
}
File src = new File( projectsDir, project ).getCanonicalFile();
Assert.assertTrue( "Test project directory does not exist: " + src.getPath(), src.isDirectory() );
File basedir = new File( workDir, name + "_" + project ).getCanonicalFile();
FileUtils.deleteDirectory( basedir );
Assert.assertTrue( "Test project working directory created", basedir.mkdirs() );
FileUtils.copyDirectoryStructure( src, basedir );
return basedir;
}
// static helpers
public static void cp( File basedir, String from, String to )
throws IOException
{
// TODO ensure destination lastModified timestamp changes
FileUtils.copyFile( new File( basedir, from ), new File( basedir, to ) );
}
public static void assertFileContents( File basedir, String expectedPath, String actualPath )
throws IOException
{
String expected = FileUtils.fileRead( new File( basedir, expectedPath ) );
String actual = FileUtils.fileRead( new File( basedir, actualPath ) );
Assert.assertEquals( expected, actual );
}
public static void assertDirectoryContents( File dir, String... expectedPaths )
{
DirectoryScanner scanner = new DirectoryScanner();
scanner.setBasedir( dir );
scanner.addDefaultExcludes();
scanner.scan();
Set<String> actual = new TreeSet<String>();
for ( String path : scanner.getIncludedFiles() )
{
actual.add( path );
}
for ( String path : scanner.getIncludedDirectories() )
{
if ( path.length() > 0 )
{
actual.add( path + "/" );
}
}
Set<String> expected = new TreeSet<String>();
if ( expectedPaths != null )
{
for ( String path : expectedPaths )
{
expected.add( path );
}
}
// compare textual representation to make diff easier to understand
Assert.assertEquals( toString( expected ), toString( actual ) );
}
private static String toString( Collection<String> strings )
{
StringBuilder sb = new StringBuilder();
for ( String string : strings )
{
sb.append( string ).append( '\n' );
}
return sb.toString();
}
public static void touch( File basedir, String path )
throws InterruptedException
{
touch( new File( basedir, path ) );
}
public static void touch( File file )
throws InterruptedException
{
if ( !file.isFile() )
{
throw new IllegalArgumentException( "Not a file " + file );
}
long lastModified = file.lastModified();
file.setLastModified( System.currentTimeMillis() );
// TODO do modern filesystems still have this silly lastModified resolution?
if ( lastModified == file.lastModified() )
{
Thread.sleep( 1000L );
file.setLastModified( System.currentTimeMillis() );
}
}
public static void rm( File basedir, String path )
{
Assert.assertTrue( "delete " + path, new File( basedir, path ).delete() );
}
/**
* @since 3.2.0
*/
public static void create( File basedir, String... paths )
throws IOException
{
if ( paths == null || paths.length == 0 )
{
throw new IllegalArgumentException();
}
for ( String path : paths )
{
File file = new File( basedir, path );
Assert.assertTrue( file.getParentFile().mkdirs() );
file.createNewFile();
Assert.assertTrue( file.isFile() && file.canRead() );
}
}
}
......@@ -36,7 +36,7 @@ import org.apache.maven.artifact.versioning.VersionRange;
* Stub class for {@link Artifact} testing.
*
* @author jesse
* @version $Id: ArtifactStub.java 1340752 2012-05-20 15:20:59Z hboutemy $
* @version $Id$
*/
public class ArtifactStub
implements Artifact
......
......@@ -25,7 +25,7 @@ import org.apache.maven.artifact.handler.ArtifactHandler;
* Minimal artifact handler used by the stub factory to create unpackable archives.
*
* @author <a href="mailto:brianf@apache.org">Brian Fox</a>
* @version $Id: DefaultArtifactHandlerStub.java 638332 2008-03-18 11:39:00Z bentmann $
* @version $Id$
*/
public class DefaultArtifactHandlerStub
implements ArtifactHandler
......
......@@ -68,7 +68,7 @@ import org.codehaus.plexus.util.xml.pull.XmlPullParserException;
* useful as a stub though.
*
* @author jesse
* @version $Id: MavenProjectStub.java 1340752 2012-05-20 15:20:59Z hboutemy $
* @version $Id$
*/
public class MavenProjectStub
extends MavenProject
......
......@@ -37,7 +37,7 @@ import org.apache.maven.repository.legacy.resolver.conflict.ConflictResolver;
/**
* @author <a href="mailto:brianf@apache.org">Brian Fox</a>
* @version $Id: StubArtifactCollector.java 834917 2009-11-11 15:40:37Z olamy $
* @version $Id$
*/
public class StubArtifactCollector
implements ArtifactCollector
......
......@@ -33,7 +33,7 @@ import java.util.List;
/**
* @author <a href="mailto:brianf@apache.org">Brian Fox</a>
* @version $Id: StubArtifactRepository.java 1206336 2011-11-25 21:41:59Z olamy $
* @version $Id$
*/
public class StubArtifactRepository
implements ArtifactRepository
......
......@@ -41,7 +41,7 @@ import org.apache.maven.wagon.events.TransferListener;
* Stub resolver. The constructor allows the specification of the exception to throw so that handling can be tested too.
*
* @author <a href="mailto:brianf@apache.org">Brian Fox</a>
* @version $Id: StubArtifactResolver.java 1340752 2012-05-20 15:20:59Z hboutemy $
* @version $Id$
*/
public class StubArtifactResolver
implements ArtifactResolver
......
......@@ -129,7 +129,69 @@ public class MyMojoTest
In this case, <<<testSomething()>>> will test <<<MyMojo>>> against a Maven project called <<<project-to-test>>>.
<<Note>>: By convention, Mojo unit tests should be in the test resources directory.
<<Note>>: By convention, projects for unit testing your should be in the test resources directory.
Alternatively to extending <<<AbstractMojoTestCase>>> and when using Junit-4.10 ff., you may use a <<<MojoRule>>>,
which just embeds an <<<AbstractMojoTestCase>>>.
When you do not need the functionality in every test method, you may use the <<<@WithoutMojo>>> annotation to
skip rule executions.
+---+
import org.apache.maven.plugin.testing.MojoRule;
import org.apache.maven.plugin.testing.WithoutMojo;
import org.junit.Rule;
import static org.junit.Assert.*;
import org.junit.Test;
public class MyMojoTest
{
@Rule
public MojoRule rule = new MojoRule()
{
@Override
protected void before() throws Throwable
{
}
@Override
protected void after()
{
}
};
/**
* @throws Exception if any
*/
@Test
public void testSomething()
throws Exception
{
File pom = rule.getTestFile( "src/test/resources/unit/project-to-test/pom.xml" );
assertNotNull( pom );
assertTrue( pom.exists() );
MyMojo myMojo = (MyMojo) rule.lookupMojo( "touch", pom );
assertNotNull( myMojo );
myMojo.execute();
...
}
/** Do not need the MojoRule. */
@WithoutMojo
@Test
public void testSomethingWhichDoesNotNeedTheMojoAndProbablyShouldBeExtractedIntoANewClassOfItsOwn()
{
...
}
}
+---+
** Configuring <<<project-to-test>>> pom
......
......@@ -27,7 +27,7 @@ import org.codehaus.plexus.util.StringUtils;
/**
* @author Edwin Punzalan
* @version $Id: ExpressionEvaluatorMojo.java 638332 2008-03-18 11:39:00Z bentmann $
* @version $Id$
*/
public class ExpressionEvaluatorMojo
extends AbstractMojo
......