View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  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,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied.  See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  package org.apache.maven.project;
20  
21  import java.io.File;
22  import java.io.InputStream;
23  import java.nio.file.Files;
24  import java.nio.file.Path;
25  import java.nio.file.StandardCopyOption;
26  import java.util.List;
27  
28  import org.apache.maven.api.Constants;
29  import org.apache.maven.api.model.InputLocation;
30  import org.apache.maven.api.model.InputSource;
31  import org.apache.maven.artifact.Artifact;
32  import org.apache.maven.execution.MavenSession;
33  import org.apache.maven.impl.InternalSession;
34  import org.apache.maven.internal.impl.DefaultProject;
35  import org.apache.maven.internal.impl.InternalMavenSession;
36  import org.apache.maven.model.Profile;
37  import org.junit.jupiter.api.BeforeEach;
38  import org.junit.jupiter.api.Disabled;
39  import org.junit.jupiter.api.Test;
40  import org.junit.jupiter.api.io.TempDir;
41  import org.mockito.Mockito;
42  
43  import static org.apache.maven.project.ProjectBuildingResultWithProblemMessageMatcher.projectBuildingResultWithProblemMessage;
44  import static org.codehaus.plexus.testing.PlexusExtension.getTestFile;
45  import static org.hamcrest.MatcherAssert.assertThat;
46  import static org.hamcrest.Matchers.contains;
47  import static org.hamcrest.Matchers.containsString;
48  import static org.hamcrest.Matchers.greaterThan;
49  import static org.hamcrest.Matchers.is;
50  import static org.junit.jupiter.api.Assertions.assertEquals;
51  import static org.junit.jupiter.api.Assertions.assertFalse;
52  import static org.junit.jupiter.api.Assertions.assertNotNull;
53  import static org.junit.jupiter.api.Assertions.assertNull;
54  import static org.junit.jupiter.api.Assertions.assertThrows;
55  import static org.junit.jupiter.api.Assertions.assertTrue;
56  import static org.junit.jupiter.api.Assertions.fail;
57  
58  class DefaultMavenProjectBuilderTest extends AbstractMavenProjectTestCase {
59  
60      // only use by reread()
61      @TempDir
62      Path projectRoot;
63  
64      @Override
65      @BeforeEach
66      public void setUp() throws Exception {
67          projectBuilder = getContainer().lookup(ProjectBuilder.class);
68      }
69  
70      protected MavenProject getProject(Artifact pom, boolean allowStub) throws Exception {
71          ProjectBuildingRequest configuration = new DefaultProjectBuildingRequest();
72          configuration.setLocalRepository(getLocalRepository());
73          initRepoSession(configuration);
74  
75          return projectBuilder.build(pom, allowStub, configuration).getProject();
76      }
77  
78      /**
79       * Check that we can build ok from the middle pom of a (parent,child,grandchild) hierarchy
80       */
81      @Test
82      void testBuildFromMiddlePom() throws Exception {
83          File f1 = getTestFile("src/test/resources/projects/grandchild-check/child/pom.xml");
84          File f2 = getTestFile("src/test/resources/projects/grandchild-check/child/grandchild/pom.xml");
85  
86          getProject(f1);
87  
88          // it's the building of the grandchild project, having already cached the child project
89          // (but not the parent project), which causes the problem.
90          getProject(f2);
91      }
92  
93      @Disabled("Maven 4 does not allow duplicate plugin declarations")
94      @Test
95      void testDuplicatePluginDefinitionsMerged() throws Exception {
96          File f1 = getTestFile("src/test/resources/projects/duplicate-plugins-merged-pom.xml");
97  
98          MavenProject project = getProject(f1);
99          assertEquals(2, project.getBuildPlugins().get(0).getDependencies().size());
100         assertEquals(2, project.getBuildPlugins().get(0).getExecutions().size());
101         assertEquals(
102                 "first", project.getBuildPlugins().get(0).getExecutions().get(0).getId());
103     }
104 
105     @Test
106     void testFutureModelVersion() throws Exception {
107         File f1 = getTestFile("src/test/resources/projects/future-model-version-pom.xml");
108 
109         ProjectBuildingException e = assertThrows(
110                 ProjectBuildingException.class, () -> getProject(f1), "Expected to fail for future versions");
111         assertThat(e.getMessage(), containsString("Building this project requires a newer version of Maven"));
112     }
113 
114     @Test
115     void testPastModelVersion() throws Exception {
116         // a Maven 1.x pom will not even
117         // update the resource if we stop supporting modelVersion 4.0.0
118         File f1 = getTestFile("src/test/resources/projects/past-model-version-pom.xml");
119 
120         ProjectBuildingException e = assertThrows(
121                 ProjectBuildingException.class, () -> getProject(f1), "Expected to fail for past versions");
122         assertThat(e.getMessage(), containsString("Building this project requires an older version of Maven"));
123     }
124 
125     @Test
126     void testFutureSchemaModelVersion() throws Exception {
127         File f1 = getTestFile("src/test/resources/projects/future-schema-model-version-pom.xml");
128 
129         ProjectBuildingException e = assertThrows(
130                 ProjectBuildingException.class, () -> getProject(f1), "Expected to fail for future versions");
131         assertThat(e.getMessage(), containsString("Building this project requires a newer version of Maven"));
132     }
133 
134     @Test
135     void testBuildStubModelForMissingRemotePom() throws Exception {
136         Artifact pom = repositorySystem.createProjectArtifact("org.apache.maven.its", "missing", "0.1");
137         MavenProject project = getProject(pom, true);
138 
139         assertNotNull(project.getArtifactId());
140 
141         assertNotNull(project.getRemoteArtifactRepositories());
142         assertTrue(project.getRemoteArtifactRepositories().isEmpty());
143 
144         assertNotNull(project.getPluginArtifactRepositories());
145         assertTrue(project.getPluginArtifactRepositories().isEmpty());
146 
147         assertNull(project.getParent());
148         assertNull(project.getParentArtifact());
149 
150         assertFalse(project.isExecutionRoot());
151     }
152 
153     @Test
154     void testPartialResultUponBadDependencyDeclaration() throws Exception {
155         File pomFile = getTestFile("src/test/resources/projects/bad-dependency.xml");
156 
157         ProjectBuildingRequest request = newBuildingRequest();
158         request.setProcessPlugins(false);
159         request.setResolveDependencies(true);
160         ProjectBuildingException e = assertThrows(
161                 ProjectBuildingException.class,
162                 () -> projectBuilder.build(pomFile, request),
163                 "Project building did not fail despite invalid POM");
164         List<ProjectBuildingResult> results = e.getResults();
165         assertNotNull(results);
166         assertEquals(1, results.size());
167         ProjectBuildingResult result = results.get(0);
168         assertNotNull(result);
169         assertNotNull(result.getProject());
170         assertEquals(1, result.getProblems().size());
171         assertEquals(1, result.getProject().getArtifacts().size());
172         assertNotNull(result.getDependencyResolutionResult());
173     }
174 
175     /**
176      * Tests whether local version range parent references are built correctly.
177      */
178     @Test
179     void testBuildValidParentVersionRangeLocally() throws Exception {
180         File f1 = getTestFile("src/test/resources/projects/parent-version-range-local-valid/child/pom.xml");
181 
182         final MavenProject childProject = getProject(f1);
183 
184         assertNotNull(childProject.getParentArtifact());
185         assertEquals("1", childProject.getParentArtifact().getVersion());
186         assertNotNull(childProject.getParent());
187         assertEquals("1", childProject.getParent().getVersion());
188         assertNotNull(childProject.getModel().getParent());
189         assertEquals("[1,10]", childProject.getModel().getParent().getVersion());
190     }
191 
192     /**
193      * Tests whether local version range parent references are built correctly.
194      */
195     @Test
196     void testBuildParentVersionRangeLocallyWithoutChildVersion() throws Exception {
197         File f1 = getTestFile(
198                 "src/test/resources/projects/parent-version-range-local-child-without-version/child/pom.xml");
199 
200         ProjectBuildingException e = assertThrows(
201                 ProjectBuildingException.class,
202                 () -> getProject(f1),
203                 "Expected 'ProjectBuildingException' not thrown.");
204         assertThat(e.getResults(), contains(projectBuildingResultWithProblemMessage("Version must be a constant")));
205     }
206 
207     /**
208      * Tests whether local version range parent references are built correctly.
209      */
210     @Test
211     void testBuildParentVersionRangeLocallyWithChildProjectVersionExpression() throws Exception {
212         File f1 = getTestFile(
213                 "src/test/resources/projects/parent-version-range-local-child-project-version-expression/child/pom.xml");
214 
215         ProjectBuildingException e = assertThrows(
216                 ProjectBuildingException.class,
217                 () -> getProject(f1),
218                 "Expected 'ProjectBuildingException' not thrown.");
219         assertThat(e.getResults(), contains(projectBuildingResultWithProblemMessage("Version must be a constant")));
220     }
221 
222     /**
223      * Tests whether local version range parent references are built correctly.
224      */
225     @Test
226     public void testBuildParentVersionRangeLocallyWithChildProjectParentVersionExpression() throws Exception {
227         File f1 = getTestFile(
228                 "src/test/resources/projects/parent-version-range-local-child-project-parent-version-expression/child/pom.xml");
229 
230         try {
231             getProject(f1);
232             fail("Expected 'ProjectBuildingException' not thrown.");
233         } catch (final ProjectBuildingException e) {
234             assertNotNull(e.getMessage());
235         }
236     }
237 
238     /**
239      * Tests whether local version range parent references are built correctly.
240      *
241      * @throws Exception
242      */
243     @Test
244     public void testBuildParentVersionRangeLocallyWithChildRevisionExpression() throws Exception {
245         File f1 = getTestFile(
246                 "src/test/resources/projects/parent-version-range-local-child-revision-expression/child/pom.xml");
247 
248         MavenProject mp = this.getProjectFromRemoteRepository(f1);
249 
250         assertEquals("1.0-SNAPSHOT", mp.getVersion());
251     }
252 
253     /**
254      * Tests whether external version range parent references are built correctly.
255      */
256     @Test
257     void testBuildParentVersionRangeExternally() throws Exception {
258         File f1 = getTestFile("src/test/resources/projects/parent-version-range-external-valid/pom.xml");
259 
260         final MavenProject childProject = this.getProjectFromRemoteRepository(f1);
261 
262         assertNotNull(childProject.getParentArtifact());
263         assertEquals("1", childProject.getParentArtifact().getVersion());
264         assertNotNull(childProject.getParent());
265         assertEquals("1", childProject.getParent().getVersion());
266         assertNotNull(childProject.getModel().getParent());
267         assertEquals("[1,1]", childProject.getModel().getParent().getVersion());
268     }
269 
270     /**
271      * Tests whether external version range parent references are built correctly.
272      */
273     @Test
274     void testBuildParentVersionRangeExternallyWithoutChildVersion() throws Exception {
275         File f1 =
276                 getTestFile("src/test/resources/projects/parent-version-range-external-child-without-version/pom.xml");
277 
278         ProjectBuildingException e = assertThrows(
279                 ProjectBuildingException.class,
280                 () -> getProjectFromRemoteRepository(f1),
281                 "Expected 'ProjectBuildingException' not thrown.");
282         assertThat(e.getResults(), contains(projectBuildingResultWithProblemMessage("Version must be a constant")));
283     }
284 
285     /**
286      * Tests whether external version range parent references are built correctly.
287      */
288     @Test
289     void testBuildParentVersionRangeExternallyWithChildProjectVersionExpression() throws Exception {
290         File f1 = getTestFile(
291                 "src/test/resources/projects/parent-version-range-external-child-project-version-expression/pom.xml");
292 
293         ProjectBuildingException e = assertThrows(
294                 ProjectBuildingException.class,
295                 () -> getProjectFromRemoteRepository(f1),
296                 "Expected 'ProjectBuildingException' not thrown.");
297         assertThat(e.getResults(), contains(projectBuildingResultWithProblemMessage("Version must be a constant")));
298     }
299 
300     /**
301      * Ensure that when re-reading a pom, it does not use the cached Model.
302      */
303     @Test
304     void rereadPomMng7063() throws Exception {
305         final Path pom = projectRoot.resolve("pom.xml");
306         final ProjectBuildingRequest buildingRequest = newBuildingRequest();
307 
308         InternalMavenSession.from(InternalSession.from(buildingRequest.getRepositorySession()))
309                 .getMavenSession()
310                 .getRequest()
311                 .setRootDirectory(projectRoot);
312 
313         try (InputStream pomResource =
314                 DefaultMavenProjectBuilderTest.class.getResourceAsStream("/projects/reread/pom1.xml")) {
315             Files.copy(pomResource, pom, StandardCopyOption.REPLACE_EXISTING);
316         }
317 
318         MavenProject project =
319                 projectBuilder.build(pom.toFile(), buildingRequest).getProject();
320         assertThat(project.getName(), is("aid")); // inherited from artifactId
321 
322         try (InputStream pomResource =
323                 DefaultMavenProjectBuilderTest.class.getResourceAsStream("/projects/reread/pom2.xml")) {
324             Files.copy(pomResource, pom, StandardCopyOption.REPLACE_EXISTING);
325         }
326 
327         project = projectBuilder.build(pom.toFile(), buildingRequest).getProject();
328         assertThat(project.getName(), is("PROJECT NAME"));
329     }
330 
331     @Test
332     void testActivatedProfileBySource() throws Exception {
333         File testPom = getTestFile("src/test/resources/projects/pom-with-profiles/pom.xml");
334 
335         ProjectBuildingRequest request = newBuildingRequest();
336         request.setLocalRepository(getLocalRepository());
337         request.setActiveProfileIds(List.of("profile1"));
338 
339         MavenProject project = projectBuilder.build(testPom, request).getProject();
340 
341         String id = project.getGroupId() + ":" + project.getArtifactId() + ":" + project.getVersion();
342         assertTrue(project.getInjectedProfileIds().keySet().containsAll(List.of("external", id)));
343         assertTrue(project.getInjectedProfileIds().get("external").isEmpty());
344         assertTrue(project.getInjectedProfileIds().get(id).stream().anyMatch("profile1"::equals));
345         assertTrue(project.getInjectedProfileIds().get(id).stream().noneMatch("profile2"::equals));
346         assertTrue(project.getInjectedProfileIds().get(id).stream().noneMatch("active-by-default"::equals));
347     }
348 
349     @Test
350     void testActivatedDefaultProfileBySource() throws Exception {
351         File testPom = getTestFile("src/test/resources/projects/pom-with-profiles/pom.xml");
352 
353         ProjectBuildingRequest request = newBuildingRequest();
354         request.setLocalRepository(getLocalRepository());
355 
356         MavenProject project = projectBuilder.build(testPom, request).getProject();
357 
358         String id = project.getGroupId() + ":" + project.getArtifactId() + ":" + project.getVersion();
359         assertTrue(project.getInjectedProfileIds().keySet().containsAll(List.of("external", id)));
360         assertTrue(project.getInjectedProfileIds().get("external").isEmpty());
361         assertTrue(project.getInjectedProfileIds().get(id).stream().noneMatch("profile1"::equals));
362         assertTrue(project.getInjectedProfileIds().get(id).stream().noneMatch("profile2"::equals));
363         assertTrue(project.getInjectedProfileIds().get(id).stream().anyMatch("active-by-default"::equals));
364 
365         InternalMavenSession session = Mockito.mock(InternalMavenSession.class);
366         List<org.apache.maven.api.model.Profile> activeProfiles =
367                 new DefaultProject(session, project).getDeclaredActiveProfiles();
368         assertEquals(1, activeProfiles.size());
369         org.apache.maven.api.model.Profile profile = activeProfiles.get(0);
370         assertEquals("active-by-default", profile.getId());
371         InputLocation location = profile.getLocation("");
372         assertNotNull(location);
373         assertThat(location.getLineNumber(), greaterThan(0));
374         assertThat(location.getColumnNumber(), greaterThan(0));
375         assertNotNull(location.getSource());
376         assertThat(location.getSource().getLocation(), containsString("pom-with-profiles/pom.xml"));
377     }
378 
379     @Test
380     void testActivatedExternalProfileBySource() throws Exception {
381         File testPom = getTestFile("src/test/resources/projects/pom-with-profiles/pom.xml");
382 
383         ProjectBuildingRequest request = newBuildingRequest();
384         request.setLocalRepository(getLocalRepository());
385 
386         final Profile externalProfile = new Profile();
387         externalProfile.setLocation(
388                 "",
389                 new org.apache.maven.model.InputLocation(
390                         1, 1, new org.apache.maven.model.InputSource(new InputSource(null, "settings.xml", null))));
391         externalProfile.setId("external-profile");
392         request.addProfile(externalProfile);
393         request.setActiveProfileIds(List.of(externalProfile.getId()));
394 
395         MavenProject project = projectBuilder.build(testPom, request).getProject();
396 
397         String id = project.getGroupId() + ":" + project.getArtifactId() + ":" + project.getVersion();
398         assertTrue(project.getInjectedProfileIds().keySet().containsAll(List.of("external", id)));
399         assertTrue(project.getInjectedProfileIds().get("external").stream().anyMatch("external-profile"::equals));
400         assertTrue(project.getInjectedProfileIds().get(id).stream().noneMatch("profile1"::equals));
401         assertTrue(project.getInjectedProfileIds().get(id).stream().noneMatch("profile2"::equals));
402         assertTrue(project.getInjectedProfileIds().get(id).stream().anyMatch("active-by-default"::equals));
403 
404         InternalMavenSession session = Mockito.mock(InternalMavenSession.class);
405         List<org.apache.maven.api.model.Profile> activeProfiles =
406                 new DefaultProject(session, project).getDeclaredActiveProfiles();
407         assertEquals(2, activeProfiles.size());
408         org.apache.maven.api.model.Profile profile = activeProfiles.get(0);
409         assertEquals("active-by-default", profile.getId());
410         InputLocation location = profile.getLocation("");
411         assertNotNull(location);
412         assertThat(location.getLineNumber(), greaterThan(0));
413         assertThat(location.getColumnNumber(), greaterThan(0));
414         assertNotNull(location.getSource());
415         assertThat(location.getSource().getLocation(), containsString("pom-with-profiles/pom.xml"));
416         profile = activeProfiles.get(1);
417         assertEquals("external-profile", profile.getId());
418         location = profile.getLocation("");
419         assertNotNull(location);
420         assertThat(location.getLineNumber(), greaterThan(0));
421         assertThat(location.getColumnNumber(), greaterThan(0));
422         assertNotNull(location.getSource());
423         assertThat(location.getSource().getLocation(), containsString("settings.xml"));
424     }
425 
426     @Test
427     void testActivatedProfileIsResolved() throws Exception {
428         File testPom = getTestFile("src/test/resources/projects/pom-with-profiles/pom.xml");
429 
430         ProjectBuildingRequest request = newBuildingRequest();
431         request.setLocalRepository(getLocalRepository());
432         request.setActiveProfileIds(List.of("profile1"));
433 
434         MavenProject project = projectBuilder.build(testPom, request).getProject();
435 
436         assertEquals(1, project.getActiveProfiles().size());
437         assertTrue(project.getActiveProfiles().stream().anyMatch(p -> "profile1".equals(p.getId())));
438         assertTrue(project.getActiveProfiles().stream().noneMatch(p -> "profile2".equals(p.getId())));
439         assertTrue(project.getActiveProfiles().stream().noneMatch(p -> "active-by-default".equals(p.getId())));
440     }
441 
442     @Test
443     void testActivatedProfileByDefaultIsResolved() throws Exception {
444         File testPom = getTestFile("src/test/resources/projects/pom-with-profiles/pom.xml");
445 
446         ProjectBuildingRequest request = newBuildingRequest();
447         request.setLocalRepository(getLocalRepository());
448 
449         MavenProject project = projectBuilder.build(testPom, request).getProject();
450 
451         assertEquals(1, project.getActiveProfiles().size());
452         assertTrue(project.getActiveProfiles().stream().noneMatch(p -> "profile1".equals(p.getId())));
453         assertTrue(project.getActiveProfiles().stream().noneMatch(p -> "profile2".equals(p.getId())));
454         assertTrue(project.getActiveProfiles().stream().anyMatch(p -> "active-by-default".equals(p.getId())));
455     }
456 
457     /**
458      * Tests whether external version range parent references are built correctly.
459      */
460     @Test
461     public void testBuildParentVersionRangeExternallyWithChildPomVersionExpression() throws Exception {
462         File f1 = getTestFile(
463                 "src/test/resources/projects/parent-version-range-external-child-pom-version-expression/pom.xml");
464 
465         try {
466             this.getProjectFromRemoteRepository(f1);
467             fail("Expected 'ProjectBuildingException' not thrown.");
468         } catch (final ProjectBuildingException e) {
469             assertNotNull(e.getMessage());
470         }
471     }
472 
473     /**
474      * Tests whether external version range parent references are built correctly.
475      */
476     @Test
477     public void testBuildParentVersionRangeExternallyWithChildPomParentVersionExpression() throws Exception {
478         File f1 = getTestFile(
479                 "src/test/resources/projects/parent-version-range-external-child-pom-parent-version-expression/pom.xml");
480 
481         try {
482             this.getProjectFromRemoteRepository(f1);
483             fail("Expected 'ProjectBuildingException' not thrown.");
484         } catch (final ProjectBuildingException e) {
485             assertNotNull(e.getMessage());
486         }
487     }
488 
489     /**
490      * Tests whether external version range parent references are built correctly.
491      */
492     @Test
493     public void testBuildParentVersionRangeExternallyWithChildProjectParentVersionExpression() throws Exception {
494         File f1 = getTestFile(
495                 "src/test/resources/projects/parent-version-range-external-child-project-parent-version-expression/pom.xml");
496 
497         try {
498             this.getProjectFromRemoteRepository(f1);
499             fail("Expected 'ProjectBuildingException' not thrown.");
500         } catch (final ProjectBuildingException e) {
501             assertNotNull(e.getMessage());
502         }
503     }
504 
505     /**
506      * Tests whether external version range parent references are built correctly.
507      */
508     @Test
509     public void testBuildParentVersionRangeExternallyWithChildRevisionExpression() throws Exception {
510         File f1 = getTestFile(
511                 "src/test/resources/projects/parent-version-range-external-child-revision-expression/pom.xml");
512 
513         MavenProject mp = this.getProjectFromRemoteRepository(f1);
514 
515         assertEquals("1.0-SNAPSHOT", mp.getVersion());
516     }
517 
518     @Test
519     public void testParentVersionResolvedFromNestedProperties() throws Exception {
520         File f1 = getTestFile("src/test/resources/projects/pom-parent-version-from-nested-properties/pom.xml");
521         ProjectBuildingRequest request = newBuildingRequest();
522         MavenSession session =
523                 InternalMavenSession.from(request.getRepositorySession()).getMavenSession();
524 
525         MavenProject mp = projectBuilder.build(f1, request).getProject();
526         assertEquals("0.1.0-DEVELOPER", mp.getVersion());
527 
528         session.getUserProperties().put("release", "true");
529         mp = projectBuilder.build(f1, request).getProject();
530         assertEquals("0.1.0", mp.getVersion());
531     }
532 
533     @Test
534     public void testSubprojectDiscovery() throws Exception {
535         File pom = getTestFile("src/test/resources/projects/subprojects-discover/pom.xml");
536         ProjectBuildingRequest configuration = newBuildingRequest();
537         InternalSession internalSession = InternalSession.from(configuration.getRepositorySession());
538         InternalMavenSession mavenSession = InternalMavenSession.from(internalSession);
539         mavenSession
540                 .getMavenSession()
541                 .getRequest()
542                 .setRootDirectory(pom.toPath().getParent());
543 
544         List<ProjectBuildingResult> results = projectBuilder.build(List.of(pom), true, configuration);
545         assertEquals(2, results.size());
546         MavenProject p1 = results.get(0).getProject();
547         MavenProject p2 = results.get(1).getProject();
548         MavenProject parent = p1.getArtifactId().equals("parent") ? p1 : p2;
549         assertEquals(List.of("child"), parent.getModel().getDelegate().getSubprojects());
550     }
551 
552     @Test
553     public void testEmptySubprojectsElementDoesNotPreventDiscovery() throws Exception {
554         File pom = getTestFile("src/test/resources/projects/subprojects-empty/pom.xml");
555         ProjectBuildingRequest configuration = newBuildingRequest();
556         InternalSession internalSession = InternalSession.from(configuration.getRepositorySession());
557         InternalMavenSession mavenSession = InternalMavenSession.from(internalSession);
558         mavenSession
559                 .getMavenSession()
560                 .getRequest()
561                 .setRootDirectory(pom.toPath().getParent());
562 
563         List<ProjectBuildingResult> results = projectBuilder.build(List.of(pom), true, configuration);
564         // Empty <subprojects /> no longer prevents discovery; use the property to opt out
565         assertEquals(2, results.size());
566     }
567 
568     @Test
569     public void testEmptyModulesElementDoesNotPreventDiscovery() throws Exception {
570         File pom = getTestFile("src/test/resources/projects/modules-empty/pom.xml");
571         ProjectBuildingRequest configuration = newBuildingRequest();
572         InternalSession internalSession = InternalSession.from(configuration.getRepositorySession());
573         InternalMavenSession mavenSession = InternalMavenSession.from(internalSession);
574         mavenSession
575                 .getMavenSession()
576                 .getRequest()
577                 .setRootDirectory(pom.toPath().getParent());
578 
579         List<ProjectBuildingResult> results = projectBuilder.build(List.of(pom), true, configuration);
580         // Empty <modules /> no longer prevents discovery; use the property to opt out
581         assertEquals(2, results.size());
582     }
583 
584     @Test
585     public void testDiscoverSubprojectsPropertyDisablesDiscovery() throws Exception {
586         File pom = getTestFile("src/test/resources/projects/subprojects-empty/pom.xml");
587         ProjectBuildingRequest configuration = newBuildingRequest();
588         InternalSession internalSession = InternalSession.from(configuration.getRepositorySession());
589         InternalMavenSession mavenSession = InternalMavenSession.from(internalSession);
590         mavenSession
591                 .getMavenSession()
592                 .getRequest()
593                 .setRootDirectory(pom.toPath().getParent());
594         mavenSession.getMavenSession().getUserProperties().put(Constants.MAVEN_PROJECT_DISCOVER_SUBPROJECTS, "false");
595 
596         List<ProjectBuildingResult> results = projectBuilder.build(List.of(pom), true, configuration);
597         // Discovery disabled via property: only the parent project should be built
598         assertEquals(1, results.size());
599         MavenProject parent = results.get(0).getProject();
600         assertEquals("parent", parent.getArtifactId());
601         assertTrue(parent.getModel().getDelegate().getSubprojects().isEmpty());
602     }
603 
604     @Test
605     void testVersionInheritedFromRemoteParent() throws Exception {
606         File f1 = getTestFile("src/test/resources/projects/parent-version-inherited-from-remote/pom.xml");
607         MavenProject project = getProject(f1);
608 
609         assertNotNull(project, "project should not be null");
610         assertEquals("1.0", project.getVersion(), "version should be inherited from remote parent");
611         assertNotNull(project.getArtifact(), "project artifact should not be null");
612         assertEquals("1.0", project.getArtifact().getVersion(), "artifact version should match inherited version");
613         assertEquals("org.different.group", project.getGroupId(), "groupId should be from child POM");
614         assertEquals("child-project", project.getArtifactId(), "artifactId should be from child POM");
615     }
616 
617     @Test
618     void testVersionInheritedFromRemoteParentMultiModule() throws Exception {
619         File pom = getTestFile("src/test/resources/projects/parent-version-inherited-from-remote-multimodule/pom.xml");
620         ProjectBuildingRequest configuration = newBuildingRequest();
621         InternalSession internalSession = InternalSession.from(configuration.getRepositorySession());
622         InternalMavenSession mavenSession = InternalMavenSession.from(internalSession);
623         mavenSession
624                 .getMavenSession()
625                 .getRequest()
626                 .setRootDirectory(pom.toPath().getParent());
627 
628         List<ProjectBuildingResult> results = projectBuilder.build(List.of(pom), true, configuration);
629         assertEquals(2, results.size());
630 
631         MavenProject child = results.stream()
632                 .map(ProjectBuildingResult::getProject)
633                 .filter(p -> "child-project".equals(p.getArtifactId()))
634                 .findFirst()
635                 .orElse(null);
636         assertNotNull(child, "child project should be found");
637         assertEquals("1.0", child.getVersion(), "version should be inherited from remote parent");
638         assertNotNull(child.getArtifact(), "child project artifact should not be null");
639         assertEquals("1.0", child.getArtifact().getVersion(), "artifact version should match inherited version");
640         assertEquals("org.different.group", child.getGroupId(), "groupId should be from child POM");
641     }
642 
643     /**
644      * Tests that parent profile source keys use consistent GAV format (groupId:artifactId:version)
645      * across both cache-miss and cache-hit paths in DefaultModelBuilder.readAsParentModel().
646      *
647      * <p>Before the fix, the cache-miss path used ModelProblemUtils.toId() (GAV) while the cache-hit
648      * path used Model.getId() (GAPV, which includes packaging). This meant the same parent's profiles
649      * could appear under different keys depending on build order.
650      */
651     @Test
652     void testParentProfileSourceKeyConsistentAcrossModules() throws Exception {
653         File pom = getTestFile("src/test/resources/projects/multimodule-parent-profiles/pom.xml");
654         ProjectBuildingRequest configuration = newBuildingRequest();
655         configuration.setLocalRepository(getLocalRepository());
656         InternalSession internalSession = InternalSession.from(configuration.getRepositorySession());
657         InternalMavenSession mavenSession = InternalMavenSession.from(internalSession);
658         mavenSession
659                 .getMavenSession()
660                 .getRequest()
661                 .setRootDirectory(pom.toPath().getParent());
662 
663         List<ProjectBuildingResult> results = projectBuilder.build(List.of(pom), true, configuration);
664         assertEquals(3, results.size());
665 
666         // The parent GAV key (without packaging) that all children should use
667         String parentGav = "org.apache.maven.test:multimodule-parent-profiles:1.0-SNAPSHOT";
668 
669         for (ProjectBuildingResult result : results) {
670             MavenProject project = result.getProject();
671             if ("pom".equals(project.getPackaging()) && "multimodule-parent-profiles".equals(project.getArtifactId())) {
672                 continue; // skip the parent itself
673             }
674 
675             // Verify that the parent profile source key uses GAV format (no packaging component)
676             assertTrue(
677                     project.getInjectedProfileIds().containsKey(parentGav),
678                     "Profile source key for " + project.getArtifactId()
679                             + " should use GAV format '" + parentGav
680                             + "', but found keys: "
681                             + project.getInjectedProfileIds().keySet());
682 
683             // Verify the parent-profile was actually tracked
684             assertTrue(
685                     project.getInjectedProfileIds().get(parentGav).contains("parent-profile"),
686                     "parent-profile should be listed under GAV key for " + project.getArtifactId());
687 
688             // Verify no GAPV key exists (would include ":pom:" packaging)
689             for (String key : project.getInjectedProfileIds().keySet()) {
690                 assertFalse(
691                         key.contains(":pom:"),
692                         "Profile source key for " + project.getArtifactId()
693                                 + " should not contain packaging, but found: " + key);
694             }
695         }
696     }
697 }