1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.maven.api.plugin.testing.stubs;
20
21 import java.net.URI;
22 import java.nio.file.Path;
23 import java.nio.file.Paths;
24 import java.util.ArrayList;
25 import java.util.Arrays;
26 import java.util.Collection;
27 import java.util.HashMap;
28 import java.util.List;
29 import java.util.Map;
30 import java.util.Optional;
31 import java.util.Properties;
32 import java.util.concurrent.ConcurrentHashMap;
33 import java.util.function.Supplier;
34
35 import org.apache.maven.api.Artifact;
36 import org.apache.maven.api.LocalRepository;
37 import org.apache.maven.api.ProducedArtifact;
38 import org.apache.maven.api.Project;
39 import org.apache.maven.api.RemoteRepository;
40 import org.apache.maven.api.Session;
41 import org.apache.maven.api.SessionData;
42 import org.apache.maven.api.model.Model;
43 import org.apache.maven.api.model.Repository;
44 import org.apache.maven.api.services.ArtifactDeployer;
45 import org.apache.maven.api.services.ArtifactDeployerRequest;
46 import org.apache.maven.api.services.ArtifactFactory;
47 import org.apache.maven.api.services.ArtifactFactoryRequest;
48 import org.apache.maven.api.services.ArtifactInstaller;
49 import org.apache.maven.api.services.ArtifactInstallerRequest;
50 import org.apache.maven.api.services.ArtifactManager;
51 import org.apache.maven.api.services.LocalRepositoryManager;
52 import org.apache.maven.api.services.Lookup;
53 import org.apache.maven.api.services.ProjectBuilder;
54 import org.apache.maven.api.services.ProjectBuilderRequest;
55 import org.apache.maven.api.services.ProjectBuilderResult;
56 import org.apache.maven.api.services.ProjectManager;
57 import org.apache.maven.api.services.RepositoryFactory;
58 import org.apache.maven.api.services.VersionParser;
59 import org.apache.maven.api.services.xml.ModelXmlFactory;
60 import org.apache.maven.impl.DefaultModelVersionParser;
61 import org.apache.maven.impl.DefaultModelXmlFactory;
62 import org.apache.maven.impl.DefaultVersionParser;
63 import org.apache.maven.impl.InternalSession;
64 import org.apache.maven.model.v4.MavenStaxReader;
65 import org.eclipse.aether.util.version.GenericVersionScheme;
66 import org.mockito.ArgumentMatchers;
67
68 import static org.mockito.ArgumentMatchers.any;
69 import static org.mockito.ArgumentMatchers.anyString;
70 import static org.mockito.ArgumentMatchers.same;
71 import static org.mockito.Mockito.doAnswer;
72 import static org.mockito.Mockito.doReturn;
73 import static org.mockito.Mockito.mock;
74 import static org.mockito.Mockito.when;
75 import static org.mockito.Mockito.withSettings;
76
77
78
79
80 public class SessionMock {
81
82 public static InternalSession getMockSession(String localRepo) {
83 LocalRepository localRepository = mock(LocalRepository.class);
84 when(localRepository.getId()).thenReturn("local");
85 when(localRepository.getPath()).thenReturn(Paths.get(localRepo));
86 return getMockSession(localRepository);
87 }
88
89 @SuppressWarnings("checkstyle:MethodLength")
90 public static InternalSession getMockSession(LocalRepository localRepository) {
91 InternalSession session = mock(InternalSession.class);
92
93
94
95
96 RepositoryFactory repositoryFactory = mock(RepositoryFactory.class);
97 when(session.createRemoteRepository(anyString(), anyString())).thenAnswer(iom -> {
98 String id = iom.getArgument(0, String.class);
99 String url = iom.getArgument(1, String.class);
100 return session.getService(RepositoryFactory.class).createRemote(id, url);
101 });
102 when(session.createRemoteRepository(any()))
103 .thenAnswer(iom -> repositoryFactory.createRemote(iom.getArgument(0, Repository.class)));
104 when(repositoryFactory.createRemote(any(Repository.class))).thenAnswer(iom -> {
105 Repository repository = iom.getArgument(0, Repository.class);
106 return repositoryFactory.createRemote(repository.getId(), repository.getUrl());
107 });
108 when(repositoryFactory.createRemote(anyString(), anyString())).thenAnswer(iom -> {
109 String id = iom.getArgument(0, String.class);
110 String url = iom.getArgument(1, String.class);
111 RemoteRepository remoteRepository =
112 mock(RemoteRepository.class, withSettings().lenient());
113 when(remoteRepository.getId()).thenReturn(id);
114 when(remoteRepository.getUrl()).thenReturn(url);
115 when(remoteRepository.getProtocol()).thenReturn(URI.create(url).getScheme());
116 return remoteRepository;
117 });
118 when(session.getService(RepositoryFactory.class)).thenReturn(repositoryFactory);
119
120
121
122
123 VersionParser versionParser =
124 new DefaultVersionParser(new DefaultModelVersionParser(new GenericVersionScheme()));
125 when(session.parseVersion(any()))
126 .thenAnswer(iom -> versionParser.parseVersion(iom.getArgument(0, String.class)));
127 when(session.getService(VersionParser.class)).thenReturn(versionParser);
128
129
130
131
132 LocalRepositoryManager localRepositoryManager = mock(LocalRepositoryManager.class);
133 when(session.getPathForLocalArtifact(any(Artifact.class)))
134 .then(iom -> localRepositoryManager.getPathForLocalArtifact(
135 session, session.getLocalRepository(), iom.getArgument(0, Artifact.class)));
136 when(session.getPathForRemoteArtifact(any(), any()))
137 .thenAnswer(iom -> localRepositoryManager.getPathForRemoteArtifact(
138 session,
139 session.getLocalRepository(),
140 iom.getArgument(0, RemoteRepository.class),
141 iom.getArgument(1, Artifact.class)));
142 when(localRepositoryManager.getPathForLocalArtifact(any(), any(), any()))
143 .thenAnswer(iom -> {
144 LocalRepository localRepo = iom.getArgument(1, LocalRepository.class);
145 Artifact artifact = iom.getArgument(2, Artifact.class);
146 return localRepo.getPath().resolve(getPathForArtifact(artifact, true));
147 });
148 when(session.getService(LocalRepositoryManager.class)).thenReturn(localRepositoryManager);
149
150
151
152
153 ArtifactInstaller artifactInstaller = mock(ArtifactInstaller.class);
154 doAnswer(iom -> {
155 artifactInstaller.install(
156 ArtifactInstallerRequest.build(session, iom.getArgument(0, Collection.class)));
157 return null;
158 })
159 .when(session)
160 .installArtifacts(any(Collection.class));
161 doAnswer(iom -> {
162 artifactInstaller.install(ArtifactInstallerRequest.build(
163 session, Arrays.asList(iom.getArgument(0, ProducedArtifact[].class))));
164 return null;
165 })
166 .when(session)
167 .installArtifacts(any(ProducedArtifact[].class));
168 doAnswer(iom -> {
169 artifactInstaller.install(ArtifactInstallerRequest.build(
170 iom.getArgument(0, Session.class), iom.getArgument(1, Collection.class)));
171 return null;
172 })
173 .when(artifactInstaller)
174 .install(any(Session.class), ArgumentMatchers.<Collection<ProducedArtifact>>any());
175 when(session.getService(ArtifactInstaller.class)).thenReturn(artifactInstaller);
176
177
178
179
180 ArtifactDeployer artifactDeployer = mock(ArtifactDeployer.class);
181 doAnswer(iom -> {
182 artifactDeployer.deploy(ArtifactDeployerRequest.build(
183 iom.getArgument(0, Session.class),
184 iom.getArgument(1, RemoteRepository.class),
185 Arrays.asList(iom.getArgument(2, ProducedArtifact[].class))));
186 return null;
187 })
188 .when(session)
189 .deployArtifact(any(), any());
190 doAnswer(iom -> {
191 artifactDeployer.deploy(ArtifactDeployerRequest.build(
192 iom.getArgument(0, Session.class),
193 iom.getArgument(1, RemoteRepository.class),
194 iom.getArgument(2, Collection.class)));
195 return null;
196 })
197 .when(artifactDeployer)
198 .deploy(any(), any(), any());
199 when(session.getService(ArtifactDeployer.class)).thenReturn(artifactDeployer);
200
201
202
203
204 ArtifactManager artifactManager = mock(ArtifactManager.class);
205 Map<Artifact, Path> paths = new HashMap<>();
206 doAnswer(iom -> {
207 paths.put(iom.getArgument(0), iom.getArgument(1));
208 return null;
209 })
210 .when(artifactManager)
211 .setPath(any(), any());
212 doAnswer(iom -> Optional.ofNullable(paths.get(iom.getArgument(0, Artifact.class))))
213 .when(artifactManager)
214 .getPath(any());
215 doAnswer(iom -> artifactManager.getPath(iom.getArgument(0, Artifact.class)))
216 .when(session)
217 .getArtifactPath(any());
218 when(session.getService(ArtifactManager.class)).thenReturn(artifactManager);
219
220
221
222
223 ProjectManager projectManager = mock(ProjectManager.class);
224 Map<Project, Collection<Artifact>> attachedArtifacts = new HashMap<>();
225 doAnswer(iom -> {
226 Project project = iom.getArgument(1, Project.class);
227 String type = iom.getArgument(2, String.class);
228 Path path = iom.getArgument(3, Path.class);
229 ProducedArtifact artifact = session.createProducedArtifact(
230 project.getGroupId(), project.getArtifactId(), project.getVersion(), null, null, type);
231 artifactManager.setPath(artifact, path);
232 attachedArtifacts
233 .computeIfAbsent(project, p -> new ArrayList<>())
234 .add(artifact);
235 return null;
236 })
237 .when(projectManager)
238 .attachArtifact(same(session), any(Project.class), any(), any());
239 doAnswer(iom -> {
240 Project project = iom.getArgument(0, Project.class);
241 ProducedArtifact artifact = iom.getArgument(1, ProducedArtifact.class);
242 Path path = iom.getArgument(2, Path.class);
243 artifactManager.setPath(artifact, path);
244 attachedArtifacts
245 .computeIfAbsent(project, p -> new ArrayList<>())
246 .add(artifact);
247 return null;
248 })
249 .when(projectManager)
250 .attachArtifact(any(Project.class), any(ProducedArtifact.class), any(Path.class));
251 when(projectManager.getAttachedArtifacts(any()))
252 .then(iom ->
253 attachedArtifacts.computeIfAbsent(iom.getArgument(0, Project.class), p -> new ArrayList<>()));
254 when(projectManager.getAllArtifacts(any())).then(iom -> {
255 Project project = iom.getArgument(0, Project.class);
256 List<Artifact> result = new ArrayList<>();
257 result.addAll(project.getArtifacts());
258 result.addAll(attachedArtifacts.computeIfAbsent(project, p -> new ArrayList<>()));
259 return result;
260 });
261 when(session.getService(ProjectManager.class)).thenReturn(projectManager);
262
263
264
265
266 ArtifactFactory artifactFactory = mock(ArtifactFactory.class);
267 when(artifactFactory.create(any())).then(iom -> {
268 ArtifactFactoryRequest request = iom.getArgument(0, ArtifactFactoryRequest.class);
269 String classifier = request.getClassifier();
270 String extension = request.getExtension();
271 String type = request.getType();
272 if (classifier == null) {
273 classifier = "";
274 }
275 if (extension == null) {
276 extension = type != null ? type : "";
277 }
278 return new ArtifactStub(
279 request.getGroupId(), request.getArtifactId(), classifier, request.getVersion(), extension);
280 });
281 when(artifactFactory.createProduced(any())).then(iom -> {
282 ArtifactFactoryRequest request = iom.getArgument(0, ArtifactFactoryRequest.class);
283 String classifier = request.getClassifier();
284 String extension = request.getExtension();
285 String type = request.getType();
286 if (classifier == null) {
287 classifier = "";
288 }
289 if (extension == null) {
290 extension = type != null ? type : "";
291 }
292 return new ProducedArtifactStub(
293 request.getGroupId(), request.getArtifactId(), classifier, request.getVersion(), extension);
294 });
295 when(session.createArtifact(any(), any(), any(), any(), any(), any())).thenAnswer(iom -> {
296 String groupId = iom.getArgument(0, String.class);
297 String artifactId = iom.getArgument(1, String.class);
298 String version = iom.getArgument(2, String.class);
299 String classifier = iom.getArgument(3, String.class);
300 String extension = iom.getArgument(4, String.class);
301 String type = iom.getArgument(5, String.class);
302 return session.getService(ArtifactFactory.class)
303 .create(ArtifactFactoryRequest.builder()
304 .session(session)
305 .groupId(groupId)
306 .artifactId(artifactId)
307 .version(version)
308 .classifier(classifier)
309 .extension(extension)
310 .type(type)
311 .build());
312 });
313 when(session.createArtifact(any(), any(), any(), any())).thenAnswer(iom -> {
314 String groupId = iom.getArgument(0, String.class);
315 String artifactId = iom.getArgument(1, String.class);
316 String version = iom.getArgument(2, String.class);
317 String extension = iom.getArgument(3, String.class);
318 return session.getService(ArtifactFactory.class)
319 .create(ArtifactFactoryRequest.builder()
320 .session(session)
321 .groupId(groupId)
322 .artifactId(artifactId)
323 .version(version)
324 .extension(extension)
325 .build());
326 });
327 when(session.createProducedArtifact(any(), any(), any(), any(), any(), any()))
328 .thenAnswer(iom -> {
329 String groupId = iom.getArgument(0, String.class);
330 String artifactId = iom.getArgument(1, String.class);
331 String version = iom.getArgument(2, String.class);
332 String classifier = iom.getArgument(3, String.class);
333 String extension = iom.getArgument(4, String.class);
334 String type = iom.getArgument(5, String.class);
335 return session.getService(ArtifactFactory.class)
336 .createProduced(ArtifactFactoryRequest.builder()
337 .session(session)
338 .groupId(groupId)
339 .artifactId(artifactId)
340 .version(version)
341 .classifier(classifier)
342 .extension(extension)
343 .type(type)
344 .build());
345 });
346 when(session.createProducedArtifact(any(), any(), any(), any())).thenAnswer(iom -> {
347 String groupId = iom.getArgument(0, String.class);
348 String artifactId = iom.getArgument(1, String.class);
349 String version = iom.getArgument(2, String.class);
350 String extension = iom.getArgument(3, String.class);
351 return session.getService(ArtifactFactory.class)
352 .createProduced(ArtifactFactoryRequest.builder()
353 .session(session)
354 .groupId(groupId)
355 .artifactId(artifactId)
356 .version(version)
357 .extension(extension)
358 .build());
359 });
360 when(session.getService(ArtifactFactory.class)).thenReturn(artifactFactory);
361
362
363
364
365 ProjectBuilder projectBuilder = mock(ProjectBuilder.class);
366 when(projectBuilder.build(any(ProjectBuilderRequest.class))).then(iom -> {
367 ProjectBuilderRequest request = iom.getArgument(0, ProjectBuilderRequest.class);
368 ProjectBuilderResult result = mock(ProjectBuilderResult.class);
369 Model model = new MavenStaxReader().read(request.getSource().get().openStream());
370 ProjectStub projectStub = new ProjectStub();
371 projectStub.setModel(model);
372 ProducedArtifactStub artifactStub = new ProducedArtifactStub(
373 model.getGroupId(), model.getArtifactId(), "", model.getVersion(), model.getPackaging());
374 if (!"pom".equals(model.getPackaging())) {
375 projectStub.setMainArtifact(artifactStub);
376 }
377 when(result.getProject()).thenReturn(Optional.of(projectStub));
378 return result;
379 });
380 when(session.getService(ProjectBuilder.class)).thenReturn(projectBuilder);
381
382
383
384
385 when(session.getService(ModelXmlFactory.class)).thenReturn(new DefaultModelXmlFactory());
386
387
388
389
390 when(session.getService(Lookup.class)).thenReturn(LookupStub.EMPTY);
391
392
393
394
395 Properties sysProps = new Properties();
396 Properties usrProps = new Properties();
397 doReturn(sysProps).when(session).getSystemProperties();
398 doReturn(usrProps).when(session).getUserProperties();
399 when(session.getLocalRepository()).thenReturn(localRepository);
400 when(session.getData()).thenReturn(new TestSessionData());
401 when(session.withLocalRepository(any()))
402 .thenAnswer(iom -> getMockSession(iom.getArgument(0, LocalRepository.class)));
403
404 return session;
405 }
406
407 static String getPathForArtifact(Artifact artifact, boolean local) {
408 StringBuilder path = new StringBuilder(128);
409 path.append(artifact.getGroupId().replace('.', '/')).append('/');
410 path.append(artifact.getArtifactId()).append('/');
411 path.append(artifact.getVersion()).append('/');
412 path.append(artifact.getArtifactId()).append('-');
413 path.append(artifact.getVersion());
414 if (artifact.getClassifier().length() > 0) {
415 path.append('-').append(artifact.getClassifier());
416 }
417 if (artifact.getExtension().length() > 0) {
418 path.append('.').append(artifact.getExtension());
419 }
420 return path.toString();
421 }
422
423 static class TestSessionData implements SessionData {
424 private final Map<Key<?>, Object> map = new ConcurrentHashMap<>();
425
426 @Override
427 public <T> void set(Key<T> key, T value) {
428 map.put(key, value);
429 }
430
431 @Override
432 public <T> boolean replace(Key<T> key, T oldValue, T newValue) {
433 return map.replace(key, oldValue, newValue);
434 }
435
436 @Override
437 @SuppressWarnings("unchecked")
438 public <T> T get(Key<T> key) {
439 return (T) map.get(key);
440 }
441
442 @Override
443 @SuppressWarnings("unchecked")
444 public <T> T computeIfAbsent(Key<T> key, Supplier<T> supplier) {
445 return (T) map.computeIfAbsent(key, k -> supplier.get());
446 }
447 }
448 }