Clover Coverage Report - Exec Maven Plugin 1.1
Coverage timestamp: Wed Dec 31 1969 19:00:00 EST
138   502   38   6.9
20   288   0.28   10
20     1.9  
2    
 
  ExecMojoTest       Line # 53 131 0% 33 165 0% 0.0
  ExecMojoTest.MockExecMojo       Line # 58 7 0% 5 13 0% 0.0
 
No Tests
 
1    package org.codehaus.mojo.exec;
2   
3    /*
4    * Copyright 2005 The Codehaus.
5    *
6    * Licensed under the Apache License, Version 2.0 (the "License");
7    * you may not use this file except in compliance with the License.
8    * You may obtain a copy of the License at
9    *
10    * http://www.apache.org/licenses/LICENSE-2.0
11    *
12    * Unless required by applicable law or agreed to in writing, software
13    * distributed under the License is distributed on an "AS IS" BASIS,
14    * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15    * See the License for the specific language governing permissions and
16    * limitations under the License.
17    */
18   
19    import org.apache.maven.artifact.repository.ArtifactRepository;
20    import org.apache.maven.artifact.repository.DefaultArtifactRepository;
21    import org.apache.maven.artifact.repository.layout.ArtifactRepositoryLayout;
22    import org.apache.maven.plugin.MojoExecutionException;
23    import org.apache.maven.plugin.logging.SystemStreamLog;
24    import org.apache.maven.project.MavenProject;
25    import org.apache.maven.project.MavenProjectBuilder;
26   
27    import java.io.BufferedReader;
28    import java.io.File;
29    import java.io.FileReader;
30    import java.io.IOException;
31    import java.io.OutputStream;
32    import java.io.PrintStream;
33    import org.codehaus.plexus.util.StringOutputStream;
34    import java.util.ArrayList;
35    import java.util.Arrays;
36    import java.util.Collections;
37    import java.util.HashMap;
38    import java.util.List;
39    import java.util.Map;
40    import org.apache.commons.exec.CommandLine;
41    import org.apache.commons.exec.ExecuteException;
42    import org.apache.commons.exec.Executor;
43    import org.apache.commons.exec.OS;
44    import org.codehaus.plexus.logging.Logger;
45    import org.codehaus.plexus.logging.console.ConsoleLogger;
46    import org.apache.maven.monitor.logging.DefaultLog;
47    import org.apache.maven.plugin.testing.AbstractMojoTestCase;
48   
49    /**
50    * @author Jerome Lacoste <jerome@coffeebreaks.org>
51    * @version $Id: ExecMojoTest.java 12372 2010-07-09 20:51:00Z rfscholte $
52    */
 
53    public class ExecMojoTest
54    extends AbstractMojoTestCase
55    {
56    private MockExecMojo mojo;
57   
 
58    static class MockExecMojo
59    extends ExecMojo
60    {
61    public int executeResult;
62   
63    public List commandLines = new ArrayList();
64   
65    public String failureMsg;
66   
67    public Map systemProperties = new HashMap();
68   
 
69  0 toggle protected int executeCommandLine( Executor exec, CommandLine commandLine, Map enviro, OutputStream out, OutputStream err )
70    throws IOException, ExecuteException
71    {
72  0 commandLines.add( commandLine );
73  0 if ( failureMsg != null )
74    {
75  0 throw new ExecuteException( failureMsg, executeResult );
76    }
77  0 return executeResult;
78    }
79   
 
80  0 toggle protected String getSystemProperty( String key )
81    {
82  0 return (String) systemProperties.get( key );
83    }
84   
 
85  0 toggle int getAmountExecutedCommandLines() {
86  0 return commandLines.size();
87    }
88   
 
89  0 toggle CommandLine getExecutedCommandline( int index ) {
90  0 return ((CommandLine) commandLines.get( index ));
91    }
92    }
93   
 
94  0 toggle public void setUp()
95    throws Exception
96    {
97  0 super.setUp();
98  0 mojo = new MockExecMojo();
99    // note: most of the tests below assume that the specified
100    // executable path is not fully specicied. See ExecMojo#getExecutablePath
101  0 mojo.setExecutable( "mvn" );
102  0 mojo.setArguments( Arrays.asList( new String[]{"--version"} ) );
103  0 mojo.executeResult = 0;
104  0 mojo.setBasedir( File.createTempFile( "mvn-temp", "txt" ).getParentFile() );
105    }
106   
107    /**
108    */
 
109  0 toggle public void testRunOK()
110    throws MojoExecutionException
111    {
112  0 mojo.execute();
113   
114  0 checkMojo( "mvn --version" );
115    }
116   
117    /*
118    This one won't work yet
119    public void xxtestSimpleRunPropertiesAndArguments()
120    throws MojoExecutionException, Exception
121    {
122    File pom = new File( getBasedir(), "src/test/projects/project1/pom.xml" );
123   
124    String output = execute( pom, "exec" );
125   
126    System.out.println(" OUTPUT" + output + "\n\n\n");
127   
128    String expectedOutput = "arg.arg1\narg.arg2\nproject.env1=value1"; // FIXME should work on Windows as well
129   
130    assertEquals( expectedOutput, output );
131    }
132    */
133   
134    /**
135    * integration test...
136    * - compile the Test class using mvn clean compile
137    * - run the test file using java, use it to generate a file whose contains are compared to expected output
138    */
139    /*
140    public void testRunOKWithAutoComputedClasspath()
141    throws MojoExecutionException, Exception
142    {
143    String projectName = "project1";
144   
145    ExecMojo mojo = new ExecMojo();
146   
147    setUpProject( projectName, mojo );
148   
149    // compile project
150    mojo.setExecutable( "mvn" );
151    mojo.setWorkingDirectory( new File( "src/test/projects/" + projectName + "/" ) );
152    mojo.setArguments( Arrays.asList( new String[]{"clean", "compile"} ) );
153   
154    mojo.execute();
155   
156    mojo.getLog().info( "executed mvn clean compile" );
157   
158    // the command executes the test class
159    mojo.setExecutable( "java" );
160    mojo.setWorkingDirectory( (File) null );
161    Classpath classpath = new Classpath();
162    mojo.setArguments( Arrays.asList( new Object[]{"-Dproject.env1=value1", "-classpath", classpath,
163    "org.codehaus.mojo.exec.test.Test",
164    new File( "src/test/projects/" + projectName + "/target/exec/output.txt" ).getAbsolutePath(), "arg1",
165    "arg2"} ) );
166   
167    mojo.execute();
168   
169    // checking the command line would involve resolving the repository
170    // checkMojo( "java -cp" );
171   
172    assertFileEquals( null, getTestFile( "src/test/projects/" + projectName + "/output.txt" ),
173    getTestFile( "src/test/projects/" + projectName + "/target/exec/output.txt" ) );
174   
175    // the command executes the test class, this time specifying the dependencies
176    mojo.setExecutable( "java" );
177    mojo.setWorkingDirectory( (File) null );
178    classpath = new Classpath();
179    List dependencies = new ArrayList();
180    dependencies.add( "commons-io:commons-io" );
181    classpath.setDependencies( dependencies );
182    mojo.setArguments( Arrays.asList( new Object[]{"-Dproject.env1=value1", "-classpath", classpath,
183    "org.codehaus.mojo.exec.test.Test",
184    new File( "src/test/projects/" + projectName + "/target/exec/output.txt" ).getAbsolutePath(), "arg1",
185    "arg2"} ) );
186   
187    mojo.execute();
188   
189    // checking the command line would involve resolving the repository
190    // checkMojo( "java -cp" );
191   
192    assertFileEquals( null, getTestFile( "src/test/projects/" + projectName + "/output.txt" ),
193    getTestFile( "src/test/projects/" + projectName + "/target/exec/output.txt" ) );
194    }
195    */
196   
197    /**
198    * @return output from System.out during mojo execution
199    */
 
200  0 toggle private String execute( File pom, String goal ) throws Exception {
201   
202  0 ExecMojo mojo;
203  0 mojo = (ExecMojo) lookupMojo( goal, pom );
204   
205  0 setUpProject( pom, mojo );
206   
207  0 MavenProject project = (MavenProject) getVariableValueFromObject( mojo, "project" );
208   
209    // why isn't this set up by the harness based on the default-value? TODO get to bottom of this!
210    // setVariableValueToObject( mojo, "includeProjectDependencies", Boolean.TRUE );
211    // setVariableValueToObject( mojo, "killAfter", new Long( -1 ) );
212   
213  0 assertNotNull( mojo );
214  0 assertNotNull( project );
215   
216    // trap System.out
217  0 PrintStream out = System.out;
218  0 StringOutputStream stringOutputStream = new StringOutputStream();
219  0 System.setOut( new PrintStream( stringOutputStream ) );
220    // ensure we don't log unnecessary stuff which would interfere with assessing success of tests
221  0 mojo.setLog( new DefaultLog( new ConsoleLogger( Logger.LEVEL_ERROR, "exec:exec" ) ) );
222   
223  0 try
224    {
225  0 mojo.execute();
226    }
227    catch ( Throwable e )
228    {
229  0 e.printStackTrace( System.err );
230  0 fail( e.getMessage() );
231    }
232    finally
233    {
234  0 System.setOut( out );
235    }
236   
237  0 return stringOutputStream.toString();
238    }
239   
240   
 
241  0 toggle private void setUpProject( File pomFile, ExecMojo mojo )
242    throws Exception
243    {
244  0 MavenProjectBuilder builder = (MavenProjectBuilder) lookup( MavenProjectBuilder.ROLE );
245   
246  0 ArtifactRepositoryLayout localRepositoryLayout =
247    (ArtifactRepositoryLayout) lookup( ArtifactRepositoryLayout.ROLE, "default" );
248   
249  0 String path = "src/test/repository";
250   
251  0 ArtifactRepository localRepository = new DefaultArtifactRepository( "local", "file://" +
252    new File( path ).getAbsolutePath(), localRepositoryLayout );
253   
254  0 mojo.setBasedir( File.createTempFile( "mvn-temp", "txt" ).getParentFile() );
255   
256  0 MavenProject project = builder.buildWithDependencies( pomFile, localRepository, null );
257   
258    // this gets the classes for these tests of this mojo (exec plugin) onto the project classpath for the test
259  0 project.getBuild().setOutputDirectory( new File( "target/test-classes" ).getAbsolutePath() );
260   
261  0 mojo.setProject( project );
262   
263  0 mojo.setLog( new SystemStreamLog()
264    {
 
265  0 toggle public boolean isDebugEnabled()
266    {
267  0 return true;
268    }
269    } );
270    }
271   
272    // MEXEC-12, MEXEC-72
 
273  0 toggle public void testGetExecutablePath() throws IOException
274    {
275   
276  0 ExecMojo realMojo = new ExecMojo();
277   
278  0 File workdir = new File( System.getProperty( "user.dir" ) );
279  0 Map enviro = new HashMap();
280   
281  0 String myJavaPath = "target" + File.separator + "javax";
282  0 File f = new File( myJavaPath );
283  0 assertTrue( "file created...", f.createNewFile() );
284  0 assertTrue( "file exists...", f.exists() );
285   
286  0 realMojo.setExecutable( myJavaPath );
287   
288  0 CommandLine cmd = realMojo.getExecutablePath(enviro, workdir);
289  0 assertTrue( "File exists so path is absolute",
290    cmd.getExecutable().startsWith( System.getProperty( "user.dir" ) ) );
291   
292  0 f.delete();
293  0 assertFalse( "file deleted...", f.exists() );
294  0 cmd = realMojo.getExecutablePath(enviro, workdir);
295  0 assertEquals( "File doesn't exist. Let the system find it (in that PATH?)",
296    myJavaPath, cmd.getExecutable() );
297   
298   
299  0 if ( OS.isFamilyWindows() ) //how to make this part of the test run on other platforms as well??
300    {
301   
302  0 myJavaPath = "target" + File.separator + "javax.bat";
303  0 f = new File( myJavaPath );
304  0 assertTrue( "file created...", f.createNewFile() );
305  0 assertTrue( "file exists...", f.exists() );
306   
307   
308  0 realMojo.setExecutable( "javax.bat" );
309  0 cmd = realMojo.getExecutablePath( enviro, workdir );
310  0 assertTrue( "is bat file on windows, execute using cmd.",
311    cmd.getExecutable().equals( "cmd" ) );
312   
313  0 enviro.put( "PATH", workdir.getAbsolutePath() + File.separator + "target" );
314  0 cmd = realMojo.getExecutablePath( enviro, workdir );
315  0 assertTrue( "is bat file on windows' PATH, execute using cmd.",
316    cmd.getExecutable().equals( "cmd" ) );
317  0 f.delete();
318  0 assertFalse( "file deleted...", f.exists() );
319    }
320    }
321   
 
322  0 toggle public void testRunFailure()
323    {
324  0 mojo.executeResult = 1;
325   
326  0 try
327    {
328  0 mojo.execute();
329  0 fail( "expected failure" );
330    }
331    catch ( MojoExecutionException e )
332    {
333  0 assertEquals( "Result of " + mojo.getExecutedCommandline( 0 ) + " execution is: '1'.",
334    e.getMessage() );
335    }
336   
337  0 checkMojo( "mvn --version" );
338    }
339   
 
340  0 toggle public void testRunError()
341    {
342  0 mojo.failureMsg = "simulated failure";
343   
344  0 try
345    {
346  0 mojo.execute();
347  0 fail( "expected failure" );
348    }
349    catch ( MojoExecutionException e )
350    {
351  0 assertEquals( "Command execution failed.", e.getMessage() );
352    }
353   
354  0 checkMojo( "mvn --version" );
355    }
356   
 
357  0 toggle public void testOverrides()
358    throws MojoExecutionException
359    {
360  0 mojo.systemProperties.put( "exec.args", "-f pom.xml" );
361  0 mojo.execute();
362   
363  0 checkMojo( "mvn -f pom.xml" );
364    }
365   
 
366  0 toggle public void testOverrides3()
367    throws MojoExecutionException
368    {
369  0 mojo.systemProperties.put( "exec.args", null );
370  0 mojo.execute();
371   
372  0 checkMojo( "mvn --version" );
373   
374  0 mojo.commandLines.clear();
375  0 mojo.systemProperties.put( "exec.args", "" );
376  0 mojo.execute();
377   
378  0 checkMojo( "mvn --version" );
379    }
380   
 
381  0 toggle public void testIsResultCodeAFailure()
382    {
383  0 ExecMojo execMojo = new ExecMojo();
384  0 assertTrue(execMojo.isResultCodeAFailure(1));
385  0 assertFalse(execMojo.isResultCodeAFailure(0));
386   
387  0 execMojo.setSuccessCodes(new ArrayList());
388  0 assertTrue(execMojo.isResultCodeAFailure(1));
389  0 assertFalse(execMojo.isResultCodeAFailure(0));
390   
391  0 execMojo.setSuccessCodes(Arrays.asList(new String[] { "2", "5" }));
392  0 assertTrue(execMojo.isResultCodeAFailure(0));
393  0 assertTrue(execMojo.isResultCodeAFailure(10));
394  0 assertFalse(execMojo.isResultCodeAFailure(2));
395  0 assertFalse(execMojo.isResultCodeAFailure(5));
396    }
397   
398    // MEXEC-81
 
399  0 toggle public void testParseCommandlineOSWin() throws Exception
400    {
401  0 ExecMojo execMojo = new ExecMojo();
402  0 final String javaHome = "C:\\Java\\jdk1.5.0_15";
403    // can only be set by expression or plugin-configuration
404  0 setVariableValueToObject( execMojo, "commandlineArgs", javaHome );
405  0 String[] args = execMojo.parseCommandlineArgs();
406  0 assertEquals( javaHome, args[0] );
407    }
408   
 
409  0 toggle private void checkMojo( String expectedCommandLine )
410    {
411  0 assertEquals( 1, mojo.getAmountExecutedCommandLines() );
412  0 CommandLine commandline = mojo.getExecutedCommandline( 0 );
413    // do NOT depend on Commandline toString()
414  0 assertEquals(expectedCommandLine, getCommandLineAsString( commandline ));
415    }
416   
 
417  0 toggle private String getCommandLineAsString( CommandLine commandline ) {
418    //for the sake of the test comparisons, cut out the eventual
419    //cmd /c *.bat conversion
420  0 String result = commandline.getExecutable();
421  0 boolean isCmd = false;
422  0 if (OS.isFamilyWindows() && result.equals("cmd")) {
423  0 result = "";
424  0 isCmd = true;
425    }
426  0 String[] arguments = commandline.getArguments();
427  0 for (int i = 0; i < arguments.length; i++)
428    {
429  0 String arg = arguments[i];
430  0 if (isCmd && i == 0 && "/c".equals(arg)) {
431  0 continue;
432    }
433  0 if (isCmd && i == 1 && arg.endsWith( ".bat")) {
434  0 arg = arg.substring( 0, arg.length() - ".bat".length());
435    }
436  0 result += (result.length() == 0 ? "" : " ") + arg;
437    }
438  0 return result;
439    }
440   
441    // TAKEN FROM NetbeansFreeformPluginTest - refactor ?
442   
443    /**
444    * This method asserts that the two given files are equals in their
445    * content.
446    *
447    * @param mavenRepo Not used.
448    * @param expectedFile The file that is expected.
449    * @param actualFile The file that is.
450    * @throws java.io.IOException if something goes wrong.
451    */
 
452  0 toggle private void assertFileEquals( String mavenRepo, File expectedFile, File actualFile )
453    throws IOException
454    {
455  0 List expectedLines = getLines( mavenRepo, expectedFile );
456   
457  0 List actualLines = getLines( mavenRepo, actualFile );
458   
459  0 for ( int i = 0; i < expectedLines.size(); i++ )
460    {
461  0 String expected = expectedLines.get( i ).toString();
462   
463  0 if ( actualLines.size() < i )
464    {
465  0 fail( "Too few lines in the actual file. Was " + actualLines.size() + ", expected: " +
466    expectedLines.size() );
467    }
468   
469  0 String actual = actualLines.get( i ).toString();
470   
471  0 assertEquals( "Checking line #" + ( i + 1 ), expected, actual );
472    }
473   
474  0 assertTrue( "Unequal number of lines.", expectedLines.size() == actualLines.size() );
475    }
476   
477    /**
478    * This method gives the list of String in a file.
479    *
480    * @param mavenRepo Not used.
481    * @param file The file to be read.
482    * @return The list of the lines of the file.
483    * @throws java.io.IOException if something goes wrong.
484    */
 
485  0 toggle private List getLines( String mavenRepo, File file )
486    throws IOException
487    {
488  0 List lines = new ArrayList();
489   
490  0 BufferedReader reader = new BufferedReader( new FileReader( file ) );
491   
492  0 String line;
493   
494  0 while ( ( line = reader.readLine() ) != null )
495    {
496  0 lines.add(
497    line ); //StringUtils.replace( line, "#ArtifactRepositoryPath#", mavenRepo.replace( '\\', '/' ) ) );
498    }
499   
500  0 return lines;
501    }
502    }