001: package org.apache.maven.embedder;
002:
003: /*
004: * Licensed to the Apache Software Foundation (ASF) under one
005: * or more contributor license agreements. See the NOTICE file
006: * distributed with this work for additional information
007: * regarding copyright ownership. The ASF licenses this file
008: * to you under the Apache License, Version 2.0 (the
009: * "License"); you may not use this file except in compliance
010: * with the License. You may obtain a copy of the License at
011: *
012: * http://www.apache.org/licenses/LICENSE-2.0
013: *
014: * Unless required by applicable law or agreed to in writing,
015: * software distributed under the License is distributed on an
016: * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
017: * KIND, either express or implied. See the License for the
018: * specific language governing permissions and limitations
019: * under the License.
020: */
021:
022: import junit.framework.TestCase;
023: import org.apache.maven.settings.SettingsConfigurationException;
024: import org.apache.maven.artifact.Artifact;
025: import org.apache.maven.execution.DefaultMavenExecutionRequest;
026: import org.apache.maven.execution.MavenExecutionRequest;
027: import org.apache.maven.execution.MavenExecutionResult;
028: import org.apache.maven.model.Build;
029: import org.apache.maven.model.Model;
030: import org.apache.maven.model.Plugin;
031: import org.apache.maven.project.MavenProject;
032: import org.apache.maven.settings.Profile;
033: import org.apache.maven.settings.Repository;
034: import org.apache.maven.settings.Settings;
035: import org.apache.maven.settings.io.xpp3.SettingsXpp3Reader;
036: import org.apache.maven.settings.io.xpp3.SettingsXpp3Writer;
037: import org.codehaus.plexus.util.FileUtils;
038: import org.codehaus.plexus.util.IOUtil;
039: import org.codehaus.plexus.util.xml.pull.XmlPullParserException;
040:
041: import java.io.File;
042: import java.io.FileReader;
043: import java.io.FileWriter;
044: import java.io.IOException;
045: import java.io.Writer;
046: import java.util.Arrays;
047: import java.util.Iterator;
048: import java.util.List;
049: import java.util.Set;
050:
051: public class MavenEmbedderTest extends TestCase {
052: protected String basedir;
053:
054: protected MavenEmbedder maven;
055:
056: protected void setUp() throws Exception {
057: super .setUp();
058:
059: basedir = System.getProperty("basedir");
060:
061: if (basedir == null) {
062: basedir = new File(".").getCanonicalPath();
063: }
064:
065: ClassLoader classLoader = Thread.currentThread()
066: .getContextClassLoader();
067:
068: Configuration configuration = new DefaultConfiguration()
069: .setClassLoader(classLoader).setMavenEmbedderLogger(
070: new MavenEmbedderConsoleLogger());
071:
072: maven = new MavenEmbedder(configuration);
073: }
074:
075: protected void tearDown() throws Exception {
076: maven.stop();
077: }
078:
079: protected void assertNoExceptions(MavenExecutionResult result) {
080: List exceptions = result.getExceptions();
081: if ((exceptions == null) || exceptions.isEmpty()) {
082: // everything is a-ok.
083: return;
084: }
085:
086: System.err.println("Encountered " + exceptions.size()
087: + " exception(s).");
088: Iterator it = exceptions.iterator();
089: while (it.hasNext()) {
090: Exception exception = (Exception) it.next();
091: exception.printStackTrace(System.err);
092: }
093:
094: fail("Encountered Exceptions in MavenExecutionResult during "
095: + getName());
096: }
097:
098: // ----------------------------------------------------------------------
099: // Goal/Phase execution tests
100: // ----------------------------------------------------------------------
101:
102: public void testExecutionUsingABaseDirectory() throws Exception {
103: File testDirectory = new File(basedir,
104: "src/test/embedder-test-project");
105:
106: File targetDirectory = new File(basedir,
107: "target/embedder-test-project0");
108:
109: FileUtils
110: .copyDirectoryStructure(testDirectory, targetDirectory);
111:
112: MavenExecutionRequest request = new DefaultMavenExecutionRequest()
113: .setBaseDirectory(targetDirectory).setShowErrors(true)
114: .setGoals(Arrays.asList(new String[] { "package" }));
115:
116: MavenExecutionResult result = maven.execute(request);
117:
118: assertNoExceptions(result);
119:
120: MavenProject project = result.getProject();
121:
122: assertEquals("embedder-test-project", project.getArtifactId());
123:
124: File jar = new File(targetDirectory,
125: "target/embedder-test-project-1.0-SNAPSHOT.jar");
126:
127: assertTrue(jar.exists());
128: }
129:
130: public void testExecutionUsingAPomFile() throws Exception {
131: File testDirectory = new File(basedir,
132: "src/test/embedder-test-project");
133:
134: File targetDirectory = new File(basedir,
135: "target/embedder-test-project1");
136:
137: FileUtils
138: .copyDirectoryStructure(testDirectory, targetDirectory);
139:
140: MavenExecutionRequest request = new DefaultMavenExecutionRequest()
141: .setPomFile(
142: new File(targetDirectory, "pom.xml")
143: .getAbsolutePath()).setShowErrors(true)
144: .setGoals(Arrays.asList(new String[] { "package" }));
145:
146: MavenExecutionResult result = maven.execute(request);
147:
148: assertNoExceptions(result);
149:
150: MavenProject project = result.getProject();
151:
152: assertEquals("embedder-test-project", project.getArtifactId());
153:
154: File jar = new File(targetDirectory,
155: "target/embedder-test-project-1.0-SNAPSHOT.jar");
156:
157: assertTrue(jar.exists());
158: }
159:
160: public void testExecutionUsingAProfileWhichSetsAProperty()
161: throws Exception {
162: File testDirectory = new File(basedir,
163: "src/test/embedder-test-project");
164:
165: File targetDirectory = new File(basedir,
166: "target/embedder-test-project2");
167:
168: FileUtils
169: .copyDirectoryStructure(testDirectory, targetDirectory);
170:
171: // Check with profile not active
172:
173: MavenExecutionRequest requestWithoutProfile = new DefaultMavenExecutionRequest()
174: .setPomFile(
175: new File(targetDirectory, "pom.xml")
176: .getAbsolutePath()).setShowErrors(true)
177: .setGoals(Arrays.asList(new String[] { "validate" }));
178:
179: MavenExecutionResult r0 = maven.execute(requestWithoutProfile);
180:
181: assertNoExceptions(r0);
182:
183: MavenProject p0 = r0.getProject();
184:
185: assertNull(p0.getProperties().getProperty("embedderProfile"));
186:
187: assertNull(p0.getProperties().getProperty("name"));
188:
189: assertNull(p0.getProperties().getProperty("occupation"));
190:
191: // Check with profile activated
192:
193: MavenExecutionRequest request = new DefaultMavenExecutionRequest()
194: .setPomFile(
195: new File(targetDirectory, "pom.xml")
196: .getAbsolutePath()).setShowErrors(true)
197: .setGoals(Arrays.asList(new String[] { "validate" }))
198: .addActiveProfile("embedderProfile");
199:
200: MavenExecutionResult r1 = maven.execute(request);
201:
202: MavenProject p1 = r1.getProject();
203:
204: assertEquals("true", p1.getProperties().getProperty(
205: "embedderProfile"));
206:
207: assertEquals("jason", p1.getProperties().getProperty("name"));
208:
209: assertEquals("somnambulance", p1.getProperties().getProperty(
210: "occupation"));
211: }
212:
213: /**
214: * Test that two executions of the embedder don't share data that has changed, see MNG-3013
215: *
216: * @throws Exception
217: */
218: public void testTwoExecutionsDoNotCacheChangedData()
219: throws Exception {
220: File testDirectory = new File(basedir,
221: "src/test/embedder-test-project");
222:
223: File targetDirectory = new File(basedir,
224: "target/embedder-test-project-caching");
225:
226: FileUtils
227: .copyDirectoryStructure(testDirectory, targetDirectory);
228:
229: File pom = new File(targetDirectory, "pom.xml");
230:
231: /* Add the surefire plugin 2.2 to the pom */
232: Model model = maven.readModel(pom);
233:
234: Plugin plugin = new Plugin();
235: plugin.setArtifactId("maven-surefire-plugin");
236: plugin.setVersion("2.2");
237: model.setBuild(new Build());
238: model.getBuild().addPlugin(plugin);
239:
240: FileWriter writer = new FileWriter(pom);
241: maven.writeModel(new FileWriter(pom), model);
242: writer.close();
243:
244: /* execute maven */
245: MavenExecutionRequest request = new DefaultMavenExecutionRequest()
246: .setPomFile(pom.getAbsolutePath()).setShowErrors(true)
247: .setGoals(Arrays.asList(new String[] { "package" }));
248:
249: MavenExecutionResult result = maven.execute(request);
250:
251: assertNoExceptions(result);
252:
253: MavenProject project = result.getProject();
254:
255: Artifact p = (Artifact) project.getPluginArtifactMap().get(
256: plugin.getKey());
257: assertEquals("2.2", p.getVersion());
258:
259: /* Add the surefire plugin 2.3 to the pom */
260: plugin.setVersion("2.3");
261: writer = new FileWriter(pom);
262: maven.writeModel(new FileWriter(pom), model);
263: writer.close();
264:
265: /* execute Maven */
266: request = new DefaultMavenExecutionRequest().setPomFile(
267: pom.getAbsolutePath()).setShowErrors(true).setGoals(
268: Arrays.asList(new String[] { "package" }));
269: result = maven.execute(request);
270:
271: assertNoExceptions(result);
272:
273: project = result.getProject();
274:
275: p = (Artifact) project.getPluginArtifactMap().get(
276: plugin.getKey());
277: assertEquals("2.3", p.getVersion());
278: }
279:
280: // ----------------------------------------------------------------------
281: // LegacyLifecycle phases
282: // ----------------------------------------------------------------------
283:
284: public void testRetrievingLifecyclePhases() throws Exception {
285: List phases = maven.getLifecyclePhases();
286:
287: assertEquals("validate", (String) phases.get(0));
288:
289: assertEquals("initialize", (String) phases.get(1));
290:
291: assertEquals("generate-sources", (String) phases.get(2));
292: }
293:
294: // ----------------------------------------------------------------------
295: // Repository
296: // ----------------------------------------------------------------------
297:
298: public void testLocalRepositoryRetrieval() throws Exception {
299: assertNotNull(maven.getLocalRepository().getBasedir());
300: }
301:
302: // ----------------------------------------------------------------------
303: // Model Reading
304: // ----------------------------------------------------------------------
305:
306: public void testModelReading() throws Exception {
307: // ----------------------------------------------------------------------
308: // Test model reading
309: // ----------------------------------------------------------------------
310:
311: Model model = maven.readModel(getPomFile());
312:
313: assertEquals("org.apache.maven", model.getGroupId());
314: }
315:
316: public void testProjectReading() throws Exception {
317: MavenExecutionRequest request = new DefaultMavenExecutionRequest()
318: .setShowErrors(true).setPomFile(
319: getPomFile().getAbsolutePath());
320:
321: MavenExecutionResult result = maven
322: .readProjectWithDependencies(request);
323:
324: assertNoExceptions(result);
325:
326: assertEquals("org.apache.maven", result.getProject()
327: .getGroupId());
328:
329: Set artifacts = result.getProject().getArtifacts();
330:
331: assertEquals(1, artifacts.size());
332:
333: artifacts.iterator().next();
334: }
335:
336: /*
337: public void testProjectReadingWithDistributionStatus()
338: throws Exception
339: {
340: File pom = new File( basedir, "src/test/resources/pom-with-distribution-status.xml" );
341: MavenExecutionRequest request = new DefaultMavenExecutionRequest().setShowErrors( true )
342: .setPomFile( pom.getAbsolutePath() );
343:
344: MavenProject project = maven.readProject( pom );
345:
346: assertEquals( "deployed", project.getDistributionManagement().getStatus() );
347:
348: MavenExecutionResult result = maven.readProjectWithDependencies( request );
349:
350: assertNoExceptions( result );
351:
352: assertEquals( "org.apache.maven", result.getProject().getGroupId() );
353:
354: assertEquals( "deployed", result.getProject().getDistributionManagement().getStatus() );
355: }
356: */
357:
358: // ----------------------------------------------------------------------------
359: // Model Writing
360: // ----------------------------------------------------------------------------
361: public void testModelWriting() throws Exception {
362: Model model = maven.readModel(getPomFile());
363:
364: model.setGroupId("org.apache.maven.new");
365:
366: File file = new File(basedir, "target/model.xml");
367:
368: Writer writer = new FileWriter(file);
369:
370: maven.writeModel(writer, model);
371:
372: writer.close();
373:
374: model = maven.readModel(file);
375:
376: assertEquals("org.apache.maven.new", model.getGroupId());
377: }
378:
379: // ----------------------------------------------------------------------
380: // Settings-File Handling
381: // ----------------------------------------------------------------------
382:
383: public void testReadSettings() throws IOException,
384: SettingsConfigurationException, MavenEmbedderException {
385: Settings s = new Settings();
386: s.setOffline(true);
387:
388: String localRepoPath = "/path/to/local/repo";
389:
390: s.setLocalRepository(localRepoPath);
391:
392: File settingsFile = File.createTempFile(
393: "embedder-test.settings.", "");
394: settingsFile.deleteOnExit();
395:
396: FileWriter writer = null;
397: try {
398: writer = new FileWriter(settingsFile);
399: new SettingsXpp3Writer().write(writer, s);
400: } finally {
401: IOUtil.close(writer);
402: }
403:
404: Settings result = MavenEmbedder.readSettings(settingsFile);
405:
406: assertEquals(localRepoPath, result.getLocalRepository());
407: assertTrue(result.isOffline());
408: }
409:
410: public void testReadSettings_shouldFailToValidate()
411: throws IOException, SettingsConfigurationException,
412: MavenEmbedderException {
413: Settings s = new Settings();
414:
415: Profile p = new Profile();
416:
417: Repository r = new Repository();
418: r.setUrl("http://example.com");
419:
420: p.addRepository(r);
421: s.addProfile(p);
422:
423: File settingsFile = File.createTempFile(
424: "embedder-test.settings.", "");
425: settingsFile.deleteOnExit();
426:
427: FileWriter writer = null;
428: try {
429: writer = new FileWriter(settingsFile);
430: new SettingsXpp3Writer().write(writer, s);
431: } finally {
432: IOUtil.close(writer);
433: }
434:
435: try {
436: MavenEmbedder.readSettings(settingsFile);
437:
438: fail("Settings should not pass validation when being read.");
439: } catch (IOException e) {
440: String message = e.getMessage();
441: assertTrue(message.indexOf("Failed to validate") > -1);
442: }
443: }
444:
445: public void testWriteSettings() throws IOException,
446: SettingsConfigurationException, MavenEmbedderException,
447: XmlPullParserException {
448: Settings s = new Settings();
449: s.setOffline(true);
450:
451: String localRepoPath = "/path/to/local/repo";
452:
453: s.setLocalRepository(localRepoPath);
454:
455: File settingsFile = File.createTempFile(
456: "embedder-test.settings.", "");
457: settingsFile.deleteOnExit();
458:
459: MavenEmbedder.writeSettings(settingsFile, s);
460:
461: FileReader reader = null;
462: try {
463: reader = new FileReader(settingsFile);
464: Settings result = new SettingsXpp3Reader().read(reader);
465:
466: assertEquals(localRepoPath, result.getLocalRepository());
467: assertTrue(result.isOffline());
468: } finally {
469: IOUtil.close(reader);
470: }
471: }
472:
473: public void testWriteSettings_shouldFailToValidate()
474: throws IOException, SettingsConfigurationException,
475: MavenEmbedderException {
476: Settings s = new Settings();
477:
478: Profile p = new Profile();
479:
480: Repository r = new Repository();
481: r.setUrl("http://example.com");
482:
483: p.addRepository(r);
484: s.addProfile(p);
485:
486: File settingsFile = File.createTempFile(
487: "embedder-test.settings.", "");
488: settingsFile.deleteOnExit();
489:
490: try {
491: MavenEmbedder.writeSettings(settingsFile, s);
492:
493: fail("Validation of settings should fail before settings are written.");
494: } catch (IOException e) {
495: String message = e.getMessage();
496: assertTrue(message.indexOf("Failed to validate") > -1);
497: }
498: }
499:
500: // ----------------------------------------------------------------------
501: // Internal Utilities
502: // ----------------------------------------------------------------------
503:
504: protected File getPomFile() {
505: return new File(basedir, "src/test/resources/pom.xml");
506: }
507: }
|