Skip to content

Commit

Permalink
Apply sorcery to temp. move Maven for test
Browse files Browse the repository at this point in the history
  • Loading branch information
fabapp2 committed Nov 6, 2023
1 parent 19a8251 commit 036b811
Show file tree
Hide file tree
Showing 15 changed files with 235 additions and 173 deletions.
11 changes: 8 additions & 3 deletions sbm-support-rewrite/.gitignore
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
/testcode/reposilite-test/dependency-project/pom.xml
/testcode/reposilite-test/dependency-project/target
/testcode/reposilite-test/dependent-project/pom.xml
/testcode/reposilite-test/dependent-project/target
/testcode/reposilite-test/user.home/**
!/testcode/reposilite-test/user.home/.m2/settings.xml.template
!/testcode/reposilite-test/user.home/.m2/settings-security.xml
testcode/reposilite-test/user.home/.m2/settings.xml
/testcode/reposilite-test/reposilite-data/**
!testcode/reposilite-test/reposilite-data/shared.configuration.json
/testcode/reposilite-test/user.home/apache-maven-3.9.5/
/testcode/**/target/**
!/testcode/reposilite-test/user.home/.m2/settings.xml.template
!/testcode/reposilite-test/user.home/.m2/settings-security.xml
!testcode/reposilite-test/reposilite-data/shared.configuration.json
6 changes: 6 additions & 0 deletions sbm-support-rewrite/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -264,6 +264,12 @@
<version>1.10.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-core</artifactId>
<version>2.0.9</version>
<scope>test</scope>
</dependency>
</dependencies>

<build>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import org.openrewrite.InMemoryExecutionContext;
import org.openrewrite.java.AddOrUpdateAnnotationAttribute;
import org.openrewrite.maven.MavenExecutionContextView;
import org.openrewrite.maven.MavenSettings;
import org.openrewrite.maven.cache.MavenPomCache;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.boot.autoconfigure.AutoConfiguration;
Expand All @@ -28,6 +29,8 @@
import org.springframework.sbm.scopes.ProjectMetadata;
import org.springframework.sbm.scopes.ScanScope;

import java.nio.file.Files;
import java.nio.file.Path;
import java.util.function.Supplier;

/**
Expand Down Expand Up @@ -61,7 +64,8 @@ public static BeanFactoryPostProcessor beanFactoryPostProcessor(ExecutionScope e
@Bean
@org.springframework.sbm.scopes.annotations.ScanScope
ProjectMetadata projectMetadata() {
return new ProjectMetadata();
ProjectMetadata projectMetadata = new ProjectMetadata();
return projectMetadata;
}

@Bean
Expand All @@ -74,9 +78,9 @@ Supplier<ExecutionContext> executionContextSupplier() {
@org.springframework.sbm.scopes.annotations.ScanScope
ExecutionContext executionContext(ProjectMetadata projectMetadata, Supplier<ExecutionContext> executionContextSupplier, MavenPomCache mavenPomCache) {
ExecutionContext executionContext = executionContextSupplier.get();
MavenExecutionContextView contextView = MavenExecutionContextView.view(executionContext);
contextView.setMavenSettings(projectMetadata.getMavenSettings());
contextView.setPomCache(mavenPomCache);
// MavenExecutionContextView contextView = MavenExecutionContextView.view(executionContext);
// contextView.setMavenSettings(projectMetadata.getMavenSettings());
// contextView.setPomCache(mavenPomCache);
return executionContext;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -77,11 +77,11 @@ Consumer<Throwable> artifactDownloaderErrorConsumer() {
@Bean
ModuleParser moduleParser() {
return new ModuleParser();
}<
}

@Bean
MavenModuleParser mavenModuleParser(ParserProperties parserPropeties, ModuleParser moduleParser) {
return new MavenModuleParser(parserPropeties, moduleParser);
MavenModuleParser mavenModuleParser(ParserProperties parserProperties, ModuleParser moduleParser) {
return new MavenModuleParser(parserProperties, moduleParser);
}

@Bean
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,10 @@
import org.openrewrite.Parser;
import org.openrewrite.maven.MavenExecutionContextView;
import org.openrewrite.maven.MavenSettings;
import org.openrewrite.maven.tree.MavenRepository;
import org.sonatype.plexus.components.sec.dispatcher.DefaultSecDispatcher;
import org.springframework.core.io.Resource;
import org.springframework.sbm.scopes.ProjectMetadata;
import org.springframework.sbm.utils.ResourceUtil;
import org.springframework.stereotype.Component;

Expand All @@ -37,18 +39,22 @@ public class MavenSettingsInitializer {

private final MavenPasswordDecrypter mavenPasswordDecrypter;
private final ExecutionContext executionContext;
private final ProjectMetadata projectMetadata;
/**
* @deprecated initialization in ExecutionoContext is done in ProjectParser
*/
public void initializeMavenSettings() {
String repo = "file://" + Path.of(System.getProperty("user.home")).resolve(".m2/repository") + "/";
MavenSettings mavenSettings = new MavenSettings(repo, null, null, null, null);
// Read .m2/settings.xml
// TODO: Add support for global Maven settings (${maven.home}/conf/settings.xml).
MavenExecutionContextView mavenExecutionContextView = MavenExecutionContextView.view(executionContext);
Path mavenSettingsFile = Path.of(System.getProperty("user.home")).resolve(".m2/settings.xml");
MavenExecutionContextView mavenExecutionContextView = MavenExecutionContextView.view(executionContext);
if (Files.exists(mavenSettingsFile)) {
MavenSettings mavenSettings = MavenSettings.parse(mavenSettingsFile, mavenExecutionContextView);
mavenExecutionContextView.setMavenSettings(mavenSettings);
mavenSettings = MavenSettings.parse(mavenSettingsFile, mavenExecutionContextView);
}
mavenExecutionContextView.setMavenSettings(mavenSettings);
projectMetadata.setMavenSettings(mavenSettings);
}

public MavenSettings initializeMavenSettings(Resource mavenSettingsFile, Path securitySettingsFilePath) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ MavenSettingsInitializer mavenSettingsInitializer(ExecutionContext executionCont
try {
SecDispatcher secDispatcher = new DefaultSecDispatcher(new DefaultPlexusCipher());
MavenPasswordDecrypter mavenPasswordDecrypter = new MavenPasswordDecrypter(secDispatcher);
return new MavenSettingsInitializer(mavenPasswordDecrypter, executionContext);
return new MavenSettingsInitializer(mavenPasswordDecrypter, executionContext, new ProjectMetadata());
} catch (PlexusCipherException e) {
throw new RuntimeException(e);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,27 +19,42 @@
import org.apache.maven.shared.invoker.*;
import org.junit.jupiter.api.*;
import org.junit.jupiter.api.io.TempDir;
import org.junitpioneer.jupiter.SetSystemProperty;
import org.mockito.Mockito;
import org.openrewrite.java.marker.JavaSourceSet;
import org.openrewrite.java.tree.J;
import org.openrewrite.java.tree.JavaType;
import org.openrewrite.maven.cache.LocalMavenArtifactCache;
import org.openrewrite.maven.cache.MavenArtifactCache;
import org.openrewrite.maven.tree.MavenRepository;
import org.powermock.reflect.Whitebox;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.sbm.boot.autoconfigure.SbmSupportRewriteConfiguration;
import org.springframework.sbm.parsers.RewriteProjectParser;
import org.springframework.sbm.parsers.RewriteProjectParsingResult;
import org.springframework.sbm.parsers.maven.RewriteMavenProjectParser;
import org.springframework.sbm.parsers.maven.SbmTestConfiguration;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.util.FileSystemUtils;
import org.testcontainers.containers.GenericContainer;
import org.testcontainers.images.builder.Transferable;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
import org.testcontainers.utility.DockerImageName;
import org.testcontainers.utility.MountableFile;

import java.io.*;
import java.lang.reflect.Field;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
Expand All @@ -53,21 +68,72 @@
/**
* @author Fabian Krüger
*/
@SpringBootTest(classes = {SbmSupportRewriteConfiguration.class, SbmTestConfiguration.class})
@SpringBootTest(classes = {MyTEstCOnfig.class, SbmSupportRewriteConfiguration.class, SbmTestConfiguration.class})
@DirtiesContext // clear beans caching Maven settings
@Testcontainers
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
public class PrivateArtifactRepositoryTest {


private static MavenRepository originalMavenRepository;
// localRepository.getUri() will differ from '"file:" + userHome + "/.m2/repository/"' because
// MavenRepository.MAVEN_LOCAL_DEFAULT gets returned and this field is statically initialized.
// For this test it means that running the test in isolation succeeds but running it in combination
// with a test that loads MavenRepository before 'user.home' was changed in this test, it fails.
// And maybe even worse, running this test before others would set the local maven repository to the
// dummy dir used in this test.
//
// To prevent this it will be set to the original settings with this line:
MavenRepository mavenLocalDefault = MavenRepository.MAVEN_LOCAL_DEFAULT;

public static final String $USER_HOME_PLACEHOLDER = "${user.home}";
public static final String $PORT_PLACEHOLDER = "${port}";
public static final String TESTCODE_DIR = "testcode/reposilite-test";
public static final String DEPENDENCY_CLASS_FQNAME = "com.example.dependency.DependencyClass";

@Container
static GenericContainer reposilite = new GenericContainer(DockerImageName.parse("dzikoysk/reposilite:3.4.10"))
.withExposedPorts(8080)
.withCopyFileToContainer(
MountableFile.forHostPath("./" + TESTCODE_DIR + "/reposilite-data/shared.configuration.json"),
"/app/data/shared.configuration.json"
)
.withCopyFileToContainer(
MountableFile.forHostPath("./" + TESTCODE_DIR + "/reposilite-test/reposilite-data/repositories/snapshots/com/example/dependency/dependency-project/maven-metadata.xml"),
"/app/data/repositories/snapshots/com/example/dependency/dependency-project/maven-metadata.xml"
)
.withCopyFileToContainer(
MountableFile.forHostPath("./" + TESTCODE_DIR + "/reposilite-test/reposilite-data/repositories/snapshots/com/example/dependency/dependency-project/maven-metadata.xml.md5"),
"/app/data/repositories/snapshots/com/example/dependency/dependency-project/maven-metadata.xml.md5"
)
.withCopyFileToContainer(
MountableFile.forHostPath("./" + TESTCODE_DIR + "/reposilite-test/reposilite-data/repositories/snapshots/com/example/dependency/dependency-project/maven-metadata.xml.sha1"),
"/app/data/repositories/snapshots/com/example/dependency/dependency-project/maven-metadata.xml.sha1"
)
.withCopyFileToContainer(
MountableFile.forHostPath("./" + TESTCODE_DIR + "/reposilite-test/reposilite-data/repositories/snapshots/com/example/dependency/dependency-project/1.0-SNAPSHOT/dependency-project-1.0-20231105.102337-1.jar"),
"/app/data/repositories/snapshots/com/example/dependency/dependency-project/1.0-SNAPSHOT/dependency-project-1.0-20231105.102337-1.jar"
)
.withCopyFileToContainer(
MountableFile.forHostPath("./" + TESTCODE_DIR + "/reposilite-test/reposilite-data/repositories/snapshots/com/example/dependency/dependency-project/1.0-SNAPSHOT/dependency-project-1.0-20231105.102337-1.jar.md5"),
"/app/data/repositories/snapshots/com/example/dependency/dependency-project/1.0-SNAPSHOT/dependency-project-1.0-20231105.102337-1.jar.md5"
)
.withCopyFileToContainer(
MountableFile.forHostPath("./" + TESTCODE_DIR + "/reposilite-test/reposilite-data/repositories/snapshots/com/example/dependency/dependency-project/1.0-SNAPSHOT/dependency-project-1.0-20231105.102337-1.jar.sha1"),
"/app/data/repositories/snapshots/com/example/dependency/dependency-project/1.0-SNAPSHOT/dependency-project-1.0-20231105.102337-1.jar.sha1"
)
.withCopyFileToContainer(
MountableFile.forHostPath("./" + TESTCODE_DIR + "/reposilite-test/reposilite-data/repositories/snapshots/com/example/dependency/dependency-project/1.0-SNAPSHOT/dependency-project-1.0-20231105.102337-1.pom"),
"/app/data/repositories/snapshots/com/example/dependency/dependency-project/1.0-SNAPSHOT/dependency-project-1.0-20231105.102337-1.pom"
)
.withCopyFileToContainer(
MountableFile.forHostPath("./" + TESTCODE_DIR + "/reposilite-test/reposilite-data/repositories/snapshots/com/example/dependency/dependency-project/1.0-SNAPSHOT/dependency-project-1.0-20231105.102337-1.pom.md5"),
"/app/data/repositories/snapshots/com/example/dependency/dependency-project/1.0-SNAPSHOT/dependency-project-1.0-20231105.102337-1.pom.md5"
)
.withCopyFileToContainer(
MountableFile.forHostPath("./" + TESTCODE_DIR + "/reposilite-test/reposilite-data/repositories/snapshots/com/example/dependency/dependency-project/1.0-SNAPSHOT/dependency-project-1.0-20231105.102337-1.pom.sha1"),
"/app/data/repositories/snapshots/com/example/dependency/dependency-project/1.0-SNAPSHOT/dependency-project-1.0-20231105.102337-1.pom.sha1"
)
// Create temp user 'user' with password 'secret'
.withEnv("REPOSILITE_OPTS", "--token user:secret --shared-config shared.configuration.json");

Expand All @@ -89,17 +155,20 @@ static void beforeAll(@TempDir Path tempDir) {
newUserHome = Path.of(".").resolve(TESTCODE_DIR + "/user.home").toAbsolutePath().normalize().toString();
System.setProperty("user.home", newUserHome);
installMavenForTestIfNotExists(tempDir);
originalMavenRepository = MavenRepository.MAVEN_LOCAL_DEFAULT;
MavenRepository mavenRepository = new MavenRepository("local", new File(System.getProperty("user.home") + "/.m2/repository").toURI().toString(), "true", "true", true, null, null, false);
Whitebox.setInternalState(MavenRepository.class, "MAVEN_LOCAL_DEFAULT", mavenRepository);
}

@AfterAll
static void afterAll() {
System.setProperty("user.home", originalUserHome);
Whitebox.setInternalState(MavenRepository.class, "MAVEN_LOCAL_DEFAULT", originalMavenRepository);
}

@Test
@Order(1)
@DisplayName("Maven settings should be read")
// @SetSystemProperty(key = "user.home", value = "testcode/reposilite-test/user.home")
void mavenSettingsShouldBeRead() throws IOException, MavenInvocationException, InterruptedException {
Integer port = reposilite.getMappedPort(8080);
System.out.println("Reposilite: http://localhost:" + port + " login with user:secret");
Expand All @@ -119,13 +188,17 @@ void mavenSettingsShouldBeRead() throws IOException, MavenInvocationException, I
deployDependency(dependencyPomPath);
// the project 'testcode/reposilite-test/reposilite-test' has been deployed to reposilite

clearDependencyFromLocalMavenRepo();

InvocationRequest request = new DefaultInvocationRequest();
request.setPomFile(dependentPomPath.toFile());
request.setShowErrors(true);
request.setUserSettingsFile(Path.of(TESTCODE_DIR + "/user.home/.m2/settings.xml").toFile());
request.setGoals(List.of("-v", "clean", "package"));
request.setGoals(List.of("clean", "package"));
request.setLocalRepositoryDirectory(localMavenRepository);
request.setBatchMode(true);
request.setGlobalChecksumPolicy(InvocationRequest.CheckSumPolicy.Warn);
request.setOutputHandler(s -> System.out.println(s));
Invoker invoker = new DefaultInvoker();
invoker.setMavenHome(Path.of(TESTCODE_DIR + "/user.home/apache-maven-3.9.5").toFile());
InvocationResult result = invoker.execute(request);
Expand All @@ -148,15 +221,15 @@ void mavenSettingsShouldBeRead() throws IOException, MavenInvocationException, I
void verifyDependenciesFromPrivateRepoWereResolved() {
// verify dependency does not exist in local Maven repo
Path dependencyArtifactDir = dependencyPathInLocalMavenRepo.getParent();
assertThat(Files.isDirectory(dependencyArtifactDir)).isTrue();
assertThat(dependencyArtifactDir).isDirectory();
assertThat(dependencyArtifactDir.toFile().listFiles()).isEmpty();

// scan a project that depends on this dependency
Path migrateApplication = Path.of(TESTCODE_DIR + "/dependent-project");
RewriteProjectParsingResult parsingResult = parser.parse(migrateApplication);

// verify dependency was downloaded
Path snapshotDir = dependencyPathInLocalMavenRepo.resolve("1.0-SNAPSHOT");
Path snapshotDir = dependencyPathInLocalMavenRepo.resolve("1.0-SNAPSHOT").toAbsolutePath().normalize();
assertThat(snapshotDir).isDirectory();
assertThat(Arrays.stream(snapshotDir.toFile().listFiles()).map(f -> f.getName()).findFirst().get()).matches("dependency-project-1.0-.*\\.jar");

Expand Down Expand Up @@ -303,3 +376,15 @@ private void deployDependency(Path pomXmlPath) throws MavenInvocationException {
}

}


@Configuration
class MyTEstCOnfig {
@Bean
MavenArtifactCache mavenArtifactCache() {
MavenArtifactCache mavenArtifactCache = new LocalMavenArtifactCache(Paths.get(System.getProperty("user.home"), ".m2", "repository")).orElse(
new LocalMavenArtifactCache(Paths.get(System.getProperty("user.home"), ".rewrite", "cache", "artifacts"))
);
return mavenArtifactCache;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
import org.springframework.sbm.parsers.maven.BuildFileParser;
import org.springframework.sbm.parsers.maven.MavenPasswordDecrypter;
import org.springframework.sbm.parsers.maven.MavenSettingsInitializer;
import org.springframework.sbm.scopes.ProjectMetadata;
import org.springframework.sbm.test.util.DummyResource;
import org.springframework.sbm.utils.ResourceUtil;

Expand Down Expand Up @@ -110,7 +111,7 @@ public class GivenSimpleMavenMultiModuleProject {
@BeforeEach
void beforeEach() throws PlexusCipherException {
ExecutionContext executionContext = new InMemoryExecutionContext(t -> {throw new RuntimeException(t);});
sut = new BuildFileParser(new MavenSettingsInitializer(new MavenPasswordDecrypter(new DefaultSecDispatcher(new DefaultPlexusCipher())), executionContext));
sut = new BuildFileParser(new MavenSettingsInitializer(new MavenPasswordDecrypter(new DefaultSecDispatcher(new DefaultPlexusCipher())), executionContext, new ProjectMetadata()));
}

@Test
Expand Down
Loading

0 comments on commit 036b811

Please sign in to comment.