Remove rarely used commands from the CLI

Closes gh-32263
This commit is contained in:
Andy Wilkinson
2022-09-08 20:49:03 +01:00
parent e112657e1a
commit 0555dda63d
170 changed files with 68 additions and 12335 deletions

View File

@@ -1,50 +0,0 @@
/*
* 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.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.cli;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.springframework.boot.test.system.CapturedOutput;
import org.springframework.boot.test.system.OutputCaptureExtension;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for CLI Classloader issues.
*
* @author Phillip Webb
*/
@ExtendWith(OutputCaptureExtension.class)
class ClassLoaderIntegrationTests {
@RegisterExtension
CliTester cli;
ClassLoaderIntegrationTests(CapturedOutput output) {
this.cli = new CliTester("src/test/resources/", output);
}
@Test
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());
assertThat(output).contains("HasClasses-false-true-false");
}
}

View File

@@ -1,211 +0,0 @@
/*
* Copyright 2012-2022 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.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.cli;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.extension.AfterEachCallback;
import org.junit.jupiter.api.extension.BeforeEachCallback;
import org.junit.jupiter.api.extension.Extension;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.springframework.boot.cli.command.AbstractCommand;
import org.springframework.boot.cli.command.OptionParsingCommand;
import org.springframework.boot.cli.command.archive.JarCommand;
import org.springframework.boot.cli.command.grab.GrabCommand;
import org.springframework.boot.cli.command.run.RunCommand;
import org.springframework.boot.test.system.CapturedOutput;
import org.springframework.boot.testsupport.BuildOutput;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.FileSystemUtils;
import org.springframework.util.StringUtils;
/**
* JUnit 5 {@link Extension} that can be used to invoke CLI commands.
*
* @author Phillip Webb
* @author Dave Syer
* @author Andy Wilkinson
*/
public class CliTester implements BeforeEachCallback, AfterEachCallback {
private final File temp;
private final BuildOutput buildOutput = new BuildOutput(getClass());
private final CapturedOutput output;
private String previousOutput = "";
private long timeout = TimeUnit.MINUTES.toMillis(6);
private final List<AbstractCommand> commands = new ArrayList<>();
private final String prefix;
private File serverPortFile;
public CliTester(String prefix, CapturedOutput output) {
this.prefix = prefix;
try {
this.temp = Files.createTempDirectory("cli-tester").toFile();
}
catch (IOException ex) {
throw new IllegalStateException("Failed to create temp directory");
}
this.output = output;
}
public void setTimeout(long timeout) {
this.timeout = timeout;
}
public String run(String... args) throws Exception {
List<String> updatedArgs = new ArrayList<>();
boolean classpathUpdated = false;
for (String arg : args) {
if (arg.startsWith("--classpath=")) {
arg = arg + ":" + this.buildOutput.getTestClassesLocation().getAbsolutePath();
arg = arg + ":" + this.buildOutput.getTestResourcesLocation().getAbsolutePath();
classpathUpdated = true;
}
updatedArgs.add(arg);
}
if (!classpathUpdated) {
updatedArgs.add("--classpath=.:" + this.buildOutput.getTestClassesLocation().getAbsolutePath() + ":"
+ this.buildOutput.getTestResourcesLocation().getAbsolutePath());
}
Future<RunCommand> future = submitCommand(new RunCommand(), StringUtils.toStringArray(updatedArgs));
this.commands.add(future.get(this.timeout, TimeUnit.MILLISECONDS));
return getOutput();
}
public String grab(String... args) throws Exception {
Future<GrabCommand> future = submitCommand(new GrabCommand(), args);
this.commands.add(future.get(this.timeout, TimeUnit.MILLISECONDS));
return getOutput();
}
public String jar(String... args) throws Exception {
Future<JarCommand> future = submitCommand(new JarCommand(), args);
this.commands.add(future.get(this.timeout, TimeUnit.MILLISECONDS));
return getOutput();
}
public File getTemp() {
return this.temp;
}
private <T extends OptionParsingCommand> Future<T> submitCommand(T command, String... args) {
final String[] sources = getSources(args);
return Executors.newSingleThreadExecutor().submit(() -> {
ClassLoader loader = Thread.currentThread().getContextClassLoader();
System.setProperty("server.port", "0");
System.setProperty("spring.application.class.name",
"org.springframework.boot.cli.CliTesterSpringApplication");
this.serverPortFile = new File(this.temp, "server.port");
System.setProperty("portfile", this.serverPortFile.getAbsolutePath());
String userHome = System.getProperty("user.home");
System.setProperty("user.home", "src/test/resources/cli-tester");
try {
command.run(sources);
return command;
}
finally {
System.clearProperty("server.port");
System.clearProperty("spring.application.class.name");
System.clearProperty("portfile");
System.setProperty("user.home", userHome);
Thread.currentThread().setContextClassLoader(loader);
}
});
}
protected String[] getSources(String... args) {
final String[] sources = new String[args.length];
for (int i = 0; i < args.length; i++) {
String arg = args[i];
if (!arg.endsWith(".groovy") && !arg.endsWith(".xml")) {
if (new File(this.prefix + arg).isDirectory()) {
sources[i] = this.prefix + arg;
}
else {
sources[i] = arg;
}
}
else {
sources[i] = new File(arg).isAbsolute() ? arg : this.prefix + arg;
}
}
return sources;
}
private String getOutput() {
String output = this.output.toString().substring(this.previousOutput.length());
this.previousOutput = output;
return output;
}
@Override
public void beforeEach(ExtensionContext extensionContext) {
Assumptions.assumeTrue(System.getProperty("spring.profiles.active", "integration").contains("integration"),
"Not running sample integration tests because integration profile not active");
System.setProperty("disableSpringSnapshotRepos", "false");
}
@Override
public void afterEach(ExtensionContext extensionContext) {
for (AbstractCommand command : this.commands) {
if (command instanceof RunCommand runCommand) {
runCommand.stop();
}
}
System.clearProperty("disableSpringSnapshotRepos");
FileSystemUtils.deleteRecursively(this.temp);
}
public String getHttpOutput() {
return getHttpOutput("/");
}
public String getHttpOutput(String uri) {
try {
int port = Integer.parseInt(FileCopyUtils.copyToString(new FileReader(this.serverPortFile)));
InputStream stream = URI.create("http://localhost:" + port + uri).toURL().openStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
return reader.lines().collect(Collectors.joining());
}
catch (Exception ex) {
throw new IllegalStateException(ex);
}
}
}

View File

@@ -1,49 +0,0 @@
/*
* Copyright 2012-2021 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.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.cli;
import org.apache.catalina.webresources.TomcatURLStreamHandlerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.web.context.WebServerPortFileWriter;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.util.ClassUtils;
/**
* Custom {@link SpringApplication} used by {@link CliTester}.
*
* @author Andy Wilkinson
*/
public class CliTesterSpringApplication extends SpringApplication {
static {
if (ClassUtils.isPresent("org.apache.catalina.webresources.TomcatURLStreamHandlerFactory",
CliTesterSpringApplication.class.getClassLoader())) {
TomcatURLStreamHandlerFactory.disable();
}
}
public CliTesterSpringApplication(Class<?>... sources) {
super(sources);
}
@Override
protected void postProcessApplicationContext(ConfigurableApplicationContext context) {
context.addApplicationListener(new WebServerPortFileWriter());
}
}

View File

@@ -1,58 +0,0 @@
/*
* 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.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.cli;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.springframework.boot.test.system.CapturedOutput;
import org.springframework.boot.test.system.OutputCaptureExtension;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Integration tests for code in directories.
*
* @author Dave Syer
*/
@ExtendWith(OutputCaptureExtension.class)
class DirectorySourcesIntegrationTests {
@RegisterExtension
CliTester cli;
DirectorySourcesIntegrationTests(CapturedOutput output) {
this.cli = new CliTester("src/test/resources/dir-sample/", output);
}
@Test
void runDirectory() throws Exception {
assertThat(this.cli.run("code")).contains("Hello World");
}
@Test
void runDirectoryRecursive() throws Exception {
assertThat(this.cli.run("")).contains("Hello World");
}
@Test
void runPathPattern() throws Exception {
assertThat(this.cli.run("**/*.groovy")).contains("Hello World");
}
}

View File

@@ -1,84 +0,0 @@
/*
* Copyright 2012-2020 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.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.cli;
import java.io.File;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.springframework.boot.cli.command.grab.GrabCommand;
import org.springframework.boot.test.system.CapturedOutput;
import org.springframework.boot.test.system.OutputCaptureExtension;
import org.springframework.util.FileSystemUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
* Integration tests for {@link GrabCommand}
*
* @author Andy Wilkinson
* @author Dave Syer
*/
@ExtendWith(OutputCaptureExtension.class)
class GrabCommandIntegrationTests {
@RegisterExtension
CliTester cli;
GrabCommandIntegrationTests(CapturedOutput output) {
this.cli = new CliTester("src/test/resources/grab-samples/", output);
}
@BeforeEach
@AfterEach
void deleteLocalRepository() {
System.clearProperty("grape.root");
System.clearProperty("groovy.grape.report.downloads");
}
@Test
void grab() throws Exception {
System.setProperty("grape.root", this.cli.getTemp().getAbsolutePath());
System.setProperty("groovy.grape.report.downloads", "true");
// Use --autoconfigure=false to limit the amount of downloaded dependencies
String output = this.cli.grab("grab.groovy", "--autoconfigure=false");
assertThat(new File(this.cli.getTemp(), "repository/com/fasterxml/jackson/core/jackson-core")).isDirectory();
assertThat(output).contains("Downloading: ");
}
@Test
void duplicateDependencyManagementBomAnnotationsProducesAnError() {
assertThatExceptionOfType(Exception.class)
.isThrownBy(() -> this.cli.grab("duplicateDependencyManagementBom.groovy"))
.withMessageContaining("Duplicate @DependencyManagementBom annotation");
}
@Test
void customMetadata() throws Exception {
System.setProperty("grape.root", this.cli.getTemp().getAbsolutePath());
File repository = new File(this.cli.getTemp().getAbsolutePath(), "repository");
FileSystemUtils.copyRecursively(new File("src/test/resources/grab-samples/repository"), repository);
this.cli.grab("customDependencyManagement.groovy", "--autoconfigure=false");
assertThat(new File(repository, "javax/ejb/ejb-api/3.0")).isDirectory();
}
}

View File

@@ -1,73 +0,0 @@
/*
* Copyright 2012-2021 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.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.cli;
import java.util.concurrent.ExecutionException;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.springframework.boot.test.system.CapturedOutput;
import org.springframework.boot.test.system.OutputCaptureExtension;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
* Integration tests to exercise and reproduce specific issues.
*
* @author Phillip Webb
* @author Andy Wilkinson
* @author Stephane Nicoll
*/
@ExtendWith(OutputCaptureExtension.class)
class ReproIntegrationTests {
@RegisterExtension
CliTester cli;
ReproIntegrationTests(CapturedOutput output) {
this.cli = new CliTester("src/test/resources/repro-samples/", output);
}
@Test
void grabAntBuilder() throws Exception {
this.cli.run("grab-ant-builder.groovy");
assertThat(this.cli.getHttpOutput()).contains("{\"message\":\"Hello World\"}");
}
// Security depends on old versions of Spring so if the dependencies aren't pinned
// this will fail
@Test
void securityDependencies() throws Exception {
assertThat(this.cli.run("secure.groovy")).contains("Hello World");
}
@Test
void dataJpaDependencies() throws Exception {
assertThat(this.cli.run("data-jpa.groovy")).contains("Hello World");
}
@Test
void jarFileExtensionNeeded() {
assertThatExceptionOfType(ExecutionException.class)
.isThrownBy(() -> this.cli.jar("secure.groovy", "data-jpa.groovy"))
.withMessageContaining("is not a JAR file");
}
}

View File

@@ -1,75 +0,0 @@
/*
* Copyright 2012-2020 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.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.cli;
import java.util.Properties;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.springframework.boot.cli.command.run.RunCommand;
import org.springframework.boot.test.system.CapturedOutput;
import org.springframework.boot.test.system.OutputCaptureExtension;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Integration tests for {@link RunCommand}.
*
* @author Andy Wilkinson
*/
@ExtendWith(OutputCaptureExtension.class)
class RunCommandIntegrationTests {
@RegisterExtension
CliTester cli;
RunCommandIntegrationTests(CapturedOutput output) {
this.cli = new CliTester("src/test/resources/run-command/", output);
}
private Properties systemProperties = new Properties();
@BeforeEach
void captureSystemProperties() {
this.systemProperties.putAll(System.getProperties());
}
@AfterEach
void restoreSystemProperties() {
System.setProperties(this.systemProperties);
}
@Test
void bannerAndLoggingIsOutputByDefault() throws Exception {
String output = this.cli.run("quiet.groovy");
assertThat(output).contains(" :: Spring Boot ::");
assertThat(output).contains("Starting application");
assertThat(output).contains("Ssshh");
}
@Test
void quietModeSuppressesAllCliOutput() throws Exception {
this.cli.run("quiet.groovy");
String output = this.cli.run("quiet.groovy", "-q");
assertThat(output).isEqualTo("Ssshh");
}
}

View File

@@ -1,153 +0,0 @@
/*
* Copyright 2012-2022 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.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.cli;
import java.io.File;
import java.net.URI;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.springframework.boot.test.system.CapturedOutput;
import org.springframework.boot.test.system.OutputCaptureExtension;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Integration tests to exercise the samples.
*
* @author Dave Syer
* @author Greg Turnquist
* @author Roy Clarkson
* @author Phillip Webb
*/
@ExtendWith(OutputCaptureExtension.class)
class SampleIntegrationTests {
@RegisterExtension
CliTester cli;
SampleIntegrationTests(CapturedOutput output) {
this.cli = new CliTester("samples/", output);
}
@Test
void retrySample() throws Exception {
String output = this.cli.run("retry.groovy");
URI scriptUri = new File("samples/retry.groovy").toURI();
assertThat(output).contains("Hello World! From " + scriptUri);
}
@Test
void beansSample() throws Exception {
this.cli.run("beans.groovy");
String output = this.cli.getHttpOutput();
assertThat(output).contains("Hello World!");
}
@Test
void templateSample() throws Exception {
String output = this.cli.run("template.groovy");
assertThat(output).contains("Hello World!");
}
@Test
void jobSample() throws Exception {
String output = this.cli.run("job.groovy", "foo=bar");
assertThat(output).contains("completed with the following parameters");
}
@Test
void jobWebSample() throws Exception {
String output = this.cli.run("job.groovy", "web.groovy", "foo=bar");
assertThat(output).contains("completed with the following parameters");
String result = this.cli.getHttpOutput();
assertThat(result).isEqualTo("World!");
}
@Test
void webSample() throws Exception {
this.cli.run("web.groovy");
assertThat(this.cli.getHttpOutput()).isEqualTo("World!");
}
@Test
void uiSample() throws Exception {
this.cli.run("ui.groovy", "--classpath=.:src/test/resources");
String result = this.cli.getHttpOutput();
assertThat(result).contains("Hello World");
result = this.cli.getHttpOutput("/css/bootstrap.min.css");
assertThat(result).contains("container");
}
@Test
void actuatorSample() throws Exception {
this.cli.run("actuator.groovy");
assertThat(this.cli.getHttpOutput()).isEqualTo("{\"message\":\"Hello World!\"}");
}
@Test
void httpSample() throws Exception {
String output = this.cli.run("http.groovy");
assertThat(output).contains("Hello World");
}
@Test
void integrationSample() throws Exception {
String output = this.cli.run("integration.groovy");
assertThat(output).contains("Hello, World");
}
@Test
void xmlSample() throws Exception {
String output = this.cli.run("runner.xml", "runner.groovy");
assertThat(output).contains("Hello World");
}
@Test
void txSample() throws Exception {
String output = this.cli.run("tx.groovy");
assertThat(output).contains("Foo count=");
}
@Test
void jmsSample() throws Exception {
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");
}
finally {
System.clearProperty("spring.artemis.embedded.queues");
}
}
@Test
@Disabled("Requires RabbitMQ to be run, so disable it by default")
void rabbitSample() throws Exception {
String output = this.cli.run("rabbit.groovy");
assertThat(output).contains("Received Greetings from Spring Boot via RabbitMQ");
}
@Test
void caching() throws Exception {
assertThat(this.cli.run("caching.groovy")).contains("Hello World");
}
}

View File

@@ -1,156 +0,0 @@
/*
* 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.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.cli.app;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link SpringApplicationLauncher}
*
* @author Andy Wilkinson
*/
class SpringApplicationLauncherTests {
private Map<String, String> env = new HashMap<>();
@AfterEach
void cleanUp() {
System.clearProperty("spring.application.class.name");
}
@Test
void defaultLaunch() {
assertThat(launch()).contains("org.springframework.boot.SpringApplication");
}
@Test
void launchWithClassConfiguredBySystemProperty() {
System.setProperty("spring.application.class.name", "system.property.SpringApplication");
assertThat(launch()).contains("system.property.SpringApplication");
}
@Test
void launchWithClassConfiguredByEnvironmentVariable() {
this.env.put("SPRING_APPLICATION_CLASS_NAME", "environment.variable.SpringApplication");
assertThat(launch()).contains("environment.variable.SpringApplication");
}
@Test
void systemPropertyOverridesEnvironmentVariable() {
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
void sourcesDefaultPropertiesAndArgsAreUsedToLaunch() throws Exception {
System.setProperty("spring.application.class.name", TestSpringApplication.class.getName());
Class<?>[] sources = new Class<?>[0];
String[] args = new String[0];
new SpringApplicationLauncher(getClass().getClassLoader()).launch(sources, args);
assertThat(sources == TestSpringApplication.sources).isTrue();
assertThat(args == TestSpringApplication.args).isTrue();
Map<String, String> defaultProperties = TestSpringApplication.defaultProperties;
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 Class<?>[0], new String[0]);
}
catch (Exception ex) {
// Launch will fail, but we can still check that the launcher tried to use
// the right class
}
return classLoader.classes;
}
static class TestClassLoader extends ClassLoader {
private Set<String> classes = new HashSet<>();
TestClassLoader(ClassLoader parent) {
super(parent);
}
@Override
protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
this.classes.add(name);
return super.loadClass(name, resolve);
}
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
this.classes.add(name);
return super.findClass(name);
}
}
public static class TestSpringApplication {
private static Object[] sources;
private static Map<String, String> defaultProperties;
private static String[] args;
TestSpringApplication(Class<?>[] sources) {
TestSpringApplication.sources = sources;
}
public void setDefaultProperties(Map<String, String> defaultProperties) {
TestSpringApplication.defaultProperties = defaultProperties;
}
public void run(String[] args) {
TestSpringApplication.args = args;
}
}
private class TestSpringApplicationLauncher extends SpringApplicationLauncher {
TestSpringApplicationLauncher(ClassLoader classLoader) {
super(classLoader);
}
@Override
protected String getEnvironmentVariable(String name) {
String variable = SpringApplicationLauncherTests.this.env.get(name);
if (variable == null) {
variable = super.getEnvironmentVariable(name);
}
return variable;
}
}
}

View File

@@ -1,133 +0,0 @@
/*
* 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.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.cli.command.archive;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import org.assertj.core.api.Condition;
import org.junit.jupiter.api.Test;
import org.springframework.boot.cli.command.archive.ResourceMatcher.MatchedResource;
import org.springframework.test.util.ReflectionTestUtils;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link ResourceMatcher}.
*
* @author Andy Wilkinson
*/
class ResourceMatcherTests {
@Test
void nonExistentRoot() throws IOException {
ResourceMatcher resourceMatcher = new ResourceMatcher(Arrays.asList("alpha/**", "bravo/*", "*"),
Arrays.asList(".*", "alpha/**/excluded"));
List<MatchedResource> matchedResources = resourceMatcher.find(Arrays.asList(new File("does-not-exist")));
assertThat(matchedResources).isEmpty();
}
@SuppressWarnings("unchecked")
@Test
void defaults() {
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
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")));
assertThat(found).areNot(new Condition<MatchedResource>() {
@Override
public boolean matches(MatchedResource value) {
return value.getFile().getName().equals("foo.jar");
}
});
}
@SuppressWarnings("unchecked")
@Test
void includedDeltas() {
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/**");
}
@SuppressWarnings("unchecked")
@Test
void includedDeltasAndNewEntries() {
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/**");
assertThat(excludes).doesNotContain("**/*.jar");
}
@SuppressWarnings("unchecked")
@Test
void excludedDeltas() {
ResourceMatcher resourceMatcher = new ResourceMatcher(Arrays.asList(""), Arrays.asList("-**/*.jar"));
Collection<String> excludes = (Collection<String>) ReflectionTestUtils.getField(resourceMatcher, "excludes");
assertThat(excludes).doesNotContain("**/*.jar");
}
@Test
void jarFileAlwaysMatches() throws Exception {
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")));
assertThat(found).areAtLeastOne(new Condition<MatchedResource>() {
@Override
public boolean matches(MatchedResource value) {
return value.getFile().getName().equals("foo.jar") && value.isRoot();
}
});
}
@Test
void resourceMatching() throws IOException {
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"),
new File("src/test/resources/resource-matcher/two"),
new File("src/test/resources/resource-matcher/three")));
List<String> paths = new ArrayList<>();
for (MatchedResource resource : matchedResources) {
paths.add(resource.getName());
}
assertThat(paths).containsOnly("alpha/nested/fileA", "bravo/fileC", "fileD", "bravo/fileE", "fileF", "three");
}
}

View File

@@ -1,129 +0,0 @@
/*
* 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.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.cli.command.install;
import java.io.File;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.boot.cli.compiler.GroovyCompilerConfiguration;
import org.springframework.boot.cli.compiler.GroovyCompilerScope;
import org.springframework.boot.cli.compiler.RepositoryConfigurationFactory;
import org.springframework.boot.cli.compiler.grape.RepositoryConfiguration;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link GroovyGrabDependencyResolver}.
*
* @author Andy Wilkinson
*/
class GroovyGrabDependencyResolverTests {
private DependencyResolver resolver;
@BeforeEach
void setupResolver() {
GroovyCompilerConfiguration configuration = new GroovyCompilerConfiguration() {
@Override
public boolean isGuessImports() {
return true;
}
@Override
public boolean isGuessDependencies() {
return true;
}
@Override
public boolean isAutoconfigure() {
return false;
}
@Override
public GroovyCompilerScope getScope() {
return GroovyCompilerScope.DEFAULT;
}
@Override
public List<RepositoryConfiguration> getRepositoryConfiguration() {
return RepositoryConfigurationFactory.createDefaultRepositoryConfiguration();
}
@Override
public String[] getClasspath() {
return new String[] { "." };
}
@Override
public boolean isQuiet() {
return false;
}
};
this.resolver = new GroovyGrabDependencyResolver(configuration);
}
@Test
void resolveArtifactWithNoDependencies() throws Exception {
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
void resolveArtifactWithDependencies() throws Exception {
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");
}
@Test
void resolveShorthandArtifactWithDependencies() throws Exception {
List<File> resolved = this.resolver.resolve(Arrays.asList("spring-beans"));
assertThat(resolved).hasSize(3);
Set<String> names = getNames(resolved);
assertThat(names).anyMatch((name) -> name.startsWith("spring-core-"));
assertThat(names).anyMatch((name) -> name.startsWith("spring-beans-"));
assertThat(names).anyMatch((name) -> name.startsWith("spring-jcl-"));
}
@Test
void resolveMultipleArtifacts() throws Exception {
List<File> resolved = this.resolver
.resolve(Arrays.asList("junit:junit:4.11", "commons-logging:commons-logging:1.1.3"));
assertThat(resolved).hasSize(4);
assertThat(getNames(resolved)).containsOnly("junit-4.11.jar", "commons-logging-1.1.3.jar",
"hamcrest-core-2.2.jar", "hamcrest-2.2.jar");
}
Set<String> getNames(Collection<File> files) {
Set<String> names = new HashSet<>(files.size());
for (File file : files) {
names.add(file.getName());
}
return names;
}
}

View File

@@ -1,121 +0,0 @@
/*
* 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.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.cli.command.install;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
/**
* Tests for {@link Installer}
*
* @author Andy Wilkinson
*/
class InstallerTests {
private final DependencyResolver resolver = mock(DependencyResolver.class);
@TempDir
File tempDir;
private Installer installer;
@BeforeEach
void setUp() throws IOException {
System.setProperty("spring.home", this.tempDir.getAbsolutePath());
this.installer = new Installer(this.resolver);
}
@AfterEach
void cleanUp() {
System.clearProperty("spring.home");
}
@Test
void installNewDependency() throws Exception {
File foo = createTemporaryFile("foo.jar");
given(this.resolver.resolve(Arrays.asList("foo"))).willReturn(Arrays.asList(foo));
this.installer.install(Arrays.asList("foo"));
assertThat(getNamesOfFilesInLibExt()).containsOnly("foo.jar", ".installed");
}
@Test
void installAndUninstall() throws Exception {
File foo = createTemporaryFile("foo.jar");
given(this.resolver.resolve(Arrays.asList("foo"))).willReturn(Arrays.asList(foo));
this.installer.install(Arrays.asList("foo"));
this.installer.uninstall(Arrays.asList("foo"));
assertThat(getNamesOfFilesInLibExt()).contains(".installed");
}
@Test
void installAndUninstallWithCommonDependencies() throws Exception {
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));
this.installer.install(Arrays.asList("bravo"));
assertThat(getNamesOfFilesInLibExt()).containsOnly("alpha.jar", "bravo.jar", ".installed");
this.installer.install(Arrays.asList("charlie"));
assertThat(getNamesOfFilesInLibExt()).containsOnly("alpha.jar", "bravo.jar", "charlie.jar", ".installed");
this.installer.uninstall(Arrays.asList("bravo"));
assertThat(getNamesOfFilesInLibExt()).containsOnly("alpha.jar", "charlie.jar", ".installed");
this.installer.uninstall(Arrays.asList("charlie"));
assertThat(getNamesOfFilesInLibExt()).containsOnly(".installed");
}
@Test
void uninstallAll() throws Exception {
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));
this.installer.install(Arrays.asList("bravo"));
this.installer.install(Arrays.asList("charlie"));
assertThat(getNamesOfFilesInLibExt()).containsOnly("alpha.jar", "bravo.jar", "charlie.jar", ".installed");
this.installer.uninstallAll();
assertThat(getNamesOfFilesInLibExt()).containsOnly(".installed");
}
private Set<String> getNamesOfFilesInLibExt() {
Set<String> names = new HashSet<>();
for (File file : new File(this.tempDir, "lib/ext").listFiles()) {
names.add(file.getName());
}
return names;
}
private File createTemporaryFile(String name) throws IOException {
File temporaryFile = new File(this.tempDir, name);
temporaryFile.createNewFile();
return temporaryFile;
}
}

View File

@@ -1,45 +0,0 @@
/*
* Copyright 2012-2021 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.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.cli.command.run;
import java.util.logging.Level;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
/**
* Tests for {@link SpringApplicationRunner}.
*
* @author Andy Wilkinson
*/
class SpringApplicationRunnerTests {
@Test
void exceptionMessageWhenSourcesContainsNoClasses() {
SpringApplicationRunnerConfiguration configuration = mock(SpringApplicationRunnerConfiguration.class);
given(configuration.getClasspath()).willReturn(new String[] { "foo", "bar" });
given(configuration.getLogLevel()).willReturn(Level.INFO);
assertThatExceptionOfType(RuntimeException.class)
.isThrownBy(
() -> new SpringApplicationRunner(configuration, new String[] { "foo", "bar" }).compileAndRun())
.withMessage("No classes found in '[foo, bar]'");
}
}

View File

@@ -1,215 +0,0 @@
/*
* Copyright 2012-2020 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.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.cli.compiler;
import java.util.List;
import groovy.lang.Grab;
import groovy.lang.GroovyClassLoader;
import org.codehaus.groovy.ast.AnnotationNode;
import org.codehaus.groovy.ast.ClassNode;
import org.codehaus.groovy.ast.ModuleNode;
import org.codehaus.groovy.ast.expr.ConstantExpression;
import org.codehaus.groovy.control.SourceUnit;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.boot.cli.compiler.dependencies.ArtifactCoordinatesResolver;
import org.springframework.boot.cli.compiler.grape.DependencyResolutionContext;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given;
/**
* Tests for {@link DependencyCustomizer}
*
* @author Andy Wilkinson
*/
@ExtendWith(MockitoExtension.class)
class DependencyCustomizerTests {
private final ModuleNode moduleNode = new ModuleNode((SourceUnit) null);
private final ClassNode classNode = new ClassNode(DependencyCustomizerTests.class);
@Mock
private ArtifactCoordinatesResolver resolver;
private DependencyCustomizer dependencyCustomizer;
@BeforeEach
void setUp() {
this.moduleNode.addClass(this.classNode);
this.dependencyCustomizer = new DependencyCustomizer(new GroovyClassLoader(getClass().getClassLoader()),
this.moduleNode, new DependencyResolutionContext() {
@Override
public ArtifactCoordinatesResolver getArtifactCoordinatesResolver() {
return DependencyCustomizerTests.this.resolver;
}
});
}
@Test
void basicAdd() {
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.getVersion("spring-boot-starter-logging")).willReturn("1.2.3");
this.dependencyCustomizer.add("spring-boot-starter-logging");
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);
}
@Test
void nonTransitiveAdd() {
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.getVersion("spring-boot-starter-logging")).willReturn("1.2.3");
this.dependencyCustomizer.add("spring-boot-starter-logging", 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", null,
null, false);
}
@Test
void fullyCustomized() {
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.getVersion("spring-boot-starter-logging")).willReturn("1.2.3");
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);
}
@Test
void anyMissingClassesWithMissingClassesPerformsAdd() {
this.dependencyCustomizer.ifAnyMissingClasses("does.not.Exist").add("spring-boot-starter-logging");
assertThat(this.classNode.getAnnotations(new ClassNode(Grab.class))).hasSize(1);
}
@Test
void anyMissingClassesWithMixtureOfClassesPerformsAdd() {
this.dependencyCustomizer.ifAnyMissingClasses(getClass().getName(), "does.not.Exist")
.add("spring-boot-starter-logging");
assertThat(this.classNode.getAnnotations(new ClassNode(Grab.class))).hasSize(1);
}
@Test
void anyMissingClassesWithNoMissingClassesDoesNotPerformAdd() {
this.dependencyCustomizer.ifAnyMissingClasses(getClass().getName()).add("spring-boot-starter-logging");
assertThat(this.classNode.getAnnotations(new ClassNode(Grab.class))).isEmpty();
}
@Test
void allMissingClassesWithNoMissingClassesDoesNotPerformAdd() {
this.dependencyCustomizer.ifAllMissingClasses(getClass().getName()).add("spring-boot-starter-logging");
assertThat(this.classNode.getAnnotations(new ClassNode(Grab.class))).isEmpty();
}
@Test
void allMissingClassesWithMixtureOfClassesDoesNotPerformAdd() {
this.dependencyCustomizer.ifAllMissingClasses(getClass().getName(), "does.not.Exist")
.add("spring-boot-starter-logging");
assertThat(this.classNode.getAnnotations(new ClassNode(Grab.class))).isEmpty();
}
@Test
void allMissingClassesWithAllClassesMissingPerformsAdd() {
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);
}
@Test
void allResourcesPresentWithAllResourcesPresentPerformsAdd() {
this.dependencyCustomizer.ifAllResourcesPresent("dependency-customizer-tests/resource1.txt",
"dependency-customizer-tests/resource2.txt").add("spring-boot-starter-logging");
assertThat(this.classNode.getAnnotations(new ClassNode(Grab.class))).hasSize(1);
}
@Test
void allResourcesPresentWithSomeResourcesPresentDoesNotPerformAdd() {
this.dependencyCustomizer.ifAllResourcesPresent("dependency-customizer-tests/resource1.txt",
"dependency-customizer-tests/does-not-exist.txt").add("spring-boot-starter-logging");
assertThat(this.classNode.getAnnotations(new ClassNode(Grab.class))).isEmpty();
}
@Test
void allResourcesPresentWithNoResourcesPresentDoesNotPerformAdd() {
this.dependencyCustomizer.ifAllResourcesPresent("dependency-customizer-tests/does-not-exist",
"dependency-customizer-tests/does-not-exist-either.txt").add("spring-boot-starter-logging");
assertThat(this.classNode.getAnnotations(new ClassNode(Grab.class))).isEmpty();
}
@Test
void anyResourcesPresentWithAllResourcesPresentPerformsAdd() {
this.dependencyCustomizer.ifAnyResourcesPresent("dependency-customizer-tests/resource1.txt",
"dependency-customizer-tests/resource2.txt").add("spring-boot-starter-logging");
assertThat(this.classNode.getAnnotations(new ClassNode(Grab.class))).hasSize(1);
}
@Test
void anyResourcesPresentWithSomeResourcesPresentPerforms() {
this.dependencyCustomizer.ifAnyResourcesPresent("dependency-customizer-tests/resource1.txt",
"dependency-customizer-tests/does-not-exist.txt").add("spring-boot-starter-logging");
assertThat(this.classNode.getAnnotations(new ClassNode(Grab.class))).hasSize(1);
}
@Test
void anyResourcesPresentWithNoResourcesPresentDoesNotPerformAdd() {
this.dependencyCustomizer.ifAnyResourcesPresent("dependency-customizer-tests/does-not-exist",
"dependency-customizer-tests/does-not-exist-either.txt").add("spring-boot-starter-logging");
assertThat(this.classNode.getAnnotations(new ClassNode(Grab.class))).isEmpty();
}
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);
assertThat(getMemberValue(annotationNode, "version")).isEqualTo(version);
if (type == null) {
assertThat(annotationNode.getMember("type")).isNull();
}
else {
assertThat(getMemberValue(annotationNode, "type")).isEqualTo(type);
}
if (classifier == null) {
assertThat(annotationNode.getMember("classifier")).isNull();
}
else {
assertThat(getMemberValue(annotationNode, "classifier")).isEqualTo(classifier);
}
assertThat(getMemberValue(annotationNode, "transitive")).isEqualTo(transitive);
}
private Object getMemberValue(AnnotationNode annotationNode, String member) {
return ((ConstantExpression) annotationNode.getMember(member)).getValue();
}
}

View File

@@ -1,61 +0,0 @@
/*
* Copyright 2012-2020 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.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.cli.compiler;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
* Tests for {@link ExtendedGroovyClassLoader}.
*
* @author Phillip Webb
*/
class ExtendedGroovyClassLoaderTests {
private final ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
private final ExtendedGroovyClassLoader defaultScopeGroovyClassLoader = new ExtendedGroovyClassLoader(
GroovyCompilerScope.DEFAULT);
@Test
void loadsGroovyFromSameClassLoader() throws Exception {
Class<?> c1 = Class.forName("groovy.lang.Script", false, this.contextClassLoader);
Class<?> c2 = Class.forName("groovy.lang.Script", false, this.defaultScopeGroovyClassLoader);
assertThat(c1.getClassLoader()).isSameAs(c2.getClassLoader());
}
@Test
void filtersNonGroovy() throws Exception {
Class.forName("org.springframework.util.StringUtils", false, this.contextClassLoader);
assertThatExceptionOfType(ClassNotFoundException.class).isThrownBy(
() -> Class.forName("org.springframework.util.StringUtils", false, this.defaultScopeGroovyClassLoader));
}
@Test
void loadsJavaTypes() throws Exception {
Class.forName("java.lang.Boolean", false, this.defaultScopeGroovyClassLoader);
}
@Test
void loadsSqlTypes() throws Exception {
Class.forName("java.sql.SQLException", false, this.contextClassLoader);
Class.forName("java.sql.SQLException", false, this.defaultScopeGroovyClassLoader);
}
}

View File

@@ -1,123 +0,0 @@
/*
* Copyright 2012-2022 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.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.cli.compiler;
import java.util.ArrayList;
import java.util.List;
import org.codehaus.groovy.ast.ASTNode;
import org.codehaus.groovy.ast.AnnotationNode;
import org.codehaus.groovy.ast.ClassHelper;
import org.codehaus.groovy.ast.ClassNode;
import org.codehaus.groovy.ast.ModuleNode;
import org.codehaus.groovy.ast.PackageNode;
import org.codehaus.groovy.ast.expr.ConstantExpression;
import org.codehaus.groovy.ast.expr.Expression;
import org.codehaus.groovy.ast.expr.ListExpression;
import org.codehaus.groovy.control.SourceUnit;
import org.codehaus.groovy.control.io.ReaderSource;
import org.codehaus.groovy.transform.ASTTransformation;
import org.junit.jupiter.api.Test;
import org.springframework.boot.groovy.DependencyManagementBom;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link ResolveDependencyCoordinatesTransformation}
*
* @author Andy Wilkinson
* @author Dave Syer
*/
final class GenericBomAstTransformationTests {
private final SourceUnit sourceUnit = new SourceUnit((String) null, (ReaderSource) null, null, null, null);
private final ModuleNode moduleNode = new ModuleNode(this.sourceUnit);
private final ASTTransformation transformation = new GenericBomAstTransformation() {
@Override
public int getOrder() {
return DependencyManagementBomTransformation.ORDER - 10;
}
@Override
protected String getBomModule() {
return "test:child:1.0.0";
}
};
@Test
void transformationOfEmptyPackage() {
this.moduleNode.setPackage(new PackageNode("foo"));
this.transformation.visit(new ASTNode[] { this.moduleNode }, this.sourceUnit);
assertThat(getValue().toString()).isEqualTo("[test:child:1.0.0]");
}
@Test
void transformationOfClass() {
this.moduleNode.addClass(ClassHelper.make("MyClass"));
this.transformation.visit(new ASTNode[] { this.moduleNode }, this.sourceUnit);
assertThat(getValue().toString()).isEqualTo("[test:child:1.0.0]");
}
@Test
void transformationOfClassWithExistingManagedDependencies() {
this.moduleNode.setPackage(new PackageNode("foo"));
ClassNode cls = ClassHelper.make("MyClass");
this.moduleNode.addClass(cls);
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]");
}
private List<String> getValue() {
Expression expression = findAnnotation().getMember("value");
if (expression instanceof ListExpression listExpression) {
List<String> list = new ArrayList<>();
for (Expression ex : listExpression.getExpressions()) {
list.add((String) ((ConstantExpression) ex).getValue());
}
return list;
}
else if (expression == null) {
return null;
}
else {
throw new IllegalStateException("Member 'value' is not a ListExpression");
}
}
private AnnotationNode findAnnotation() {
PackageNode packageNode = this.moduleNode.getPackage();
ClassNode bom = ClassHelper.make(DependencyManagementBom.class);
if (packageNode != null) {
if (!packageNode.getAnnotations(bom).isEmpty()) {
return packageNode.getAnnotations(bom).get(0);
}
}
if (!this.moduleNode.getClasses().isEmpty()) {
return this.moduleNode.getClasses().get(0).getAnnotations(bom).get(0);
}
throw new IllegalStateException("No package or class node found");
}
}

View File

@@ -1,105 +0,0 @@
/*
* 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.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.cli.compiler;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.junit.jupiter.api.Test;
import org.springframework.boot.cli.compiler.grape.RepositoryConfiguration;
import org.springframework.boot.test.util.TestPropertyValues;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link RepositoryConfigurationFactory}
*
* @author Andy Wilkinson
*/
class RepositoryConfigurationFactoryTests {
@Test
void defaultRepositories() {
TestPropertyValues.of("user.home:src/test/resources/maven-settings/basic").applyToSystemProperties(() -> {
List<RepositoryConfiguration> repositoryConfiguration = RepositoryConfigurationFactory
.createDefaultRepositoryConfiguration();
assertRepositoryConfiguration(repositoryConfiguration, "central", "local", "spring-snapshot",
"spring-milestone");
return null;
});
}
@Test
void snapshotRepositoriesDisabled() {
TestPropertyValues.of("user.home:src/test/resources/maven-settings/basic", "disableSpringSnapshotRepos:true")
.applyToSystemProperties(() -> {
List<RepositoryConfiguration> repositoryConfiguration = RepositoryConfigurationFactory
.createDefaultRepositoryConfiguration();
assertRepositoryConfiguration(repositoryConfiguration, "central", "local");
return null;
});
}
@Test
void activeByDefaultProfileRepositories() {
TestPropertyValues.of("user.home:src/test/resources/maven-settings/active-profile-repositories")
.applyToSystemProperties(() -> {
List<RepositoryConfiguration> repositoryConfiguration = RepositoryConfigurationFactory
.createDefaultRepositoryConfiguration();
assertRepositoryConfiguration(repositoryConfiguration, "central", "local", "spring-snapshot",
"spring-milestone", "active-by-default");
return null;
});
}
@Test
void activeByPropertyProfileRepositories() {
TestPropertyValues.of("user.home:src/test/resources/maven-settings/active-profile-repositories", "foo:bar")
.applyToSystemProperties(() -> {
List<RepositoryConfiguration> repositoryConfiguration = RepositoryConfigurationFactory
.createDefaultRepositoryConfiguration();
assertRepositoryConfiguration(repositoryConfiguration, "central", "local", "spring-snapshot",
"spring-milestone", "active-by-property");
return null;
});
}
@Test
void interpolationProfileRepositories() {
TestPropertyValues
.of("user.home:src/test/resources/maven-settings/active-profile-repositories", "interpolate:true")
.applyToSystemProperties(() -> {
List<RepositoryConfiguration> repositoryConfiguration = RepositoryConfigurationFactory
.createDefaultRepositoryConfiguration();
assertRepositoryConfiguration(repositoryConfiguration, "central", "local", "spring-snapshot",
"spring-milestone", "interpolate-releases", "interpolate-snapshots");
return null;
});
}
private void assertRepositoryConfiguration(List<RepositoryConfiguration> configurations, String... expectedNames) {
assertThat(configurations).hasSize(expectedNames.length);
Set<String> actualNames = new HashSet<>();
for (RepositoryConfiguration configuration : configurations) {
actualNames.add(configuration.getName());
}
assertThat(actualNames).containsOnly(expectedNames);
}
}

View File

@@ -1,239 +0,0 @@
/*
* Copyright 2012-2022 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.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.cli.compiler;
import java.util.Arrays;
import groovy.lang.Grab;
import org.codehaus.groovy.ast.ASTNode;
import org.codehaus.groovy.ast.AnnotationNode;
import org.codehaus.groovy.ast.ClassNode;
import org.codehaus.groovy.ast.ConstructorNode;
import org.codehaus.groovy.ast.FieldNode;
import org.codehaus.groovy.ast.MethodNode;
import org.codehaus.groovy.ast.ModuleNode;
import org.codehaus.groovy.ast.PackageNode;
import org.codehaus.groovy.ast.Parameter;
import org.codehaus.groovy.ast.VariableScope;
import org.codehaus.groovy.ast.expr.ConstantExpression;
import org.codehaus.groovy.ast.expr.DeclarationExpression;
import org.codehaus.groovy.ast.expr.Expression;
import org.codehaus.groovy.ast.expr.VariableExpression;
import org.codehaus.groovy.ast.stmt.BlockStatement;
import org.codehaus.groovy.ast.stmt.ExpressionStatement;
import org.codehaus.groovy.control.SourceUnit;
import org.codehaus.groovy.control.io.ReaderSource;
import org.codehaus.groovy.transform.ASTTransformation;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.boot.cli.compiler.dependencies.ArtifactCoordinatesResolver;
import org.springframework.boot.cli.compiler.dependencies.SpringBootDependenciesDependencyManagement;
import org.springframework.boot.cli.compiler.grape.DependencyResolutionContext;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
/**
* Tests for {@link ResolveDependencyCoordinatesTransformation}
*
* @author Andy Wilkinson
*/
final class ResolveDependencyCoordinatesTransformationTests {
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 DependencyResolutionContext resolutionContext = new DependencyResolutionContext() {
{
addDependencyManagement(new SpringBootDependenciesDependencyManagement());
}
@Override
public ArtifactCoordinatesResolver getArtifactCoordinatesResolver() {
return ResolveDependencyCoordinatesTransformationTests.this.coordinatesResolver;
}
};
private final ASTTransformation transformation = new ResolveDependencyCoordinatesTransformation(
this.resolutionContext);
@BeforeEach
void setUpExpectations() {
given(this.coordinatesResolver.getGroupId("spring-core")).willReturn("org.springframework");
}
@Test
void transformationOfAnnotationOnImport() {
ClassNode classNode = new ClassNode("Test", 0, new ClassNode(Object.class));
this.moduleNode.addImport("alias", classNode, Arrays.asList(this.grabAnnotation));
assertGrabAnnotationHasBeenTransformed();
}
@Test
void transformationOfAnnotationOnStarImport() {
this.moduleNode.addStarImport("org.springframework.util", Arrays.asList(this.grabAnnotation));
assertGrabAnnotationHasBeenTransformed();
}
@Test
void transformationOfAnnotationOnStaticImport() {
ClassNode classNode = new ClassNode("Test", 0, new ClassNode(Object.class));
this.moduleNode.addStaticImport(classNode, "field", "alias", Arrays.asList(this.grabAnnotation));
assertGrabAnnotationHasBeenTransformed();
}
@Test
void transformationOfAnnotationOnStaticStarImport() {
ClassNode classNode = new ClassNode("Test", 0, new ClassNode(Object.class));
this.moduleNode.addStaticStarImport("test", classNode, Arrays.asList(this.grabAnnotation));
assertGrabAnnotationHasBeenTransformed();
}
@Test
void transformationOfAnnotationOnPackage() {
PackageNode packageNode = new PackageNode("test");
packageNode.addAnnotation(this.grabAnnotation);
this.moduleNode.setPackage(packageNode);
assertGrabAnnotationHasBeenTransformed();
}
@Test
void transformationOfAnnotationOnClass() {
ClassNode classNode = new ClassNode("Test", 0, new ClassNode(Object.class));
classNode.addAnnotation(this.grabAnnotation);
this.moduleNode.addClass(classNode);
assertGrabAnnotationHasBeenTransformed();
}
@Test
void transformationOfAnnotationOnAnnotation() {
}
@Test
void transformationOfAnnotationOnField() {
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);
classNode.addField(fieldNode);
fieldNode.addAnnotation(this.grabAnnotation);
assertGrabAnnotationHasBeenTransformed();
}
@Test
void transformationOfAnnotationOnConstructor() {
ClassNode classNode = new ClassNode("Test", 0, new ClassNode(Object.class));
this.moduleNode.addClass(classNode);
ConstructorNode constructorNode = new ConstructorNode(0, null);
constructorNode.addAnnotation(this.grabAnnotation);
classNode.addMethod(constructorNode);
assertGrabAnnotationHasBeenTransformed();
}
@Test
void transformationOfAnnotationOnMethod() {
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.addAnnotation(this.grabAnnotation);
classNode.addMethod(methodNode);
assertGrabAnnotationHasBeenTransformed();
}
@Test
void transformationOfAnnotationOnMethodParameter() {
ClassNode classNode = new ClassNode("Test", 0, new ClassNode(Object.class));
this.moduleNode.addClass(classNode);
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);
classNode.addMethod(methodNode);
assertGrabAnnotationHasBeenTransformed();
}
@Test
void transformationOfAnnotationOnLocalVariable() {
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.addAnnotation(this.grabAnnotation);
BlockStatement code = new BlockStatement(Arrays.asList(new ExpressionStatement(declarationExpression)),
new VariableScope());
MethodNode methodNode = new MethodNode("test", 0, new ClassNode(Void.class), new Parameter[0], new ClassNode[0],
code);
classNode.addMethod(methodNode);
assertGrabAnnotationHasBeenTransformed();
}
private AnnotationNode createGrabAnnotation() {
ClassNode classNode = new ClassNode(Grab.class);
AnnotationNode annotationNode = new AnnotationNode(classNode);
annotationNode.addMember("value", new ConstantExpression("spring-core"));
return annotationNode;
}
private void assertGrabAnnotationHasBeenTransformed() {
this.transformation.visit(new ASTNode[] { this.moduleNode }, this.sourceUnit);
assertThat(getGrabAnnotationMemberAsString("group")).isEqualTo("org.springframework");
assertThat(getGrabAnnotationMemberAsString("module")).isEqualTo("spring-core");
}
private Object getGrabAnnotationMemberAsString(String memberName) {
Expression expression = this.grabAnnotation.getMember(memberName);
if (expression instanceof ConstantExpression constantExpression) {
return constantExpression.getValue();
}
else if (expression == null) {
return null;
}
else {
throw new IllegalStateException("Member '" + memberName + "' is not a ConstantExpression");
}
}
}

View File

@@ -1,84 +0,0 @@
/*
* Copyright 2012-2020 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.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.cli.compiler.dependencies;
import java.util.Arrays;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given;
/**
* Tests for {@link CompositeDependencyManagement}
*
* @author Andy Wilkinson
*/
@ExtendWith(MockitoExtension.class)
class CompositeDependencyManagementTests {
@Mock
private DependencyManagement dependencyManagement1;
@Mock
private DependencyManagement dependencyManagement2;
@Test
void unknownSpringBootVersion() {
given(this.dependencyManagement1.getSpringBootVersion()).willReturn(null);
given(this.dependencyManagement2.getSpringBootVersion()).willReturn(null);
assertThat(new CompositeDependencyManagement(this.dependencyManagement1, this.dependencyManagement2)
.getSpringBootVersion()).isNull();
}
@Test
void knownSpringBootVersion() {
given(this.dependencyManagement1.getSpringBootVersion()).willReturn("1.2.3");
assertThat(new CompositeDependencyManagement(this.dependencyManagement1, this.dependencyManagement2)
.getSpringBootVersion()).isEqualTo("1.2.3");
}
@Test
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();
}
@Test
void knownDependency() {
given(this.dependencyManagement1.find("artifact")).willReturn(new Dependency("test", "artifact", "1.2.3"));
assertThat(new CompositeDependencyManagement(this.dependencyManagement1, this.dependencyManagement2)
.find("artifact")).isEqualTo(new Dependency("test", "artifact", "1.2.3"));
}
@Test
void getDependencies() {
given(this.dependencyManagement1.getDependencies())
.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"),
new Dependency("test", "artifact", "1.2.4"));
}
}

View File

@@ -1,65 +0,0 @@
/*
* Copyright 2012-2022 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.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.cli.compiler.dependencies;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.then;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
/**
* Tests for {@link DependencyManagementArtifactCoordinatesResolver}.
*
* @author Phillip Webb
* @author Andy Wilkinson
*/
class DependencyManagementArtifactCoordinatesResolverTests {
private DependencyManagement dependencyManagement;
private DependencyManagementArtifactCoordinatesResolver resolver;
@BeforeEach
void setup() {
this.dependencyManagement = mock(DependencyManagement.class);
given(this.dependencyManagement.find("a1")).willReturn(new Dependency("g1", "a1", "0"));
given(this.dependencyManagement.getSpringBootVersion()).willReturn("1");
this.resolver = new DependencyManagementArtifactCoordinatesResolver(this.dependencyManagement);
}
@Test
void getGroupIdForBootArtifact() {
assertThat(this.resolver.getGroupId("spring-boot-something")).isEqualTo("org.springframework.boot");
then(this.dependencyManagement).should(never()).find(anyString());
}
@Test
void getGroupIdFound() {
assertThat(this.resolver.getGroupId("a1")).isEqualTo("g1");
}
@Test
void getGroupIdNotFound() {
assertThat(this.resolver.getGroupId("a2")).isNull();
}
}

View File

@@ -1,50 +0,0 @@
/*
* Copyright 2012-2020 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.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.cli.compiler.dependencies;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link SpringBootDependenciesDependencyManagement}
*
* @author Andy Wilkinson
*/
class SpringBootDependenciesDependencyManagementTests {
private final DependencyManagement dependencyManagement = new SpringBootDependenciesDependencyManagement();
@Test
void springBootVersion() {
assertThat(this.dependencyManagement.getSpringBootVersion()).isNotNull();
}
@Test
void find() {
Dependency dependency = this.dependencyManagement.find("spring-boot");
assertThat(dependency).isNotNull();
assertThat(dependency.getGroupId()).isEqualTo("org.springframework.boot");
assertThat(dependency.getArtifactId()).isEqualTo("spring-boot");
}
@Test
void getDependencies() {
assertThat(this.dependencyManagement.getDependencies()).isNotEmpty();
}
}

View File

@@ -1,44 +0,0 @@
/*
* 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.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.cli.compiler.grape;
import org.junit.jupiter.api.Test;
import org.springframework.boot.cli.compiler.dependencies.SpringBootDependenciesDependencyManagement;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link DependencyResolutionContext}.
*
* @author Dave Syer
*/
class DependencyResolutionContextTests {
@Test
void defaultDependenciesEmpty() {
assertThat(new DependencyResolutionContext().getManagedDependencies()).isEmpty();
}
@Test
void canAddSpringBootDependencies() {
DependencyResolutionContext dependencyResolutionContext = new DependencyResolutionContext();
dependencyResolutionContext.addDependencyManagement(new SpringBootDependenciesDependencyManagement());
assertThat(dependencyResolutionContext.getManagedDependencies()).isNotEmpty();
}
}

View File

@@ -1,77 +0,0 @@
/*
* 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.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.cli.compiler.grape;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import org.eclipse.aether.DefaultRepositorySystemSession;
import org.eclipse.aether.transfer.TransferCancelledException;
import org.eclipse.aether.transfer.TransferEvent;
import org.eclipse.aether.transfer.TransferResource;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link DetailedProgressReporter}.
*
* @author Andy Wilkinson
*/
final class DetailedProgressReporterTests {
private static final String REPOSITORY = "https://repo.example.com/";
private static final String ARTIFACT = "org/alpha/bravo/charlie/1.2.3/charlie-1.2.3.jar";
private final TransferResource resource = new TransferResource(null, REPOSITORY, ARTIFACT, null, null);
private final ByteArrayOutputStream baos = new ByteArrayOutputStream();
private final PrintStream out = new PrintStream(this.baos);
private final DefaultRepositorySystemSession session = new DefaultRepositorySystemSession();
@BeforeEach
void initialize() {
new DetailedProgressReporter(this.session, this.out);
}
@Test
void downloading() throws TransferCancelledException {
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));
}
@Test
void downloaded() throws InterruptedException {
// Ensure some transfer time
Thread.sleep(100);
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);
assertThat(message).contains("4KB at");
assertThat(message).contains("KB/sec");
assertThat(message).endsWith("\n");
}
}

View File

@@ -1,93 +0,0 @@
/*
* Copyright 2012-2022 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.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.cli.compiler.grape;
import java.io.File;
import org.apache.maven.repository.internal.MavenRepositorySystemUtils;
import org.eclipse.aether.DefaultRepositorySystemSession;
import org.eclipse.aether.RepositorySystem;
import org.eclipse.aether.internal.impl.SimpleLocalRepositoryManagerFactory;
import org.eclipse.aether.repository.LocalRepository;
import org.eclipse.aether.repository.LocalRepositoryManager;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.stubbing.Answer;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.then;
import static org.mockito.Mockito.never;
/**
* Tests for {@link GrapeRootRepositorySystemSessionAutoConfiguration}
*
* @author Andy Wilkinson
*/
@ExtendWith(MockitoExtension.class)
class GrapeRootRepositorySystemSessionAutoConfigurationTests {
private DefaultRepositorySystemSession session = MavenRepositorySystemUtils.newSession();
@Mock
private RepositorySystem repositorySystem;
@Test
void noLocalRepositoryWhenNoGrapeRoot() {
new GrapeRootRepositorySystemSessionAutoConfiguration().apply(this.session, this.repositorySystem);
then(this.repositorySystem).should(never()).newLocalRepositoryManager(eq(this.session),
any(LocalRepository.class));
assertThat(this.session.getLocalRepository()).isNull();
}
@Test
void grapeRootConfiguresLocalRepositoryLocation() {
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);
}
finally {
System.clearProperty("grape.root");
}
then(this.repositorySystem).should().newLocalRepositoryManager(eq(this.session), any(LocalRepository.class));
assertThat(this.session.getLocalRepository()).isNotNull();
assertThat(this.session.getLocalRepository().getBasedir().getAbsolutePath())
.endsWith(File.separatorChar + "foo" + File.separatorChar + "repository");
}
private class LocalRepositoryManagerAnswer implements Answer<LocalRepositoryManager> {
@Override
public LocalRepositoryManager answer(InvocationOnMock invocation) throws Throwable {
LocalRepository localRepository = invocation.getArgument(1);
return new SimpleLocalRepositoryManagerFactory()
.newInstance(GrapeRootRepositorySystemSessionAutoConfigurationTests.this.session, localRepository);
}
}
}

View File

@@ -1,253 +0,0 @@
/*
* Copyright 2012-2022 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.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.cli.compiler.grape;
import java.io.File;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import groovy.grape.GrapeEngine;
import groovy.lang.GroovyClassLoader;
import org.eclipse.aether.DefaultRepositorySystemSession;
import org.eclipse.aether.repository.Authentication;
import org.eclipse.aether.repository.RemoteRepository;
import org.junit.jupiter.api.Test;
import org.springframework.boot.cli.compiler.dependencies.SpringBootDependenciesDependencyManagement;
import org.springframework.test.util.ReflectionTestUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* Tests for {@link MavenResolverGrapeEngine}.
*
* @author Andy Wilkinson
*/
class MavenResolverGrapeEngineTests {
private final GroovyClassLoader groovyClassLoader = new GroovyClassLoader();
private final RepositoryConfiguration springMilestone = new RepositoryConfiguration("spring-milestone",
URI.create("https://repo.spring.io/milestone"), false);
private final RepositoryConfiguration springSnapshot = new RepositoryConfiguration("spring-snapshot",
URI.create("https://repo.spring.io/snapshot"), true);
private GrapeEngine createGrapeEngine(RepositoryConfiguration... additionalRepositories) {
List<RepositoryConfiguration> repositoryConfigurations = new ArrayList<>();
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 MavenResolverGrapeEngineFactory.create(this.groovyClassLoader, repositoryConfigurations,
dependencyResolutionContext, false);
}
@Test
void dependencyResolution() {
Map<String, Object> args = new HashMap<>();
createGrapeEngine(this.springMilestone, this.springSnapshot).grab(args,
createDependency("org.springframework", "spring-jdbc", null));
assertThat(this.groovyClassLoader.getURLs()).hasSize(5);
}
@Test
void proxySelector() {
doWithCustomUserHome(() -> {
GrapeEngine grapeEngine = createGrapeEngine();
DefaultRepositorySystemSession session = (DefaultRepositorySystemSession) ReflectionTestUtils
.getField(grapeEngine, "session");
assertThat(session.getProxySelector() instanceof CompositeProxySelector).isTrue();
});
}
@Test
void repositoryMirrors() {
doWithCustomUserHome(() -> {
List<RemoteRepository> repositories = getRepositories();
assertThat(repositories).hasSize(1);
assertThat(repositories.get(0).getId()).isEqualTo("central-mirror");
});
}
@Test
void repositoryAuthentication() {
doWithCustomUserHome(() -> {
List<RemoteRepository> repositories = getRepositories();
assertThat(repositories).hasSize(1);
Authentication authentication = repositories.get(0).getAuthentication();
assertThat(authentication).isNotNull();
});
}
@Test
void dependencyResolutionWithExclusions() {
Map<String, Object> args = new HashMap<>();
args.put("excludes", Arrays.asList(createExclusion("org.springframework", "spring-core")));
createGrapeEngine(this.springMilestone, this.springSnapshot).grab(args,
createDependency("org.springframework", "spring-jdbc", "3.2.4.RELEASE"),
createDependency("org.springframework", "spring-beans", "3.2.4.RELEASE"));
assertThat(this.groovyClassLoader.getURLs()).hasSize(3);
}
@Test
void nonTransitiveDependencyResolution() {
Map<String, Object> args = new HashMap<>();
createGrapeEngine().grab(args, createDependency("org.springframework", "spring-jdbc", "3.2.4.RELEASE", false));
assertThat(this.groovyClassLoader.getURLs()).hasSize(1);
}
@Test
void dependencyResolutionWithCustomClassLoader() {
Map<String, Object> args = new HashMap<>();
GroovyClassLoader customClassLoader = new GroovyClassLoader();
args.put("classLoader", customClassLoader);
createGrapeEngine(this.springMilestone, this.springSnapshot).grab(args,
createDependency("org.springframework", "spring-jdbc", null));
assertThat(this.groovyClassLoader.getURLs()).isEmpty();
assertThat(customClassLoader.getURLs()).hasSize(5);
}
@Test
void resolutionWithCustomResolver() {
Map<String, Object> args = new HashMap<>();
GrapeEngine grapeEngine = createGrapeEngine();
grapeEngine.addResolver(createResolver("spring-releases", "https://repo.spring.io/release"));
Map<String, Object> dependency = createDependency("io.spring.docresources", "spring-doc-resources",
"0.1.1.RELEASE");
dependency.put("ext", "zip");
grapeEngine.grab(args, dependency);
assertThat(this.groovyClassLoader.getURLs()).hasSize(1);
}
@Test
void differingTypeAndExt() {
Map<String, Object> dependency = createDependency("org.grails", "grails-dependencies", "2.4.0");
dependency.put("type", "foo");
dependency.put("ext", "bar");
GrapeEngine grapeEngine = createGrapeEngine();
assertThatIllegalArgumentException().isThrownBy(() -> grapeEngine.grab(Collections.emptyMap(), dependency));
}
@Test
void pomDependencyResolutionViaType() {
Map<String, Object> args = new HashMap<>();
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();
assertThat(urls).hasSize(1);
assertThat(urls[0].toExternalForm().endsWith(".pom")).isTrue();
}
@Test
void pomDependencyResolutionViaExt() {
Map<String, Object> args = new HashMap<>();
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();
assertThat(urls).hasSize(1);
assertThat(urls[0].toExternalForm().endsWith(".pom")).isTrue();
}
@Test
void resolutionWithClassifier() {
Map<String, Object> args = new HashMap<>();
Map<String, Object> dependency = createDependency("org.springframework", "spring-jdbc", "3.2.4.RELEASE", false);
dependency.put("classifier", "sources");
createGrapeEngine().grab(args, dependency);
URL[] urls = this.groovyClassLoader.getURLs();
assertThat(urls).hasSize(1);
assertThat(urls[0].toExternalForm().endsWith("-sources.jar")).isTrue();
}
@SuppressWarnings("unchecked")
private List<RemoteRepository> getRepositories() {
GrapeEngine grapeEngine = createGrapeEngine();
return (List<RemoteRepository>) ReflectionTestUtils.getField(grapeEngine, "repositories");
}
private Map<String, Object> createDependency(String group, String module, String version) {
Map<String, Object> dependency = new HashMap<>();
dependency.put("group", group);
dependency.put("module", module);
dependency.put("version", version);
return dependency;
}
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;
}
private Map<String, Object> createResolver(String name, String url) {
Map<String, Object> resolver = new HashMap<>();
resolver.put("name", name);
resolver.put("root", url);
return resolver;
}
private Map<String, Object> createExclusion(String group, String module) {
Map<String, Object> exclusion = new HashMap<>();
exclusion.put("group", group);
exclusion.put("module", module);
return exclusion;
}
private void doWithCustomUserHome(Runnable action) {
doWithSystemProperty("user.home", new File("src/test/resources").getAbsolutePath(), action);
}
private void doWithSystemProperty(String key, String value, Runnable action) {
String previousValue = setOrClearSystemProperty(key, value);
try {
action.run();
}
finally {
setOrClearSystemProperty(key, previousValue);
}
}
private String setOrClearSystemProperty(String key, String value) {
if (value != null) {
return System.setProperty(key, value);
}
return System.clearProperty(key);
}
}

View File

@@ -1,120 +0,0 @@
/*
* Copyright 2012-2020 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.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.cli.compiler.grape;
import java.io.File;
import org.apache.maven.repository.internal.MavenRepositorySystemUtils;
import org.eclipse.aether.DefaultRepositorySystemSession;
import org.eclipse.aether.RepositorySystem;
import org.eclipse.aether.internal.impl.SimpleLocalRepositoryManagerFactory;
import org.eclipse.aether.repository.Authentication;
import org.eclipse.aether.repository.AuthenticationContext;
import org.eclipse.aether.repository.LocalRepository;
import org.eclipse.aether.repository.Proxy;
import org.eclipse.aether.repository.RemoteRepository;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.boot.test.util.TestPropertyValues;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.given;
/**
* Tests for {@link SettingsXmlRepositorySystemSessionAutoConfiguration}.
*
* @author Andy Wilkinson
*/
@ExtendWith(MockitoExtension.class)
class SettingsXmlRepositorySystemSessionAutoConfigurationTests {
@Mock
private RepositorySystem repositorySystem;
@Test
void basicSessionCustomization() {
assertSessionCustomization("src/test/resources/maven-settings/basic");
}
@Test
void encryptedSettingsSessionCustomization() {
assertSessionCustomization("src/test/resources/maven-settings/encrypted");
}
@Test
void propertyInterpolation() {
final DefaultRepositorySystemSession session = MavenRepositorySystemUtils.newSession();
given(this.repositorySystem.newLocalRepositoryManager(eq(session), any(LocalRepository.class)))
.willAnswer((invocation) -> {
LocalRepository localRepository = invocation.getArgument(1);
return new SimpleLocalRepositoryManagerFactory().newInstance(session, localRepository);
});
TestPropertyValues.of("user.home:src/test/resources/maven-settings/property-interpolation", "foo:bar")
.applyToSystemProperties(() -> {
new SettingsXmlRepositorySystemSessionAutoConfiguration().apply(session,
SettingsXmlRepositorySystemSessionAutoConfigurationTests.this.repositorySystem);
return null;
});
assertThat(session.getLocalRepository().getBasedir().getAbsolutePath())
.endsWith(File.separatorChar + "bar" + File.separatorChar + "repository");
}
private void assertSessionCustomization(String userHome) {
final DefaultRepositorySystemSession session = MavenRepositorySystemUtils.newSession();
TestPropertyValues.of("user.home:" + userHome).applyToSystemProperties(() -> {
new SettingsXmlRepositorySystemSessionAutoConfiguration().apply(session,
SettingsXmlRepositorySystemSessionAutoConfigurationTests.this.repositorySystem);
return null;
});
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) {
Proxy proxy = session.getProxySelector().getProxy(repository);
repository = new RemoteRepository.Builder(repository).setProxy(proxy).build();
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");
}
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.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");
}
}

View File

@@ -1,140 +0,0 @@
/*
* 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.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.cli.util;
import java.io.File;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.springframework.util.ClassUtils;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link ResourceUtils}.
*
* @author Dave Syer
*/
class ResourceUtilsTests {
@Test
void explicitClasspathResource() {
List<String> urls = ResourceUtils.getUrls("classpath:init.groovy", ClassUtils.getDefaultClassLoader());
assertThat(urls).hasSize(1);
assertThat(urls.get(0).startsWith("file:")).isTrue();
}
@Test
void duplicateResource() throws Exception {
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);
assertThat(urls.get(0).startsWith("file:")).isTrue();
}
@Test
void explicitClasspathResourceWithSlash() {
List<String> urls = ResourceUtils.getUrls("classpath:/init.groovy", ClassUtils.getDefaultClassLoader());
assertThat(urls).hasSize(1);
assertThat(urls.get(0).startsWith("file:")).isTrue();
}
@Test
void implicitClasspathResource() {
List<String> urls = ResourceUtils.getUrls("init.groovy", ClassUtils.getDefaultClassLoader());
assertThat(urls).hasSize(1);
assertThat(urls.get(0).startsWith("file:")).isTrue();
}
@Test
void implicitClasspathResourceWithSlash() {
List<String> urls = ResourceUtils.getUrls("/init.groovy", ClassUtils.getDefaultClassLoader());
assertThat(urls).hasSize(1);
assertThat(urls.get(0).startsWith("file:")).isTrue();
}
@Test
void nonexistentClasspathResource() {
List<String> urls = ResourceUtils.getUrls("classpath:nonexistent.groovy", null);
assertThat(urls).isEmpty();
}
@Test
void explicitFile() {
List<String> urls = ResourceUtils.getUrls("file:src/test/resources/init.groovy",
ClassUtils.getDefaultClassLoader());
assertThat(urls).hasSize(1);
assertThat(urls.get(0).startsWith("file:")).isTrue();
}
@Test
void implicitFile() {
List<String> urls = ResourceUtils.getUrls("src/test/resources/init.groovy", ClassUtils.getDefaultClassLoader());
assertThat(urls).hasSize(1);
assertThat(urls.get(0).startsWith("file:")).isTrue();
}
@Test
void nonexistentFile() {
List<String> urls = ResourceUtils.getUrls("file:nonexistent.groovy", null);
assertThat(urls).isEmpty();
}
@Test
void recursiveFiles() {
List<String> urls = ResourceUtils.getUrls("src/test/resources/dir-sample", ClassUtils.getDefaultClassLoader());
assertThat(urls).hasSize(1);
assertThat(urls.get(0).startsWith("file:")).isTrue();
}
@Test
void recursiveFilesByPatternWithPrefix() {
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();
}
@Test
void recursiveFilesByPattern() {
List<String> urls = ResourceUtils.getUrls("src/test/resources/dir-sample/**/*.groovy",
ClassUtils.getDefaultClassLoader());
assertThat(urls).hasSize(1);
assertThat(urls.get(0).startsWith("file:")).isTrue();
}
@Test
void directoryOfFilesWithPrefix() {
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();
}
@Test
void directoryOfFiles() {
List<String> urls = ResourceUtils.getUrls("src/test/resources/dir-sample/code/*",
ClassUtils.getDefaultClassLoader());
assertThat(urls).hasSize(1);
assertThat(urls.get(0).startsWith("file:")).isTrue();
}
}