PageRenderTime 46ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/src/test/java/ut/com/atlassian/maven/plugins/jgitflow/manager/AbstractFlowManagerTest.java

https://bitbucket.org/jbowman/maven-jgitflow-plugin
Java | 396 lines | 309 code | 79 blank | 8 comment | 19 complexity | 6ac2811f4d02151b968bacc2bad36428 MD5 | raw file
  1. package ut.com.atlassian.maven.plugins.jgitflow.manager;
  2. import java.io.File;
  3. import java.io.IOException;
  4. import java.io.InputStream;
  5. import java.security.SecureRandom;
  6. import java.util.*;
  7. import com.atlassian.jgitflow.core.JGitFlow;
  8. import com.atlassian.maven.plugins.jgitflow.ReleaseContext;
  9. import com.atlassian.maven.plugins.jgitflow.manager.FlowReleaseManager;
  10. import com.google.common.base.Strings;
  11. import org.apache.maven.artifact.Artifact;
  12. import org.apache.maven.artifact.ArtifactUtils;
  13. import org.apache.maven.artifact.factory.ArtifactFactory;
  14. import org.apache.maven.artifact.manager.WagonManager;
  15. import org.apache.maven.artifact.metadata.ArtifactMetadataSource;
  16. import org.apache.maven.artifact.repository.ArtifactRepository;
  17. import org.apache.maven.artifact.repository.DefaultArtifactRepository;
  18. import org.apache.maven.artifact.repository.layout.ArtifactRepositoryLayout;
  19. import org.apache.maven.artifact.repository.layout.DefaultRepositoryLayout;
  20. import org.apache.maven.artifact.resolver.ArtifactCollector;
  21. import org.apache.maven.artifact.resolver.ArtifactResolutionResult;
  22. import org.apache.maven.artifact.versioning.InvalidVersionSpecificationException;
  23. import org.apache.maven.artifact.versioning.VersionRange;
  24. import org.apache.maven.model.Dependency;
  25. import org.apache.maven.model.DependencyManagement;
  26. import org.apache.maven.model.Profile;
  27. import org.apache.maven.model.Repository;
  28. import org.apache.maven.profiles.DefaultProfileManager;
  29. import org.apache.maven.profiles.ProfileManager;
  30. import org.apache.maven.project.MavenProject;
  31. import org.apache.maven.project.MavenProjectBuilder;
  32. import org.apache.maven.project.ProjectBuildingException;
  33. import org.apache.maven.project.ProjectSorter;
  34. import org.apache.maven.shared.release.util.ReleaseUtil;
  35. import org.codehaus.plexus.PlexusJUnit4TestCase;
  36. import org.codehaus.plexus.context.ContextException;
  37. import org.codehaus.plexus.context.DefaultContext;
  38. import org.codehaus.plexus.personality.plexus.lifecycle.phase.Contextualizable;
  39. import org.codehaus.plexus.util.FileUtils;
  40. import org.codehaus.plexus.util.StringUtils;
  41. import org.junit.After;
  42. import org.junit.Before;
  43. import static org.junit.Assert.assertEquals;
  44. import static org.junit.Assert.assertTrue;
  45. /**
  46. * @since version
  47. */
  48. public abstract class AbstractFlowManagerTest extends PlexusJUnit4TestCase
  49. {
  50. protected MavenProjectBuilder projectBuilder;
  51. protected ArtifactRepository localRepository;
  52. protected File testFileBase;
  53. private static final SecureRandom random = new SecureRandom();
  54. private static final DefaultContext EMPTY_CONTEXT = new DefaultContext()
  55. {
  56. public Object get( Object key ) throws ContextException
  57. {
  58. return null;
  59. }
  60. };
  61. @Before
  62. public void doSetup() throws Exception
  63. {
  64. projectBuilder = (MavenProjectBuilder) lookup(MavenProjectBuilder.ROLE);
  65. ArtifactRepositoryLayout layout = (ArtifactRepositoryLayout) lookup(ArtifactRepositoryLayout.ROLE, "default");
  66. String localRepoPath = getTestFile("target/local-repository").getAbsolutePath().replace('\\', '/');
  67. localRepository = new DefaultArtifactRepository("local", "file://" + localRepoPath, layout);
  68. this.testFileBase = newTempDir();
  69. }
  70. @After
  71. public void doTearDown() throws Exception
  72. {
  73. ((Contextualizable) projectBuilder).contextualize(EMPTY_CONTEXT);
  74. ((Contextualizable) lookup(WagonManager.ROLE)).contextualize(EMPTY_CONTEXT);
  75. if(null != testFileBase && testFileBase.exists())
  76. {
  77. try
  78. {
  79. FileUtils.deleteDirectory(testFileBase);
  80. }
  81. catch (IOException e)
  82. {
  83. //ignore
  84. }
  85. }
  86. }
  87. @Override
  88. protected InputStream getCustomConfiguration() throws Exception
  89. {
  90. return getClass().getResourceAsStream("/default-components.xml");
  91. }
  92. protected void basicReleaseRewriteTest(String projectName) throws Exception
  93. {
  94. basicReleaseRewriteTest(projectName,"");
  95. }
  96. protected void basicReleaseRewriteTest(String projectName, String releaseVersion) throws Exception
  97. {
  98. List<MavenProject> projects = createReactorProjects("rewrite-for-release",projectName);
  99. File projectRoot = projects.get(0).getBasedir();
  100. ReleaseContext ctx = new ReleaseContext(projectRoot);
  101. if(!Strings.isNullOrEmpty(releaseVersion))
  102. {
  103. ctx.setDefaultReleaseVersion(releaseVersion);
  104. }
  105. ctx.setInteractive(false).setNoTag(true).setPush(false);
  106. basicReleaseRewriteTest(projectName, ctx);
  107. }
  108. protected void basicReleaseRewriteTest(String projectName, ReleaseContext ctx) throws Exception
  109. {
  110. List<MavenProject> projects = createReactorProjects("rewrite-for-release",projectName);
  111. File projectRoot = ctx.getBaseDir();
  112. JGitFlow flow = JGitFlow.getOrInit(projectRoot);
  113. assertOnDevelop(flow);
  114. initialCommitAll(flow);
  115. FlowReleaseManager relman = getReleaseManager();
  116. relman.start(ctx,projects);
  117. assertOnRelease(flow, ctx.getDefaultReleaseVersion());
  118. comparePomFiles(projects);
  119. }
  120. protected void initialCommitAll(JGitFlow flow) throws Exception
  121. {
  122. flow.git().add().addFilepattern(".").call();
  123. flow.git().commit().setMessage("initial commit").call();
  124. }
  125. protected void assertOnDevelop(JGitFlow flow) throws Exception
  126. {
  127. assertEquals(flow.getDevelopBranchName(), flow.git().getRepository().getBranch());
  128. }
  129. protected void assertOnRelease(JGitFlow flow, String version) throws Exception
  130. {
  131. if(Strings.isNullOrEmpty(version))
  132. {
  133. assertTrue(flow.git().getRepository().getBranch().startsWith(flow.getReleaseBranchPrefix()));
  134. }
  135. else
  136. {
  137. assertEquals(flow.getReleaseBranchPrefix() + version, flow.git().getRepository().getBranch());
  138. }
  139. }
  140. protected void assertOnHotfix(JGitFlow flow, String version) throws Exception
  141. {
  142. assertEquals(flow.getHotfixBranchPrefix() + version, flow.git().getRepository().getBranch());
  143. }
  144. protected FlowReleaseManager getReleaseManager() throws Exception
  145. {
  146. return (FlowReleaseManager) lookup(FlowReleaseManager.class.getName());
  147. }
  148. protected String readTestProjectFile(String fileName) throws IOException
  149. {
  150. return ReleaseUtil.readXmlFile(getTestFile("target/test-classes/projects/" + fileName));
  151. }
  152. protected List<MavenProject> createReactorProjects(String path, String subpath) throws Exception
  153. {
  154. return createReactorProjects(path, path, subpath, true);
  155. }
  156. protected List<MavenProject> createReactorProjectsNoClean(String path, String subpath) throws Exception
  157. {
  158. return createReactorProjects(path, path, subpath, false);
  159. }
  160. protected List<MavenProject> createReactorProjects( String path, String targetPath, String subpath, boolean clean )
  161. throws Exception
  162. {
  163. File testFile = null;
  164. if(Strings.isNullOrEmpty(subpath))
  165. {
  166. testFile = new File( testFileBase, "projects/" + path + "/pom.xml" );
  167. }
  168. else
  169. {
  170. testFile = new File( testFileBase, "projects/" + path + "/" + subpath + "/pom.xml" );
  171. }
  172. Stack<File> projectFiles = new Stack<File>();
  173. projectFiles.push( testFile );
  174. List<DefaultArtifactRepository> repos =
  175. Collections.singletonList( new DefaultArtifactRepository( "central", getRemoteRepositoryURL(), new DefaultRepositoryLayout() ) );
  176. Repository repository = new Repository();
  177. repository.setId( "central" );
  178. repository.setUrl( getRemoteRepositoryURL() );
  179. ProfileManager profileManager = new DefaultProfileManager( getContainer() );
  180. Profile profile = new Profile();
  181. profile.setId( "profile" );
  182. profile.addRepository( repository );
  183. profileManager.addProfile( profile );
  184. profileManager.activateAsDefault( profile.getId() );
  185. List<MavenProject> reactorProjects = new ArrayList<MavenProject>();
  186. String cleaned = "";
  187. while ( !projectFiles.isEmpty() )
  188. {
  189. File file = (File) projectFiles.pop();
  190. // Recopy the test resources since they are modified in some tests
  191. //FileUtils.copyDirectory(srcDir,file.getParentFile());
  192. String filePath = file.getPath();
  193. int index = filePath.indexOf( "projects" );
  194. filePath = filePath.substring( index ).replace( '\\', '/' );
  195. File newFile = new File( testFileBase, StringUtils.replace( filePath, path, targetPath ) );
  196. if(clean && !cleaned.equals(newFile.getParentFile().getName()))
  197. {
  198. //clean the parent dir
  199. newFile.mkdirs();
  200. FileUtils.cleanDirectory(newFile.getParentFile());
  201. File srcDir = new File(getTestFile( "src/test/resources/"),filePath).getParentFile();
  202. FileUtils.copyDirectoryStructure(srcDir, newFile.getParentFile());
  203. cleaned = newFile.getParentFile().getName();
  204. }
  205. MavenProject project = projectBuilder.build( newFile, localRepository, profileManager );
  206. for ( Iterator i = project.getModules().iterator(); i.hasNext(); )
  207. {
  208. String module = (String) i.next();
  209. projectFiles.push( new File( file.getParentFile(), module + "/pom.xml" ) );
  210. }
  211. reactorProjects.add( project );
  212. }
  213. ProjectSorter sorter = new ProjectSorter( reactorProjects );
  214. reactorProjects = sorter.getSortedProjects();
  215. ArtifactFactory artifactFactory = (ArtifactFactory) lookup( ArtifactFactory.ROLE );
  216. ArtifactCollector artifactCollector = (ArtifactCollector) lookup( ArtifactCollector.class.getName() );
  217. ArtifactMetadataSource artifactMetadataSource = (ArtifactMetadataSource) lookup( ArtifactMetadataSource.ROLE );
  218. // pass back over and resolve dependencies - can't be done earlier as the order may not be correct
  219. for ( Iterator i = reactorProjects.iterator(); i.hasNext(); )
  220. {
  221. MavenProject project = (MavenProject) i.next();
  222. project.setRemoteArtifactRepositories( repos );
  223. project.setPluginArtifactRepositories( repos );
  224. Artifact projectArtifact = project.getArtifact();
  225. Map managedVersions = createManagedVersionMap(
  226. ArtifactUtils.versionlessKey(projectArtifact.getGroupId(), projectArtifact.getArtifactId()),
  227. project.getDependencyManagement(), artifactFactory );
  228. project.setDependencyArtifacts( project.createArtifacts( artifactFactory, null, null ) );
  229. ArtifactResolutionResult result = artifactCollector.collect( project.getDependencyArtifacts(),
  230. projectArtifact, managedVersions,
  231. localRepository, repos, artifactMetadataSource,
  232. null, Collections.EMPTY_LIST );
  233. project.setArtifacts( result.getArtifacts() );
  234. }
  235. return reactorProjects;
  236. }
  237. private Map<String,Artifact> createManagedVersionMap(String projectId, DependencyManagement dependencyManagement, ArtifactFactory artifactFactory) throws ProjectBuildingException
  238. {
  239. Map<String,Artifact> map;
  240. if ( dependencyManagement != null && dependencyManagement.getDependencies() != null )
  241. {
  242. map = new HashMap<String,Artifact>();
  243. for ( Iterator i = dependencyManagement.getDependencies().iterator(); i.hasNext(); )
  244. {
  245. Dependency d = (Dependency) i.next();
  246. try
  247. {
  248. VersionRange versionRange = VersionRange.createFromVersionSpec( d.getVersion() );
  249. Artifact artifact = artifactFactory.createDependencyArtifact( d.getGroupId(), d.getArtifactId(),
  250. versionRange, d.getType(),
  251. d.getClassifier(), d.getScope() );
  252. map.put( d.getManagementKey(), artifact );
  253. }
  254. catch ( InvalidVersionSpecificationException e )
  255. {
  256. throw new ProjectBuildingException( projectId, "Unable to parse version '" + d.getVersion() +
  257. "' for dependency '" + d.getManagementKey() + "': " + e.getMessage(), e );
  258. }
  259. }
  260. }
  261. else
  262. {
  263. map = Collections.emptyMap();
  264. }
  265. return map;
  266. }
  267. private String getRemoteRepositoryURL() throws IOException
  268. {
  269. File testFile = getTestFile( "src/test/remote-repository" );
  270. if (testFile.getAbsolutePath().equals( testFile.getCanonicalPath() ) )
  271. {
  272. return "file://" + getTestFile( "src/test/remote-repository" ).getAbsolutePath().replace( '\\', '/' );
  273. }
  274. return "file://" + getTestFile( "src/test/remote-repository" ).getCanonicalPath().replace( '\\', '/' );
  275. }
  276. protected void comparePomFiles(List<MavenProject> reactorProjects)throws IOException
  277. {
  278. for (MavenProject project : reactorProjects)
  279. {
  280. comparePomFiles(project);
  281. }
  282. }
  283. protected void comparePomFiles(MavenProject project) throws IOException
  284. {
  285. File actualFile = project.getFile();
  286. File expectedFile = new File(actualFile.getParentFile(), "expected-pom.xml" );
  287. comparePomFiles(expectedFile, actualFile);
  288. }
  289. protected void comparePomFiles(File expectedFile, File actualFile) throws IOException
  290. {
  291. String expectedPom = ReleaseUtil.readXmlFile(expectedFile);
  292. String actualPom = ReleaseUtil.readXmlFile(actualFile);
  293. assertEquals(expectedPom,actualPom);
  294. }
  295. public File newTempDir()
  296. {
  297. File baseDir = new File(System.getProperty("java.io.tmpdir"));
  298. String name = randomName("mvngf-");
  299. File tmp = new File(baseDir,name);
  300. tmp.mkdirs();
  301. return tmp;
  302. }
  303. public File newDir(String name)
  304. {
  305. return new File(testFileBase,name);
  306. }
  307. public File newDir()
  308. {
  309. return newDir(randomName("mvngftest"));
  310. }
  311. private String randomName(String base)
  312. {
  313. long n = random.nextLong();
  314. n = (n == Long.MIN_VALUE) ? 0 : Math.abs(n);
  315. return base + Long.toString(n);
  316. }
  317. }