Upgrade to spring-javaformat 0.0.11

This commit is contained in:
Andy Wilkinson
2019-06-07 09:44:58 +01:00
parent d548c5ed31
commit 8f1be4cded
1940 changed files with 16814 additions and 28498 deletions

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2016 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -34,8 +34,7 @@ public class ClassLoaderIntegrationTests {
@Test
public void runWithIsolatedClassLoader() throws Exception {
// CLI classes or dependencies should not be exposed to the app
String output = this.cli.run("classloader-test-app.groovy",
SpringCli.class.getName());
String output = this.cli.run("classloader-test-app.groovy", SpringCli.class.getName());
assertThat(output).contains("HasClasses-false-true-false");
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2016 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -100,8 +100,7 @@ public class CliTester implements TestRule {
return getOutput();
}
private <T extends OptionParsingCommand> Future<T> submitCommand(final T command,
String... args) {
private <T extends OptionParsingCommand> Future<T> submitCommand(final T command, String... args) {
clearUrlHandler();
final String[] sources = getSources(args);
return Executors.newSingleThreadExecutor().submit(new Callable<T>() {
@@ -161,16 +160,13 @@ public class CliTester implements TestRule {
@Override
public Statement apply(final Statement base, final Description description) {
final Statement statement = CliTester.this.outputCapture
.apply(new RunLauncherStatement(base), description);
final Statement statement = CliTester.this.outputCapture.apply(new RunLauncherStatement(base), description);
return new Statement() {
@Override
public void evaluate() throws Throwable {
Assume.assumeTrue(
"Not running sample integration tests because integration profile not active",
System.getProperty("spring.profiles.active", "integration")
.contains("integration"));
Assume.assumeTrue("Not running sample integration tests because integration profile not active",
System.getProperty("spring.profiles.active", "integration").contains("integration"));
statement.evaluate();
}
};
@@ -182,8 +178,7 @@ public class CliTester implements TestRule {
public String getHttpOutput(String uri) {
try {
InputStream stream = URI.create("http://localhost:" + this.port + uri).toURL()
.openStream();
InputStream stream = URI.create("http://localhost:" + this.port + uri).toURL().openStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
String line;
StringBuilder result = new StringBuilder();

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2016 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -56,34 +56,29 @@ public class GrabCommandIntegrationTests {
// Use --autoconfigure=false to limit the amount of downloaded dependencies
String output = this.cli.grab("grab.groovy", "--autoconfigure=false");
assertThat(new File("target/repository/joda-time/joda-time").isDirectory())
.isTrue();
assertThat(new File("target/repository/joda-time/joda-time").isDirectory()).isTrue();
// Should be resolved from local repository cache
assertThat(output.contains("Downloading: file:")).isTrue();
}
@Test
public void duplicateDependencyManagementBomAnnotationsProducesAnError()
throws Exception {
public void duplicateDependencyManagementBomAnnotationsProducesAnError() throws Exception {
try {
this.cli.grab("duplicateDependencyManagementBom.groovy");
fail();
}
catch (Exception ex) {
assertThat(ex.getMessage())
.contains("Duplicate @DependencyManagementBom annotation");
assertThat(ex.getMessage()).contains("Duplicate @DependencyManagementBom annotation");
}
}
@Test
public void customMetadata() throws Exception {
System.setProperty("grape.root", "target");
FileSystemUtils.copyRecursively(
new File("src/test/resources/grab-samples/repository"),
FileSystemUtils.copyRecursively(new File("src/test/resources/grab-samples/repository"),
new File("target/repository"));
this.cli.grab("customDependencyManagement.groovy", "--autoconfigure=false");
assertThat(new File("target/repository/javax/ejb/ejb-api/3.0").isDirectory())
.isTrue();
assertThat(new File("target/repository/javax/ejb/ejb-api/3.0").isDirectory()).isTrue();
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2016 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -147,8 +147,7 @@ public class SampleIntegrationTests {
System.setProperty("spring.artemis.embedded.queues", "spring-boot");
try {
String output = this.cli.run("jms.groovy");
assertThat(output)
.contains("Received Greetings from Spring Boot via Artemis");
assertThat(output).contains("Received Greetings from Spring Boot via Artemis");
}
finally {
System.clearProperty("spring.artemis.embedded.queues");

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2016 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -47,32 +47,27 @@ public class SpringApplicationLauncherTests {
@Test
public void launchWithClassConfiguredBySystemProperty() {
System.setProperty("spring.application.class.name",
"system.property.SpringApplication");
System.setProperty("spring.application.class.name", "system.property.SpringApplication");
assertThat(launch()).contains("system.property.SpringApplication");
}
@Test
public void launchWithClassConfiguredByEnvironmentVariable() {
this.env.put("SPRING_APPLICATION_CLASS_NAME",
"environment.variable.SpringApplication");
this.env.put("SPRING_APPLICATION_CLASS_NAME", "environment.variable.SpringApplication");
assertThat(launch()).contains("environment.variable.SpringApplication");
}
@Test
public void systemPropertyOverridesEnvironmentVariable() {
System.setProperty("spring.application.class.name",
"system.property.SpringApplication");
this.env.put("SPRING_APPLICATION_CLASS_NAME",
"environment.variable.SpringApplication");
System.setProperty("spring.application.class.name", "system.property.SpringApplication");
this.env.put("SPRING_APPLICATION_CLASS_NAME", "environment.variable.SpringApplication");
assertThat(launch()).contains("system.property.SpringApplication");
}
@Test
public void sourcesDefaultPropertiesAndArgsAreUsedToLaunch() throws Exception {
System.setProperty("spring.application.class.name",
TestSpringApplication.class.getName());
System.setProperty("spring.application.class.name", TestSpringApplication.class.getName());
Object[] sources = new Object[0];
String[] args = new String[0];
new SpringApplicationLauncher(getClass().getClassLoader()).launch(sources, args);
@@ -81,15 +76,14 @@ public class SpringApplicationLauncherTests {
assertThat(args == TestSpringApplication.args).isTrue();
Map<String, String> defaultProperties = TestSpringApplication.defaultProperties;
assertThat(defaultProperties).hasSize(1)
.containsEntry("spring.groovy.template.check-template-location", "false");
assertThat(defaultProperties).hasSize(1).containsEntry("spring.groovy.template.check-template-location",
"false");
}
private Set<String> launch() {
TestClassLoader classLoader = new TestClassLoader(getClass().getClassLoader());
try {
new TestSpringApplicationLauncher(classLoader).launch(new Object[0],
new String[0]);
new TestSpringApplicationLauncher(classLoader).launch(new Object[0], new String[0]);
}
catch (Exception ex) {
// Launch will fail, but we can still check that the launcher tried to use
@@ -107,8 +101,7 @@ public class SpringApplicationLauncherTests {
}
@Override
protected Class<?> loadClass(String name, boolean resolve)
throws ClassNotFoundException {
protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
this.classes.add(name);
return super.loadClass(name, resolve);
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2016 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -33,8 +33,7 @@ public class OptionParsingCommandTests {
public void optionHelp() {
OptionHandler handler = new OptionHandler();
handler.option("bar", "Bar");
OptionParsingCommand command = new TestOptionParsingCommand("foo", "Foo",
handler);
OptionParsingCommand command = new TestOptionParsingCommand("foo", "Foo", handler);
assertThat(command.getHelp()).contains("--bar");
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2016 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -40,33 +40,26 @@ public class ResourceMatcherTests {
@Test
public void nonExistentRoot() throws IOException {
ResourceMatcher resourceMatcher = new ResourceMatcher(
Arrays.asList("alpha/**", "bravo/*", "*"),
ResourceMatcher resourceMatcher = new ResourceMatcher(Arrays.asList("alpha/**", "bravo/*", "*"),
Arrays.asList(".*", "alpha/**/excluded"));
List<MatchedResource> matchedResources = resourceMatcher
.find(Arrays.asList(new File("does-not-exist")));
List<MatchedResource> matchedResources = resourceMatcher.find(Arrays.asList(new File("does-not-exist")));
assertThat(matchedResources).isEmpty();
}
@SuppressWarnings("unchecked")
@Test
public void defaults() throws Exception {
ResourceMatcher resourceMatcher = new ResourceMatcher(Arrays.asList(""),
Arrays.asList(""));
Collection<String> includes = (Collection<String>) ReflectionTestUtils
.getField(resourceMatcher, "includes");
Collection<String> excludes = (Collection<String>) ReflectionTestUtils
.getField(resourceMatcher, "excludes");
ResourceMatcher resourceMatcher = new ResourceMatcher(Arrays.asList(""), Arrays.asList(""));
Collection<String> includes = (Collection<String>) ReflectionTestUtils.getField(resourceMatcher, "includes");
Collection<String> excludes = (Collection<String>) ReflectionTestUtils.getField(resourceMatcher, "excludes");
assertThat(includes).contains("static/**");
assertThat(excludes).contains("**/*.jar");
}
@Test
public void excludedWins() throws Exception {
ResourceMatcher resourceMatcher = new ResourceMatcher(Arrays.asList("*"),
Arrays.asList("**/*.jar"));
List<MatchedResource> found = resourceMatcher
.find(Arrays.asList(new File("src/test/resources")));
ResourceMatcher resourceMatcher = new ResourceMatcher(Arrays.asList("*"), Arrays.asList("**/*.jar"));
List<MatchedResource> found = resourceMatcher.find(Arrays.asList(new File("src/test/resources")));
assertThat(found).areNot(new Condition<MatchedResource>() {
@Override
@@ -80,10 +73,8 @@ public class ResourceMatcherTests {
@SuppressWarnings("unchecked")
@Test
public void includedDeltas() throws Exception {
ResourceMatcher resourceMatcher = new ResourceMatcher(Arrays.asList("-static/**"),
Arrays.asList(""));
Collection<String> includes = (Collection<String>) ReflectionTestUtils
.getField(resourceMatcher, "includes");
ResourceMatcher resourceMatcher = new ResourceMatcher(Arrays.asList("-static/**"), Arrays.asList(""));
Collection<String> includes = (Collection<String>) ReflectionTestUtils.getField(resourceMatcher, "includes");
assertThat(includes).contains("templates/**");
assertThat(includes).doesNotContain("static/**");
}
@@ -91,12 +82,10 @@ public class ResourceMatcherTests {
@SuppressWarnings("unchecked")
@Test
public void includedDeltasAndNewEntries() throws Exception {
ResourceMatcher resourceMatcher = new ResourceMatcher(
Arrays.asList("-static/**", "foo.jar"), Arrays.asList("-**/*.jar"));
Collection<String> includes = (Collection<String>) ReflectionTestUtils
.getField(resourceMatcher, "includes");
Collection<String> excludes = (Collection<String>) ReflectionTestUtils
.getField(resourceMatcher, "excludes");
ResourceMatcher resourceMatcher = new ResourceMatcher(Arrays.asList("-static/**", "foo.jar"),
Arrays.asList("-**/*.jar"));
Collection<String> includes = (Collection<String>) ReflectionTestUtils.getField(resourceMatcher, "includes");
Collection<String> excludes = (Collection<String>) ReflectionTestUtils.getField(resourceMatcher, "excludes");
assertThat(includes).contains("foo.jar");
assertThat(includes).contains("templates/**");
assertThat(includes).doesNotContain("static/**");
@@ -106,20 +95,16 @@ public class ResourceMatcherTests {
@SuppressWarnings("unchecked")
@Test
public void excludedDeltas() throws Exception {
ResourceMatcher resourceMatcher = new ResourceMatcher(Arrays.asList(""),
Arrays.asList("-**/*.jar"));
Collection<String> excludes = (Collection<String>) ReflectionTestUtils
.getField(resourceMatcher, "excludes");
ResourceMatcher resourceMatcher = new ResourceMatcher(Arrays.asList(""), Arrays.asList("-**/*.jar"));
Collection<String> excludes = (Collection<String>) ReflectionTestUtils.getField(resourceMatcher, "excludes");
assertThat(excludes).doesNotContain("**/*.jar");
}
@Test
public void jarFileAlwaysMatches() throws Exception {
ResourceMatcher resourceMatcher = new ResourceMatcher(Arrays.asList("*"),
Arrays.asList("**/*.jar"));
ResourceMatcher resourceMatcher = new ResourceMatcher(Arrays.asList("*"), Arrays.asList("**/*.jar"));
List<MatchedResource> found = resourceMatcher
.find(Arrays.asList(new File("src/test/resources/templates"),
new File("src/test/resources/foo.jar")));
.find(Arrays.asList(new File("src/test/resources/templates"), new File("src/test/resources/foo.jar")));
assertThat(found).areAtLeastOne(new Condition<MatchedResource>() {
@Override
@@ -132,8 +117,7 @@ public class ResourceMatcherTests {
@Test
public void resourceMatching() throws IOException {
ResourceMatcher resourceMatcher = new ResourceMatcher(
Arrays.asList("alpha/**", "bravo/*", "*"),
ResourceMatcher resourceMatcher = new ResourceMatcher(Arrays.asList("alpha/**", "bravo/*", "*"),
Arrays.asList(".*", "alpha/**/excluded"));
List<MatchedResource> matchedResources = resourceMatcher
.find(Arrays.asList(new File("src/test/resources/resource-matcher/one"),
@@ -143,8 +127,7 @@ public class ResourceMatcherTests {
for (MatchedResource resource : matchedResources) {
paths.add(resource.getName());
}
assertThat(paths).containsOnly("alpha/nested/fileA", "bravo/fileC", "fileD",
"bravo/fileE", "fileF", "three");
assertThat(paths).containsOnly("alpha/nested/fileA", "bravo/fileC", "fileD", "bravo/fileE", "fileF", "three");
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -51,30 +51,26 @@ public abstract class AbstractHttpClientMockTests {
protected final CloseableHttpClient http = mock(CloseableHttpClient.class);
protected void mockSuccessfulMetadataTextGet() throws IOException {
mockSuccessfulMetadataGet("metadata/service-metadata-2.1.0.txt", "text/plain",
true);
mockSuccessfulMetadataGet("metadata/service-metadata-2.1.0.txt", "text/plain", true);
}
protected void mockSuccessfulMetadataGet(boolean serviceCapabilities)
protected void mockSuccessfulMetadataGet(boolean serviceCapabilities) throws IOException {
mockSuccessfulMetadataGet("metadata/service-metadata-2.1.0.json", "application/vnd.initializr.v2.1+json",
serviceCapabilities);
}
protected void mockSuccessfulMetadataGetV2(boolean serviceCapabilities) throws IOException {
mockSuccessfulMetadataGet("metadata/service-metadata-2.0.0.json", "application/vnd.initializr.v2+json",
serviceCapabilities);
}
protected void mockSuccessfulMetadataGet(String contentPath, String contentType, boolean serviceCapabilities)
throws IOException {
mockSuccessfulMetadataGet("metadata/service-metadata-2.1.0.json",
"application/vnd.initializr.v2.1+json", serviceCapabilities);
}
protected void mockSuccessfulMetadataGetV2(boolean serviceCapabilities)
throws IOException {
mockSuccessfulMetadataGet("metadata/service-metadata-2.0.0.json",
"application/vnd.initializr.v2+json", serviceCapabilities);
}
protected void mockSuccessfulMetadataGet(String contentPath, String contentType,
boolean serviceCapabilities) throws IOException {
CloseableHttpResponse response = mock(CloseableHttpResponse.class);
byte[] content = readClasspathResource(contentPath);
mockHttpEntity(response, content, contentType);
mockStatus(response, 200);
given(this.http.execute(argThat(getForMetadata(serviceCapabilities))))
.willReturn(response);
given(this.http.execute(argThat(getForMetadata(serviceCapabilities)))).willReturn(response);
}
protected byte[] readClasspathResource(String contentPath) throws IOException {
@@ -82,46 +78,38 @@ public abstract class AbstractHttpClientMockTests {
return StreamUtils.copyToByteArray(resource.getInputStream());
}
protected void mockSuccessfulProjectGeneration(
MockHttpProjectGenerationRequest request) throws IOException {
protected void mockSuccessfulProjectGeneration(MockHttpProjectGenerationRequest request) throws IOException {
// Required for project generation as the metadata is read first
mockSuccessfulMetadataGet(false);
CloseableHttpResponse response = mock(CloseableHttpResponse.class);
mockHttpEntity(response, request.content, request.contentType);
mockStatus(response, 200);
String header = (request.fileName != null)
? contentDispositionValue(request.fileName) : null;
String header = (request.fileName != null) ? contentDispositionValue(request.fileName) : null;
mockHttpHeader(response, "Content-Disposition", header);
given(this.http.execute(argThat(getForNonMetadata()))).willReturn(response);
}
protected void mockProjectGenerationError(int status, String message)
throws IOException, JSONException {
protected void mockProjectGenerationError(int status, String message) throws IOException, JSONException {
// Required for project generation as the metadata is read first
mockSuccessfulMetadataGet(false);
CloseableHttpResponse response = mock(CloseableHttpResponse.class);
mockHttpEntity(response, createJsonError(status, message).getBytes(),
"application/json");
mockHttpEntity(response, createJsonError(status, message).getBytes(), "application/json");
mockStatus(response, status);
given(this.http.execute(isA(HttpGet.class))).willReturn(response);
}
protected void mockMetadataGetError(int status, String message)
throws IOException, JSONException {
protected void mockMetadataGetError(int status, String message) throws IOException, JSONException {
CloseableHttpResponse response = mock(CloseableHttpResponse.class);
mockHttpEntity(response, createJsonError(status, message).getBytes(),
"application/json");
mockHttpEntity(response, createJsonError(status, message).getBytes(), "application/json");
mockStatus(response, status);
given(this.http.execute(isA(HttpGet.class))).willReturn(response);
}
protected HttpEntity mockHttpEntity(CloseableHttpResponse response, byte[] content,
String contentType) {
protected HttpEntity mockHttpEntity(CloseableHttpResponse response, byte[] content, String contentType) {
try {
HttpEntity entity = mock(HttpEntity.class);
given(entity.getContent()).willReturn(new ByteArrayInputStream(content));
Header contentTypeHeader = (contentType != null)
? new BasicHeader("Content-Type", contentType) : null;
Header contentTypeHeader = (contentType != null) ? new BasicHeader("Content-Type", contentType) : null;
given(entity.getContentType()).willReturn(contentTypeHeader);
given(response.getEntity()).willReturn(entity);
return entity;
@@ -137,8 +125,7 @@ public abstract class AbstractHttpClientMockTests {
given(response.getStatusLine()).willReturn(statusLine);
}
protected void mockHttpHeader(CloseableHttpResponse response, String headerName,
String value) {
protected void mockHttpHeader(CloseableHttpResponse response, String headerName, String value) {
Header header = (value != null) ? new BasicHeader(headerName, value) : null;
given(response.getFirstHeader(headerName)).willReturn(header);
}
@@ -179,8 +166,7 @@ public abstract class AbstractHttpClientMockTests {
this(contentType, fileName, new byte[] { 0, 0, 0, 0 });
}
public MockHttpProjectGenerationRequest(String contentType, String fileName,
byte[] content) {
public MockHttpProjectGenerationRequest(String contentType, String fileName, byte[] content) {
this.contentType = contentType;
this.fileName = fileName;
this.content = content;

View File

@@ -92,8 +92,7 @@ public class InitCommandTests extends AbstractHttpClientMockTests {
String fileName = UUID.randomUUID().toString() + ".zip";
File file = new File(fileName);
assertThat(file.exists()).as("file should not exist").isFalse();
MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest(
"application/zip", fileName);
MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest("application/zip", fileName);
mockSuccessfulProjectGeneration(request);
try {
assertThat(this.command.run()).isEqualTo(ExitStatus.OK);
@@ -106,8 +105,7 @@ public class InitCommandTests extends AbstractHttpClientMockTests {
@Test
public void generateProjectNoFileNameAvailable() throws Exception {
MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest(
"application/zip", null);
MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest("application/zip", null);
mockSuccessfulProjectGeneration(request);
assertThat(this.command.run()).isEqualTo(ExitStatus.ERROR);
}
@@ -116,25 +114,22 @@ public class InitCommandTests extends AbstractHttpClientMockTests {
public void generateProjectAndExtract() throws Exception {
File folder = this.temporaryFolder.newFolder();
byte[] archive = createFakeZipArchive("test.txt", "Fake content");
MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest(
"application/zip", "demo.zip", archive);
MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest("application/zip", "demo.zip",
archive);
mockSuccessfulProjectGeneration(request);
assertThat(this.command.run("--extract", folder.getAbsolutePath()))
.isEqualTo(ExitStatus.OK);
assertThat(this.command.run("--extract", folder.getAbsolutePath())).isEqualTo(ExitStatus.OK);
File archiveFile = new File(folder, "test.txt");
assertThat(archiveFile).exists();
}
@Test
public void generateProjectAndExtractWillNotWriteEntriesOutsideOutputLocation()
throws Exception {
public void generateProjectAndExtractWillNotWriteEntriesOutsideOutputLocation() throws Exception {
File folder = this.temporaryFolder.newFolder();
byte[] archive = createFakeZipArchive("../outside.txt", "Fake content");
MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest(
"application/zip", "demo.zip", archive);
MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest("application/zip", "demo.zip",
archive);
mockSuccessfulProjectGeneration(request);
assertThat(this.command.run("--extract", folder.getAbsolutePath()))
.isEqualTo(ExitStatus.ERROR);
assertThat(this.command.run("--extract", folder.getAbsolutePath())).isEqualTo(ExitStatus.ERROR);
File archiveFile = new File(folder.getParentFile(), "outside.txt");
assertThat(archiveFile).doesNotExist();
}
@@ -143,11 +138,10 @@ public class InitCommandTests extends AbstractHttpClientMockTests {
public void generateProjectAndExtractWithConvention() throws Exception {
File folder = this.temporaryFolder.newFolder();
byte[] archive = createFakeZipArchive("test.txt", "Fake content");
MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest(
"application/zip", "demo.zip", archive);
MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest("application/zip", "demo.zip",
archive);
mockSuccessfulProjectGeneration(request);
assertThat(this.command.run(folder.getAbsolutePath() + "/"))
.isEqualTo(ExitStatus.OK);
assertThat(this.command.run(folder.getAbsolutePath() + "/")).isEqualTo(ExitStatus.OK);
File archiveFile = new File(folder, "test.txt");
assertThat(archiveFile).exists();
}
@@ -157,8 +151,8 @@ public class InitCommandTests extends AbstractHttpClientMockTests {
String fileName = UUID.randomUUID().toString();
assertThat(fileName.contains(".")).as("No dot in filename").isFalse();
byte[] archive = createFakeZipArchive("test.txt", "Fake content");
MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest(
"application/zip", "demo.zip", archive);
MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest("application/zip", "demo.zip",
archive);
mockSuccessfulProjectGeneration(request);
File file = new File(fileName);
File archiveFile = new File(file, "test.txt");
@@ -177,8 +171,8 @@ public class InitCommandTests extends AbstractHttpClientMockTests {
String fileName = UUID.randomUUID().toString();
String content = "Fake Content";
byte[] archive = content.getBytes();
MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest(
"application/octet-stream", "pom.xml", archive);
MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest("application/octet-stream",
"pom.xml", archive);
mockSuccessfulProjectGeneration(request);
File file = new File(fileName);
try {
@@ -199,11 +193,10 @@ public class InitCommandTests extends AbstractHttpClientMockTests {
assertThat(file.exists()).as("file should not exist").isFalse();
try {
byte[] archive = createFakeZipArchive("test.txt", "Fake content");
MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest(
"application/foobar", fileName, archive);
MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest("application/foobar",
fileName, archive);
mockSuccessfulProjectGeneration(request);
assertThat(this.command.run("--extract", folder.getAbsolutePath()))
.isEqualTo(ExitStatus.OK);
assertThat(this.command.run("--extract", folder.getAbsolutePath())).isEqualTo(ExitStatus.OK);
assertThat(file.exists()).as("file should have been saved instead").isTrue();
}
finally {
@@ -219,11 +212,9 @@ public class InitCommandTests extends AbstractHttpClientMockTests {
assertThat(file.exists()).as("file should not exist").isFalse();
try {
byte[] archive = createFakeZipArchive("test.txt", "Fake content");
MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest(
null, fileName, archive);
MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest(null, fileName, archive);
mockSuccessfulProjectGeneration(request);
assertThat(this.command.run("--extract", folder.getAbsolutePath()))
.isEqualTo(ExitStatus.OK);
assertThat(this.command.run("--extract", folder.getAbsolutePath())).isEqualTo(ExitStatus.OK);
assertThat(file.exists()).as("file should have been saved instead").isTrue();
}
finally {
@@ -235,21 +226,19 @@ public class InitCommandTests extends AbstractHttpClientMockTests {
public void fileNotOverwrittenByDefault() throws Exception {
File file = this.temporaryFolder.newFile();
long fileLength = file.length();
MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest(
"application/zip", file.getAbsolutePath());
MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest("application/zip",
file.getAbsolutePath());
mockSuccessfulProjectGeneration(request);
assertThat(this.command.run()).as("Should have failed")
.isEqualTo(ExitStatus.ERROR);
assertThat(file.length()).as("File should not have changed")
.isEqualTo(fileLength);
assertThat(this.command.run()).as("Should have failed").isEqualTo(ExitStatus.ERROR);
assertThat(file.length()).as("File should not have changed").isEqualTo(fileLength);
}
@Test
public void overwriteFile() throws Exception {
File file = this.temporaryFolder.newFile();
long fileLength = file.length();
MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest(
"application/zip", file.getAbsolutePath());
MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest("application/zip",
file.getAbsolutePath());
mockSuccessfulProjectGeneration(request);
assertThat(this.command.run("--force")).isEqualTo(ExitStatus.OK);
assertThat(fileLength != file.length()).as("File should have changed").isTrue();
@@ -259,33 +248,28 @@ public class InitCommandTests extends AbstractHttpClientMockTests {
public void fileInArchiveNotOverwrittenByDefault() throws Exception {
File folder = this.temporaryFolder.newFolder();
File conflict = new File(folder, "test.txt");
assertThat(conflict.createNewFile()).as("Should have been able to create file")
.isTrue();
assertThat(conflict.createNewFile()).as("Should have been able to create file").isTrue();
long fileLength = conflict.length();
// also contains test.txt
byte[] archive = createFakeZipArchive("test.txt", "Fake content");
MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest(
"application/zip", "demo.zip", archive);
MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest("application/zip", "demo.zip",
archive);
mockSuccessfulProjectGeneration(request);
assertThat(this.command.run("--extract", folder.getAbsolutePath()))
.isEqualTo(ExitStatus.ERROR);
assertThat(conflict.length()).as("File should not have changed")
.isEqualTo(fileLength);
assertThat(this.command.run("--extract", folder.getAbsolutePath())).isEqualTo(ExitStatus.ERROR);
assertThat(conflict.length()).as("File should not have changed").isEqualTo(fileLength);
}
@Test
public void parseProjectOptions() throws Exception {
this.handler.disableProjectGeneration();
this.command.run("-g=org.demo", "-a=acme", "-v=1.2.3-SNAPSHOT", "-n=acme-sample",
"--description=Acme sample project", "--package-name=demo.foo",
"-t=ant-project", "--build=grunt", "--format=web", "-p=war", "-j=1.9",
"-l=groovy", "-b=1.2.0.RELEASE", "-d=web,data-jpa");
"--description=Acme sample project", "--package-name=demo.foo", "-t=ant-project", "--build=grunt",
"--format=web", "-p=war", "-j=1.9", "-l=groovy", "-b=1.2.0.RELEASE", "-d=web,data-jpa");
assertThat(this.handler.lastRequest.getGroupId()).isEqualTo("org.demo");
assertThat(this.handler.lastRequest.getArtifactId()).isEqualTo("acme");
assertThat(this.handler.lastRequest.getVersion()).isEqualTo("1.2.3-SNAPSHOT");
assertThat(this.handler.lastRequest.getName()).isEqualTo("acme-sample");
assertThat(this.handler.lastRequest.getDescription())
.isEqualTo("Acme sample project");
assertThat(this.handler.lastRequest.getDescription()).isEqualTo("Acme sample project");
assertThat(this.handler.lastRequest.getPackageName()).isEqualTo("demo.foo");
assertThat(this.handler.lastRequest.getType()).isEqualTo("ant-project");
assertThat(this.handler.lastRequest.getBuild()).isEqualTo("grunt");
@@ -304,18 +288,15 @@ public class InitCommandTests extends AbstractHttpClientMockTests {
public void overwriteFileInArchive() throws Exception {
File folder = this.temporaryFolder.newFolder();
File conflict = new File(folder, "test.txt");
assertThat(conflict.createNewFile()).as("Should have been able to create file")
.isTrue();
assertThat(conflict.createNewFile()).as("Should have been able to create file").isTrue();
long fileLength = conflict.length();
// also contains test.txt
byte[] archive = createFakeZipArchive("test.txt", "Fake content");
MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest(
"application/zip", "demo.zip", archive);
MockHttpProjectGenerationRequest request = new MockHttpProjectGenerationRequest("application/zip", "demo.zip",
archive);
mockSuccessfulProjectGeneration(request);
assertThat(this.command.run("--force", "--extract", folder.getAbsolutePath()))
.isEqualTo(ExitStatus.OK);
assertThat(fileLength != conflict.length()).as("File should have changed")
.isTrue();
assertThat(this.command.run("--force", "--extract", folder.getAbsolutePath())).isEqualTo(ExitStatus.OK);
assertThat(fileLength != conflict.length()).as("File should have changed").isTrue();
}
@Test
@@ -377,8 +358,7 @@ public class InitCommandTests extends AbstractHttpClientMockTests {
assertThat(agent.getValue()).startsWith("SpringBootCli/");
}
private byte[] createFakeZipArchive(String fileName, String content)
throws IOException {
private byte[] createFakeZipArchive(String fileName, String content) throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ZipOutputStream zos = new ZipOutputStream(bos);
try {
@@ -393,8 +373,7 @@ public class InitCommandTests extends AbstractHttpClientMockTests {
return bos.toByteArray();
}
private static class TestableInitCommandOptionHandler
extends InitCommand.InitOptionHandler {
private static class TestableInitCommandOptionHandler extends InitCommand.InitOptionHandler {
private boolean disableProjectGeneration;

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -44,8 +44,7 @@ public class InitializrServiceMetadataTests {
assertThat(metadata.getDefaults().get("javaVersion")).isEqualTo("1.7");
assertThat(metadata.getDefaults().get("groupId")).isEqualTo("org.test");
assertThat(metadata.getDefaults().get("name")).isEqualTo("demo");
assertThat(metadata.getDefaults().get("description"))
.isEqualTo("Demo project for Spring Boot");
assertThat(metadata.getDefaults().get("description")).isEqualTo("Demo project for Spring Boot");
assertThat(metadata.getDefaults().get("packaging")).isEqualTo("jar");
assertThat(metadata.getDefaults().get("language")).isEqualTo("java");
assertThat(metadata.getDefaults().get("artifactId")).isEqualTo("demo");
@@ -63,8 +62,7 @@ public class InitializrServiceMetadataTests {
// Security description
assertThat(metadata.getDependency("aop").getName()).isEqualTo("AOP");
assertThat(metadata.getDependency("security").getName()).isEqualTo("Security");
assertThat(metadata.getDependency("security").getDescription())
.isEqualTo("Security description");
assertThat(metadata.getDependency("security").getDescription()).isEqualTo("Security description");
assertThat(metadata.getDependency("jdbc").getName()).isEqualTo("JDBC");
assertThat(metadata.getDependency("data-jpa").getName()).isEqualTo("JPA");
assertThat(metadata.getDependency("data-mongodb").getName()).isEqualTo("MongoDB");
@@ -79,8 +77,7 @@ public class InitializrServiceMetadataTests {
assertThat(projectType.getTags().get("format")).isEqualTo("project");
}
private static InitializrServiceMetadata createInstance(String version)
throws JSONException {
private static InitializrServiceMetadata createInstance(String version) throws JSONException {
try {
return new InitializrServiceMetadata(readJson(version));
}
@@ -90,12 +87,10 @@ public class InitializrServiceMetadataTests {
}
private static JSONObject readJson(String version) throws IOException, JSONException {
Resource resource = new ClassPathResource(
"metadata/service-metadata-" + version + ".json");
Resource resource = new ClassPathResource("metadata/service-metadata-" + version + ".json");
InputStream stream = resource.getInputStream();
try {
return new JSONObject(
StreamUtils.copyToString(stream, Charset.forName("UTF-8")));
return new JSONObject(StreamUtils.copyToString(stream, Charset.forName("UTF-8")));
}
finally {
stream.close();

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -49,19 +49,18 @@ public class InitializrServiceTests extends AbstractHttpClientMockTests {
@Test
public void generateSimpleProject() throws Exception {
ProjectGenerationRequest request = new ProjectGenerationRequest();
MockHttpProjectGenerationRequest mockHttpRequest = new MockHttpProjectGenerationRequest(
"application/xml", "foo.zip");
MockHttpProjectGenerationRequest mockHttpRequest = new MockHttpProjectGenerationRequest("application/xml",
"foo.zip");
ProjectGenerationResponse entity = generateProject(request, mockHttpRequest);
assertProjectEntity(entity, mockHttpRequest.contentType,
mockHttpRequest.fileName);
assertProjectEntity(entity, mockHttpRequest.contentType, mockHttpRequest.fileName);
}
@Test
public void generateProjectCustomTargetFilename() throws Exception {
ProjectGenerationRequest request = new ProjectGenerationRequest();
request.setOutput("bar.zip");
MockHttpProjectGenerationRequest mockHttpRequest = new MockHttpProjectGenerationRequest(
"application/xml", null);
MockHttpProjectGenerationRequest mockHttpRequest = new MockHttpProjectGenerationRequest("application/xml",
null);
ProjectGenerationResponse entity = generateProject(request, mockHttpRequest);
assertProjectEntity(entity, mockHttpRequest.contentType, null);
}
@@ -69,8 +68,8 @@ public class InitializrServiceTests extends AbstractHttpClientMockTests {
@Test
public void generateProjectNoDefaultFileName() throws Exception {
ProjectGenerationRequest request = new ProjectGenerationRequest();
MockHttpProjectGenerationRequest mockHttpRequest = new MockHttpProjectGenerationRequest(
"application/xml", null);
MockHttpProjectGenerationRequest mockHttpRequest = new MockHttpProjectGenerationRequest("application/xml",
null);
ProjectGenerationResponse entity = generateProject(request, mockHttpRequest);
assertProjectEntity(entity, mockHttpRequest.contentType, null);
}
@@ -144,13 +143,11 @@ public class InitializrServiceTests extends AbstractHttpClientMockTests {
MockHttpProjectGenerationRequest mockRequest) throws Exception {
mockSuccessfulProjectGeneration(mockRequest);
ProjectGenerationResponse entity = this.invoker.generate(request);
assertThat(entity.getContent()).as("wrong body content")
.isEqualTo(mockRequest.content);
assertThat(entity.getContent()).as("wrong body content").isEqualTo(mockRequest.content);
return entity;
}
private static void assertProjectEntity(ProjectGenerationResponse entity,
String mimeType, String fileName) {
private static void assertProjectEntity(ProjectGenerationResponse entity, String mimeType, String fileName) {
if (mimeType == null) {
assertThat(entity.getContentType()).isNull();
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -43,8 +43,7 @@ import static org.assertj.core.api.Assertions.assertThat;
*/
public class ProjectGenerationRequestTests {
public static final Map<String, String> EMPTY_TAGS = Collections
.<String, String>emptyMap();
public static final Map<String, String> EMPTY_TAGS = Collections.<String, String>emptyMap();
@Rule
public final ExpectedException thrown = ExpectedException.none();
@@ -53,8 +52,7 @@ public class ProjectGenerationRequestTests {
@Test
public void defaultSettings() {
assertThat(this.request.generateUrl(createDefaultMetadata()))
.isEqualTo(createDefaultUrl("?type=test-type"));
assertThat(this.request.generateUrl(createDefaultMetadata())).isEqualTo(createDefaultUrl("?type=test-type"));
}
@Test
@@ -62,8 +60,8 @@ public class ProjectGenerationRequestTests {
String customServerUrl = "http://foo:8080/initializr";
this.request.setServiceUrl(customServerUrl);
this.request.getDependencies().add("security");
assertThat(this.request.generateUrl(createDefaultMetadata())).isEqualTo(new URI(
customServerUrl + "/starter.zip?dependencies=security&type=test-type"));
assertThat(this.request.generateUrl(createDefaultMetadata()))
.isEqualTo(new URI(customServerUrl + "/starter.zip?dependencies=security&type=test-type"));
}
@Test
@@ -84,8 +82,8 @@ public class ProjectGenerationRequestTests {
public void multipleDependencies() {
this.request.getDependencies().add("web");
this.request.getDependencies().add("data-jpa");
assertThat(this.request.generateUrl(createDefaultMetadata())).isEqualTo(
createDefaultUrl("?dependencies=web%2Cdata-jpa&type=test-type"));
assertThat(this.request.generateUrl(createDefaultMetadata()))
.isEqualTo(createDefaultUrl("?dependencies=web%2Cdata-jpa&type=test-type"));
}
@Test
@@ -104,14 +102,12 @@ public class ProjectGenerationRequestTests {
@Test
public void customType() throws URISyntaxException {
ProjectType projectType = new ProjectType("custom", "Custom Type", "/foo", true,
EMPTY_TAGS);
ProjectType projectType = new ProjectType("custom", "Custom Type", "/foo", true, EMPTY_TAGS);
InitializrServiceMetadata metadata = new InitializrServiceMetadata(projectType);
this.request.setType("custom");
this.request.getDependencies().add("data-rest");
assertThat(this.request.generateUrl(metadata))
.isEqualTo(new URI(ProjectGenerationRequest.DEFAULT_SERVICE_URL
+ "/foo?dependencies=data-rest&type=custom"));
assertThat(this.request.generateUrl(metadata)).isEqualTo(
new URI(ProjectGenerationRequest.DEFAULT_SERVICE_URL + "/foo?dependencies=data-rest&type=custom"));
}
@Test
@@ -135,9 +131,8 @@ public class ProjectGenerationRequestTests {
this.request.setVersion("1.0.1-SNAPSHOT");
this.request.setDescription("Spring Boot Test");
assertThat(this.request.generateUrl(createDefaultMetadata()))
.isEqualTo(createDefaultUrl(
"?groupId=org.acme&artifactId=sample&version=1.0.1-SNAPSHOT"
+ "&description=Spring+Boot+Test&type=test-type"));
.isEqualTo(createDefaultUrl("?groupId=org.acme&artifactId=sample&version=1.0.1-SNAPSHOT"
+ "&description=Spring+Boot+Test&type=test-type"));
}
@Test
@@ -157,8 +152,8 @@ public class ProjectGenerationRequestTests {
@Test
public void outputArchiveWithDotsCustomizeArtifactId() {
this.request.setOutput("my.nice.project.zip");
assertThat(this.request.generateUrl(createDefaultMetadata())).isEqualTo(
createDefaultUrl("?artifactId=my.nice.project&type=test-type"));
assertThat(this.request.generateUrl(createDefaultMetadata()))
.isEqualTo(createDefaultUrl("?artifactId=my.nice.project&type=test-type"));
}
@Test
@@ -192,8 +187,7 @@ public class ProjectGenerationRequestTests {
public void buildOneMatch() throws Exception {
InitializrServiceMetadata metadata = readMetadata();
setBuildAndFormat("gradle", null);
assertThat(this.request.generateUrl(metadata))
.isEqualTo(createDefaultUrl("?type=gradle-project"));
assertThat(this.request.generateUrl(metadata)).isEqualTo(createDefaultUrl("?type=gradle-project"));
}
@Test
@@ -201,8 +195,7 @@ public class ProjectGenerationRequestTests {
InitializrServiceMetadata metadata = readMetadata();
setBuildAndFormat("gradle", "project");
this.request.setType("maven-build");
assertThat(this.request.generateUrl(metadata))
.isEqualTo(createUrl("/pom.xml?type=maven-build"));
assertThat(this.request.generateUrl(metadata)).isEqualTo(createUrl("/pom.xml?type=maven-build"));
}
@Test
@@ -239,8 +232,7 @@ public class ProjectGenerationRequestTests {
}
private static InitializrServiceMetadata createDefaultMetadata() {
ProjectType projectType = new ProjectType("test-type", "The test type",
"/starter.zip", true, EMPTY_TAGS);
ProjectType projectType = new ProjectType("test-type", "The test type", "/starter.zip", true, EMPTY_TAGS);
return new InitializrServiceMetadata(projectType);
}
@@ -248,13 +240,10 @@ public class ProjectGenerationRequestTests {
return readMetadata("2.0.0");
}
private static InitializrServiceMetadata readMetadata(String version)
throws JSONException {
private static InitializrServiceMetadata readMetadata(String version) throws JSONException {
try {
Resource resource = new ClassPathResource(
"metadata/service-metadata-" + version + ".json");
String content = StreamUtils.copyToString(resource.getInputStream(),
Charset.forName("UTF-8"));
Resource resource = new ClassPathResource("metadata/service-metadata-" + version + ".json");
String content = StreamUtils.copyToString(resource.getInputStream(), Charset.forName("UTF-8"));
JSONObject json = new JSONObject(content);
return new InitializrServiceMetadata(json);
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2016 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -35,8 +35,7 @@ public class ServiceCapabilitiesReportGeneratorTests extends AbstractHttpClientM
@Test
public void listMetadataFromServer() throws IOException {
mockSuccessfulMetadataTextGet();
String expected = new String(
readClasspathResource("metadata/service-metadata-2.1.0.txt"));
String expected = new String(readClasspathResource("metadata/service-metadata-2.1.0.txt"));
String content = this.command.generate("http://localhost");
assertThat(content).isEqualTo(expected);
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2017 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -72,8 +72,7 @@ public class GroovyGrabDependencyResolverTests {
@Override
public List<RepositoryConfiguration> getRepositoryConfiguration() {
return RepositoryConfigurationFactory
.createDefaultRepositoryConfiguration();
return RepositoryConfigurationFactory.createDefaultRepositoryConfiguration();
}
@Override
@@ -92,19 +91,16 @@ public class GroovyGrabDependencyResolverTests {
@Test
public void resolveArtifactWithNoDependencies() throws Exception {
List<File> resolved = this.resolver
.resolve(Arrays.asList("commons-logging:commons-logging:1.1.3"));
List<File> resolved = this.resolver.resolve(Arrays.asList("commons-logging:commons-logging:1.1.3"));
assertThat(resolved).hasSize(1);
assertThat(getNames(resolved)).containsOnly("commons-logging-1.1.3.jar");
}
@Test
public void resolveArtifactWithDependencies() throws Exception {
List<File> resolved = this.resolver
.resolve(Arrays.asList("org.springframework:spring-core:4.1.1.RELEASE"));
List<File> resolved = this.resolver.resolve(Arrays.asList("org.springframework:spring-core:4.1.1.RELEASE"));
assertThat(resolved).hasSize(2);
assertThat(getNames(resolved)).containsOnly("commons-logging-1.1.3.jar",
"spring-core-4.1.1.RELEASE.jar");
assertThat(getNames(resolved)).containsOnly("commons-logging-1.1.3.jar", "spring-core-4.1.1.RELEASE.jar");
}
@Test
@@ -112,17 +108,17 @@ public class GroovyGrabDependencyResolverTests {
public void resolveShorthandArtifactWithDependencies() throws Exception {
List<File> resolved = this.resolver.resolve(Arrays.asList("spring-core"));
assertThat(resolved).hasSize(2);
assertThat(getNames(resolved)).has((Condition) Matched.by(
hasItems(startsWith("commons-logging-"), startsWith("spring-core-"))));
assertThat(getNames(resolved))
.has((Condition) Matched.by(hasItems(startsWith("commons-logging-"), startsWith("spring-core-"))));
}
@Test
public void resolveMultipleArtifacts() throws Exception {
List<File> resolved = this.resolver.resolve(Arrays.asList("junit:junit:4.11",
"commons-logging:commons-logging:1.1.3"));
List<File> resolved = this.resolver
.resolve(Arrays.asList("junit:junit:4.11", "commons-logging:commons-logging:1.1.3"));
assertThat(resolved).hasSize(3);
assertThat(getNames(resolved)).containsOnly("junit-4.11.jar",
"commons-logging-1.1.3.jar", "hamcrest-core-1.3.jar");
assertThat(getNames(resolved)).containsOnly("junit-4.11.jar", "commons-logging-1.1.3.jar",
"hamcrest-core-1.3.jar");
}
public Set<String> getNames(Collection<File> files) {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2016 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -83,19 +83,14 @@ public class InstallerTests {
File alpha = createTemporaryFile("alpha.jar");
File bravo = createTemporaryFile("bravo.jar");
File charlie = createTemporaryFile("charlie.jar");
given(this.resolver.resolve(Arrays.asList("bravo")))
.willReturn(Arrays.asList(bravo, alpha));
given(this.resolver.resolve(Arrays.asList("charlie")))
.willReturn(Arrays.asList(charlie, alpha));
given(this.resolver.resolve(Arrays.asList("bravo"))).willReturn(Arrays.asList(bravo, alpha));
given(this.resolver.resolve(Arrays.asList("charlie"))).willReturn(Arrays.asList(charlie, alpha));
this.installer.install(Arrays.asList("bravo"));
assertThat(getNamesOfFilesInLibExt()).containsOnly("alpha.jar", "bravo.jar",
".installed");
assertThat(getNamesOfFilesInLibExt()).containsOnly("alpha.jar", "bravo.jar", ".installed");
this.installer.install(Arrays.asList("charlie"));
assertThat(getNamesOfFilesInLibExt()).containsOnly("alpha.jar", "bravo.jar",
"charlie.jar", ".installed");
assertThat(getNamesOfFilesInLibExt()).containsOnly("alpha.jar", "bravo.jar", "charlie.jar", ".installed");
this.installer.uninstall(Arrays.asList("bravo"));
assertThat(getNamesOfFilesInLibExt()).containsOnly("alpha.jar", "charlie.jar",
".installed");
assertThat(getNamesOfFilesInLibExt()).containsOnly("alpha.jar", "charlie.jar", ".installed");
this.installer.uninstall(Arrays.asList("charlie"));
assertThat(getNamesOfFilesInLibExt()).containsOnly(".installed");
}
@@ -105,14 +100,11 @@ public class InstallerTests {
File alpha = createTemporaryFile("alpha.jar");
File bravo = createTemporaryFile("bravo.jar");
File charlie = createTemporaryFile("charlie.jar");
given(this.resolver.resolve(Arrays.asList("bravo")))
.willReturn(Arrays.asList(bravo, alpha));
given(this.resolver.resolve(Arrays.asList("charlie")))
.willReturn(Arrays.asList(charlie, alpha));
given(this.resolver.resolve(Arrays.asList("bravo"))).willReturn(Arrays.asList(bravo, alpha));
given(this.resolver.resolve(Arrays.asList("charlie"))).willReturn(Arrays.asList(charlie, alpha));
this.installer.install(Arrays.asList("bravo"));
this.installer.install(Arrays.asList("charlie"));
assertThat(getNamesOfFilesInLibExt()).containsOnly("alpha.jar", "bravo.jar",
"charlie.jar", ".installed");
assertThat(getNamesOfFilesInLibExt()).containsOnly("alpha.jar", "bravo.jar", "charlie.jar", ".installed");
this.installer.uninstallAll();
assertThat(getNamesOfFilesInLibExt()).containsOnly(".installed");
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2015 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -38,14 +38,12 @@ public class SpringApplicationRunnerTests {
@Test
public void exceptionMessageWhenSourcesContainsNoClasses() throws Exception {
SpringApplicationRunnerConfiguration configuration = mock(
SpringApplicationRunnerConfiguration.class);
SpringApplicationRunnerConfiguration configuration = mock(SpringApplicationRunnerConfiguration.class);
given(configuration.getClasspath()).willReturn(new String[] { "foo", "bar" });
given(configuration.getLogLevel()).willReturn(Level.INFO);
this.thrown.expect(RuntimeException.class);
this.thrown.expectMessage(equalTo("No classes found in '[foo, bar]'"));
new SpringApplicationRunner(configuration, new String[] { "foo", "bar" })
.compileAndRun();
new SpringApplicationRunner(configuration, new String[] { "foo", "bar" }).compileAndRun();
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2016 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -33,8 +33,7 @@ public class EscapeAwareWhiteSpaceArgumentDelimiterTests {
@Test
public void simple() throws Exception {
String s = "one two";
assertThat(this.delimiter.delimit(s, 0).getArguments()).containsExactly("one",
"two");
assertThat(this.delimiter.delimit(s, 0).getArguments()).containsExactly("one", "two");
assertThat(this.delimiter.parseArguments(s)).containsExactly("one", "two");
assertThat(this.delimiter.isDelimiter(s, 2)).isFalse();
assertThat(this.delimiter.isDelimiter(s, 3)).isTrue();
@@ -44,8 +43,7 @@ public class EscapeAwareWhiteSpaceArgumentDelimiterTests {
@Test
public void escaped() throws Exception {
String s = "o\\ ne two";
assertThat(this.delimiter.delimit(s, 0).getArguments()).containsExactly("o\\ ne",
"two");
assertThat(this.delimiter.delimit(s, 0).getArguments()).containsExactly("o\\ ne", "two");
assertThat(this.delimiter.parseArguments(s)).containsExactly("o ne", "two");
assertThat(this.delimiter.isDelimiter(s, 2)).isFalse();
assertThat(this.delimiter.isDelimiter(s, 3)).isFalse();
@@ -56,26 +54,22 @@ public class EscapeAwareWhiteSpaceArgumentDelimiterTests {
@Test
public void quoted() throws Exception {
String s = "'o ne' 't w o'";
assertThat(this.delimiter.delimit(s, 0).getArguments()).containsExactly("'o ne'",
"'t w o'");
assertThat(this.delimiter.delimit(s, 0).getArguments()).containsExactly("'o ne'", "'t w o'");
assertThat(this.delimiter.parseArguments(s)).containsExactly("o ne", "t w o");
}
@Test
public void doubleQuoted() throws Exception {
String s = "\"o ne\" \"t w o\"";
assertThat(this.delimiter.delimit(s, 0).getArguments())
.containsExactly("\"o ne\"", "\"t w o\"");
assertThat(this.delimiter.delimit(s, 0).getArguments()).containsExactly("\"o ne\"", "\"t w o\"");
assertThat(this.delimiter.parseArguments(s)).containsExactly("o ne", "t w o");
}
@Test
public void nestedQuotes() throws Exception {
String s = "\"o 'n''e\" 't \"w o'";
assertThat(this.delimiter.delimit(s, 0).getArguments())
.containsExactly("\"o 'n''e\"", "'t \"w o'");
assertThat(this.delimiter.parseArguments(s)).containsExactly("o 'n''e",
"t \"w o");
assertThat(this.delimiter.delimit(s, 0).getArguments()).containsExactly("\"o 'n''e\"", "'t \"w o'");
assertThat(this.delimiter.parseArguments(s)).containsExactly("o 'n''e", "t \"w o");
}
@Test

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2016 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -55,14 +55,11 @@ public class DependencyCustomizerTests {
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
given(this.resolver.getGroupId("spring-boot-starter-logging"))
.willReturn("org.springframework.boot");
given(this.resolver.getArtifactId("spring-boot-starter-logging"))
.willReturn("spring-boot-starter-logging");
given(this.resolver.getGroupId("spring-boot-starter-logging")).willReturn("org.springframework.boot");
given(this.resolver.getArtifactId("spring-boot-starter-logging")).willReturn("spring-boot-starter-logging");
this.moduleNode.addClass(this.classNode);
this.dependencyCustomizer = new DependencyCustomizer(
new GroovyClassLoader(getClass().getClassLoader()), this.moduleNode,
new DependencyResolutionContext() {
this.dependencyCustomizer = new DependencyCustomizer(new GroovyClassLoader(getClass().getClassLoader()),
this.moduleNode, new DependencyResolutionContext() {
@Override
public ArtifactCoordinatesResolver getArtifactCoordinatesResolver() {
@@ -75,86 +72,74 @@ public class DependencyCustomizerTests {
@Test
public void basicAdd() {
this.dependencyCustomizer.add("spring-boot-starter-logging");
List<AnnotationNode> grabAnnotations = this.classNode
.getAnnotations(new ClassNode(Grab.class));
List<AnnotationNode> grabAnnotations = this.classNode.getAnnotations(new ClassNode(Grab.class));
assertThat(grabAnnotations).hasSize(1);
AnnotationNode annotationNode = grabAnnotations.get(0);
assertGrabAnnotation(annotationNode, "org.springframework.boot",
"spring-boot-starter-logging", "1.2.3", null, null, true);
assertGrabAnnotation(annotationNode, "org.springframework.boot", "spring-boot-starter-logging", "1.2.3", null,
null, true);
}
@Test
public void nonTransitiveAdd() {
this.dependencyCustomizer.add("spring-boot-starter-logging", false);
List<AnnotationNode> grabAnnotations = this.classNode
.getAnnotations(new ClassNode(Grab.class));
List<AnnotationNode> grabAnnotations = this.classNode.getAnnotations(new ClassNode(Grab.class));
assertThat(grabAnnotations).hasSize(1);
AnnotationNode annotationNode = grabAnnotations.get(0);
assertGrabAnnotation(annotationNode, "org.springframework.boot",
"spring-boot-starter-logging", "1.2.3", null, null, false);
assertGrabAnnotation(annotationNode, "org.springframework.boot", "spring-boot-starter-logging", "1.2.3", null,
null, false);
}
@Test
public void fullyCustomized() {
this.dependencyCustomizer.add("spring-boot-starter-logging", "my-classifier",
"my-type", false);
List<AnnotationNode> grabAnnotations = this.classNode
.getAnnotations(new ClassNode(Grab.class));
this.dependencyCustomizer.add("spring-boot-starter-logging", "my-classifier", "my-type", false);
List<AnnotationNode> grabAnnotations = this.classNode.getAnnotations(new ClassNode(Grab.class));
assertThat(grabAnnotations).hasSize(1);
AnnotationNode annotationNode = grabAnnotations.get(0);
assertGrabAnnotation(annotationNode, "org.springframework.boot",
"spring-boot-starter-logging", "1.2.3", "my-classifier", "my-type",
false);
assertGrabAnnotation(annotationNode, "org.springframework.boot", "spring-boot-starter-logging", "1.2.3",
"my-classifier", "my-type", false);
}
@Test
public void anyMissingClassesWithMissingClassesPerformsAdd() {
this.dependencyCustomizer.ifAnyMissingClasses("does.not.Exist")
.add("spring-boot-starter-logging");
this.dependencyCustomizer.ifAnyMissingClasses("does.not.Exist").add("spring-boot-starter-logging");
assertThat(this.classNode.getAnnotations(new ClassNode(Grab.class))).hasSize(1);
}
@Test
public void anyMissingClassesWithMixtureOfClassesPerformsAdd() {
this.dependencyCustomizer
.ifAnyMissingClasses(getClass().getName(), "does.not.Exist")
this.dependencyCustomizer.ifAnyMissingClasses(getClass().getName(), "does.not.Exist")
.add("spring-boot-starter-logging");
assertThat(this.classNode.getAnnotations(new ClassNode(Grab.class))).hasSize(1);
}
@Test
public void anyMissingClassesWithNoMissingClassesDoesNotPerformAdd() {
this.dependencyCustomizer.ifAnyMissingClasses(getClass().getName())
.add("spring-boot-starter-logging");
this.dependencyCustomizer.ifAnyMissingClasses(getClass().getName()).add("spring-boot-starter-logging");
assertThat(this.classNode.getAnnotations(new ClassNode(Grab.class))).isEmpty();
}
@Test
public void allMissingClassesWithNoMissingClassesDoesNotPerformAdd() {
this.dependencyCustomizer.ifAllMissingClasses(getClass().getName())
.add("spring-boot-starter-logging");
this.dependencyCustomizer.ifAllMissingClasses(getClass().getName()).add("spring-boot-starter-logging");
assertThat(this.classNode.getAnnotations(new ClassNode(Grab.class))).isEmpty();
}
@Test
public void allMissingClassesWithMixtureOfClassesDoesNotPerformAdd() {
this.dependencyCustomizer
.ifAllMissingClasses(getClass().getName(), "does.not.Exist")
this.dependencyCustomizer.ifAllMissingClasses(getClass().getName(), "does.not.Exist")
.add("spring-boot-starter-logging");
assertThat(this.classNode.getAnnotations(new ClassNode(Grab.class))).isEmpty();
}
@Test
public void allMissingClassesWithAllClassesMissingPerformsAdd() {
this.dependencyCustomizer
.ifAllMissingClasses("does.not.Exist", "does.not.exist.Either")
this.dependencyCustomizer.ifAllMissingClasses("does.not.Exist", "does.not.exist.Either")
.add("spring-boot-starter-logging");
assertThat(this.classNode.getAnnotations(new ClassNode(Grab.class))).hasSize(1);
}
private void assertGrabAnnotation(AnnotationNode annotationNode, String group,
String module, String version, String classifier, String type,
boolean transitive) {
private void assertGrabAnnotation(AnnotationNode annotationNode, String group, String module, String version,
String classifier, String type, boolean transitive) {
assertThat(getMemberValue(annotationNode, "group")).isEqualTo(group);
assertThat(getMemberValue(annotationNode, "module")).isEqualTo(module);
if (type == null) {
@@ -167,8 +152,7 @@ public class DependencyCustomizerTests {
assertThat(annotationNode.getMember("classifier")).isNull();
}
else {
assertThat(getMemberValue(annotationNode, "classifier"))
.isEqualTo(classifier);
assertThat(getMemberValue(annotationNode, "classifier")).isEqualTo(classifier);
}
assertThat(getMemberValue(annotationNode, "transitive")).isEqualTo(transitive);
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2016 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -40,8 +40,7 @@ public class ExtendedGroovyClassLoaderTests {
@Before
public void setup() {
this.contextClassLoader = Thread.currentThread().getContextClassLoader();
this.defaultScopeGroovyClassLoader = new ExtendedGroovyClassLoader(
GroovyCompilerScope.DEFAULT);
this.defaultScopeGroovyClassLoader = new ExtendedGroovyClassLoader(GroovyCompilerScope.DEFAULT);
}
@Test
@@ -55,8 +54,7 @@ public class ExtendedGroovyClassLoaderTests {
public void filtersNonGroovy() throws Exception {
this.contextClassLoader.loadClass("org.springframework.util.StringUtils");
this.thrown.expect(ClassNotFoundException.class);
this.defaultScopeGroovyClassLoader
.loadClass("org.springframework.util.StringUtils");
this.defaultScopeGroovyClassLoader.loadClass("org.springframework.util.StringUtils");
}
@Test

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2016 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -45,8 +45,7 @@ import static org.assertj.core.api.Assertions.assertThat;
*/
public final class GenericBomAstTransformationTests {
private final SourceUnit sourceUnit = new SourceUnit((String) null,
(ReaderSource) null, null, null, null);
private final SourceUnit sourceUnit = new SourceUnit((String) null, (ReaderSource) null, null, null, null);
private final ModuleNode moduleNode = new ModuleNode(this.sourceUnit);
@@ -83,13 +82,11 @@ public final class GenericBomAstTransformationTests {
this.moduleNode.setPackage(new PackageNode("foo"));
ClassNode cls = ClassHelper.make("MyClass");
this.moduleNode.addClass(cls);
AnnotationNode annotation = new AnnotationNode(
ClassHelper.make(DependencyManagementBom.class));
AnnotationNode annotation = new AnnotationNode(ClassHelper.make(DependencyManagementBom.class));
annotation.addMember("value", new ConstantExpression("test:parent:1.0.0"));
cls.addAnnotation(annotation);
this.transformation.visit(new ASTNode[] { this.moduleNode }, this.sourceUnit);
assertThat(getValue().toString())
.isEqualTo("[test:parent:1.0.0, test:child:1.0.0]");
assertThat(getValue().toString()).isEqualTo("[test:parent:1.0.0, test:child:1.0.0]");
}
private List<String> getValue() {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2016 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -41,8 +41,8 @@ public class RepositoryConfigurationFactoryTests {
public void run() {
List<RepositoryConfiguration> repositoryConfiguration = RepositoryConfigurationFactory
.createDefaultRepositoryConfiguration();
assertRepositoryConfiguration(repositoryConfiguration, "central", "local",
"spring-snapshot", "spring-milestone");
assertRepositoryConfiguration(repositoryConfiguration, "central", "local", "spring-snapshot",
"spring-milestone");
}
}, "user.home:src/test/resources/maven-settings/basic");
}
@@ -54,11 +54,9 @@ public class RepositoryConfigurationFactoryTests {
public void run() {
List<RepositoryConfiguration> repositoryConfiguration = RepositoryConfigurationFactory
.createDefaultRepositoryConfiguration();
assertRepositoryConfiguration(repositoryConfiguration, "central",
"local");
assertRepositoryConfiguration(repositoryConfiguration, "central", "local");
}
}, "user.home:src/test/resources/maven-settings/basic",
"disableSpringSnapshotRepos:true");
}, "user.home:src/test/resources/maven-settings/basic", "disableSpringSnapshotRepos:true");
}
@Test
@@ -68,8 +66,8 @@ public class RepositoryConfigurationFactoryTests {
public void run() {
List<RepositoryConfiguration> repositoryConfiguration = RepositoryConfigurationFactory
.createDefaultRepositoryConfiguration();
assertRepositoryConfiguration(repositoryConfiguration, "central", "local",
"spring-snapshot", "spring-milestone", "active-by-default");
assertRepositoryConfiguration(repositoryConfiguration, "central", "local", "spring-snapshot",
"spring-milestone", "active-by-default");
}
}, "user.home:src/test/resources/maven-settings/active-profile-repositories");
}
@@ -81,11 +79,10 @@ public class RepositoryConfigurationFactoryTests {
public void run() {
List<RepositoryConfiguration> repositoryConfiguration = RepositoryConfigurationFactory
.createDefaultRepositoryConfiguration();
assertRepositoryConfiguration(repositoryConfiguration, "central", "local",
"spring-snapshot", "spring-milestone", "active-by-property");
assertRepositoryConfiguration(repositoryConfiguration, "central", "local", "spring-snapshot",
"spring-milestone", "active-by-property");
}
}, "user.home:src/test/resources/maven-settings/active-profile-repositories",
"foo:bar");
}, "user.home:src/test/resources/maven-settings/active-profile-repositories", "foo:bar");
}
@Test
@@ -95,16 +92,13 @@ public class RepositoryConfigurationFactoryTests {
public void run() {
List<RepositoryConfiguration> repositoryConfiguration = RepositoryConfigurationFactory
.createDefaultRepositoryConfiguration();
assertRepositoryConfiguration(repositoryConfiguration, "central", "local",
"spring-snapshot", "spring-milestone", "interpolate-releases",
"interpolate-snapshots");
assertRepositoryConfiguration(repositoryConfiguration, "central", "local", "spring-snapshot",
"spring-milestone", "interpolate-releases", "interpolate-snapshots");
}
}, "user.home:src/test/resources/maven-settings/active-profile-repositories",
"interpolate:true");
}, "user.home:src/test/resources/maven-settings/active-profile-repositories", "interpolate:true");
}
private void assertRepositoryConfiguration(
List<RepositoryConfiguration> configurations, String... expectedNames) {
private void assertRepositoryConfiguration(List<RepositoryConfiguration> configurations, String... expectedNames) {
assertThat(configurations).hasSize(expectedNames.length);
Set<String> actualNames = new HashSet<String>();
for (RepositoryConfiguration configuration : configurations) {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2016 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -57,15 +57,13 @@ import static org.mockito.Mockito.mock;
*/
public final class ResolveDependencyCoordinatesTransformationTests {
private final SourceUnit sourceUnit = new SourceUnit((String) null,
(ReaderSource) null, null, null, null);
private final SourceUnit sourceUnit = new SourceUnit((String) null, (ReaderSource) null, null, null, null);
private final ModuleNode moduleNode = new ModuleNode(this.sourceUnit);
private final AnnotationNode grabAnnotation = createGrabAnnotation();
private final ArtifactCoordinatesResolver coordinatesResolver = mock(
ArtifactCoordinatesResolver.class);
private final ArtifactCoordinatesResolver coordinatesResolver = mock(ArtifactCoordinatesResolver.class);
private final DependencyResolutionContext resolutionContext = new DependencyResolutionContext() {
@@ -85,8 +83,7 @@ public final class ResolveDependencyCoordinatesTransformationTests {
@Before
public void setupExpectations() {
given(this.coordinatesResolver.getGroupId("spring-core"))
.willReturn("org.springframework");
given(this.coordinatesResolver.getGroupId("spring-core")).willReturn("org.springframework");
}
@Test
@@ -97,24 +94,21 @@ public final class ResolveDependencyCoordinatesTransformationTests {
@Test
public void transformationOfAnnotationOnStarImport() {
this.moduleNode.addStarImport("org.springframework.util",
Arrays.asList(this.grabAnnotation));
this.moduleNode.addStarImport("org.springframework.util", Arrays.asList(this.grabAnnotation));
assertGrabAnnotationHasBeenTransformed();
}
@Test
public void transformationOfAnnotationOnStaticImport() {
this.moduleNode.addStaticImport(null, null, null,
Arrays.asList(this.grabAnnotation));
this.moduleNode.addStaticImport(null, null, null, Arrays.asList(this.grabAnnotation));
assertGrabAnnotationHasBeenTransformed();
}
@Test
public void transformationOfAnnotationOnStaticStarImport() {
this.moduleNode.addStaticStarImport(null, null,
Arrays.asList(this.grabAnnotation));
this.moduleNode.addStaticStarImport(null, null, Arrays.asList(this.grabAnnotation));
assertGrabAnnotationHasBeenTransformed();
}
@@ -146,8 +140,7 @@ public final class ResolveDependencyCoordinatesTransformationTests {
ClassNode classNode = new ClassNode("Test", 0, new ClassNode(Object.class));
this.moduleNode.addClass(classNode);
FieldNode fieldNode = new FieldNode("test", 0, new ClassNode(Object.class),
classNode, null);
FieldNode fieldNode = new FieldNode("test", 0, new ClassNode(Object.class), classNode, null);
classNode.addField(fieldNode);
fieldNode.addAnnotation(this.grabAnnotation);
@@ -172,8 +165,8 @@ public final class ResolveDependencyCoordinatesTransformationTests {
ClassNode classNode = new ClassNode("Test", 0, new ClassNode(Object.class));
this.moduleNode.addClass(classNode);
MethodNode methodNode = new MethodNode("test", 0, new ClassNode(Void.class),
new Parameter[0], new ClassNode[0], null);
MethodNode methodNode = new MethodNode("test", 0, new ClassNode(Void.class), new Parameter[0], new ClassNode[0],
null);
methodNode.addAnnotation(this.grabAnnotation);
classNode.addMethod(methodNode);
@@ -188,8 +181,8 @@ public final class ResolveDependencyCoordinatesTransformationTests {
Parameter parameter = new Parameter(new ClassNode(Object.class), "test");
parameter.addAnnotation(this.grabAnnotation);
MethodNode methodNode = new MethodNode("test", 0, new ClassNode(Void.class),
new Parameter[] { parameter }, new ClassNode[0], null);
MethodNode methodNode = new MethodNode("test", 0, new ClassNode(Void.class), new Parameter[] { parameter },
new ClassNode[0], null);
classNode.addMethod(methodNode);
assertGrabAnnotationHasBeenTransformed();
@@ -200,16 +193,15 @@ public final class ResolveDependencyCoordinatesTransformationTests {
ClassNode classNode = new ClassNode("Test", 0, new ClassNode(Object.class));
this.moduleNode.addClass(classNode);
DeclarationExpression declarationExpression = new DeclarationExpression(
new VariableExpression("test"), null, new ConstantExpression("test"));
DeclarationExpression declarationExpression = new DeclarationExpression(new VariableExpression("test"), null,
new ConstantExpression("test"));
declarationExpression.addAnnotation(this.grabAnnotation);
BlockStatement code = new BlockStatement(
Arrays.asList((Statement) new ExpressionStatement(declarationExpression)),
new VariableScope());
Arrays.asList((Statement) new ExpressionStatement(declarationExpression)), new VariableScope());
MethodNode methodNode = new MethodNode("test", 0, new ClassNode(Void.class),
new Parameter[0], new ClassNode[0], code);
MethodNode methodNode = new MethodNode("test", 0, new ClassNode(Void.class), new Parameter[0], new ClassNode[0],
code);
classNode.addMethod(methodNode);
@@ -225,8 +217,7 @@ public final class ResolveDependencyCoordinatesTransformationTests {
private void assertGrabAnnotationHasBeenTransformed() {
this.transformation.visit(new ASTNode[] { this.moduleNode }, this.sourceUnit);
assertThat(getGrabAnnotationMemberAsString("group"))
.isEqualTo("org.springframework");
assertThat(getGrabAnnotationMemberAsString("group")).isEqualTo("org.springframework");
assertThat(getGrabAnnotationMemberAsString("module")).isEqualTo("spring-core");
}
@@ -239,8 +230,7 @@ public final class ResolveDependencyCoordinatesTransformationTests {
return null;
}
else {
throw new IllegalStateException(
"Member '" + memberName + "' is not a ConstantExpression");
throw new IllegalStateException("Member '" + memberName + "' is not a ConstantExpression");
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2016 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -48,35 +48,32 @@ public class CompositeDependencyManagementTests {
public void unknownSpringBootVersion() {
given(this.dependencyManagement1.getSpringBootVersion()).willReturn(null);
given(this.dependencyManagement2.getSpringBootVersion()).willReturn(null);
assertThat(new CompositeDependencyManagement(this.dependencyManagement1,
this.dependencyManagement2).getSpringBootVersion()).isNull();
assertThat(new CompositeDependencyManagement(this.dependencyManagement1, this.dependencyManagement2)
.getSpringBootVersion()).isNull();
}
@Test
public void knownSpringBootVersion() {
given(this.dependencyManagement1.getSpringBootVersion()).willReturn("1.2.3");
given(this.dependencyManagement2.getSpringBootVersion()).willReturn("1.2.4");
assertThat(new CompositeDependencyManagement(this.dependencyManagement1,
this.dependencyManagement2).getSpringBootVersion()).isEqualTo("1.2.3");
assertThat(new CompositeDependencyManagement(this.dependencyManagement1, this.dependencyManagement2)
.getSpringBootVersion()).isEqualTo("1.2.3");
}
@Test
public void unknownDependency() {
given(this.dependencyManagement1.find("artifact")).willReturn(null);
given(this.dependencyManagement2.find("artifact")).willReturn(null);
assertThat(new CompositeDependencyManagement(this.dependencyManagement1,
this.dependencyManagement2).find("artifact")).isNull();
assertThat(new CompositeDependencyManagement(this.dependencyManagement1, this.dependencyManagement2)
.find("artifact")).isNull();
}
@Test
public void knownDependency() {
given(this.dependencyManagement1.find("artifact"))
.willReturn(new Dependency("test", "artifact", "1.2.3"));
given(this.dependencyManagement2.find("artifact"))
.willReturn(new Dependency("test", "artifact", "1.2.4"));
assertThat(new CompositeDependencyManagement(this.dependencyManagement1,
this.dependencyManagement2).find("artifact"))
.isEqualTo(new Dependency("test", "artifact", "1.2.3"));
given(this.dependencyManagement1.find("artifact")).willReturn(new Dependency("test", "artifact", "1.2.3"));
given(this.dependencyManagement2.find("artifact")).willReturn(new Dependency("test", "artifact", "1.2.4"));
assertThat(new CompositeDependencyManagement(this.dependencyManagement1, this.dependencyManagement2)
.find("artifact")).isEqualTo(new Dependency("test", "artifact", "1.2.3"));
}
@Test
@@ -85,9 +82,8 @@ public class CompositeDependencyManagementTests {
.willReturn(Arrays.asList(new Dependency("test", "artifact", "1.2.3")));
given(this.dependencyManagement2.getDependencies())
.willReturn(Arrays.asList(new Dependency("test", "artifact", "1.2.4")));
assertThat(new CompositeDependencyManagement(this.dependencyManagement1,
this.dependencyManagement2).getDependencies()).containsOnly(
new Dependency("test", "artifact", "1.2.3"),
assertThat(new CompositeDependencyManagement(this.dependencyManagement1, this.dependencyManagement2)
.getDependencies()).containsOnly(new Dependency("test", "artifact", "1.2.3"),
new Dependency("test", "artifact", "1.2.4"));
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2016 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -41,17 +41,14 @@ public class DependencyManagementArtifactCoordinatesResolverTests {
@Before
public void setup() {
this.dependencyManagement = mock(DependencyManagement.class);
given(this.dependencyManagement.find("a1"))
.willReturn(new Dependency("g1", "a1", "0"));
given(this.dependencyManagement.find("a1")).willReturn(new Dependency("g1", "a1", "0"));
given(this.dependencyManagement.getSpringBootVersion()).willReturn("1");
this.resolver = new DependencyManagementArtifactCoordinatesResolver(
this.dependencyManagement);
this.resolver = new DependencyManagementArtifactCoordinatesResolver(this.dependencyManagement);
}
@Test
public void getGroupIdForBootArtifact() throws Exception {
assertThat(this.resolver.getGroupId("spring-boot-something"))
.isEqualTo("org.springframework.boot");
assertThat(this.resolver.getGroupId("spring-boot-something")).isEqualTo("org.springframework.boot");
verify(this.dependencyManagement, never()).find(anyString());
}

View File

@@ -46,20 +46,18 @@ public class AetherGrapeEngineTests {
private final GroovyClassLoader groovyClassLoader = new GroovyClassLoader();
private final RepositoryConfiguration springMilestones = new RepositoryConfiguration(
"spring-milestones", URI.create("https://repo.spring.io/milestone"), false);
private final RepositoryConfiguration springMilestones = new RepositoryConfiguration("spring-milestones",
URI.create("https://repo.spring.io/milestone"), false);
private AetherGrapeEngine createGrapeEngine(
RepositoryConfiguration... additionalRepositories) {
private AetherGrapeEngine createGrapeEngine(RepositoryConfiguration... additionalRepositories) {
List<RepositoryConfiguration> repositoryConfigurations = new ArrayList<RepositoryConfiguration>();
repositoryConfigurations.add(new RepositoryConfiguration("central",
URI.create("https://repo1.maven.org/maven2"), false));
repositoryConfigurations
.add(new RepositoryConfiguration("central", URI.create("https://repo1.maven.org/maven2"), false));
repositoryConfigurations.addAll(Arrays.asList(additionalRepositories));
DependencyResolutionContext dependencyResolutionContext = new DependencyResolutionContext();
dependencyResolutionContext.addDependencyManagement(
new SpringBootDependenciesDependencyManagement());
return AetherGrapeEngineFactory.create(this.groovyClassLoader,
repositoryConfigurations, dependencyResolutionContext, false);
dependencyResolutionContext.addDependencyManagement(new SpringBootDependenciesDependencyManagement());
return AetherGrapeEngineFactory.create(this.groovyClassLoader, repositoryConfigurations,
dependencyResolutionContext, false);
}
@Test
@@ -81,8 +79,7 @@ public class AetherGrapeEngineTests {
DefaultRepositorySystemSession session = (DefaultRepositorySystemSession) ReflectionTestUtils
.getField(grapeEngine, "session");
assertThat(session.getProxySelector() instanceof CompositeProxySelector)
.isTrue();
assertThat(session.getProxySelector() instanceof CompositeProxySelector).isTrue();
}
});
@@ -97,8 +94,8 @@ public class AetherGrapeEngineTests {
public void run() {
AetherGrapeEngine grapeEngine = createGrapeEngine();
List<RemoteRepository> repositories = (List<RemoteRepository>) ReflectionTestUtils
.getField(grapeEngine, "repositories");
List<RemoteRepository> repositories = (List<RemoteRepository>) ReflectionTestUtils.getField(grapeEngine,
"repositories");
assertThat(repositories).hasSize(1);
assertThat(repositories.get(0).getId()).isEqualTo("central-mirror");
}
@@ -114,8 +111,8 @@ public class AetherGrapeEngineTests {
public void run() {
AetherGrapeEngine grapeEngine = createGrapeEngine();
List<RemoteRepository> repositories = (List<RemoteRepository>) ReflectionTestUtils
.getField(grapeEngine, "repositories");
List<RemoteRepository> repositories = (List<RemoteRepository>) ReflectionTestUtils.getField(grapeEngine,
"repositories");
assertThat(repositories).hasSize(1);
Authentication authentication = repositories.get(0).getAuthentication();
assertThat(authentication).isNotNull();
@@ -126,8 +123,7 @@ public class AetherGrapeEngineTests {
@Test
public void dependencyResolutionWithExclusions() {
Map<String, Object> args = new HashMap<String, Object>();
args.put("excludes",
Arrays.asList(createExclusion("org.springframework", "spring-core")));
args.put("excludes", Arrays.asList(createExclusion("org.springframework", "spring-core")));
createGrapeEngine(this.springMilestones).grab(args,
createDependency("org.springframework", "spring-jdbc", "3.2.4.RELEASE"),
@@ -140,8 +136,7 @@ public class AetherGrapeEngineTests {
public void nonTransitiveDependencyResolution() {
Map<String, Object> args = new HashMap<String, Object>();
createGrapeEngine().grab(args, createDependency("org.springframework",
"spring-jdbc", "3.2.4.RELEASE", false));
createGrapeEngine().grab(args, createDependency("org.springframework", "spring-jdbc", "3.2.4.RELEASE", false));
assertThat(this.groovyClassLoader.getURLs().length).isEqualTo(1);
}
@@ -163,16 +158,14 @@ public class AetherGrapeEngineTests {
public void resolutionWithCustomResolver() {
Map<String, Object> args = new HashMap<String, Object>();
AetherGrapeEngine grapeEngine = this.createGrapeEngine();
grapeEngine
.addResolver(createResolver("restlet.org", "https://maven.restlet.org"));
grapeEngine.addResolver(createResolver("restlet.org", "https://maven.restlet.org"));
grapeEngine.grab(args, createDependency("org.restlet", "org.restlet", "1.1.6"));
assertThat(this.groovyClassLoader.getURLs().length).isEqualTo(1);
}
@Test(expected = IllegalArgumentException.class)
public void differingTypeAndExt() {
Map<String, Object> dependency = createDependency("org.grails",
"grails-dependencies", "2.4.0");
Map<String, Object> dependency = createDependency("org.grails", "grails-dependencies", "2.4.0");
dependency.put("type", "foo");
dependency.put("ext", "bar");
createGrapeEngine().grab(Collections.emptyMap(), dependency);
@@ -181,8 +174,8 @@ public class AetherGrapeEngineTests {
@Test
public void pomDependencyResolutionViaType() {
Map<String, Object> args = new HashMap<String, Object>();
Map<String, Object> dependency = createDependency("org.springframework",
"spring-framework-bom", "4.0.5.RELEASE");
Map<String, Object> dependency = createDependency("org.springframework", "spring-framework-bom",
"4.0.5.RELEASE");
dependency.put("type", "pom");
createGrapeEngine().grab(args, dependency);
URL[] urls = this.groovyClassLoader.getURLs();
@@ -193,8 +186,8 @@ public class AetherGrapeEngineTests {
@Test
public void pomDependencyResolutionViaExt() {
Map<String, Object> args = new HashMap<String, Object>();
Map<String, Object> dependency = createDependency("org.springframework",
"spring-framework-bom", "4.0.5.RELEASE");
Map<String, Object> dependency = createDependency("org.springframework", "spring-framework-bom",
"4.0.5.RELEASE");
dependency.put("ext", "pom");
createGrapeEngine().grab(args, dependency);
URL[] urls = this.groovyClassLoader.getURLs();
@@ -206,8 +199,7 @@ public class AetherGrapeEngineTests {
public void resolutionWithClassifier() {
Map<String, Object> args = new HashMap<String, Object>();
Map<String, Object> dependency = createDependency("org.springframework",
"spring-jdbc", "3.2.4.RELEASE", false);
Map<String, Object> dependency = createDependency("org.springframework", "spring-jdbc", "3.2.4.RELEASE", false);
dependency.put("classifier", "sources");
createGrapeEngine().grab(args, dependency);
@@ -216,8 +208,7 @@ public class AetherGrapeEngineTests {
assertThat(urls[0].toExternalForm().endsWith("-sources.jar")).isTrue();
}
private Map<String, Object> createDependency(String group, String module,
String version) {
private Map<String, Object> createDependency(String group, String module, String version) {
Map<String, Object> dependency = new HashMap<String, Object>();
dependency.put("group", group);
dependency.put("module", module);
@@ -225,8 +216,7 @@ public class AetherGrapeEngineTests {
return dependency;
}
private Map<String, Object> createDependency(String group, String module,
String version, boolean transitive) {
private Map<String, Object> createDependency(String group, String module, String version, boolean transitive) {
Map<String, Object> dependency = createDependency(group, module, version);
dependency.put("transitive", transitive);
return dependency;
@@ -247,8 +237,7 @@ public class AetherGrapeEngineTests {
}
private void doWithCustomUserHome(Runnable action) {
doWithSystemProperty("user.home",
new File("src/test/resources").getAbsolutePath(), action);
doWithSystemProperty("user.home", new File("src/test/resources").getAbsolutePath(), action);
}
private void doWithSystemProperty(String key, String value, Runnable action) {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2016 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -36,8 +36,7 @@ public class DependencyResolutionContextTests {
@Test
public void canAddSpringBootDependencies() {
DependencyResolutionContext dependencyResolutionContext = new DependencyResolutionContext();
dependencyResolutionContext.addDependencyManagement(
new SpringBootDependenciesDependencyManagement());
dependencyResolutionContext.addDependencyManagement(new SpringBootDependenciesDependencyManagement());
assertThat(dependencyResolutionContext.getManagedDependencies()).isNotEmpty();
}

View File

@@ -39,8 +39,7 @@ public final class DetailedProgressReporterTests {
private static final String ARTIFACT = "org/alpha/bravo/charlie/1.2.3/charlie-1.2.3.jar";
private final TransferResource resource = new TransferResource(REPOSITORY, ARTIFACT,
null, null);
private final TransferResource resource = new TransferResource(REPOSITORY, ARTIFACT, null, null);
private final ByteArrayOutputStream baos = new ByteArrayOutputStream();
@@ -55,8 +54,7 @@ public final class DetailedProgressReporterTests {
@Test
public void downloading() throws TransferCancelledException {
TransferEvent startedEvent = new TransferEvent.Builder(this.session,
this.resource).build();
TransferEvent startedEvent = new TransferEvent.Builder(this.session, this.resource).build();
this.session.getTransferListener().transferStarted(startedEvent);
assertThat(new String(this.baos.toByteArray()))
.isEqualTo(String.format("Downloading: %s%s%n", REPOSITORY, ARTIFACT));
@@ -66,8 +64,8 @@ public final class DetailedProgressReporterTests {
public void downloaded() throws InterruptedException {
// Ensure some transfer time
Thread.sleep(100);
TransferEvent completedEvent = new TransferEvent.Builder(this.session,
this.resource).addTransferredBytes(4096).build();
TransferEvent completedEvent = new TransferEvent.Builder(this.session, this.resource).addTransferredBytes(4096)
.build();
this.session.getTransferListener().transferSucceeded(completedEvent);
String message = new String(this.baos.toByteArray()).replace("\\", "/");
assertThat(message).startsWith("Downloaded: " + REPOSITORY + ARTIFACT);

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2016 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -45,8 +45,7 @@ import static org.mockito.Mockito.verify;
*/
public class GrapeRootRepositorySystemSessionAutoConfigurationTests {
private DefaultRepositorySystemSession session = MavenRepositorySystemUtils
.newSession();
private DefaultRepositorySystemSession session = MavenRepositorySystemUtils.newSession();
@Mock
private RepositorySystem repositorySystem;
@@ -58,46 +57,36 @@ public class GrapeRootRepositorySystemSessionAutoConfigurationTests {
@Test
public void noLocalRepositoryWhenNoGrapeRoot() {
given(this.repositorySystem.newLocalRepositoryManager(eq(this.session),
any(LocalRepository.class)))
.willAnswer(new Answer<LocalRepositoryManager>() {
given(this.repositorySystem.newLocalRepositoryManager(eq(this.session), any(LocalRepository.class)))
.willAnswer(new Answer<LocalRepositoryManager>() {
@Override
public LocalRepositoryManager answer(
InvocationOnMock invocation) throws Throwable {
LocalRepository localRepository = invocation
.getArgumentAt(1, LocalRepository.class);
return new SimpleLocalRepositoryManagerFactory()
.newInstance(
GrapeRootRepositorySystemSessionAutoConfigurationTests.this.session,
localRepository);
}
@Override
public LocalRepositoryManager answer(InvocationOnMock invocation) throws Throwable {
LocalRepository localRepository = invocation.getArgumentAt(1, LocalRepository.class);
return new SimpleLocalRepositoryManagerFactory().newInstance(
GrapeRootRepositorySystemSessionAutoConfigurationTests.this.session, localRepository);
}
});
new GrapeRootRepositorySystemSessionAutoConfiguration().apply(this.session,
this.repositorySystem);
verify(this.repositorySystem, times(0))
.newLocalRepositoryManager(eq(this.session), any(LocalRepository.class));
});
new GrapeRootRepositorySystemSessionAutoConfiguration().apply(this.session, this.repositorySystem);
verify(this.repositorySystem, times(0)).newLocalRepositoryManager(eq(this.session), any(LocalRepository.class));
assertThat(this.session.getLocalRepository()).isNull();
}
@Test
public void grapeRootConfiguresLocalRepositoryLocation() {
given(this.repositorySystem.newLocalRepositoryManager(eq(this.session),
any(LocalRepository.class)))
.willAnswer(new LocalRepositoryManagerAnswer());
given(this.repositorySystem.newLocalRepositoryManager(eq(this.session), any(LocalRepository.class)))
.willAnswer(new LocalRepositoryManagerAnswer());
System.setProperty("grape.root", "foo");
try {
new GrapeRootRepositorySystemSessionAutoConfiguration().apply(this.session,
this.repositorySystem);
new GrapeRootRepositorySystemSessionAutoConfiguration().apply(this.session, this.repositorySystem);
}
finally {
System.clearProperty("grape.root");
}
verify(this.repositorySystem, times(1))
.newLocalRepositoryManager(eq(this.session), any(LocalRepository.class));
verify(this.repositorySystem, times(1)).newLocalRepositoryManager(eq(this.session), any(LocalRepository.class));
assertThat(this.session.getLocalRepository()).isNotNull();
assertThat(this.session.getLocalRepository().getBasedir().getAbsolutePath())
@@ -107,13 +96,10 @@ public class GrapeRootRepositorySystemSessionAutoConfigurationTests {
private class LocalRepositoryManagerAnswer implements Answer<LocalRepositoryManager> {
@Override
public LocalRepositoryManager answer(InvocationOnMock invocation)
throws Throwable {
LocalRepository localRepository = invocation.getArgumentAt(1,
LocalRepository.class);
return new SimpleLocalRepositoryManagerFactory().newInstance(
GrapeRootRepositorySystemSessionAutoConfigurationTests.this.session,
localRepository);
public LocalRepositoryManager answer(InvocationOnMock invocation) throws Throwable {
LocalRepository localRepository = invocation.getArgumentAt(1, LocalRepository.class);
return new SimpleLocalRepositoryManagerFactory()
.newInstance(GrapeRootRepositorySystemSessionAutoConfigurationTests.this.session, localRepository);
}
}

View File

@@ -75,21 +75,16 @@ public class SettingsXmlRepositorySystemSessionAutoConfigurationTests {
@Test
public void propertyInterpolation() throws SettingsBuildingException {
final DefaultRepositorySystemSession session = MavenRepositorySystemUtils
.newSession();
given(this.repositorySystem.newLocalRepositoryManager(eq(session),
any(LocalRepository.class)))
.willAnswer(new Answer<LocalRepositoryManager>() {
final DefaultRepositorySystemSession session = MavenRepositorySystemUtils.newSession();
given(this.repositorySystem.newLocalRepositoryManager(eq(session), any(LocalRepository.class)))
.willAnswer(new Answer<LocalRepositoryManager>() {
@Override
public LocalRepositoryManager answer(
InvocationOnMock invocation) throws Throwable {
LocalRepository localRepository = invocation
.getArgumentAt(1, LocalRepository.class);
return new SimpleLocalRepositoryManagerFactory()
.newInstance(session, localRepository);
}
});
@Override
public LocalRepositoryManager answer(InvocationOnMock invocation) throws Throwable {
LocalRepository localRepository = invocation.getArgumentAt(1, LocalRepository.class);
return new SimpleLocalRepositoryManagerFactory().newInstance(session, localRepository);
}
});
SystemProperties.doWithSystemProperties(new Runnable() {
@Override
@@ -97,16 +92,14 @@ public class SettingsXmlRepositorySystemSessionAutoConfigurationTests {
new SettingsXmlRepositorySystemSessionAutoConfiguration().apply(session,
SettingsXmlRepositorySystemSessionAutoConfigurationTests.this.repositorySystem);
}
}, "user.home:src/test/resources/maven-settings/property-interpolation",
"foo:bar");
}, "user.home:src/test/resources/maven-settings/property-interpolation", "foo:bar");
assertThat(session.getLocalRepository().getBasedir().getAbsolutePath())
.endsWith(File.separatorChar + "bar" + File.separatorChar + "repository");
}
private void assertSessionCustomization(String userHome) {
final DefaultRepositorySystemSession session = MavenRepositorySystemUtils
.newSession();
final DefaultRepositorySystemSession session = MavenRepositorySystemUtils.newSession();
SystemProperties.doWithSystemProperties(new Runnable() {
@Override
public void run() {
@@ -115,46 +108,36 @@ public class SettingsXmlRepositorySystemSessionAutoConfigurationTests {
}
}, "user.home:" + userHome);
RemoteRepository repository = new RemoteRepository.Builder("my-server", "default",
"https://maven.example.com").build();
RemoteRepository repository = new RemoteRepository.Builder("my-server", "default", "https://maven.example.com")
.build();
assertMirrorSelectorConfiguration(session, repository);
assertProxySelectorConfiguration(session, repository);
assertAuthenticationSelectorConfiguration(session, repository);
}
private void assertProxySelectorConfiguration(DefaultRepositorySystemSession session,
RemoteRepository repository) {
private void assertProxySelectorConfiguration(DefaultRepositorySystemSession session, RemoteRepository repository) {
Proxy proxy = session.getProxySelector().getProxy(repository);
repository = new RemoteRepository.Builder(repository).setProxy(proxy).build();
AuthenticationContext authenticationContext = AuthenticationContext
.forProxy(session, repository);
AuthenticationContext authenticationContext = AuthenticationContext.forProxy(session, repository);
assertThat(proxy.getHost()).isEqualTo("proxy.example.com");
assertThat(authenticationContext.get(AuthenticationContext.USERNAME))
.isEqualTo("proxyuser");
assertThat(authenticationContext.get(AuthenticationContext.PASSWORD))
.isEqualTo("somepassword");
assertThat(authenticationContext.get(AuthenticationContext.USERNAME)).isEqualTo("proxyuser");
assertThat(authenticationContext.get(AuthenticationContext.PASSWORD)).isEqualTo("somepassword");
}
private void assertMirrorSelectorConfiguration(DefaultRepositorySystemSession session,
RemoteRepository repository) {
RemoteRepository mirror = session.getMirrorSelector().getMirror(repository);
assertThat(mirror).as("Mirror configured for repository " + repository.getId())
.isNotNull();
assertThat(mirror).as("Mirror configured for repository " + repository.getId()).isNotNull();
assertThat(mirror.getHost()).isEqualTo("maven.example.com");
}
private void assertAuthenticationSelectorConfiguration(
DefaultRepositorySystemSession session, RemoteRepository repository) {
Authentication authentication = session.getAuthenticationSelector()
.getAuthentication(repository);
repository = new RemoteRepository.Builder(repository)
.setAuthentication(authentication).build();
AuthenticationContext authenticationContext = AuthenticationContext
.forRepository(session, repository);
assertThat(authenticationContext.get(AuthenticationContext.USERNAME))
.isEqualTo("tester");
assertThat(authenticationContext.get(AuthenticationContext.PASSWORD))
.isEqualTo("secret");
private void assertAuthenticationSelectorConfiguration(DefaultRepositorySystemSession session,
RemoteRepository repository) {
Authentication authentication = session.getAuthenticationSelector().getAuthentication(repository);
repository = new RemoteRepository.Builder(repository).setAuthentication(authentication).build();
AuthenticationContext authenticationContext = AuthenticationContext.forRepository(session, repository);
assertThat(authenticationContext.get(AuthenticationContext.USERNAME)).isEqualTo("tester");
assertThat(authenticationContext.get(AuthenticationContext.PASSWORD)).isEqualTo("secret");
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2016 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -37,8 +37,7 @@ public final class SystemProperties {
* @param systemPropertyPairs The system properties, each in the form
* {@code key:value}
*/
public static void doWithSystemProperties(Runnable action,
String... systemPropertyPairs) {
public static void doWithSystemProperties(Runnable action, String... systemPropertyPairs) {
Map<String, String> originalValues = new HashMap<String, String>();
for (String pair : systemPropertyPairs) {
String[] components = pair.split(":");

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2016 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -36,16 +36,14 @@ public class ResourceUtilsTests {
@Test
public void explicitClasspathResource() {
List<String> urls = ResourceUtils.getUrls("classpath:init.groovy",
ClassUtils.getDefaultClassLoader());
List<String> urls = ResourceUtils.getUrls("classpath:init.groovy", ClassUtils.getDefaultClassLoader());
assertThat(urls).hasSize(1);
assertThat(urls.get(0).startsWith("file:")).isTrue();
}
@Test
public void duplicateResource() throws Exception {
URLClassLoader loader = new URLClassLoader(new URL[] {
new URL("file:./src/test/resources/"),
URLClassLoader loader = new URLClassLoader(new URL[] { new URL("file:./src/test/resources/"),
new File("src/test/resources/").getAbsoluteFile().toURI().toURL() });
List<String> urls = ResourceUtils.getUrls("classpath:init.groovy", loader);
assertThat(urls).hasSize(1);
@@ -54,24 +52,21 @@ public class ResourceUtilsTests {
@Test
public void explicitClasspathResourceWithSlash() {
List<String> urls = ResourceUtils.getUrls("classpath:/init.groovy",
ClassUtils.getDefaultClassLoader());
List<String> urls = ResourceUtils.getUrls("classpath:/init.groovy", ClassUtils.getDefaultClassLoader());
assertThat(urls).hasSize(1);
assertThat(urls.get(0).startsWith("file:")).isTrue();
}
@Test
public void implicitClasspathResource() {
List<String> urls = ResourceUtils.getUrls("init.groovy",
ClassUtils.getDefaultClassLoader());
List<String> urls = ResourceUtils.getUrls("init.groovy", ClassUtils.getDefaultClassLoader());
assertThat(urls).hasSize(1);
assertThat(urls.get(0).startsWith("file:")).isTrue();
}
@Test
public void implicitClasspathResourceWithSlash() {
List<String> urls = ResourceUtils.getUrls("/init.groovy",
ClassUtils.getDefaultClassLoader());
List<String> urls = ResourceUtils.getUrls("/init.groovy", ClassUtils.getDefaultClassLoader());
assertThat(urls).hasSize(1);
assertThat(urls.get(0).startsWith("file:")).isTrue();
}
@@ -92,8 +87,7 @@ public class ResourceUtilsTests {
@Test
public void implicitFile() {
List<String> urls = ResourceUtils.getUrls("src/test/resources/init.groovy",
ClassUtils.getDefaultClassLoader());
List<String> urls = ResourceUtils.getUrls("src/test/resources/init.groovy", ClassUtils.getDefaultClassLoader());
assertThat(urls).hasSize(1);
assertThat(urls.get(0).startsWith("file:")).isTrue();
}
@@ -106,16 +100,14 @@ public class ResourceUtilsTests {
@Test
public void recursiveFiles() {
List<String> urls = ResourceUtils.getUrls("src/test/resources/dir-sample",
ClassUtils.getDefaultClassLoader());
List<String> urls = ResourceUtils.getUrls("src/test/resources/dir-sample", ClassUtils.getDefaultClassLoader());
assertThat(urls).hasSize(1);
assertThat(urls.get(0).startsWith("file:")).isTrue();
}
@Test
public void recursiveFilesByPatternWithPrefix() {
List<String> urls = ResourceUtils.getUrls(
"file:src/test/resources/dir-sample/**/*.groovy",
List<String> urls = ResourceUtils.getUrls("file:src/test/resources/dir-sample/**/*.groovy",
ClassUtils.getDefaultClassLoader());
assertThat(urls).hasSize(1);
assertThat(urls.get(0).startsWith("file:")).isTrue();
@@ -123,8 +115,7 @@ public class ResourceUtilsTests {
@Test
public void recursiveFilesByPattern() {
List<String> urls = ResourceUtils.getUrls(
"src/test/resources/dir-sample/**/*.groovy",
List<String> urls = ResourceUtils.getUrls("src/test/resources/dir-sample/**/*.groovy",
ClassUtils.getDefaultClassLoader());
assertThat(urls).hasSize(1);
assertThat(urls.get(0).startsWith("file:")).isTrue();
@@ -132,8 +123,7 @@ public class ResourceUtilsTests {
@Test
public void directoryOfFilesWithPrefix() {
List<String> urls = ResourceUtils.getUrls(
"file:src/test/resources/dir-sample/code/*",
List<String> urls = ResourceUtils.getUrls("file:src/test/resources/dir-sample/code/*",
ClassUtils.getDefaultClassLoader());
assertThat(urls).hasSize(1);
assertThat(urls.get(0).startsWith("file:")).isTrue();