Move tests to JUnit 5 wherever possible

This commit is contained in:
Andy Wilkinson
2019-05-24 11:24:29 +01:00
parent 36f56d034a
commit b18fffaf14
1320 changed files with 13424 additions and 14185 deletions

View File

@@ -16,15 +16,15 @@
package org.springframework.boot.autoconfigureprocessor;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.springframework.boot.testsupport.compiler.TestCompiler;
@@ -35,20 +35,20 @@ import static org.assertj.core.api.Assertions.assertThat;
*
* @author Madhura Bhave
*/
public class AutoConfigureAnnotationProcessorTests {
class AutoConfigureAnnotationProcessorTests {
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
@TempDir
File tempDir;
private TestCompiler compiler;
@Before
@BeforeEach
public void createCompiler() throws IOException {
this.compiler = new TestCompiler(this.temporaryFolder);
this.compiler = new TestCompiler(this.tempDir);
}
@Test
public void annotatedClass() throws Exception {
void annotatedClass() throws Exception {
Properties properties = compile(TestClassConfiguration.class);
assertThat(properties).hasSize(6);
assertThat(properties).containsEntry(
@@ -71,7 +71,7 @@ public class AutoConfigureAnnotationProcessorTests {
}
@Test
public void annotatedClassWithOnBeanThatHasName() throws Exception {
void annotatedClassWithOnBeanThatHasName() throws Exception {
Properties properties = compile(TestOnBeanWithNameClassConfiguration.class);
assertThat(properties).hasSize(3);
assertThat(properties).containsEntry(
@@ -80,7 +80,7 @@ public class AutoConfigureAnnotationProcessorTests {
}
@Test
public void annotatedMethod() throws Exception {
void annotatedMethod() throws Exception {
Properties properties = compile(TestMethodConfiguration.class);
List<String> matching = new ArrayList<>();
for (Object key : properties.keySet()) {
@@ -94,7 +94,7 @@ public class AutoConfigureAnnotationProcessorTests {
}
@Test
public void annotatedClassWithOrder() throws Exception {
void annotatedClassWithOrder() throws Exception {
Properties properties = compile(TestOrderedClassConfiguration.class);
assertThat(properties).containsEntry(
"org.springframework.boot.autoconfigureprocessor." + "TestOrderedClassConfiguration.ConditionalOnClass",

View File

@@ -16,7 +16,7 @@
package org.springframework.boot.configurationdocs;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.springframework.boot.configurationmetadata.ConfigurationMetadataProperty;

View File

@@ -16,7 +16,7 @@
package org.springframework.boot.configurationdocs;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.springframework.boot.configurationmetadata.ConfigurationMetadataProperty;

View File

@@ -16,7 +16,7 @@
package org.springframework.boot.configurationdocs;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.springframework.boot.configurationmetadata.ConfigurationMetadataProperty;

View File

@@ -20,7 +20,7 @@ import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
@@ -30,16 +30,16 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException
*
* @author Stephane Nicoll
*/
public class ConfigurationMetadataRepositoryJsonBuilderTests extends AbstractConfigurationMetadataTests {
class ConfigurationMetadataRepositoryJsonBuilderTests extends AbstractConfigurationMetadataTests {
@Test
public void nullResource() throws IOException {
void nullResource() throws IOException {
assertThatIllegalArgumentException()
.isThrownBy(() -> ConfigurationMetadataRepositoryJsonBuilder.create().withJsonResource(null));
}
@Test
public void simpleRepository() throws IOException {
void simpleRepository() throws IOException {
try (InputStream foo = getInputStreamFor("foo")) {
ConfigurationMetadataRepository repo = ConfigurationMetadataRepositoryJsonBuilder.create(foo).build();
validateFoo(repo);
@@ -50,7 +50,7 @@ public class ConfigurationMetadataRepositoryJsonBuilderTests extends AbstractCon
}
@Test
public void hintsOnMaps() throws IOException {
void hintsOnMaps() throws IOException {
try (InputStream map = getInputStreamFor("map")) {
ConfigurationMetadataRepository repo = ConfigurationMetadataRepositoryJsonBuilder.create(map).build();
validateMap(repo);
@@ -62,7 +62,7 @@ public class ConfigurationMetadataRepositoryJsonBuilderTests extends AbstractCon
}
@Test
public void severalRepositoriesNoConflict() throws IOException {
void severalRepositoriesNoConflict() throws IOException {
try (InputStream foo = getInputStreamFor("foo"); InputStream bar = getInputStreamFor("bar")) {
ConfigurationMetadataRepository repo = ConfigurationMetadataRepositoryJsonBuilder.create(foo, bar).build();
validateFoo(repo);
@@ -75,7 +75,7 @@ public class ConfigurationMetadataRepositoryJsonBuilderTests extends AbstractCon
}
@Test
public void repositoryWithRoot() throws IOException {
void repositoryWithRoot() throws IOException {
try (InputStream foo = getInputStreamFor("foo"); InputStream root = getInputStreamFor("root")) {
ConfigurationMetadataRepository repo = ConfigurationMetadataRepositoryJsonBuilder.create(foo, root).build();
validateFoo(repo);
@@ -88,7 +88,7 @@ public class ConfigurationMetadataRepositoryJsonBuilderTests extends AbstractCon
}
@Test
public void severalRepositoriesIdenticalGroups() throws IOException {
void severalRepositoriesIdenticalGroups() throws IOException {
try (InputStream foo = getInputStreamFor("foo"); InputStream foo2 = getInputStreamFor("foo2")) {
ConfigurationMetadataRepository repo = ConfigurationMetadataRepositoryJsonBuilder.create(foo, foo2).build();
assertThat(repo.getAllGroups()).hasSize(1);
@@ -105,7 +105,7 @@ public class ConfigurationMetadataRepositoryJsonBuilderTests extends AbstractCon
}
@Test
public void emptyGroups() throws IOException {
void emptyGroups() throws IOException {
try (InputStream in = getInputStreamFor("empty-groups")) {
ConfigurationMetadataRepository repo = ConfigurationMetadataRepositoryJsonBuilder.create(in).build();
validateEmptyGroup(repo);
@@ -116,7 +116,7 @@ public class ConfigurationMetadataRepositoryJsonBuilderTests extends AbstractCon
}
@Test
public void multiGroups() throws IOException {
void multiGroups() throws IOException {
try (InputStream in = getInputStreamFor("multi-groups")) {
ConfigurationMetadataRepository repo = ConfigurationMetadataRepositoryJsonBuilder.create(in).build();
assertThat(repo.getAllGroups()).containsOnlyKeys("test.group.one.retry", "test.group.two.retry",
@@ -134,7 +134,7 @@ public class ConfigurationMetadataRepositoryJsonBuilderTests extends AbstractCon
}
@Test
public void builderInstancesAreIsolated() throws IOException {
void builderInstancesAreIsolated() throws IOException {
try (InputStream foo = getInputStreamFor("foo"); InputStream bar = getInputStreamFor("bar")) {
ConfigurationMetadataRepositoryJsonBuilder builder = ConfigurationMetadataRepositoryJsonBuilder.create();
ConfigurationMetadataRepository firstRepo = builder.withJsonResource(foo).build();

View File

@@ -22,7 +22,7 @@ import java.nio.charset.StandardCharsets;
import java.util.List;
import org.json.JSONException;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
@@ -32,26 +32,26 @@ import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
*
* @author Stephane Nicoll
*/
public class JsonReaderTests extends AbstractConfigurationMetadataTests {
class JsonReaderTests extends AbstractConfigurationMetadataTests {
private static final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8;
private final JsonReader reader = new JsonReader();
@Test
public void emptyMetadata() throws IOException {
void emptyMetadata() throws IOException {
RawConfigurationMetadata rawMetadata = readFor("empty");
assertThat(rawMetadata.getSources()).isEmpty();
assertThat(rawMetadata.getItems()).isEmpty();
}
@Test
public void invalidMetadata() throws IOException {
void invalidMetadata() throws IOException {
assertThatIllegalStateException().isThrownBy(() -> readFor("invalid")).withCauseInstanceOf(JSONException.class);
}
@Test
public void emptyGroupName() throws IOException {
void emptyGroupName() throws IOException {
RawConfigurationMetadata rawMetadata = readFor("empty-groups");
List<ConfigurationMetadataItem> items = rawMetadata.getItems();
assertThat(items).hasSize(2);
@@ -63,7 +63,7 @@ public class JsonReaderTests extends AbstractConfigurationMetadataTests {
}
@Test
public void simpleMetadata() throws IOException {
void simpleMetadata() throws IOException {
RawConfigurationMetadata rawMetadata = readFor("foo");
List<ConfigurationMetadataSource> sources = rawMetadata.getSources();
assertThat(sources).hasSize(2);
@@ -104,7 +104,7 @@ public class JsonReaderTests extends AbstractConfigurationMetadataTests {
}
@Test
public void metadataHints() throws IOException {
void metadataHints() throws IOException {
RawConfigurationMetadata rawMetadata = readFor("bar");
List<ConfigurationMetadataHint> hints = rawMetadata.getHints();
assertThat(hints).hasSize(1);
@@ -130,7 +130,7 @@ public class JsonReaderTests extends AbstractConfigurationMetadataTests {
}
@Test
public void rootMetadata() throws IOException {
void rootMetadata() throws IOException {
RawConfigurationMetadata rawMetadata = readFor("root");
List<ConfigurationMetadataSource> sources = rawMetadata.getSources();
assertThat(sources).isEmpty();
@@ -141,7 +141,7 @@ public class JsonReaderTests extends AbstractConfigurationMetadataTests {
}
@Test
public void deprecatedMetadata() throws IOException {
void deprecatedMetadata() throws IOException {
RawConfigurationMetadata rawMetadata = readFor("deprecated");
List<ConfigurationMetadataItem> items = rawMetadata.getItems();
assertThat(items).hasSize(5);
@@ -185,7 +185,7 @@ public class JsonReaderTests extends AbstractConfigurationMetadataTests {
}
@Test
public void multiGroupsMetadata() throws IOException {
void multiGroupsMetadata() throws IOException {
RawConfigurationMetadata rawMetadata = readFor("multi-groups");
List<ConfigurationMetadataItem> items = rawMetadata.getItems();
assertThat(items).hasSize(3);

View File

@@ -16,7 +16,7 @@
package org.springframework.boot.configurationmetadata;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
@@ -25,46 +25,46 @@ import static org.assertj.core.api.Assertions.assertThat;
*
* @author Stephane Nicoll
*/
public class SentenceExtractorTests {
class SentenceExtractorTests {
private static final String NEW_LINE = System.lineSeparator();
private SentenceExtractor extractor = new SentenceExtractor();
@Test
public void extractFirstSentence() {
void extractFirstSentence() {
String sentence = this.extractor.getFirstSentence("My short " + "description. More stuff.");
assertThat(sentence).isEqualTo("My short description.");
}
@Test
public void extractFirstSentenceNewLineBeforeDot() {
void extractFirstSentenceNewLineBeforeDot() {
String sentence = this.extractor
.getFirstSentence("My short" + NEW_LINE + "description." + NEW_LINE + "More stuff.");
assertThat(sentence).isEqualTo("My short description.");
}
@Test
public void extractFirstSentenceNewLineBeforeDotWithSpaces() {
void extractFirstSentenceNewLineBeforeDotWithSpaces() {
String sentence = this.extractor
.getFirstSentence("My short " + NEW_LINE + " description. " + NEW_LINE + "More stuff.");
assertThat(sentence).isEqualTo("My short description.");
}
@Test
public void extractFirstSentenceNoDot() {
void extractFirstSentenceNoDot() {
String sentence = this.extractor.getFirstSentence("My short description");
assertThat(sentence).isEqualTo("My short description");
}
@Test
public void extractFirstSentenceNoDotMultipleLines() {
void extractFirstSentenceNoDotMultipleLines() {
String sentence = this.extractor.getFirstSentence("My short description " + NEW_LINE + " More stuff");
assertThat(sentence).isEqualTo("My short description");
}
@Test
public void extractFirstSentenceNull() {
void extractFirstSentenceNull() {
assertThat(this.extractor.getFirstSentence(null)).isNull();
}

View File

@@ -16,11 +16,11 @@
package org.springframework.boot.configurationprocessor;
import java.io.File;
import java.io.IOException;
import org.junit.Before;
import org.junit.Rule;
import org.junit.rules.TemporaryFolder;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.io.TempDir;
import org.springframework.boot.configurationprocessor.metadata.ConfigurationMetadata;
import org.springframework.boot.configurationprocessor.test.TestConfigurationMetadataAnnotationProcessor;
@@ -33,14 +33,14 @@ import org.springframework.boot.testsupport.compiler.TestCompiler;
*/
public abstract class AbstractMetadataGenerationTests {
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
@TempDir
File tempDir;
private TestCompiler compiler;
@Before
@BeforeEach
public void createCompiler() throws IOException {
this.compiler = new TestCompiler(this.temporaryFolder);
this.compiler = new TestCompiler(this.tempDir);
}
protected TestCompiler getCompiler() {

View File

@@ -16,7 +16,7 @@
package org.springframework.boot.configurationprocessor;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.springframework.boot.configurationprocessor.metadata.ConfigurationMetadata;
import org.springframework.boot.configurationprocessor.metadata.Metadata;
@@ -62,16 +62,16 @@ import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
* @author Kris De Volder
* @author Jonas Keßler
*/
public class ConfigurationMetadataAnnotationProcessorTests extends AbstractMetadataGenerationTests {
class ConfigurationMetadataAnnotationProcessorTests extends AbstractMetadataGenerationTests {
@Test
public void notAnnotated() {
void notAnnotated() {
ConfigurationMetadata metadata = compile(NotAnnotated.class);
assertThat(metadata.getItems()).isEmpty();
}
@Test
public void simpleProperties() {
void simpleProperties() {
ConfigurationMetadata metadata = compile(SimpleProperties.class);
assertThat(metadata).has(Metadata.withGroup("simple").fromSource(SimpleProperties.class));
assertThat(metadata).has(Metadata.withProperty("simple.the-name", String.class)
@@ -85,7 +85,7 @@ public class ConfigurationMetadataAnnotationProcessorTests extends AbstractMetad
}
@Test
public void simplePrefixValueProperties() {
void simplePrefixValueProperties() {
ConfigurationMetadata metadata = compile(SimplePrefixValueProperties.class);
assertThat(metadata).has(Metadata.withGroup("simple").fromSource(SimplePrefixValueProperties.class));
assertThat(metadata)
@@ -93,7 +93,7 @@ public class ConfigurationMetadataAnnotationProcessorTests extends AbstractMetad
}
@Test
public void simpleTypeProperties() {
void simpleTypeProperties() {
ConfigurationMetadata metadata = compile(SimpleTypeProperties.class);
assertThat(metadata).has(Metadata.withGroup("simple.type").fromSource(SimpleTypeProperties.class));
assertThat(metadata).has(Metadata.withProperty("simple.type.my-string", String.class));
@@ -122,7 +122,7 @@ public class ConfigurationMetadataAnnotationProcessorTests extends AbstractMetad
}
@Test
public void hierarchicalProperties() {
void hierarchicalProperties() {
ConfigurationMetadata metadata = compile(HierarchicalProperties.class, HierarchicalPropertiesParent.class,
HierarchicalPropertiesGrandparent.class);
assertThat(metadata).has(Metadata.withGroup("hierarchical").fromSource(HierarchicalProperties.class));
@@ -135,7 +135,7 @@ public class ConfigurationMetadataAnnotationProcessorTests extends AbstractMetad
}
@Test
public void descriptionProperties() {
void descriptionProperties() {
ConfigurationMetadata metadata = compile(DescriptionProperties.class);
assertThat(metadata).has(Metadata.withGroup("description").fromSource(DescriptionProperties.class));
assertThat(metadata).has(Metadata.withProperty("description.simple", String.class)
@@ -147,7 +147,7 @@ public class ConfigurationMetadataAnnotationProcessorTests extends AbstractMetad
@Test
@SuppressWarnings("deprecation")
public void deprecatedProperties() {
void deprecatedProperties() {
Class<?> type = org.springframework.boot.configurationsample.simple.DeprecatedProperties.class;
ConfigurationMetadata metadata = compile(type);
assertThat(metadata).has(Metadata.withGroup("deprecated").fromSource(type));
@@ -158,7 +158,7 @@ public class ConfigurationMetadataAnnotationProcessorTests extends AbstractMetad
}
@Test
public void singleDeprecatedProperty() {
void singleDeprecatedProperty() {
Class<?> type = DeprecatedSingleProperty.class;
ConfigurationMetadata metadata = compile(type);
assertThat(metadata).has(Metadata.withGroup("singledeprecated").fromSource(type));
@@ -168,7 +168,7 @@ public class ConfigurationMetadataAnnotationProcessorTests extends AbstractMetad
}
@Test
public void deprecatedOnUnrelatedSetter() {
void deprecatedOnUnrelatedSetter() {
Class<?> type = DeprecatedUnrelatedMethodPojo.class;
ConfigurationMetadata metadata = compile(type);
assertThat(metadata).has(Metadata.withGroup("not.deprecated").fromSource(type));
@@ -179,7 +179,7 @@ public class ConfigurationMetadataAnnotationProcessorTests extends AbstractMetad
}
@Test
public void boxingOnSetter() {
void boxingOnSetter() {
Class<?> type = BoxingPojo.class;
ConfigurationMetadata metadata = compile(type);
assertThat(metadata).has(Metadata.withGroup("boxing").fromSource(type));
@@ -189,7 +189,7 @@ public class ConfigurationMetadataAnnotationProcessorTests extends AbstractMetad
}
@Test
public void parseCollectionConfig() {
void parseCollectionConfig() {
ConfigurationMetadata metadata = compile(SimpleCollectionProperties.class);
// getter and setter
assertThat(metadata).has(Metadata.withProperty("collection.integers-to-names",
@@ -206,7 +206,7 @@ public class ConfigurationMetadataAnnotationProcessorTests extends AbstractMetad
}
@Test
public void parseArrayConfig() throws Exception {
void parseArrayConfig() throws Exception {
ConfigurationMetadata metadata = compile(SimpleArrayProperties.class);
assertThat(metadata).has(Metadata.withGroup("array").ofType(SimpleArrayProperties.class));
assertThat(metadata).has(Metadata.withProperty("array.primitive", "java.lang.Integer[]"));
@@ -219,7 +219,7 @@ public class ConfigurationMetadataAnnotationProcessorTests extends AbstractMetad
}
@Test
public void annotatedGetter() {
void annotatedGetter() {
ConfigurationMetadata metadata = compile(AnnotatedGetter.class);
assertThat(metadata).has(Metadata.withGroup("specific").fromSource(AnnotatedGetter.class));
assertThat(metadata)
@@ -227,7 +227,7 @@ public class ConfigurationMetadataAnnotationProcessorTests extends AbstractMetad
}
@Test
public void staticAccessor() {
void staticAccessor() {
ConfigurationMetadata metadata = compile(StaticAccessor.class);
assertThat(metadata).has(Metadata.withGroup("specific").fromSource(StaticAccessor.class));
assertThat(metadata).has(Metadata.withProperty("specific.counter", Integer.class)
@@ -238,13 +238,13 @@ public class ConfigurationMetadataAnnotationProcessorTests extends AbstractMetad
}
@Test
public void innerClassRootConfig() {
void innerClassRootConfig() {
ConfigurationMetadata metadata = compile(InnerClassRootConfig.class);
assertThat(metadata).has(Metadata.withProperty("config.name"));
}
@Test
public void innerClassProperties() {
void innerClassProperties() {
ConfigurationMetadata metadata = compile(InnerClassProperties.class);
assertThat(metadata).has(Metadata.withGroup("config").fromSource(InnerClassProperties.class));
assertThat(metadata).has(Metadata.withGroup("config.first").ofType(InnerClassProperties.Foo.class)
@@ -263,7 +263,7 @@ public class ConfigurationMetadataAnnotationProcessorTests extends AbstractMetad
}
@Test
public void innerClassPropertiesHierarchical() {
void innerClassPropertiesHierarchical() {
ConfigurationMetadata metadata = compile(InnerClassHierarchicalProperties.class);
assertThat(metadata).has(Metadata.withGroup("config.foo").ofType(InnerClassHierarchicalProperties.Foo.class));
assertThat(metadata)
@@ -275,7 +275,7 @@ public class ConfigurationMetadataAnnotationProcessorTests extends AbstractMetad
}
@Test
public void innerClassAnnotatedGetterConfig() {
void innerClassAnnotatedGetterConfig() {
ConfigurationMetadata metadata = compile(InnerClassAnnotatedGetterConfig.class);
assertThat(metadata).has(Metadata.withProperty("specific.value"));
assertThat(metadata).has(Metadata.withProperty("foo.name"));
@@ -283,7 +283,7 @@ public class ConfigurationMetadataAnnotationProcessorTests extends AbstractMetad
}
@Test
public void nestedClassChildProperties() {
void nestedClassChildProperties() {
ConfigurationMetadata metadata = compile(ClassWithNestedProperties.class);
assertThat(metadata).has(
Metadata.withGroup("nestedChildProps").fromSource(ClassWithNestedProperties.NestedChildClass.class));
@@ -294,13 +294,13 @@ public class ConfigurationMetadataAnnotationProcessorTests extends AbstractMetad
}
@Test
public void builderPojo() {
void builderPojo() {
ConfigurationMetadata metadata = compile(BuilderPojo.class);
assertThat(metadata).has(Metadata.withProperty("builder.name"));
}
@Test
public void excludedTypesPojo() {
void excludedTypesPojo() {
ConfigurationMetadata metadata = compile(ExcludedTypesPojo.class);
assertThat(metadata).has(Metadata.withProperty("excluded.name"));
assertThat(metadata).isNotEqualTo(Metadata.withProperty("excluded.class-loader"));
@@ -311,14 +311,14 @@ public class ConfigurationMetadataAnnotationProcessorTests extends AbstractMetad
}
@Test
public void invalidAccessor() {
void invalidAccessor() {
ConfigurationMetadata metadata = compile(InvalidAccessorProperties.class);
assertThat(metadata).has(Metadata.withGroup("config"));
assertThat(metadata.getItems()).hasSize(1);
}
@Test
public void doubleRegistration() {
void doubleRegistration() {
ConfigurationMetadata metadata = compile(DoubleRegistrationProperties.class);
assertThat(metadata).has(Metadata.withGroup("one"));
assertThat(metadata).has(Metadata.withGroup("two"));
@@ -328,25 +328,25 @@ public class ConfigurationMetadataAnnotationProcessorTests extends AbstractMetad
}
@Test
public void invalidDoubleRegistration() {
void invalidDoubleRegistration() {
assertThatIllegalStateException().isThrownBy(() -> compile(InvalidDoubleRegistrationProperties.class))
.withMessageContaining("Compilation failed");
}
@Test
public void constructorParameterPropertyWithInvalidDefaultValueOnNumber() {
void constructorParameterPropertyWithInvalidDefaultValueOnNumber() {
assertThatIllegalStateException().isThrownBy(() -> compile(InvalidDefaultValueNumberProperties.class))
.withMessageContaining("Compilation failed");
}
@Test
public void constructorParameterPropertyWithInvalidDefaultValueOnFloatingPoint() {
void constructorParameterPropertyWithInvalidDefaultValueOnFloatingPoint() {
assertThatIllegalStateException().isThrownBy(() -> compile(InvalidDefaultValueFloatingPointProperties.class))
.withMessageContaining("Compilation failed");
}
@Test
public void constructorParameterPropertyWithInvalidDefaultValueOnCharacter() {
void constructorParameterPropertyWithInvalidDefaultValueOnCharacter() {
assertThatIllegalStateException().isThrownBy(() -> compile(InvalidDefaultValueCharacterProperties.class))
.withMessageContaining("Compilation failed");
}

View File

@@ -26,7 +26,7 @@ import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.util.ElementFilter;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.springframework.boot.configurationsample.immutable.ImmutableCollectionProperties;
import org.springframework.boot.configurationsample.immutable.ImmutableInnerClassProperties;
@@ -42,10 +42,10 @@ import static org.assertj.core.api.Assertions.assertThat;
*
* @author Stephane Nicoll
*/
public class ConstructorParameterPropertyDescriptorTests extends PropertyDescriptorTests {
class ConstructorParameterPropertyDescriptorTests extends PropertyDescriptorTests {
@Test
public void constructorParameterSimpleProperty() throws IOException {
void constructorParameterSimpleProperty() throws IOException {
process(ImmutableSimpleProperties.class, (roundEnv, metadataEnv) -> {
TypeElement ownerElement = roundEnv.getRootElement(ImmutableSimpleProperties.class);
ConstructorParameterPropertyDescriptor property = createPropertyDescriptor(ownerElement, "theName");
@@ -58,7 +58,7 @@ public class ConstructorParameterPropertyDescriptorTests extends PropertyDescrip
}
@Test
public void constructorParameterNestedPropertySameClass() throws IOException {
void constructorParameterNestedPropertySameClass() throws IOException {
process(ImmutableInnerClassProperties.class, (roundEnv, metadataEnv) -> {
TypeElement ownerElement = roundEnv.getRootElement(ImmutableInnerClassProperties.class);
ConstructorParameterPropertyDescriptor property = createPropertyDescriptor(ownerElement, "first");
@@ -71,7 +71,7 @@ public class ConstructorParameterPropertyDescriptorTests extends PropertyDescrip
}
@Test
public void constructorParameterNestedPropertyWithAnnotation() throws IOException {
void constructorParameterNestedPropertyWithAnnotation() throws IOException {
process(ImmutableInnerClassProperties.class, (roundEnv, metadataEnv) -> {
TypeElement ownerElement = roundEnv.getRootElement(ImmutableInnerClassProperties.class);
ConstructorParameterPropertyDescriptor property = createPropertyDescriptor(ownerElement, "third");
@@ -84,7 +84,7 @@ public class ConstructorParameterPropertyDescriptorTests extends PropertyDescrip
}
@Test
public void constructorParameterSimplePropertyWithNoAccessorShouldBeExposed() throws IOException {
void constructorParameterSimplePropertyWithNoAccessorShouldBeExposed() throws IOException {
process(ImmutableSimpleProperties.class, (roundEnv, metadataEnv) -> {
TypeElement ownerElement = roundEnv.getRootElement(ImmutableSimpleProperties.class);
ConstructorParameterPropertyDescriptor property = createPropertyDescriptor(ownerElement, "counter");
@@ -97,7 +97,7 @@ public class ConstructorParameterPropertyDescriptorTests extends PropertyDescrip
}
@Test
public void constructorParameterMetadataSimpleProperty() throws IOException {
void constructorParameterMetadataSimpleProperty() throws IOException {
process(ImmutableSimpleProperties.class, (roundEnv, metadataEnv) -> {
TypeElement ownerElement = roundEnv.getRootElement(ImmutableSimpleProperties.class);
ConstructorParameterPropertyDescriptor property = createPropertyDescriptor(ownerElement, "counter");
@@ -107,7 +107,7 @@ public class ConstructorParameterPropertyDescriptorTests extends PropertyDescrip
}
@Test
public void constructorParameterMetadataNestedGroup() throws IOException {
void constructorParameterMetadataNestedGroup() throws IOException {
process(ImmutableInnerClassProperties.class, (roundEnv, metadataEnv) -> {
TypeElement ownerElement = roundEnv.getRootElement(ImmutableInnerClassProperties.class);
ConstructorParameterPropertyDescriptor property = createPropertyDescriptor(ownerElement, "first");
@@ -119,7 +119,7 @@ public class ConstructorParameterPropertyDescriptorTests extends PropertyDescrip
}
@Test
public void constructorParameterDeprecatedPropertyOnGetter() throws IOException {
void constructorParameterDeprecatedPropertyOnGetter() throws IOException {
process(ImmutableSimpleProperties.class, (roundEnv, metadataEnv) -> {
TypeElement ownerElement = roundEnv.getRootElement(ImmutableSimpleProperties.class);
ExecutableElement getter = getMethod(ownerElement, "isFlag");
@@ -132,7 +132,7 @@ public class ConstructorParameterPropertyDescriptorTests extends PropertyDescrip
}
@Test
public void constructorParameterPropertyWithDescription() throws IOException {
void constructorParameterPropertyWithDescription() throws IOException {
process(ImmutableSimpleProperties.class, (roundEnv, metadataEnv) -> {
TypeElement ownerElement = roundEnv.getRootElement(ImmutableSimpleProperties.class);
ConstructorParameterPropertyDescriptor property = createPropertyDescriptor(ownerElement, "theName");
@@ -142,7 +142,7 @@ public class ConstructorParameterPropertyDescriptorTests extends PropertyDescrip
}
@Test
public void constructorParameterPropertyWithDefaultValue() throws IOException {
void constructorParameterPropertyWithDefaultValue() throws IOException {
process(ImmutableSimpleProperties.class, (roundEnv, metadataEnv) -> {
TypeElement ownerElement = roundEnv.getRootElement(ImmutableSimpleProperties.class);
ConstructorParameterPropertyDescriptor property = createPropertyDescriptor(ownerElement, "theName");
@@ -151,7 +151,7 @@ public class ConstructorParameterPropertyDescriptorTests extends PropertyDescrip
}
@Test
public void constructorParameterPropertyWithPrimitiveTypes() throws IOException {
void constructorParameterPropertyWithPrimitiveTypes() throws IOException {
process(ImmutablePrimitiveProperties.class, (roundEnv, metadataEnv) -> {
TypeElement ownerElement = roundEnv.getRootElement(ImmutablePrimitiveProperties.class);
assertItemMetadata(metadataEnv, createPropertyDescriptor(ownerElement, "flag")).hasDefaultValue(false);
@@ -166,7 +166,7 @@ public class ConstructorParameterPropertyDescriptorTests extends PropertyDescrip
}
@Test
public void constructorParameterPropertyWithPrimitiveTypesAndDefaultValues() throws IOException {
void constructorParameterPropertyWithPrimitiveTypesAndDefaultValues() throws IOException {
process(ImmutablePrimitiveWithDefaultsProperties.class, (roundEnv, metadataEnv) -> {
TypeElement ownerElement = roundEnv.getRootElement(ImmutablePrimitiveWithDefaultsProperties.class);
assertItemMetadata(metadataEnv, createPropertyDescriptor(ownerElement, "flag")).hasDefaultValue(true);
@@ -181,7 +181,7 @@ public class ConstructorParameterPropertyDescriptorTests extends PropertyDescrip
}
@Test
public void constructorParameterPropertyWithPrimitiveWrapperTypesAndDefaultValues() throws IOException {
void constructorParameterPropertyWithPrimitiveWrapperTypesAndDefaultValues() throws IOException {
process(ImmutablePrimitiveWrapperWithDefaultsProperties.class, (roundEnv, metadataEnv) -> {
TypeElement ownerElement = roundEnv.getRootElement(ImmutablePrimitiveWrapperWithDefaultsProperties.class);
assertItemMetadata(metadataEnv, createPropertyDescriptor(ownerElement, "flag")).hasDefaultValue(true);
@@ -196,7 +196,7 @@ public class ConstructorParameterPropertyDescriptorTests extends PropertyDescrip
}
@Test
public void constructorParameterPropertyWithCollectionTypesAndDefaultValues() throws IOException {
void constructorParameterPropertyWithCollectionTypesAndDefaultValues() throws IOException {
process(ImmutableCollectionProperties.class, (roundEnv, metadataEnv) -> {
TypeElement ownerElement = roundEnv.getRootElement(ImmutableCollectionProperties.class);
assertItemMetadata(metadataEnv, createPropertyDescriptor(ownerElement, "names")).hasDefaultValue(null);

View File

@@ -18,7 +18,7 @@ package org.springframework.boot.configurationprocessor;
import java.time.Duration;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.springframework.boot.configurationprocessor.metadata.ConfigurationMetadata;
import org.springframework.boot.configurationprocessor.metadata.Metadata;
@@ -37,10 +37,10 @@ import static org.assertj.core.api.Assertions.assertThat;
*
* @author Stephane Nicoll
*/
public class EndpointMetadataGenerationTests extends AbstractMetadataGenerationTests {
class EndpointMetadataGenerationTests extends AbstractMetadataGenerationTests {
@Test
public void simpleEndpoint() {
void simpleEndpoint() {
ConfigurationMetadata metadata = compile(SimpleEndpoint.class);
assertThat(metadata).has(Metadata.withGroup("management.endpoint.simple").fromSource(SimpleEndpoint.class));
assertThat(metadata).has(enabledFlag("simple", true));
@@ -49,7 +49,7 @@ public class EndpointMetadataGenerationTests extends AbstractMetadataGenerationT
}
@Test
public void disableEndpoint() {
void disableEndpoint() {
ConfigurationMetadata metadata = compile(DisabledEndpoint.class);
assertThat(metadata).has(Metadata.withGroup("management.endpoint.disabled").fromSource(DisabledEndpoint.class));
assertThat(metadata).has(enabledFlag("disabled", false));
@@ -57,7 +57,7 @@ public class EndpointMetadataGenerationTests extends AbstractMetadataGenerationT
}
@Test
public void enabledEndpoint() {
void enabledEndpoint() {
ConfigurationMetadata metadata = compile(EnabledEndpoint.class);
assertThat(metadata).has(Metadata.withGroup("management.endpoint.enabled").fromSource(EnabledEndpoint.class));
assertThat(metadata).has(enabledFlag("enabled", true));
@@ -65,7 +65,7 @@ public class EndpointMetadataGenerationTests extends AbstractMetadataGenerationT
}
@Test
public void customPropertiesEndpoint() {
void customPropertiesEndpoint() {
ConfigurationMetadata metadata = compile(CustomPropertiesEndpoint.class);
assertThat(metadata)
.has(Metadata.withGroup("management.endpoint.customprops").fromSource(CustomPropertiesEndpoint.class));
@@ -77,7 +77,7 @@ public class EndpointMetadataGenerationTests extends AbstractMetadataGenerationT
}
@Test
public void specificEndpoint() {
void specificEndpoint() {
ConfigurationMetadata metadata = compile(SpecificEndpoint.class);
assertThat(metadata).has(Metadata.withGroup("management.endpoint.specific").fromSource(SpecificEndpoint.class));
assertThat(metadata).has(enabledFlag("specific", true));
@@ -86,7 +86,7 @@ public class EndpointMetadataGenerationTests extends AbstractMetadataGenerationT
}
@Test
public void camelCaseEndpoint() {
void camelCaseEndpoint() {
ConfigurationMetadata metadata = compile(CamelCaseEndpoint.class);
assertThat(metadata)
.has(Metadata.withGroup("management.endpoint.pascal-case").fromSource(CamelCaseEndpoint.class));
@@ -95,8 +95,8 @@ public class EndpointMetadataGenerationTests extends AbstractMetadataGenerationT
}
@Test
public void incrementalEndpointBuildChangeGeneralEnabledFlag() throws Exception {
TestProject project = new TestProject(this.temporaryFolder, IncrementalEndpoint.class);
void incrementalEndpointBuildChangeGeneralEnabledFlag() throws Exception {
TestProject project = new TestProject(this.tempDir, IncrementalEndpoint.class);
ConfigurationMetadata metadata = project.fullBuild();
assertThat(metadata)
.has(Metadata.withGroup("management.endpoint.incremental").fromSource(IncrementalEndpoint.class));
@@ -114,8 +114,8 @@ public class EndpointMetadataGenerationTests extends AbstractMetadataGenerationT
}
@Test
public void incrementalEndpointBuildChangeCacheFlag() throws Exception {
TestProject project = new TestProject(this.temporaryFolder, IncrementalEndpoint.class);
void incrementalEndpointBuildChangeCacheFlag() throws Exception {
TestProject project = new TestProject(this.tempDir, IncrementalEndpoint.class);
ConfigurationMetadata metadata = project.fullBuild();
assertThat(metadata)
.has(Metadata.withGroup("management.endpoint.incremental").fromSource(IncrementalEndpoint.class));
@@ -131,8 +131,8 @@ public class EndpointMetadataGenerationTests extends AbstractMetadataGenerationT
}
@Test
public void incrementalEndpointBuildEnableSpecificEndpoint() throws Exception {
TestProject project = new TestProject(this.temporaryFolder, SpecificEndpoint.class);
void incrementalEndpointBuildEnableSpecificEndpoint() throws Exception {
TestProject project = new TestProject(this.tempDir, SpecificEndpoint.class);
ConfigurationMetadata metadata = project.fullBuild();
assertThat(metadata).has(Metadata.withGroup("management.endpoint.specific").fromSource(SpecificEndpoint.class));
assertThat(metadata).has(enabledFlag("specific", true));

View File

@@ -16,7 +16,7 @@
package org.springframework.boot.configurationprocessor;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.springframework.boot.configurationprocessor.metadata.ConfigurationMetadata;
import org.springframework.boot.configurationprocessor.metadata.Metadata;
@@ -35,10 +35,10 @@ import static org.assertj.core.api.Assertions.assertThat;
*
* @author Stephane Nicoll
*/
public class GenericsMetadataGenerationTests extends AbstractMetadataGenerationTests {
class GenericsMetadataGenerationTests extends AbstractMetadataGenerationTests {
@Test
public void simpleGenericProperties() {
void simpleGenericProperties() {
ConfigurationMetadata metadata = compile(AbstractGenericProperties.class, SimpleGenericProperties.class);
assertThat(metadata).has(Metadata.withGroup("generic").fromSource(SimpleGenericProperties.class));
assertThat(metadata).has(Metadata.withProperty("generic.name", String.class)
@@ -50,7 +50,7 @@ public class GenericsMetadataGenerationTests extends AbstractMetadataGenerationT
}
@Test
public void complexGenericProperties() {
void complexGenericProperties() {
ConfigurationMetadata metadata = compile(ComplexGenericProperties.class);
assertThat(metadata).has(Metadata.withGroup("generic").fromSource(ComplexGenericProperties.class));
assertThat(metadata).has(Metadata.withGroup("generic.test").ofType(UpperBoundGenericPojo.class)
@@ -62,7 +62,7 @@ public class GenericsMetadataGenerationTests extends AbstractMetadataGenerationT
}
@Test
public void unresolvedGenericProperties() {
void unresolvedGenericProperties() {
ConfigurationMetadata metadata = compile(AbstractGenericProperties.class, UnresolvedGenericProperties.class);
assertThat(metadata).has(Metadata.withGroup("generic").fromSource(UnresolvedGenericProperties.class));
assertThat(metadata).has(Metadata.withProperty("generic.name", String.class)
@@ -75,7 +75,7 @@ public class GenericsMetadataGenerationTests extends AbstractMetadataGenerationT
}
@Test
public void genericTypes() {
void genericTypes() {
ConfigurationMetadata metadata = compile(GenericConfig.class);
assertThat(metadata).has(Metadata.withGroup("generic")
.ofType("org.springframework.boot.configurationsample.generic.GenericConfig"));
@@ -100,7 +100,7 @@ public class GenericsMetadataGenerationTests extends AbstractMetadataGenerationT
}
@Test
public void wildcardTypes() {
void wildcardTypes() {
ConfigurationMetadata metadata = compile(WildcardConfig.class);
assertThat(metadata).has(Metadata.withGroup("wildcard").ofType(WildcardConfig.class));
assertThat(metadata).has(Metadata.withProperty("wildcard.string-to-number")

View File

@@ -16,7 +16,7 @@
package org.springframework.boot.configurationprocessor;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.springframework.boot.configurationprocessor.metadata.ConfigurationMetadata;
import org.springframework.boot.configurationprocessor.metadata.Metadata;
@@ -29,10 +29,10 @@ import static org.assertj.core.api.Assertions.assertThat;
*
* @author Stephane Nicoll
*/
public class ImmutablePropertiesMetadataGenerationTests extends AbstractMetadataGenerationTests {
class ImmutablePropertiesMetadataGenerationTests extends AbstractMetadataGenerationTests {
@Test
public void immutableSimpleProperties() {
void immutableSimpleProperties() {
ConfigurationMetadata metadata = compile(ImmutableSimpleProperties.class);
assertThat(metadata).has(Metadata.withGroup("immutable").fromSource(ImmutableSimpleProperties.class));
assertThat(metadata).has(

View File

@@ -16,7 +16,7 @@
package org.springframework.boot.configurationprocessor;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.springframework.boot.configurationprocessor.metadata.ConfigurationMetadata;
import org.springframework.boot.configurationprocessor.metadata.Metadata;
@@ -31,11 +31,11 @@ import static org.assertj.core.api.Assertions.assertThat;
*
* @author Stephane Nicoll
*/
public class IncrementalBuildMetadataGenerationTests extends AbstractMetadataGenerationTests {
class IncrementalBuildMetadataGenerationTests extends AbstractMetadataGenerationTests {
@Test
public void incrementalBuild() throws Exception {
TestProject project = new TestProject(this.temporaryFolder, FooProperties.class, BarProperties.class);
void incrementalBuild() throws Exception {
TestProject project = new TestProject(this.tempDir, FooProperties.class, BarProperties.class);
assertThat(project.getOutputFile(MetadataStore.METADATA_PATH).exists()).isFalse();
ConfigurationMetadata metadata = project.fullBuild();
assertThat(project.getOutputFile(MetadataStore.METADATA_PATH).exists()).isTrue();
@@ -61,8 +61,8 @@ public class IncrementalBuildMetadataGenerationTests extends AbstractMetadataGen
}
@Test
public void incrementalBuildAnnotationRemoved() throws Exception {
TestProject project = new TestProject(this.temporaryFolder, FooProperties.class, BarProperties.class);
void incrementalBuildAnnotationRemoved() throws Exception {
TestProject project = new TestProject(this.tempDir, FooProperties.class, BarProperties.class);
ConfigurationMetadata metadata = project.fullBuild();
assertThat(metadata).has(Metadata.withProperty("foo.counter").withDefaultValue(0));
assertThat(metadata).has(Metadata.withProperty("bar.counter").withDefaultValue(0));
@@ -73,8 +73,8 @@ public class IncrementalBuildMetadataGenerationTests extends AbstractMetadataGen
}
@Test
public void incrementalBuildTypeRenamed() throws Exception {
TestProject project = new TestProject(this.temporaryFolder, FooProperties.class, BarProperties.class);
void incrementalBuildTypeRenamed() throws Exception {
TestProject project = new TestProject(this.tempDir, FooProperties.class, BarProperties.class);
ConfigurationMetadata metadata = project.fullBuild();
assertThat(metadata)
.has(Metadata.withProperty("foo.counter").fromSource(FooProperties.class).withDefaultValue(0));

View File

@@ -22,7 +22,7 @@ import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.springframework.boot.configurationsample.simple.DeprecatedSingleProperty;
import org.springframework.boot.configurationsample.simple.SimpleCollectionProperties;
@@ -37,10 +37,10 @@ import static org.assertj.core.api.Assertions.assertThat;
*
* @author Stephane Nicoll
*/
public class JavaBeanPropertyDescriptorTests extends PropertyDescriptorTests {
class JavaBeanPropertyDescriptorTests extends PropertyDescriptorTests {
@Test
public void javaBeanSimpleProperty() throws IOException {
void javaBeanSimpleProperty() throws IOException {
process(SimpleTypeProperties.class, (roundEnv, metadataEnv) -> {
TypeElement ownerElement = roundEnv.getRootElement(SimpleTypeProperties.class);
JavaBeanPropertyDescriptor property = createPropertyDescriptor(ownerElement, "myString");
@@ -54,7 +54,7 @@ public class JavaBeanPropertyDescriptorTests extends PropertyDescriptorTests {
}
@Test
public void javaBeanCollectionProperty() throws IOException {
void javaBeanCollectionProperty() throws IOException {
process(SimpleCollectionProperties.class, (roundEnv, metadataEnv) -> {
TypeElement ownerElement = roundEnv.getRootElement(SimpleCollectionProperties.class);
JavaBeanPropertyDescriptor property = createPropertyDescriptor(ownerElement, "doubles");
@@ -67,7 +67,7 @@ public class JavaBeanPropertyDescriptorTests extends PropertyDescriptorTests {
}
@Test
public void javaBeanNestedPropertySameClass() throws IOException {
void javaBeanNestedPropertySameClass() throws IOException {
process(InnerClassProperties.class, (roundEnv, metadataEnv) -> {
TypeElement ownerElement = roundEnv.getRootElement(InnerClassProperties.class);
JavaBeanPropertyDescriptor property = createPropertyDescriptor(ownerElement, "first");
@@ -80,7 +80,7 @@ public class JavaBeanPropertyDescriptorTests extends PropertyDescriptorTests {
}
@Test
public void javaBeanNestedPropertyWithAnnotation() throws IOException {
void javaBeanNestedPropertyWithAnnotation() throws IOException {
process(InnerClassProperties.class, (roundEnv, metadataEnv) -> {
TypeElement ownerElement = roundEnv.getRootElement(InnerClassProperties.class);
JavaBeanPropertyDescriptor property = createPropertyDescriptor(ownerElement, "third");
@@ -93,7 +93,7 @@ public class JavaBeanPropertyDescriptorTests extends PropertyDescriptorTests {
}
@Test
public void javaBeanSimplePropertyWithOnlyGetterShouldNotBeExposed() throws IOException {
void javaBeanSimplePropertyWithOnlyGetterShouldNotBeExposed() throws IOException {
process(SimpleProperties.class, (roundEnv, metadataEnv) -> {
TypeElement ownerElement = roundEnv.getRootElement(SimpleProperties.class);
ExecutableElement getter = getMethod(ownerElement, "getSize");
@@ -110,7 +110,7 @@ public class JavaBeanPropertyDescriptorTests extends PropertyDescriptorTests {
}
@Test
public void javaBeanSimplePropertyWithOnlySetterShouldNotBeExposed() throws IOException {
void javaBeanSimplePropertyWithOnlySetterShouldNotBeExposed() throws IOException {
process(SimpleProperties.class, (roundEnv, metadataEnv) -> {
TypeElement ownerElement = roundEnv.getRootElement(SimpleProperties.class);
VariableElement field = getField(ownerElement, "counter");
@@ -126,7 +126,7 @@ public class JavaBeanPropertyDescriptorTests extends PropertyDescriptorTests {
}
@Test
public void javaBeanMetadataSimpleProperty() throws IOException {
void javaBeanMetadataSimpleProperty() throws IOException {
process(SimpleTypeProperties.class, (roundEnv, metadataEnv) -> {
TypeElement ownerElement = roundEnv.getRootElement(SimpleTypeProperties.class);
JavaBeanPropertyDescriptor property = createPropertyDescriptor(ownerElement, "myString");
@@ -136,7 +136,7 @@ public class JavaBeanPropertyDescriptorTests extends PropertyDescriptorTests {
}
@Test
public void javaBeanMetadataCollectionProperty() throws IOException {
void javaBeanMetadataCollectionProperty() throws IOException {
process(SimpleCollectionProperties.class, (roundEnv, metadataEnv) -> {
TypeElement ownerElement = roundEnv.getRootElement(SimpleCollectionProperties.class);
JavaBeanPropertyDescriptor property = createPropertyDescriptor(ownerElement, "doubles");
@@ -147,7 +147,7 @@ public class JavaBeanPropertyDescriptorTests extends PropertyDescriptorTests {
}
@Test
public void javaBeanMetadataNestedGroup() throws IOException {
void javaBeanMetadataNestedGroup() throws IOException {
process(InnerClassProperties.class, (roundEnv, metadataEnv) -> {
TypeElement ownerElement = roundEnv.getRootElement(InnerClassProperties.class);
JavaBeanPropertyDescriptor property = createPropertyDescriptor(ownerElement, "first");
@@ -159,7 +159,7 @@ public class JavaBeanPropertyDescriptorTests extends PropertyDescriptorTests {
}
@Test
public void javaBeanMetadataNotACandidatePropertyShouldReturnNull() throws IOException {
void javaBeanMetadataNotACandidatePropertyShouldReturnNull() throws IOException {
process(SimpleProperties.class, (roundEnv, metadataEnv) -> {
TypeElement ownerElement = roundEnv.getRootElement(SimpleProperties.class);
VariableElement field = getField(ownerElement, "counter");
@@ -171,7 +171,7 @@ public class JavaBeanPropertyDescriptorTests extends PropertyDescriptorTests {
@Test
@SuppressWarnings("deprecation")
public void javaBeanDeprecatedPropertyOnClass() throws IOException {
void javaBeanDeprecatedPropertyOnClass() throws IOException {
process(org.springframework.boot.configurationsample.simple.DeprecatedProperties.class,
(roundEnv, metadataEnv) -> {
TypeElement ownerElement = roundEnv.getRootElement(
@@ -182,7 +182,7 @@ public class JavaBeanPropertyDescriptorTests extends PropertyDescriptorTests {
}
@Test
public void javaBeanMetadataDeprecatedPropertyWithAnnotation() throws IOException {
void javaBeanMetadataDeprecatedPropertyWithAnnotation() throws IOException {
process(DeprecatedSingleProperty.class, (roundEnv, metadataEnv) -> {
TypeElement ownerElement = roundEnv.getRootElement(DeprecatedSingleProperty.class);
JavaBeanPropertyDescriptor property = createPropertyDescriptor(ownerElement, "name");
@@ -192,7 +192,7 @@ public class JavaBeanPropertyDescriptorTests extends PropertyDescriptorTests {
}
@Test
public void javaBeanDeprecatedPropertyOnGetter() throws IOException {
void javaBeanDeprecatedPropertyOnGetter() throws IOException {
process(SimpleProperties.class, (roundEnv, metadataEnv) -> {
TypeElement ownerElement = roundEnv.getRootElement(SimpleProperties.class);
JavaBeanPropertyDescriptor property = createPropertyDescriptor(ownerElement, "flag", "isFlag", "setFlag");
@@ -201,7 +201,7 @@ public class JavaBeanPropertyDescriptorTests extends PropertyDescriptorTests {
}
@Test
public void javaBeanDeprecatedPropertyOnSetter() throws IOException {
void javaBeanDeprecatedPropertyOnSetter() throws IOException {
process(SimpleProperties.class, (roundEnv, metadataEnv) -> {
TypeElement ownerElement = roundEnv.getRootElement(SimpleProperties.class);
JavaBeanPropertyDescriptor property = createPropertyDescriptor(ownerElement, "theName");
@@ -210,7 +210,7 @@ public class JavaBeanPropertyDescriptorTests extends PropertyDescriptorTests {
}
@Test
public void javaBeanPropertyWithDescription() throws IOException {
void javaBeanPropertyWithDescription() throws IOException {
process(SimpleProperties.class, (roundEnv, metadataEnv) -> {
TypeElement ownerElement = roundEnv.getRootElement(SimpleProperties.class);
JavaBeanPropertyDescriptor property = createPropertyDescriptor(ownerElement, "theName");
@@ -220,7 +220,7 @@ public class JavaBeanPropertyDescriptorTests extends PropertyDescriptorTests {
}
@Test
public void javaBeanPropertyWithDefaultValue() throws IOException {
void javaBeanPropertyWithDefaultValue() throws IOException {
process(SimpleProperties.class, (roundEnv, metadataEnv) -> {
TypeElement ownerElement = roundEnv.getRootElement(SimpleProperties.class);
JavaBeanPropertyDescriptor property = createPropertyDescriptor(ownerElement, "theName");

View File

@@ -16,7 +16,7 @@
package org.springframework.boot.configurationprocessor;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.springframework.boot.configurationprocessor.metadata.ConfigurationMetadata;
import org.springframework.boot.configurationprocessor.metadata.Metadata;
@@ -38,56 +38,56 @@ import static org.assertj.core.api.Assertions.assertThat;
*
* @author Stephane Nicoll
*/
public class LombokMetadataGenerationTests extends AbstractMetadataGenerationTests {
class LombokMetadataGenerationTests extends AbstractMetadataGenerationTests {
@Test
public void lombokDataProperties() {
void lombokDataProperties() {
ConfigurationMetadata metadata = compile(LombokSimpleDataProperties.class);
assertSimpleLombokProperties(metadata, LombokSimpleDataProperties.class, "data");
}
@Test
public void lombokSimpleProperties() {
void lombokSimpleProperties() {
ConfigurationMetadata metadata = compile(LombokSimpleProperties.class);
assertSimpleLombokProperties(metadata, LombokSimpleProperties.class, "simple");
}
@Test
public void lombokExplicitProperties() {
void lombokExplicitProperties() {
ConfigurationMetadata metadata = compile(LombokExplicitProperties.class);
assertSimpleLombokProperties(metadata, LombokExplicitProperties.class, "explicit");
assertThat(metadata.getItems()).hasSize(6);
}
@Test
public void lombokAccessLevelProperties() {
void lombokAccessLevelProperties() {
ConfigurationMetadata metadata = compile(LombokAccessLevelProperties.class);
assertAccessLevelLombokProperties(metadata, LombokAccessLevelProperties.class, "accesslevel", 2);
}
@Test
public void lombokAccessLevelOverwriteDataProperties() {
void lombokAccessLevelOverwriteDataProperties() {
ConfigurationMetadata metadata = compile(LombokAccessLevelOverwriteDataProperties.class);
assertAccessLevelOverwriteLombokProperties(metadata, LombokAccessLevelOverwriteDataProperties.class,
"accesslevel.overwrite.data");
}
@Test
public void lombokAccessLevelOverwriteExplicitProperties() {
void lombokAccessLevelOverwriteExplicitProperties() {
ConfigurationMetadata metadata = compile(LombokAccessLevelOverwriteExplicitProperties.class);
assertAccessLevelOverwriteLombokProperties(metadata, LombokAccessLevelOverwriteExplicitProperties.class,
"accesslevel.overwrite.explicit");
}
@Test
public void lombokAccessLevelOverwriteDefaultProperties() {
void lombokAccessLevelOverwriteDefaultProperties() {
ConfigurationMetadata metadata = compile(LombokAccessLevelOverwriteDefaultProperties.class);
assertAccessLevelOverwriteLombokProperties(metadata, LombokAccessLevelOverwriteDefaultProperties.class,
"accesslevel.overwrite.default");
}
@Test
public void lombokInnerClassProperties() {
void lombokInnerClassProperties() {
ConfigurationMetadata metadata = compile(LombokInnerClassProperties.class);
assertThat(metadata).has(Metadata.withGroup("config").fromSource(LombokInnerClassProperties.class));
assertThat(metadata).has(Metadata.withGroup("config.first").ofType(LombokInnerClassProperties.Foo.class)
@@ -111,7 +111,7 @@ public class LombokMetadataGenerationTests extends AbstractMetadataGenerationTes
}
@Test
public void lombokInnerClassWithGetterProperties() {
void lombokInnerClassWithGetterProperties() {
ConfigurationMetadata metadata = compile(LombokInnerClassWithGetterProperties.class);
assertThat(metadata).has(Metadata.withGroup("config").fromSource(LombokInnerClassWithGetterProperties.class));
assertThat(metadata)

View File

@@ -22,7 +22,7 @@ import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.springframework.boot.configurationsample.lombok.LombokDefaultValueProperties;
import org.springframework.boot.configurationsample.lombok.LombokDeprecatedSingleProperty;
@@ -40,10 +40,10 @@ import static org.assertj.core.api.Assertions.assertThat;
*
* @author Stephane Nicoll
*/
public class LombokPropertyDescriptorTests extends PropertyDescriptorTests {
class LombokPropertyDescriptorTests extends PropertyDescriptorTests {
@Test
public void lombokSimpleProperty() throws IOException {
void lombokSimpleProperty() throws IOException {
process(LombokSimpleProperties.class, (roundEnv, metadataEnv) -> {
TypeElement ownerElement = roundEnv.getRootElement(LombokSimpleProperties.class);
LombokPropertyDescriptor property = createPropertyDescriptor(ownerElement, "name");
@@ -56,7 +56,7 @@ public class LombokPropertyDescriptorTests extends PropertyDescriptorTests {
}
@Test
public void lombokCollectionProperty() throws IOException {
void lombokCollectionProperty() throws IOException {
process(LombokSimpleProperties.class, (roundEnv, metadataEnv) -> {
TypeElement ownerElement = roundEnv.getRootElement(LombokSimpleProperties.class);
LombokPropertyDescriptor property = createPropertyDescriptor(ownerElement, "items");
@@ -69,7 +69,7 @@ public class LombokPropertyDescriptorTests extends PropertyDescriptorTests {
}
@Test
public void lombokNestedPropertySameClass() throws IOException {
void lombokNestedPropertySameClass() throws IOException {
process(LombokInnerClassProperties.class, (roundEnv, metadataEnv) -> {
TypeElement ownerElement = roundEnv.getRootElement(LombokInnerClassProperties.class);
LombokPropertyDescriptor property = createPropertyDescriptor(ownerElement, "first");
@@ -82,7 +82,7 @@ public class LombokPropertyDescriptorTests extends PropertyDescriptorTests {
}
@Test
public void lombokNestedPropertyWithAnnotation() throws IOException {
void lombokNestedPropertyWithAnnotation() throws IOException {
process(LombokInnerClassProperties.class, (roundEnv, metadataEnv) -> {
TypeElement ownerElement = roundEnv.getRootElement(LombokInnerClassProperties.class);
LombokPropertyDescriptor property = createPropertyDescriptor(ownerElement, "third");
@@ -95,7 +95,7 @@ public class LombokPropertyDescriptorTests extends PropertyDescriptorTests {
}
@Test
public void lombokSimplePropertyWithOnlyGetterOnClassShouldNotBeExposed() throws IOException {
void lombokSimplePropertyWithOnlyGetterOnClassShouldNotBeExposed() throws IOException {
process(LombokSimpleProperties.class, (roundEnv, metadataEnv) -> {
TypeElement ownerElement = roundEnv.getRootElement(LombokSimpleProperties.class);
LombokPropertyDescriptor property = createPropertyDescriptor(ownerElement, "ignored");
@@ -105,7 +105,7 @@ public class LombokPropertyDescriptorTests extends PropertyDescriptorTests {
}
@Test
public void lombokSimplePropertyWithOnlyGetterOnDataClassShouldNotBeExposed() throws IOException {
void lombokSimplePropertyWithOnlyGetterOnDataClassShouldNotBeExposed() throws IOException {
process(LombokSimpleDataProperties.class, (roundEnv, metadataEnv) -> {
TypeElement ownerElement = roundEnv.getRootElement(LombokSimpleDataProperties.class);
LombokPropertyDescriptor property = createPropertyDescriptor(ownerElement, "ignored");
@@ -115,7 +115,7 @@ public class LombokPropertyDescriptorTests extends PropertyDescriptorTests {
}
@Test
public void lombokSimplePropertyWithOnlyGetterOnFieldShouldNotBeExposed() throws IOException {
void lombokSimplePropertyWithOnlyGetterOnFieldShouldNotBeExposed() throws IOException {
process(LombokExplicitProperties.class, (roundEnv, metadataEnv) -> {
TypeElement ownerElement = roundEnv.getRootElement(LombokExplicitProperties.class);
LombokPropertyDescriptor property = createPropertyDescriptor(ownerElement, "ignoredOnlyGetter");
@@ -125,7 +125,7 @@ public class LombokPropertyDescriptorTests extends PropertyDescriptorTests {
}
@Test
public void lombokSimplePropertyWithOnlySetterOnFieldShouldNotBeExposed() throws IOException {
void lombokSimplePropertyWithOnlySetterOnFieldShouldNotBeExposed() throws IOException {
process(LombokExplicitProperties.class, (roundEnv, metadataEnv) -> {
TypeElement ownerElement = roundEnv.getRootElement(LombokExplicitProperties.class);
LombokPropertyDescriptor property = createPropertyDescriptor(ownerElement, "ignoredOnlySetter");
@@ -135,7 +135,7 @@ public class LombokPropertyDescriptorTests extends PropertyDescriptorTests {
}
@Test
public void lombokMetadataSimpleProperty() throws IOException {
void lombokMetadataSimpleProperty() throws IOException {
process(LombokSimpleProperties.class, (roundEnv, metadataEnv) -> {
TypeElement ownerElement = roundEnv.getRootElement(LombokSimpleProperties.class);
LombokPropertyDescriptor property = createPropertyDescriptor(ownerElement, "description");
@@ -145,7 +145,7 @@ public class LombokPropertyDescriptorTests extends PropertyDescriptorTests {
}
@Test
public void lombokMetadataCollectionProperty() throws IOException {
void lombokMetadataCollectionProperty() throws IOException {
process(LombokSimpleProperties.class, (roundEnv, metadataEnv) -> {
TypeElement ownerElement = roundEnv.getRootElement(LombokSimpleProperties.class);
LombokPropertyDescriptor property = createPropertyDescriptor(ownerElement, "items");
@@ -156,7 +156,7 @@ public class LombokPropertyDescriptorTests extends PropertyDescriptorTests {
}
@Test
public void lombokMetadataNestedGroup() throws IOException {
void lombokMetadataNestedGroup() throws IOException {
process(LombokInnerClassProperties.class, (roundEnv, metadataEnv) -> {
TypeElement ownerElement = roundEnv.getRootElement(LombokInnerClassProperties.class);
VariableElement field = getField(ownerElement, "third");
@@ -171,7 +171,7 @@ public class LombokPropertyDescriptorTests extends PropertyDescriptorTests {
}
@Test
public void lombokMetadataNestedGroupNoGetter() throws IOException {
void lombokMetadataNestedGroupNoGetter() throws IOException {
process(LombokInnerClassProperties.class, (roundEnv, metadataEnv) -> {
TypeElement ownerElement = roundEnv.getRootElement(LombokInnerClassProperties.class);
LombokPropertyDescriptor property = createPropertyDescriptor(ownerElement, "first");
@@ -183,7 +183,7 @@ public class LombokPropertyDescriptorTests extends PropertyDescriptorTests {
}
@Test
public void lombokMetadataNotACandidatePropertyShouldReturnNull() throws IOException {
void lombokMetadataNotACandidatePropertyShouldReturnNull() throws IOException {
process(LombokSimpleProperties.class, (roundEnv, metadataEnv) -> {
TypeElement ownerElement = roundEnv.getRootElement(LombokSimpleProperties.class);
LombokPropertyDescriptor property = createPropertyDescriptor(ownerElement, "ignored");
@@ -193,7 +193,7 @@ public class LombokPropertyDescriptorTests extends PropertyDescriptorTests {
@Test
@SuppressWarnings("deprecation")
public void lombokDeprecatedPropertyOnClass() throws IOException {
void lombokDeprecatedPropertyOnClass() throws IOException {
process(org.springframework.boot.configurationsample.lombok.LombokDeprecatedProperties.class,
(roundEnv, metadataEnv) -> {
TypeElement ownerElement = roundEnv.getRootElement(
@@ -204,7 +204,7 @@ public class LombokPropertyDescriptorTests extends PropertyDescriptorTests {
}
@Test
public void lombokDeprecatedPropertyOnField() throws IOException {
void lombokDeprecatedPropertyOnField() throws IOException {
process(LombokDeprecatedSingleProperty.class, (roundEnv, metadataEnv) -> {
TypeElement ownerElement = roundEnv.getRootElement(LombokDeprecatedSingleProperty.class);
LombokPropertyDescriptor property = createPropertyDescriptor(ownerElement, "name");
@@ -213,7 +213,7 @@ public class LombokPropertyDescriptorTests extends PropertyDescriptorTests {
}
@Test
public void lombokPropertyWithDescription() throws IOException {
void lombokPropertyWithDescription() throws IOException {
process(LombokSimpleProperties.class, (roundEnv, metadataEnv) -> {
TypeElement ownerElement = roundEnv.getRootElement(LombokSimpleProperties.class);
LombokPropertyDescriptor property = createPropertyDescriptor(ownerElement, "name");
@@ -222,7 +222,7 @@ public class LombokPropertyDescriptorTests extends PropertyDescriptorTests {
}
@Test
public void lombokPropertyWithDefaultValue() throws IOException {
void lombokPropertyWithDefaultValue() throws IOException {
process(LombokDefaultValueProperties.class, (roundEnv, metadataEnv) -> {
TypeElement ownerElement = roundEnv.getRootElement(LombokDefaultValueProperties.class);
LombokPropertyDescriptor property = createPropertyDescriptor(ownerElement, "description");
@@ -231,7 +231,7 @@ public class LombokPropertyDescriptorTests extends PropertyDescriptorTests {
}
@Test
public void lombokPropertyNotCandidate() throws IOException {
void lombokPropertyNotCandidate() throws IOException {
process(SimpleProperties.class, (roundEnv, metadataEnv) -> {
TypeElement ownerElement = roundEnv.getRootElement(SimpleProperties.class);
LombokPropertyDescriptor property = createPropertyDescriptor(ownerElement, "theName");
@@ -241,7 +241,7 @@ public class LombokPropertyDescriptorTests extends PropertyDescriptorTests {
}
@Test
public void lombokNestedPropertyNotCandidate() throws IOException {
void lombokNestedPropertyNotCandidate() throws IOException {
process(InnerClassProperties.class, (roundEnv, metadataEnv) -> {
TypeElement ownerElement = roundEnv.getRootElement(InnerClassProperties.class);
LombokPropertyDescriptor property = createPropertyDescriptor(ownerElement, "first");

View File

@@ -24,7 +24,7 @@ import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.springframework.boot.configurationprocessor.json.JSONArray;
import org.springframework.boot.configurationprocessor.json.JSONObject;
@@ -47,10 +47,10 @@ import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
*
* @author Stephane Nicoll
*/
public class MergeMetadataGenerationTests extends AbstractMetadataGenerationTests {
class MergeMetadataGenerationTests extends AbstractMetadataGenerationTests {
@Test
public void mergingOfAdditionalProperty() throws Exception {
void mergingOfAdditionalProperty() throws Exception {
ItemMetadata property = ItemMetadata.newProperty(null, "foo", "java.lang.String",
AdditionalMetadata.class.getName(), null, null, null, null);
writeAdditionalMetadata(property);
@@ -60,7 +60,7 @@ public class MergeMetadataGenerationTests extends AbstractMetadataGenerationTest
}
@Test
public void mergingOfAdditionalPropertyMatchingGroup() throws Exception {
void mergingOfAdditionalPropertyMatchingGroup() throws Exception {
ItemMetadata property = ItemMetadata.newProperty(null, "simple", "java.lang.String", null, null, null, null,
null);
writeAdditionalMetadata(property);
@@ -70,7 +70,7 @@ public class MergeMetadataGenerationTests extends AbstractMetadataGenerationTest
}
@Test
public void mergeExistingPropertyDefaultValue() throws Exception {
void mergeExistingPropertyDefaultValue() throws Exception {
ItemMetadata property = ItemMetadata.newProperty("simple", "flag", null, null, null, null, true, null);
writeAdditionalMetadata(property);
ConfigurationMetadata metadata = compile(SimpleProperties.class);
@@ -80,7 +80,7 @@ public class MergeMetadataGenerationTests extends AbstractMetadataGenerationTest
}
@Test
public void mergeExistingPropertyWithSeveralCandidates() throws Exception {
void mergeExistingPropertyWithSeveralCandidates() throws Exception {
ItemMetadata property = ItemMetadata.newProperty("simple", "flag", Boolean.class.getName(), null, null, null,
true, null);
writeAdditionalMetadata(property);
@@ -104,7 +104,7 @@ public class MergeMetadataGenerationTests extends AbstractMetadataGenerationTest
}
@Test
public void mergeExistingPropertyDescription() throws Exception {
void mergeExistingPropertyDescription() throws Exception {
ItemMetadata property = ItemMetadata.newProperty("simple", "comparator", null, null, null, "A nice comparator.",
null, null);
writeAdditionalMetadata(property);
@@ -115,7 +115,7 @@ public class MergeMetadataGenerationTests extends AbstractMetadataGenerationTest
}
@Test
public void mergeExistingPropertyDeprecation() throws Exception {
void mergeExistingPropertyDeprecation() throws Exception {
ItemMetadata property = ItemMetadata.newProperty("simple", "comparator", null, null, null, null, null,
new ItemDeprecation("Don't use this.", "simple.complex-comparator", "error"));
writeAdditionalMetadata(property);
@@ -127,7 +127,7 @@ public class MergeMetadataGenerationTests extends AbstractMetadataGenerationTest
}
@Test
public void mergeExistingPropertyDeprecationOverride() throws Exception {
void mergeExistingPropertyDeprecationOverride() throws Exception {
ItemMetadata property = ItemMetadata.newProperty("singledeprecated", "name", null, null, null, null, null,
new ItemDeprecation("Don't use this.", "single.name"));
writeAdditionalMetadata(property);
@@ -138,7 +138,7 @@ public class MergeMetadataGenerationTests extends AbstractMetadataGenerationTest
}
@Test
public void mergeExistingPropertyDeprecationOverrideLevel() throws Exception {
void mergeExistingPropertyDeprecationOverrideLevel() throws Exception {
ItemMetadata property = ItemMetadata.newProperty("singledeprecated", "name", null, null, null, null, null,
new ItemDeprecation(null, null, "error"));
writeAdditionalMetadata(property);
@@ -150,7 +150,7 @@ public class MergeMetadataGenerationTests extends AbstractMetadataGenerationTest
}
@Test
public void mergeOfInvalidAdditionalMetadata() throws IOException {
void mergeOfInvalidAdditionalMetadata() throws IOException {
File additionalMetadataFile = createAdditionalMetadataFile();
FileCopyUtils.copy("Hello World", new FileWriter(additionalMetadataFile));
assertThatIllegalStateException().isThrownBy(() -> compile(SimpleProperties.class))
@@ -158,7 +158,7 @@ public class MergeMetadataGenerationTests extends AbstractMetadataGenerationTest
}
@Test
public void mergingOfSimpleHint() throws Exception {
void mergingOfSimpleHint() throws Exception {
writeAdditionalHints(ItemHint.newHint("simple.the-name", new ItemHint.ValueHint("boot", "Bla bla"),
new ItemHint.ValueHint("spring", null)));
ConfigurationMetadata metadata = compile(SimpleProperties.class);
@@ -170,7 +170,7 @@ public class MergeMetadataGenerationTests extends AbstractMetadataGenerationTest
}
@Test
public void mergingOfHintWithNonCanonicalName() throws Exception {
void mergingOfHintWithNonCanonicalName() throws Exception {
writeAdditionalHints(ItemHint.newHint("simple.theName", new ItemHint.ValueHint("boot", "Bla bla")));
ConfigurationMetadata metadata = compile(SimpleProperties.class);
assertThat(metadata).has(Metadata.withProperty("simple.the-name", String.class)
@@ -180,7 +180,7 @@ public class MergeMetadataGenerationTests extends AbstractMetadataGenerationTest
}
@Test
public void mergingOfHintWithProvider() throws Exception {
void mergingOfHintWithProvider() throws Exception {
writeAdditionalHints(new ItemHint("simple.theName", Collections.emptyList(),
Arrays.asList(new ItemHint.ValueProvider("first", Collections.singletonMap("target", "org.foo")),
new ItemHint.ValueProvider("second", null))));
@@ -193,7 +193,7 @@ public class MergeMetadataGenerationTests extends AbstractMetadataGenerationTest
}
@Test
public void mergingOfAdditionalDeprecation() throws Exception {
void mergingOfAdditionalDeprecation() throws Exception {
writePropertyDeprecation(ItemMetadata.newProperty("simple", "wrongName", "java.lang.String", null, null, null,
null, new ItemDeprecation("Lame name.", "simple.the-name")));
ConfigurationMetadata metadata = compile(SimpleProperties.class);
@@ -202,7 +202,7 @@ public class MergeMetadataGenerationTests extends AbstractMetadataGenerationTest
}
@Test
public void mergingOfAdditionalMetadata() throws Exception {
void mergingOfAdditionalMetadata() throws Exception {
File metaInfFolder = new File(getCompiler().getOutputLocation(), "META-INF");
metaInfFolder.mkdirs();
File additionalMetadataFile = new File(metaInfFolder, "additional-spring-configuration-metadata.json");

View File

@@ -22,9 +22,8 @@ import java.util.Collections;
import javax.annotation.processing.ProcessingEnvironment;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
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;
@@ -35,18 +34,18 @@ import static org.mockito.Mockito.mock;
*
* @author Andy Wilkinson
*/
public class MetadataStoreTests {
class MetadataStoreTests {
@Rule
public final TemporaryFolder temp = new TemporaryFolder();
@TempDir
File tempDir;
private final ProcessingEnvironment environment = mock(ProcessingEnvironment.class);
private final MetadataStore metadataStore = new MetadataStore(this.environment);
@Test
public void additionalMetadataIsLocatedInMavenBuild() throws IOException {
File app = this.temp.newFolder("app");
void additionalMetadataIsLocatedInMavenBuild() throws IOException {
File app = new File(this.tempDir, "app");
File classesLocation = new File(app, "target/classes");
File metaInf = new File(classesLocation, "META-INF");
metaInf.mkdirs();
@@ -58,8 +57,8 @@ public class MetadataStoreTests {
}
@Test
public void additionalMetadataIsLocatedInGradle3Build() throws IOException {
File app = this.temp.newFolder("app");
void additionalMetadataIsLocatedInGradle3Build() throws IOException {
File app = new File(this.tempDir, "app");
File classesLocation = new File(app, "build/classes/main");
File resourcesLocation = new File(app, "build/resources/main");
File metaInf = new File(resourcesLocation, "META-INF");
@@ -72,8 +71,8 @@ public class MetadataStoreTests {
}
@Test
public void additionalMetadataIsLocatedInGradle4Build() throws IOException {
File app = this.temp.newFolder("app");
void additionalMetadataIsLocatedInGradle4Build() throws IOException {
File app = new File(this.tempDir, "app");
File classesLocation = new File(app, "build/classes/java/main");
File resourcesLocation = new File(app, "build/resources/main");
File metaInf = new File(resourcesLocation, "META-INF");
@@ -86,8 +85,8 @@ public class MetadataStoreTests {
}
@Test
public void additionalMetadataIsLocatedUsingLocationsOption() throws IOException {
File app = this.temp.newFolder("app");
void additionalMetadataIsLocatedUsingLocationsOption() throws IOException {
File app = new File(this.tempDir, "app");
File location = new File(app, "src/main/resources");
File metaInf = new File(location, "META-INF");
metaInf.mkdirs();

View File

@@ -16,7 +16,7 @@
package org.springframework.boot.configurationprocessor;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.springframework.boot.configurationprocessor.metadata.ConfigurationMetadata;
import org.springframework.boot.configurationprocessor.metadata.Metadata;
@@ -33,10 +33,10 @@ import static org.assertj.core.api.Assertions.assertThat;
*
* @author Stephane Nicoll
*/
public class MethodBasedMetadataGenerationTests extends AbstractMetadataGenerationTests {
class MethodBasedMetadataGenerationTests extends AbstractMetadataGenerationTests {
@Test
public void simpleMethodConfig() {
void simpleMethodConfig() {
ConfigurationMetadata metadata = compile(SimpleMethodConfig.class);
assertThat(metadata).has(Metadata.withGroup("foo").fromSource(SimpleMethodConfig.class));
assertThat(metadata)
@@ -46,7 +46,7 @@ public class MethodBasedMetadataGenerationTests extends AbstractMetadataGenerati
}
@Test
public void invalidMethodConfig() {
void invalidMethodConfig() {
ConfigurationMetadata metadata = compile(InvalidMethodConfig.class);
assertThat(metadata)
.has(Metadata.withProperty("something.name", String.class).fromSource(InvalidMethodConfig.class));
@@ -54,7 +54,7 @@ public class MethodBasedMetadataGenerationTests extends AbstractMetadataGenerati
}
@Test
public void methodAndClassConfig() {
void methodAndClassConfig() {
ConfigurationMetadata metadata = compile(MethodAndClassConfig.class);
assertThat(metadata)
.has(Metadata.withProperty("conflict.name", String.class).fromSource(MethodAndClassConfig.Foo.class));
@@ -65,13 +65,13 @@ public class MethodBasedMetadataGenerationTests extends AbstractMetadataGenerati
}
@Test
public void emptyTypeMethodConfig() {
void emptyTypeMethodConfig() {
ConfigurationMetadata metadata = compile(EmptyTypeMethodConfig.class);
assertThat(metadata).isNotEqualTo(Metadata.withProperty("something.foo"));
}
@Test
public void deprecatedMethodConfig() {
void deprecatedMethodConfig() {
Class<DeprecatedMethodConfig> type = DeprecatedMethodConfig.class;
ConfigurationMetadata metadata = compile(type);
assertThat(metadata).has(Metadata.withGroup("foo").fromSource(type));
@@ -83,7 +83,7 @@ public class MethodBasedMetadataGenerationTests extends AbstractMetadataGenerati
@Test
@SuppressWarnings("deprecation")
public void deprecatedMethodConfigOnClass() {
void deprecatedMethodConfigOnClass() {
Class<?> type = org.springframework.boot.configurationsample.method.DeprecatedClassMethodConfig.class;
ConfigurationMetadata metadata = compile(type);
assertThat(metadata).has(Metadata.withGroup("foo").fromSource(type));

View File

@@ -16,6 +16,7 @@
package org.springframework.boot.configurationprocessor;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
@@ -27,9 +28,8 @@ import java.util.stream.Stream;
import javax.lang.model.element.TypeElement;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.springframework.boot.configurationprocessor.metadata.ItemMetadata;
import org.springframework.boot.configurationprocessor.test.RoundEnvironmentTester;
@@ -52,19 +52,19 @@ import static org.assertj.core.api.Assertions.assertThat;
*
* @author Stephane Nicoll
*/
public class PropertyDescriptorResolverTests {
class PropertyDescriptorResolverTests {
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
@TempDir
File tempDir;
@Test
public void propertiesWithJavaBeanProperties() throws IOException {
void propertiesWithJavaBeanProperties() throws IOException {
process(SimpleProperties.class,
propertyNames((stream) -> assertThat(stream).containsExactly("theName", "flag", "comparator")));
}
@Test
public void propertiesWithJavaBeanHierarchicalProperties() throws IOException {
void propertiesWithJavaBeanHierarchicalProperties() throws IOException {
process(HierarchicalProperties.class,
Arrays.asList(HierarchicalPropertiesParent.class, HierarchicalPropertiesGrandparent.class),
(type, metadataEnv) -> {
@@ -78,31 +78,31 @@ public class PropertyDescriptorResolverTests {
}
@Test
public void propertiesWithLombokGetterSetterAtClassLevel() throws IOException {
void propertiesWithLombokGetterSetterAtClassLevel() throws IOException {
process(LombokSimpleProperties.class, propertyNames(
(stream) -> assertThat(stream).containsExactly("name", "description", "counter", "number", "items")));
}
@Test
public void propertiesWithLombokGetterSetterAtFieldLevel() throws IOException {
void propertiesWithLombokGetterSetterAtFieldLevel() throws IOException {
process(LombokExplicitProperties.class, propertyNames(
(stream) -> assertThat(stream).containsExactly("name", "description", "counter", "number", "items")));
}
@Test
public void propertiesWithLombokDataClass() throws IOException {
void propertiesWithLombokDataClass() throws IOException {
process(LombokSimpleDataProperties.class, propertyNames(
(stream) -> assertThat(stream).containsExactly("name", "description", "counter", "number", "items")));
}
@Test
public void propertiesWithConstructorParameters() throws IOException {
void propertiesWithConstructorParameters() throws IOException {
process(ImmutableSimpleProperties.class, propertyNames(
(stream) -> assertThat(stream).containsExactly("theName", "flag", "comparator", "counter")));
}
@Test
public void propertiesWithSeveralConstructors() throws IOException {
void propertiesWithSeveralConstructors() throws IOException {
process(TwoConstructorsExample.class, propertyNames((stream) -> assertThat(stream).containsExactly("name")));
process(TwoConstructorsExample.class,
properties((stream) -> assertThat(stream).element(0).isInstanceOf(JavaBeanPropertyDescriptor.class)));
@@ -134,7 +134,7 @@ public class PropertyDescriptorResolverTests {
};
TestableAnnotationProcessor<MetadataGenerationEnvironment> processor = new TestableAnnotationProcessor<>(
internalConsumer, new MetadataGenerationEnvironmentFactory());
TestCompiler compiler = new TestCompiler(this.temporaryFolder);
TestCompiler compiler = new TestCompiler(this.tempDir);
ArrayList<Class<?>> allClasses = new ArrayList<>();
allClasses.add(target);
allClasses.addAll(additionalClasses);

View File

@@ -16,6 +16,7 @@
package org.springframework.boot.configurationprocessor;
import java.io.File;
import java.io.IOException;
import java.util.function.BiConsumer;
@@ -25,8 +26,7 @@ import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.util.ElementFilter;
import org.junit.Rule;
import org.junit.rules.TemporaryFolder;
import org.junit.jupiter.api.io.TempDir;
import org.springframework.boot.configurationprocessor.test.ItemMetadataAssert;
import org.springframework.boot.configurationprocessor.test.RoundEnvironmentTester;
@@ -40,8 +40,8 @@ import org.springframework.boot.testsupport.compiler.TestCompiler;
*/
public abstract class PropertyDescriptorTests {
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
@TempDir
File tempDir;
protected String createAccessorMethodName(String prefix, String name) {
char[] chars = name.toCharArray();
@@ -70,7 +70,7 @@ public abstract class PropertyDescriptorTests {
throws IOException {
TestableAnnotationProcessor<MetadataGenerationEnvironment> processor = new TestableAnnotationProcessor<>(
consumer, new MetadataGenerationEnvironmentFactory());
TestCompiler compiler = new TestCompiler(this.temporaryFolder);
TestCompiler compiler = new TestCompiler(this.tempDir);
compiler.getTask(target).call(processor);
}

View File

@@ -28,15 +28,13 @@ import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Set;
import org.junit.Assert;
import org.junit.rules.TemporaryFolder;
import org.springframework.boot.configurationprocessor.metadata.ConfigurationMetadata;
import org.springframework.boot.configurationprocessor.test.TestConfigurationMetadataAnnotationProcessor;
import org.springframework.boot.configurationsample.ConfigurationProperties;
import org.springframework.boot.configurationsample.NestedConfigurationProperty;
import org.springframework.boot.testsupport.compiler.TestCompiler;
import org.springframework.boot.testsupport.compiler.TestCompiler.TestCompilationTask;
import org.springframework.util.Assert;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.FileSystemUtils;
@@ -64,9 +62,9 @@ public class TestProject {
private Set<File> sourceFiles = new LinkedHashSet<>();
public TestProject(TemporaryFolder tempFolder, Class<?>... classes) throws IOException {
this.sourceFolder = tempFolder.newFolder();
this.compiler = new TestCompiler(tempFolder) {
public TestProject(File tempFolder, Class<?>... classes) throws IOException {
this.sourceFolder = new File(tempFolder, "src");
this.compiler = new TestCompiler(new File(tempFolder, "build")) {
@Override
protected File getSourceFolder() {
return TestProject.this.sourceFolder;
@@ -123,7 +121,7 @@ public class TestProject {
* @return the output file
*/
public File getOutputFile(String relativePath) {
Assert.assertFalse(new File(relativePath).isAbsolute());
Assert.isTrue(!new File(relativePath).isAbsolute(), "'" + relativePath + "' was absolute");
return new File(this.compiler.getOutputLocation(), relativePath);
}
@@ -158,7 +156,7 @@ public class TestProject {
* @throws IOException on IO error
*/
public void revert(Class<?> type) throws IOException {
Assert.assertTrue(getSourceFile(type).exists());
Assert.isTrue(getSourceFile(type).exists(), "Source file for type '" + type + "' does not exist");
copySources(type);
}
@@ -168,7 +166,7 @@ public class TestProject {
* @throws IOException on IO error
*/
public void add(Class<?> type) throws IOException {
Assert.assertFalse(getSourceFile(type).exists());
Assert.isTrue(!getSourceFile(type).exists(), "Source file for type '" + type + "' already exists");
copySources(type);
}

View File

@@ -16,13 +16,13 @@
package org.springframework.boot.configurationprocessor;
import java.io.File;
import java.io.IOException;
import java.time.Duration;
import java.util.function.BiConsumer;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.springframework.boot.configurationprocessor.TypeUtils.TypeDescriptor;
import org.springframework.boot.configurationprocessor.test.RoundEnvironmentTester;
@@ -39,13 +39,13 @@ import static org.assertj.core.api.Assertions.assertThat;
*
* @author Stephane Nicoll
*/
public class TypeUtilsTests {
class TypeUtilsTests {
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
@TempDir
File tempDir;
@Test
public void resolveTypeDescriptorOnConcreteClass() throws IOException {
void resolveTypeDescriptorOnConcreteClass() throws IOException {
process(SimpleGenericProperties.class, (roundEnv, typeUtils) -> {
TypeDescriptor typeDescriptor = typeUtils
.resolveTypeDescriptor(roundEnv.getRootElement(SimpleGenericProperties.class));
@@ -59,7 +59,7 @@ public class TypeUtilsTests {
}
@Test
public void resolveTypeDescriptorOnIntermediateClass() throws IOException {
void resolveTypeDescriptorOnIntermediateClass() throws IOException {
process(AbstractIntermediateGenericProperties.class, (roundEnv, typeUtils) -> {
TypeDescriptor typeDescriptor = typeUtils
.resolveTypeDescriptor(roundEnv.getRootElement(AbstractIntermediateGenericProperties.class));
@@ -72,7 +72,7 @@ public class TypeUtilsTests {
}
@Test
public void resolveTypeDescriptorWithOnlyGenerics() throws IOException {
void resolveTypeDescriptorWithOnlyGenerics() throws IOException {
process(AbstractGenericProperties.class, (roundEnv, typeUtils) -> {
TypeDescriptor typeDescriptor = typeUtils
.resolveTypeDescriptor(roundEnv.getRootElement(AbstractGenericProperties.class));
@@ -84,7 +84,7 @@ public class TypeUtilsTests {
private void process(Class<?> target, BiConsumer<RoundEnvironmentTester, TypeUtils> consumer) throws IOException {
TestableAnnotationProcessor<TypeUtils> processor = new TestableAnnotationProcessor<>(consumer, TypeUtils::new);
TestCompiler compiler = new TestCompiler(this.temporaryFolder);
TestCompiler compiler = new TestCompiler(this.tempDir);
compiler.getTask(target).call(processor);
}

View File

@@ -16,6 +16,7 @@
package org.springframework.boot.configurationprocessor.fieldvalues;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
@@ -29,9 +30,8 @@ import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.TypeElement;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.springframework.boot.configurationsample.fieldvalues.FieldValues;
import org.springframework.boot.testsupport.compiler.TestCompiler;
@@ -46,15 +46,15 @@ import static org.assertj.core.api.Assertions.assertThat;
*/
public abstract class AbstractFieldValuesProcessorTests {
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
@TempDir
File tempDir;
protected abstract FieldValuesParser createProcessor(ProcessingEnvironment env);
@Test
public void getFieldValues() throws Exception {
void getFieldValues() throws Exception {
TestProcessor processor = new TestProcessor();
TestCompiler compiler = new TestCompiler(this.temporaryFolder);
TestCompiler compiler = new TestCompiler(this.tempDir);
compiler.getTask(FieldValues.class).call(processor);
Map<String, Object> values = processor.getValues();
assertThat(values.get("string")).isEqualTo("1");

View File

@@ -18,11 +18,11 @@ package org.springframework.boot.configurationprocessor.fieldvalues.javac;
import javax.annotation.processing.ProcessingEnvironment;
import org.opentest4j.TestAbortedException;
import org.springframework.boot.configurationprocessor.fieldvalues.AbstractFieldValuesProcessorTests;
import org.springframework.boot.configurationprocessor.fieldvalues.FieldValuesParser;
import static org.junit.Assume.assumeNoException;
/**
* Tests for {@link JavaCompilerFieldValuesParser}.
*
@@ -36,8 +36,7 @@ public class JavaCompilerFieldValuesProcessorTests extends AbstractFieldValuesPr
return new JavaCompilerFieldValuesParser(env);
}
catch (Throwable ex) {
assumeNoException(ex);
throw new IllegalStateException();
throw new TestAbortedException();
}
}

View File

@@ -16,7 +16,7 @@
package org.springframework.boot.configurationprocessor.metadata;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
@@ -25,55 +25,55 @@ import static org.assertj.core.api.Assertions.assertThat;
*
* @author Stephane Nicoll
*/
public class ConfigurationMetadataTests {
class ConfigurationMetadataTests {
@Test
public void toDashedCaseCamelCase() {
void toDashedCaseCamelCase() {
assertThat(toDashedCase("simpleCamelCase")).isEqualTo("simple-camel-case");
}
@Test
public void toDashedCaseUpperCamelCaseSuffix() {
void toDashedCaseUpperCamelCaseSuffix() {
assertThat(toDashedCase("myDLQ")).isEqualTo("my-d-l-q");
}
@Test
public void toDashedCaseUpperCamelCaseMiddle() {
void toDashedCaseUpperCamelCaseMiddle() {
assertThat(toDashedCase("someDLQKey")).isEqualTo("some-d-l-q-key");
}
@Test
public void toDashedCaseWordsUnderscore() {
void toDashedCaseWordsUnderscore() {
assertThat(toDashedCase("Word_With_underscore")).isEqualTo("word-with-underscore");
}
@Test
public void toDashedCaseWordsSeveralUnderscores() {
void toDashedCaseWordsSeveralUnderscores() {
assertThat(toDashedCase("Word___With__underscore")).isEqualTo("word---with--underscore");
}
@Test
public void toDashedCaseLowerCaseUnderscore() {
void toDashedCaseLowerCaseUnderscore() {
assertThat(toDashedCase("lower_underscore")).isEqualTo("lower-underscore");
}
@Test
public void toDashedCaseUpperUnderscoreSuffix() {
void toDashedCaseUpperUnderscoreSuffix() {
assertThat(toDashedCase("my_DLQ")).isEqualTo("my-d-l-q");
}
@Test
public void toDashedCaseUpperUnderscoreMiddle() {
void toDashedCaseUpperUnderscoreMiddle() {
assertThat(toDashedCase("some_DLQ_key")).isEqualTo("some-d-l-q-key");
}
@Test
public void toDashedCaseMultipleUnderscores() {
void toDashedCaseMultipleUnderscores() {
assertThat(toDashedCase("super___crazy")).isEqualTo("super---crazy");
}
@Test
public void toDashedCaseLowercase() {
void toDashedCaseLowercase() {
assertThat(toDashedCase("lowercase")).isEqualTo("lowercase");
}

View File

@@ -16,7 +16,7 @@
package org.springframework.boot.configurationprocessor.metadata;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
@@ -25,20 +25,20 @@ import static org.assertj.core.api.Assertions.assertThat;
*
* @author Stephane Nicoll
*/
public class ItemMetadataTests {
class ItemMetadataTests {
@Test
public void newItemMetadataPrefixWithCapitalizedPrefix() {
void newItemMetadataPrefixWithCapitalizedPrefix() {
assertThat(newItemMetadataPrefix("Prefix.", "value")).isEqualTo("prefix.value");
}
@Test
public void newItemMetadataPrefixWithCamelCaseSuffix() {
void newItemMetadataPrefixWithCamelCaseSuffix() {
assertThat(newItemMetadataPrefix("prefix.", "myValue")).isEqualTo("prefix.my-value");
}
@Test
public void newItemMetadataPrefixWithUpperCamelCaseSuffix() {
void newItemMetadataPrefixWithUpperCamelCaseSuffix() {
assertThat(newItemMetadataPrefix("prefix.", "MyValue")).isEqualTo("prefix.my-value");
}

View File

@@ -23,7 +23,7 @@ import java.io.InputStream;
import java.util.Arrays;
import java.util.Collections;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
@@ -33,10 +33,10 @@ import static org.assertj.core.api.Assertions.assertThat;
* @author Phillip Webb
* @author Stephane Nicoll
*/
public class JsonMarshallerTests {
class JsonMarshallerTests {
@Test
public void marshallAndUnmarshal() throws Exception {
void marshallAndUnmarshal() throws Exception {
ConfigurationMetadata metadata = new ConfigurationMetadata();
metadata.add(ItemMetadata.newProperty("a", "b", StringBuffer.class.getName(), InputStream.class.getName(),
"sourceMethod", "desc", "x", new ItemDeprecation("Deprecation comment", "b.c.d")));
@@ -69,7 +69,7 @@ public class JsonMarshallerTests {
}
@Test
public void marshallOrderItems() throws IOException {
void marshallOrderItems() throws IOException {
ConfigurationMetadata metadata = new ConfigurationMetadata();
metadata.add(ItemHint.newHint("fff"));
metadata.add(ItemHint.newHint("eee"));
@@ -89,7 +89,7 @@ public class JsonMarshallerTests {
}
@Test
public void marshallPutDeprecatedItemsAtTheEnd() throws IOException {
void marshallPutDeprecatedItemsAtTheEnd() throws IOException {
ConfigurationMetadata metadata = new ConfigurationMetadata();
metadata.add(ItemMetadata.newProperty("com.example.bravo", "bbb", null, null, null, null, null, null));
metadata.add(ItemMetadata.newProperty("com.example.bravo", "aaa", null, null, null, null, null,

View File

@@ -16,7 +16,6 @@
package org.springframework.boot.gradle.docs;
import org.junit.Assume;
import org.junit.jupiter.api.TestTemplate;
import org.junit.jupiter.api.extension.ExtendWith;
@@ -25,6 +24,7 @@ import org.springframework.boot.gradle.testkit.Dsl;
import org.springframework.boot.gradle.testkit.GradleBuild;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assumptions.assumingThat;
/**
* Tests for the managing dependencies documentation.
@@ -56,10 +56,11 @@ public class ManagingDependenciesDocumentationTests {
@TestTemplate
public void dependencyManagementInIsolationWithPluginsBlock() {
Assume.assumeTrue(this.gradleBuild.getDsl() == Dsl.KOTLIN);
assertThat(this.gradleBuild.script("src/main/gradle/managing-dependencies/configure-bom-with-plugins")
.build("dependencyManagement").getOutput())
.contains("org.springframework.boot:spring-boot-starter TEST-SNAPSHOT");
assumingThat(this.gradleBuild.getDsl() == Dsl.KOTLIN,
() -> assertThat(
this.gradleBuild.script("src/main/gradle/managing-dependencies/configure-bom-with-plugins")
.build("dependencyManagement").getOutput())
.contains("org.springframework.boot:spring-boot-starter TEST-SNAPSHOT"));
}
}

View File

@@ -21,9 +21,8 @@ import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.springframework.util.FileCopyUtils;
@@ -36,100 +35,100 @@ import static org.assertj.core.api.Assertions.assertThat;
* @author Andy Wilkinson
* @author Justin Rosenberg
*/
public class DefaultLaunchScriptTests {
class DefaultLaunchScriptTests {
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
@TempDir
File tempDir;
@Test
public void loadsDefaultScript() throws Exception {
void loadsDefaultScript() throws Exception {
DefaultLaunchScript script = new DefaultLaunchScript(null, null);
String content = new String(script.toByteArray());
assertThat(content).contains("Spring Boot Startup Script");
}
@Test
public void logFilenameCanBeReplaced() throws Exception {
void logFilenameCanBeReplaced() throws Exception {
assertThatPlaceholderCanBeReplaced("logFilename");
}
@Test
public void pidFilenameCanBeReplaced() throws Exception {
void pidFilenameCanBeReplaced() throws Exception {
assertThatPlaceholderCanBeReplaced("pidFilename");
}
@Test
public void initInfoProvidesCanBeReplaced() throws Exception {
void initInfoProvidesCanBeReplaced() throws Exception {
assertThatPlaceholderCanBeReplaced("initInfoProvides");
}
@Test
public void initInfoRequiredStartCanBeReplaced() throws Exception {
void initInfoRequiredStartCanBeReplaced() throws Exception {
assertThatPlaceholderCanBeReplaced("initInfoRequiredStart");
}
@Test
public void initInfoRequiredStopCanBeReplaced() throws Exception {
void initInfoRequiredStopCanBeReplaced() throws Exception {
assertThatPlaceholderCanBeReplaced("initInfoRequiredStop");
}
@Test
public void initInfoDefaultStartCanBeReplaced() throws Exception {
void initInfoDefaultStartCanBeReplaced() throws Exception {
assertThatPlaceholderCanBeReplaced("initInfoDefaultStart");
}
@Test
public void initInfoDefaultStopCanBeReplaced() throws Exception {
void initInfoDefaultStopCanBeReplaced() throws Exception {
assertThatPlaceholderCanBeReplaced("initInfoDefaultStop");
}
@Test
public void initInfoShortDescriptionCanBeReplaced() throws Exception {
void initInfoShortDescriptionCanBeReplaced() throws Exception {
assertThatPlaceholderCanBeReplaced("initInfoShortDescription");
}
@Test
public void initInfoDescriptionCanBeReplaced() throws Exception {
void initInfoDescriptionCanBeReplaced() throws Exception {
assertThatPlaceholderCanBeReplaced("initInfoDescription");
}
@Test
public void initInfoChkconfigCanBeReplaced() throws Exception {
void initInfoChkconfigCanBeReplaced() throws Exception {
assertThatPlaceholderCanBeReplaced("initInfoChkconfig");
}
@Test
public void modeCanBeReplaced() throws Exception {
void modeCanBeReplaced() throws Exception {
assertThatPlaceholderCanBeReplaced("mode");
}
@Test
public void useStartStopDaemonCanBeReplaced() throws Exception {
void useStartStopDaemonCanBeReplaced() throws Exception {
assertThatPlaceholderCanBeReplaced("useStartStopDaemon");
}
@Test
public void logFolderCanBeReplaced() throws Exception {
void logFolderCanBeReplaced() throws Exception {
assertThatPlaceholderCanBeReplaced("logFolder");
}
@Test
public void pidFolderCanBeReplaced() throws Exception {
void pidFolderCanBeReplaced() throws Exception {
assertThatPlaceholderCanBeReplaced("pidFolder");
}
@Test
public void confFolderCanBeReplaced() throws Exception {
void confFolderCanBeReplaced() throws Exception {
assertThatPlaceholderCanBeReplaced("confFolder");
}
@Test
public void stopWaitTimeCanBeReplaced() throws Exception {
void stopWaitTimeCanBeReplaced() throws Exception {
assertThatPlaceholderCanBeReplaced("stopWaitTime");
}
@Test
public void inlinedConfScriptFileLoad() throws IOException {
void inlinedConfScriptFileLoad() throws IOException {
DefaultLaunchScript script = new DefaultLaunchScript(null,
createProperties("inlinedConfScript:src/test/resources/example.script"));
String content = new String(script.toByteArray());
@@ -137,29 +136,29 @@ public class DefaultLaunchScriptTests {
}
@Test
public void defaultForUseStartStopDaemonIsTrue() throws Exception {
void defaultForUseStartStopDaemonIsTrue() throws Exception {
DefaultLaunchScript script = new DefaultLaunchScript(null, null);
String content = new String(script.toByteArray());
assertThat(content).contains("USE_START_STOP_DAEMON=\"true\"");
}
@Test
public void defaultForModeIsAuto() throws Exception {
void defaultForModeIsAuto() throws Exception {
DefaultLaunchScript script = new DefaultLaunchScript(null, null);
String content = new String(script.toByteArray());
assertThat(content).contains("MODE=\"auto\"");
}
@Test
public void defaultForStopWaitTimeIs60() throws Exception {
void defaultForStopWaitTimeIs60() throws Exception {
DefaultLaunchScript script = new DefaultLaunchScript(null, null);
String content = new String(script.toByteArray());
assertThat(content).contains("STOP_WAIT_TIME=\"60\"");
}
@Test
public void loadFromFile() throws Exception {
File file = this.temporaryFolder.newFile();
void loadFromFile() throws Exception {
File file = new File(this.tempDir, "script");
FileCopyUtils.copy("ABC".getBytes(), file);
DefaultLaunchScript script = new DefaultLaunchScript(file, null);
String content = new String(script.toByteArray());
@@ -167,8 +166,8 @@ public class DefaultLaunchScriptTests {
}
@Test
public void expandVariables() throws Exception {
File file = this.temporaryFolder.newFile();
void expandVariables() throws Exception {
File file = new File(this.tempDir, "script");
FileCopyUtils.copy("h{{a}}ll{{b}}".getBytes(), file);
DefaultLaunchScript script = new DefaultLaunchScript(file, createProperties("a:e", "b:o"));
String content = new String(script.toByteArray());
@@ -176,8 +175,8 @@ public class DefaultLaunchScriptTests {
}
@Test
public void expandVariablesMultiLine() throws Exception {
File file = this.temporaryFolder.newFile();
void expandVariablesMultiLine() throws Exception {
File file = new File(this.tempDir, "script");
FileCopyUtils.copy("h{{a}}l\nl{{b}}".getBytes(), file);
DefaultLaunchScript script = new DefaultLaunchScript(file, createProperties("a:e", "b:o"));
String content = new String(script.toByteArray());
@@ -185,8 +184,8 @@ public class DefaultLaunchScriptTests {
}
@Test
public void expandVariablesWithDefaults() throws Exception {
File file = this.temporaryFolder.newFile();
void expandVariablesWithDefaults() throws Exception {
File file = new File(this.tempDir, "script");
FileCopyUtils.copy("h{{a:e}}ll{{b:o}}".getBytes(), file);
DefaultLaunchScript script = new DefaultLaunchScript(file, null);
String content = new String(script.toByteArray());
@@ -194,8 +193,8 @@ public class DefaultLaunchScriptTests {
}
@Test
public void expandVariablesCanDefaultToBlank() throws Exception {
File file = this.temporaryFolder.newFile();
void expandVariablesCanDefaultToBlank() throws Exception {
File file = new File(this.tempDir, "script");
FileCopyUtils.copy("s{{p:}}{{r:}}ing".getBytes(), file);
DefaultLaunchScript script = new DefaultLaunchScript(file, null);
String content = new String(script.toByteArray());
@@ -203,8 +202,8 @@ public class DefaultLaunchScriptTests {
}
@Test
public void expandVariablesWithDefaultsOverride() throws Exception {
File file = this.temporaryFolder.newFile();
void expandVariablesWithDefaultsOverride() throws Exception {
File file = new File(this.tempDir, "script");
FileCopyUtils.copy("h{{a:e}}ll{{b:o}}".getBytes(), file);
DefaultLaunchScript script = new DefaultLaunchScript(file, createProperties("a:a"));
String content = new String(script.toByteArray());
@@ -212,8 +211,8 @@ public class DefaultLaunchScriptTests {
}
@Test
public void expandVariablesMissingAreUnchanged() throws Exception {
File file = this.temporaryFolder.newFile();
void expandVariablesMissingAreUnchanged() throws Exception {
File file = new File(this.tempDir, "script");
FileCopyUtils.copy("h{{a}}ll{{b}}".getBytes(), file);
DefaultLaunchScript script = new DefaultLaunchScript(file, null);
String content = new String(script.toByteArray());

View File

@@ -21,12 +21,9 @@ import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.springframework.util.FileSystemUtils;
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;
@@ -36,27 +33,25 @@ import static org.assertj.core.api.Assertions.assertThat;
* @author Dave Syer
* @author Phillip Webb
*/
public class FileUtilsTests {
class FileUtilsTests {
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
@TempDir
File tempDir;
private File outputDirectory;
private File originDirectory;
@Before
@BeforeEach
public void init() throws IOException {
this.outputDirectory = this.temporaryFolder.newFolder("remove");
this.originDirectory = this.temporaryFolder.newFolder("keep");
FileSystemUtils.deleteRecursively(this.outputDirectory);
FileSystemUtils.deleteRecursively(this.originDirectory);
this.outputDirectory = new File(this.tempDir, "remove");
this.originDirectory = new File(this.tempDir, "keep");
this.outputDirectory.mkdirs();
this.originDirectory.mkdirs();
}
@Test
public void simpleDuplicateFile() throws IOException {
void simpleDuplicateFile() throws IOException {
File file = new File(this.outputDirectory, "logback.xml");
file.createNewFile();
new File(this.originDirectory, "logback.xml").createNewFile();
@@ -65,7 +60,7 @@ public class FileUtilsTests {
}
@Test
public void nestedDuplicateFile() throws IOException {
void nestedDuplicateFile() throws IOException {
assertThat(new File(this.outputDirectory, "sub").mkdirs()).isTrue();
assertThat(new File(this.originDirectory, "sub").mkdirs()).isTrue();
File file = new File(this.outputDirectory, "sub/logback.xml");
@@ -76,7 +71,7 @@ public class FileUtilsTests {
}
@Test
public void nestedNonDuplicateFile() throws IOException {
void nestedNonDuplicateFile() throws IOException {
assertThat(new File(this.outputDirectory, "sub").mkdirs()).isTrue();
assertThat(new File(this.originDirectory, "sub").mkdirs()).isTrue();
File file = new File(this.outputDirectory, "sub/logback.xml");
@@ -87,7 +82,7 @@ public class FileUtilsTests {
}
@Test
public void nonDuplicateFile() throws IOException {
void nonDuplicateFile() throws IOException {
File file = new File(this.outputDirectory, "logback.xml");
file.createNewFile();
new File(this.originDirectory, "different.xml").createNewFile();
@@ -96,8 +91,8 @@ public class FileUtilsTests {
}
@Test
public void hash() throws Exception {
File file = this.temporaryFolder.newFile();
void hash() throws Exception {
File file = new File(this.tempDir, "file");
try (OutputStream outputStream = new FileOutputStream(file)) {
outputStream.write(new byte[] { 1, 2, 3 });
}

View File

@@ -18,7 +18,7 @@ package org.springframework.boot.loader.tools;
import java.io.File;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
@@ -29,10 +29,10 @@ import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
* @author Phillip Webb
* @author Andy Wilkinson
*/
public class LayoutsTests {
class LayoutsTests {
@Test
public void jarFile() {
void jarFile() {
assertThat(Layouts.forFile(new File("test.jar"))).isInstanceOf(Layouts.Jar.class);
assertThat(Layouts.forFile(new File("test.JAR"))).isInstanceOf(Layouts.Jar.class);
assertThat(Layouts.forFile(new File("test.jAr"))).isInstanceOf(Layouts.Jar.class);
@@ -40,7 +40,7 @@ public class LayoutsTests {
}
@Test
public void warFile() {
void warFile() {
assertThat(Layouts.forFile(new File("test.war"))).isInstanceOf(Layouts.War.class);
assertThat(Layouts.forFile(new File("test.WAR"))).isInstanceOf(Layouts.War.class);
assertThat(Layouts.forFile(new File("test.wAr"))).isInstanceOf(Layouts.War.class);
@@ -48,13 +48,13 @@ public class LayoutsTests {
}
@Test
public void unknownFile() {
void unknownFile() {
assertThatIllegalStateException().isThrownBy(() -> Layouts.forFile(new File("test.txt")))
.withMessageContaining("Unable to deduce layout for 'test.txt'");
}
@Test
public void jarLayout() {
void jarLayout() {
Layout layout = new Layouts.Jar();
assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.COMPILE)).isEqualTo("BOOT-INF/lib/");
assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.CUSTOM)).isEqualTo("BOOT-INF/lib/");
@@ -63,7 +63,7 @@ public class LayoutsTests {
}
@Test
public void warLayout() {
void warLayout() {
Layout layout = new Layouts.War();
assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.COMPILE)).isEqualTo("WEB-INF/lib/");
assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.CUSTOM)).isEqualTo("WEB-INF/lib/");

View File

@@ -16,14 +16,14 @@
package org.springframework.boot.loader.tools;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.springframework.boot.loader.tools.MainClassFinder.MainClass;
import org.springframework.boot.loader.tools.MainClassFinder.MainClassCallback;
@@ -39,20 +39,17 @@ import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
*
* @author Phillip Webb
*/
public class MainClassFinderTests {
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
class MainClassFinderTests {
private TestJarFile testJarFile;
@Before
public void setup() throws IOException {
this.testJarFile = new TestJarFile(this.temporaryFolder);
@BeforeEach
public void setup(@TempDir File tempDir) throws IOException {
this.testJarFile = new TestJarFile(tempDir);
}
@Test
public void findMainClassInJar() throws Exception {
void findMainClassInJar() throws Exception {
this.testJarFile.addClass("B.class", ClassWithMainMethod.class);
this.testJarFile.addClass("A.class", ClassWithoutMainMethod.class);
String actual = MainClassFinder.findMainClass(this.testJarFile.getJarFile(), "");
@@ -60,7 +57,7 @@ public class MainClassFinderTests {
}
@Test
public void findMainClassInJarSubFolder() throws Exception {
void findMainClassInJarSubFolder() throws Exception {
this.testJarFile.addClass("a/b/c/D.class", ClassWithMainMethod.class);
this.testJarFile.addClass("a/b/c/E.class", ClassWithoutMainMethod.class);
this.testJarFile.addClass("a/b/F.class", ClassWithoutMainMethod.class);
@@ -69,7 +66,7 @@ public class MainClassFinderTests {
}
@Test
public void usesBreadthFirstJarSearch() throws Exception {
void usesBreadthFirstJarSearch() throws Exception {
this.testJarFile.addClass("a/B.class", ClassWithMainMethod.class);
this.testJarFile.addClass("a/b/c/E.class", ClassWithMainMethod.class);
String actual = MainClassFinder.findMainClass(this.testJarFile.getJarFile(), "");
@@ -77,7 +74,7 @@ public class MainClassFinderTests {
}
@Test
public void findSingleJarSearch() throws Exception {
void findSingleJarSearch() throws Exception {
this.testJarFile.addClass("a/B.class", ClassWithMainMethod.class);
this.testJarFile.addClass("a/b/c/E.class", ClassWithMainMethod.class);
assertThatIllegalStateException()
@@ -87,7 +84,7 @@ public class MainClassFinderTests {
}
@Test
public void findSingleJarSearchPrefersAnnotatedMainClass() throws Exception {
void findSingleJarSearchPrefersAnnotatedMainClass() throws Exception {
this.testJarFile.addClass("a/B.class", ClassWithMainMethod.class);
this.testJarFile.addClass("a/b/c/E.class", AnnotatedClassWithMainMethod.class);
String mainClass = MainClassFinder.findSingleMainClass(this.testJarFile.getJarFile(), "",
@@ -96,7 +93,7 @@ public class MainClassFinderTests {
}
@Test
public void findMainClassInJarSubLocation() throws Exception {
void findMainClassInJarSubLocation() throws Exception {
this.testJarFile.addClass("a/B.class", ClassWithMainMethod.class);
this.testJarFile.addClass("a/b/c/E.class", ClassWithMainMethod.class);
String actual = MainClassFinder.findMainClass(this.testJarFile.getJarFile(), "a/");
@@ -105,7 +102,7 @@ public class MainClassFinderTests {
}
@Test
public void findMainClassInFolder() throws Exception {
void findMainClassInFolder() throws Exception {
this.testJarFile.addClass("B.class", ClassWithMainMethod.class);
this.testJarFile.addClass("A.class", ClassWithoutMainMethod.class);
String actual = MainClassFinder.findMainClass(this.testJarFile.getJarSource());
@@ -113,7 +110,7 @@ public class MainClassFinderTests {
}
@Test
public void findMainClassInSubFolder() throws Exception {
void findMainClassInSubFolder() throws Exception {
this.testJarFile.addClass("a/b/c/D.class", ClassWithMainMethod.class);
this.testJarFile.addClass("a/b/c/E.class", ClassWithoutMainMethod.class);
this.testJarFile.addClass("a/b/F.class", ClassWithoutMainMethod.class);
@@ -122,7 +119,7 @@ public class MainClassFinderTests {
}
@Test
public void usesBreadthFirstFolderSearch() throws Exception {
void usesBreadthFirstFolderSearch() throws Exception {
this.testJarFile.addClass("a/B.class", ClassWithMainMethod.class);
this.testJarFile.addClass("a/b/c/E.class", ClassWithMainMethod.class);
String actual = MainClassFinder.findMainClass(this.testJarFile.getJarSource());
@@ -130,7 +127,7 @@ public class MainClassFinderTests {
}
@Test
public void findSingleFolderSearch() throws Exception {
void findSingleFolderSearch() throws Exception {
this.testJarFile.addClass("a/B.class", ClassWithMainMethod.class);
this.testJarFile.addClass("a/b/c/E.class", ClassWithMainMethod.class);
assertThatIllegalStateException()
@@ -140,7 +137,7 @@ public class MainClassFinderTests {
}
@Test
public void findSingleFolderSearchPrefersAnnotatedMainClass() throws Exception {
void findSingleFolderSearchPrefersAnnotatedMainClass() throws Exception {
this.testJarFile.addClass("a/B.class", ClassWithMainMethod.class);
this.testJarFile.addClass("a/b/c/E.class", AnnotatedClassWithMainMethod.class);
String mainClass = MainClassFinder.findSingleMainClass(this.testJarFile.getJarSource(),
@@ -149,7 +146,7 @@ public class MainClassFinderTests {
}
@Test
public void doWithFolderMainMethods() throws Exception {
void doWithFolderMainMethods() throws Exception {
this.testJarFile.addClass("a/b/c/D.class", ClassWithMainMethod.class);
this.testJarFile.addClass("a/b/c/E.class", ClassWithoutMainMethod.class);
this.testJarFile.addClass("a/b/F.class", ClassWithoutMainMethod.class);
@@ -160,7 +157,7 @@ public class MainClassFinderTests {
}
@Test
public void doWithJarMainMethods() throws Exception {
void doWithJarMainMethods() throws Exception {
this.testJarFile.addClass("a/b/c/D.class", ClassWithMainMethod.class);
this.testJarFile.addClass("a/b/c/E.class", ClassWithoutMainMethod.class);
this.testJarFile.addClass("a/b/F.class", ClassWithoutMainMethod.class);

View File

@@ -37,10 +37,9 @@ import java.util.zip.ZipOutputStream;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipFile;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.zeroturnaround.zip.ZipUtil;
import org.springframework.boot.loader.tools.sample.ClassWithMainMethod;
@@ -61,7 +60,7 @@ import static org.mockito.Mockito.mock;
* @author Phillip Webb
* @author Andy Wilkinson
*/
public class RepackagerTests {
class RepackagerTests {
private static final Libraries NO_LIBRARIES = (callback) -> {
};
@@ -79,33 +78,33 @@ public class RepackagerTests {
JAN_1_1985 = calendar.getTime().getTime();
}
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
@TempDir
File tempDir;
private TestJarFile testJarFile;
@Before
@BeforeEach
public void setup() throws IOException {
this.testJarFile = new TestJarFile(this.temporaryFolder);
this.testJarFile = new TestJarFile(this.tempDir);
}
@Test
public void nullSource() {
void nullSource() {
assertThatIllegalArgumentException().isThrownBy(() -> new Repackager(null));
}
@Test
public void missingSource() {
void missingSource() {
assertThatIllegalArgumentException().isThrownBy(() -> new Repackager(new File("missing")));
}
@Test
public void directorySource() {
assertThatIllegalArgumentException().isThrownBy(() -> new Repackager(this.temporaryFolder.getRoot()));
void directorySource() {
assertThatIllegalArgumentException().isThrownBy(() -> new Repackager(this.tempDir));
}
@Test
public void specificMainClass() throws Exception {
void specificMainClass() throws Exception {
this.testJarFile.addClass("a/b/C.class", ClassWithoutMainMethod.class);
File file = this.testJarFile.getFile();
Repackager repackager = new Repackager(file);
@@ -119,7 +118,7 @@ public class RepackagerTests {
}
@Test
public void mainClassFromManifest() throws Exception {
void mainClassFromManifest() throws Exception {
this.testJarFile.addClass("a/b/C.class", ClassWithoutMainMethod.class);
Manifest manifest = new Manifest();
manifest.getMainAttributes().putValue("Manifest-Version", "1.0");
@@ -136,7 +135,7 @@ public class RepackagerTests {
}
@Test
public void mainClassFound() throws Exception {
void mainClassFound() throws Exception {
this.testJarFile.addClass("a/b/C.class", ClassWithMainMethod.class);
File file = this.testJarFile.getFile();
Repackager repackager = new Repackager(file);
@@ -149,7 +148,7 @@ public class RepackagerTests {
}
@Test
public void jarIsOnlyRepackagedOnce() throws Exception {
void jarIsOnlyRepackagedOnce() throws Exception {
this.testJarFile.addClass("a/b/C.class", ClassWithMainMethod.class);
File file = this.testJarFile.getFile();
Repackager repackager = new Repackager(file);
@@ -163,7 +162,7 @@ public class RepackagerTests {
}
@Test
public void multipleMainClassFound() throws Exception {
void multipleMainClassFound() throws Exception {
this.testJarFile.addClass("a/b/C.class", ClassWithMainMethod.class);
this.testJarFile.addClass("a/b/D.class", ClassWithMainMethod.class);
File file = this.testJarFile.getFile();
@@ -173,7 +172,7 @@ public class RepackagerTests {
}
@Test
public void noMainClass() throws Exception {
void noMainClass() throws Exception {
this.testJarFile.addClass("a/b/C.class", ClassWithoutMainMethod.class);
assertThatIllegalStateException()
.isThrownBy(() -> new Repackager(this.testJarFile.getFile()).repackage(NO_LIBRARIES))
@@ -181,7 +180,7 @@ public class RepackagerTests {
}
@Test
public void noMainClassAndLayoutIsNone() throws Exception {
void noMainClassAndLayoutIsNone() throws Exception {
this.testJarFile.addClass("a/b/C.class", ClassWithMainMethod.class);
File file = this.testJarFile.getFile();
Repackager repackager = new Repackager(file);
@@ -193,7 +192,7 @@ public class RepackagerTests {
}
@Test
public void noMainClassAndLayoutIsNoneWithNoMain() throws Exception {
void noMainClassAndLayoutIsNoneWithNoMain() throws Exception {
this.testJarFile.addClass("a/b/C.class", ClassWithoutMainMethod.class);
File file = this.testJarFile.getFile();
Repackager repackager = new Repackager(file);
@@ -205,7 +204,7 @@ public class RepackagerTests {
}
@Test
public void sameSourceAndDestinationWithBackup() throws Exception {
void sameSourceAndDestinationWithBackup() throws Exception {
this.testJarFile.addClass("a/b/C.class", ClassWithMainMethod.class);
File file = this.testJarFile.getFile();
Repackager repackager = new Repackager(file);
@@ -215,7 +214,7 @@ public class RepackagerTests {
}
@Test
public void sameSourceAndDestinationWithoutBackup() throws Exception {
void sameSourceAndDestinationWithoutBackup() throws Exception {
this.testJarFile.addClass("a/b/C.class", ClassWithMainMethod.class);
File file = this.testJarFile.getFile();
Repackager repackager = new Repackager(file);
@@ -226,10 +225,10 @@ public class RepackagerTests {
}
@Test
public void differentDestination() throws Exception {
void differentDestination() throws Exception {
this.testJarFile.addClass("a/b/C.class", ClassWithMainMethod.class);
File source = this.testJarFile.getFile();
File dest = this.temporaryFolder.newFile("different.jar");
File dest = new File(this.tempDir, "different.jar");
Repackager repackager = new Repackager(source);
repackager.repackage(dest, NO_LIBRARIES);
assertThat(new File(source.getParent(), source.getName() + ".original")).doesNotExist();
@@ -238,7 +237,7 @@ public class RepackagerTests {
}
@Test
public void nullDestination() throws Exception {
void nullDestination() throws Exception {
this.testJarFile.addClass("a/b/C.class", ClassWithMainMethod.class);
Repackager repackager = new Repackager(this.testJarFile.getFile());
assertThatIllegalArgumentException().isThrownBy(() -> repackager.repackage(null, NO_LIBRARIES))
@@ -246,26 +245,25 @@ public class RepackagerTests {
}
@Test
public void destinationIsDirectory() throws Exception {
void destinationIsDirectory() throws Exception {
this.testJarFile.addClass("a/b/C.class", ClassWithMainMethod.class);
Repackager repackager = new Repackager(this.testJarFile.getFile());
assertThatIllegalArgumentException()
.isThrownBy(() -> repackager.repackage(this.temporaryFolder.getRoot(), NO_LIBRARIES))
assertThatIllegalArgumentException().isThrownBy(() -> repackager.repackage(this.tempDir, NO_LIBRARIES))
.withMessageContaining("Invalid destination");
}
@Test
public void overwriteDestination() throws Exception {
void overwriteDestination() throws Exception {
this.testJarFile.addClass("a/b/C.class", ClassWithMainMethod.class);
Repackager repackager = new Repackager(this.testJarFile.getFile());
File dest = this.temporaryFolder.newFile("dest.jar");
File dest = new File(this.tempDir, "dest.jar");
dest.createNewFile();
repackager.repackage(dest, NO_LIBRARIES);
assertThat(hasLauncherClasses(dest)).isTrue();
}
@Test
public void nullLibraries() throws Exception {
void nullLibraries() throws Exception {
this.testJarFile.addClass("a/b/C.class", ClassWithMainMethod.class);
File file = this.testJarFile.getFile();
Repackager repackager = new Repackager(file);
@@ -274,12 +272,12 @@ public class RepackagerTests {
}
@Test
public void libraries() throws Exception {
TestJarFile libJar = new TestJarFile(this.temporaryFolder);
void libraries() throws Exception {
TestJarFile libJar = new TestJarFile(this.tempDir);
libJar.addClass("a/b/C.class", ClassWithoutMainMethod.class, JAN_1_1985);
File libJarFile = libJar.getFile();
File libJarFileToUnpack = libJar.getFile();
File libNonJarFile = this.temporaryFolder.newFile();
File libNonJarFile = new File(this.tempDir, "non-lib.jar");
FileCopyUtils.copy(new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8 }, libNonJarFile);
this.testJarFile.addClass("a/b/C.class", ClassWithMainMethod.class);
this.testJarFile.addFile("BOOT-INF/lib/" + libJarFileToUnpack.getName(), libJarFileToUnpack);
@@ -302,8 +300,8 @@ public class RepackagerTests {
}
@Test
public void duplicateLibraries() throws Exception {
TestJarFile libJar = new TestJarFile(this.temporaryFolder);
void duplicateLibraries() throws Exception {
TestJarFile libJar = new TestJarFile(this.tempDir);
libJar.addClass("a/b/C.class", ClassWithoutMainMethod.class);
File libJarFile = libJar.getFile();
this.testJarFile.addClass("a/b/C.class", ClassWithMainMethod.class);
@@ -316,8 +314,8 @@ public class RepackagerTests {
}
@Test
public void customLayout() throws Exception {
TestJarFile libJar = new TestJarFile(this.temporaryFolder);
void customLayout() throws Exception {
TestJarFile libJar = new TestJarFile(this.tempDir);
libJar.addClass("a/b/C.class", ClassWithoutMainMethod.class);
File libJarFile = libJar.getFile();
this.testJarFile.addClass("a/b/C.class", ClassWithMainMethod.class);
@@ -336,8 +334,8 @@ public class RepackagerTests {
}
@Test
public void customLayoutNoBootLib() throws Exception {
TestJarFile libJar = new TestJarFile(this.temporaryFolder);
void customLayoutNoBootLib() throws Exception {
TestJarFile libJar = new TestJarFile(this.tempDir);
libJar.addClass("a/b/C.class", ClassWithoutMainMethod.class);
File libJarFile = libJar.getFile();
this.testJarFile.addClass("a/b/C.class", ClassWithMainMethod.class);
@@ -353,7 +351,7 @@ public class RepackagerTests {
}
@Test
public void springBootVersion() throws Exception {
void springBootVersion() throws Exception {
this.testJarFile.addClass("a/b/C.class", ClassWithMainMethod.class);
File file = this.testJarFile.getFile();
Repackager repackager = new Repackager(file);
@@ -363,7 +361,7 @@ public class RepackagerTests {
}
@Test
public void executableJarLayoutAttributes() throws Exception {
void executableJarLayoutAttributes() throws Exception {
this.testJarFile.addClass("a/b/C.class", ClassWithMainMethod.class);
File file = this.testJarFile.getFile();
Repackager repackager = new Repackager(file);
@@ -376,7 +374,7 @@ public class RepackagerTests {
}
@Test
public void executableWarLayoutAttributes() throws Exception {
void executableWarLayoutAttributes() throws Exception {
this.testJarFile.addClass("WEB-INF/classes/a/b/C.class", ClassWithMainMethod.class);
File file = this.testJarFile.getFile("war");
Repackager repackager = new Repackager(file);
@@ -389,7 +387,7 @@ public class RepackagerTests {
}
@Test
public void nullCustomLayout() throws Exception {
void nullCustomLayout() throws Exception {
this.testJarFile.addClass("a/b/C.class", ClassWithoutMainMethod.class);
Repackager repackager = new Repackager(this.testJarFile.getFile());
assertThatIllegalArgumentException().isThrownBy(() -> repackager.setLayout(null))
@@ -397,8 +395,8 @@ public class RepackagerTests {
}
@Test
public void dontRecompressZips() throws Exception {
TestJarFile nested = new TestJarFile(this.temporaryFolder);
void dontRecompressZips() throws Exception {
TestJarFile nested = new TestJarFile(this.tempDir);
nested.addClass("a/b/C.class", ClassWithoutMainMethod.class);
File nestedFile = nested.getFile();
this.testJarFile.addFile("test/nested.jar", nestedFile);
@@ -414,10 +412,10 @@ public class RepackagerTests {
}
@Test
public void addLauncherScript() throws Exception {
void addLauncherScript() throws Exception {
this.testJarFile.addClass("a/b/C.class", ClassWithMainMethod.class);
File source = this.testJarFile.getFile();
File dest = this.temporaryFolder.newFile("dest.jar");
File dest = new File(this.tempDir, "dest.jar");
Repackager repackager = new Repackager(source);
LaunchScript script = new MockLauncherScript("ABC");
repackager.repackage(dest, NO_LIBRARIES, script);
@@ -434,8 +432,8 @@ public class RepackagerTests {
}
@Test
public void unpackLibrariesTakePrecedenceOverExistingSourceEntries() throws Exception {
TestJarFile nested = new TestJarFile(this.temporaryFolder);
void unpackLibrariesTakePrecedenceOverExistingSourceEntries() throws Exception {
TestJarFile nested = new TestJarFile(this.tempDir);
nested.addClass("a/b/C.class", ClassWithoutMainMethod.class);
File nestedFile = nested.getFile();
String name = "BOOT-INF/lib/" + nestedFile.getName();
@@ -450,8 +448,8 @@ public class RepackagerTests {
}
@Test
public void existingSourceEntriesTakePrecedenceOverStandardLibraries() throws Exception {
TestJarFile nested = new TestJarFile(this.temporaryFolder);
void existingSourceEntriesTakePrecedenceOverStandardLibraries() throws Exception {
TestJarFile nested = new TestJarFile(this.tempDir);
nested.addClass("a/b/C.class", ClassWithoutMainMethod.class);
File nestedFile = nested.getFile();
this.testJarFile.addFile("BOOT-INF/lib/" + nestedFile.getName(), nested.getFile());
@@ -461,7 +459,8 @@ public class RepackagerTests {
long sourceLength = nestedFile.length();
repackager.repackage((callback) -> {
nestedFile.delete();
File toZip = RepackagerTests.this.temporaryFolder.newFile();
File toZip = new File(this.tempDir, "to-zip");
toZip.createNewFile();
ZipUtil.packEntry(toZip, nestedFile);
callback.library(new Library(nestedFile, LibraryScope.COMPILE));
});
@@ -471,11 +470,13 @@ public class RepackagerTests {
}
@Test
public void metaInfIndexListIsRemovedFromRepackagedJar() throws Exception {
void metaInfIndexListIsRemovedFromRepackagedJar() throws Exception {
this.testJarFile.addClass("A.class", ClassWithMainMethod.class);
this.testJarFile.addFile("META-INF/INDEX.LIST", this.temporaryFolder.newFile("INDEX.LIST"));
File indexList = new File(this.tempDir, "INDEX.LIST");
indexList.createNewFile();
this.testJarFile.addFile("META-INF/INDEX.LIST", indexList);
File source = this.testJarFile.getFile();
File dest = this.temporaryFolder.newFile("dest.jar");
File dest = new File(this.tempDir, "dest.jar");
Repackager repackager = new Repackager(source);
repackager.repackage(dest, NO_LIBRARIES);
try (JarFile jarFile = new JarFile(dest)) {
@@ -484,7 +485,7 @@ public class RepackagerTests {
}
@Test
public void customLayoutFactoryWithoutLayout() throws Exception {
void customLayoutFactoryWithoutLayout() throws Exception {
this.testJarFile.addClass("a/b/C.class", ClassWithMainMethod.class);
File source = this.testJarFile.getFile();
Repackager repackager = new Repackager(source, new TestLayoutFactory());
@@ -495,7 +496,7 @@ public class RepackagerTests {
}
@Test
public void customLayoutFactoryWithLayout() throws Exception {
void customLayoutFactoryWithLayout() throws Exception {
this.testJarFile.addClass("a/b/C.class", ClassWithMainMethod.class);
File source = this.testJarFile.getFile();
Repackager repackager = new Repackager(source, new TestLayoutFactory());
@@ -507,11 +508,13 @@ public class RepackagerTests {
}
@Test
public void metaInfAopXmlIsMovedBeneathBootInfClassesWhenRepackaged() throws Exception {
void metaInfAopXmlIsMovedBeneathBootInfClassesWhenRepackaged() throws Exception {
this.testJarFile.addClass("A.class", ClassWithMainMethod.class);
this.testJarFile.addFile("META-INF/aop.xml", this.temporaryFolder.newFile("aop.xml"));
File aopXml = new File(this.tempDir, "aop.xml");
aopXml.createNewFile();
this.testJarFile.addFile("META-INF/aop.xml", aopXml);
File source = this.testJarFile.getFile();
File dest = this.temporaryFolder.newFile("dest.jar");
File dest = new File(this.tempDir, "dest.jar");
Repackager repackager = new Repackager(source);
repackager.repackage(dest, NO_LIBRARIES);
try (JarFile jarFile = new JarFile(dest)) {
@@ -521,10 +524,10 @@ public class RepackagerTests {
}
@Test
public void allEntriesUseUnixPlatformAndUtf8NameEncoding() throws IOException {
void allEntriesUseUnixPlatformAndUtf8NameEncoding() throws IOException {
this.testJarFile.addClass("A.class", ClassWithMainMethod.class);
File source = this.testJarFile.getFile();
File dest = this.temporaryFolder.newFile("dest.jar");
File dest = new File(this.tempDir, "dest.jar");
Repackager repackager = new Repackager(source);
repackager.repackage(dest, NO_LIBRARIES);
try (ZipFile zip = new ZipFile(dest)) {
@@ -538,10 +541,10 @@ public class RepackagerTests {
}
@Test
public void loaderIsWrittenFirstThenApplicationClassesThenLibraries() throws IOException {
void loaderIsWrittenFirstThenApplicationClassesThenLibraries() throws IOException {
this.testJarFile.addClass("com/example/Application.class", ClassWithMainMethod.class);
File source = this.testJarFile.getFile();
File dest = this.temporaryFolder.newFile("dest.jar");
File dest = new File(this.tempDir, "dest.jar");
File libraryOne = createLibrary();
File libraryTwo = createLibrary();
File libraryThree = createLibrary();
@@ -557,12 +560,12 @@ public class RepackagerTests {
}
@Test
public void existingEntryThatMatchesUnpackLibraryIsMarkedForUnpack() throws IOException {
void existingEntryThatMatchesUnpackLibraryIsMarkedForUnpack() throws IOException {
File library = createLibrary();
this.testJarFile.addClass("WEB-INF/classes/com/example/Application.class", ClassWithMainMethod.class);
this.testJarFile.addFile("WEB-INF/lib/" + library.getName(), library);
File source = this.testJarFile.getFile("war");
File dest = this.temporaryFolder.newFile("dest.war");
File dest = new File(this.tempDir, "dest.war");
Repackager repackager = new Repackager(source);
repackager.setLayout(new Layouts.War());
repackager.repackage(dest, (callback) -> callback.library(new Library(library, LibraryScope.COMPILE, true)));
@@ -573,8 +576,8 @@ public class RepackagerTests {
}
@Test
public void layoutCanOmitLibraries() throws IOException {
TestJarFile libJar = new TestJarFile(this.temporaryFolder);
void layoutCanOmitLibraries() throws IOException {
TestJarFile libJar = new TestJarFile(this.tempDir);
libJar.addClass("a/b/C.class", ClassWithoutMainMethod.class);
File libJarFile = libJar.getFile();
this.testJarFile.addClass("a/b/C.class", ClassWithMainMethod.class);
@@ -589,8 +592,8 @@ public class RepackagerTests {
}
@Test
public void jarThatUsesCustomCompressionConfigurationCanBeRepackaged() throws IOException {
File source = this.temporaryFolder.newFile("source.jar");
void jarThatUsesCustomCompressionConfigurationCanBeRepackaged() throws IOException {
File source = new File(this.tempDir, "source.jar");
ZipOutputStream output = new ZipOutputStream(new FileOutputStream(source)) {
{
this.def = new Deflater(Deflater.NO_COMPRESSION, true);
@@ -603,18 +606,18 @@ public class RepackagerTests {
output.write(data);
output.closeEntry();
output.close();
File dest = this.temporaryFolder.newFile("dest.jar");
File dest = new File(this.tempDir, "dest.jar");
Repackager repackager = new Repackager(source);
repackager.setMainClass("com.example.Main");
repackager.repackage(dest, NO_LIBRARIES);
}
@Test
public void moduleInfoClassRemainsInRootOfJarWhenRepackaged() throws Exception {
void moduleInfoClassRemainsInRootOfJarWhenRepackaged() throws Exception {
this.testJarFile.addClass("A.class", ClassWithMainMethod.class);
this.testJarFile.addClass("module-info.class", ClassWithoutMainMethod.class);
File source = this.testJarFile.getFile();
File dest = this.temporaryFolder.newFile("dest.jar");
File dest = new File(this.tempDir, "dest.jar");
Repackager repackager = new Repackager(source);
repackager.repackage(dest, NO_LIBRARIES);
try (JarFile jarFile = new JarFile(dest)) {
@@ -624,11 +627,13 @@ public class RepackagerTests {
}
@Test
public void kotlinModuleMetadataMovesBeneathBootInfClassesWhenRepackaged() throws Exception {
void kotlinModuleMetadataMovesBeneathBootInfClassesWhenRepackaged() throws Exception {
this.testJarFile.addClass("A.class", ClassWithMainMethod.class);
this.testJarFile.addFile("META-INF/test.kotlin_module", this.temporaryFolder.newFile("test.kotlin_module"));
File kotlinModule = new File(this.tempDir, "test.kotlin_module");
kotlinModule.createNewFile();
this.testJarFile.addFile("META-INF/test.kotlin_module", kotlinModule);
File source = this.testJarFile.getFile();
File dest = this.temporaryFolder.newFile("dest.jar");
File dest = new File(this.tempDir, "dest.jar");
Repackager repackager = new Repackager(source);
repackager.repackage(dest, NO_LIBRARIES);
try (JarFile jarFile = new JarFile(dest)) {
@@ -638,7 +643,7 @@ public class RepackagerTests {
}
private File createLibrary() throws IOException {
TestJarFile library = new TestJarFile(this.temporaryFolder);
TestJarFile library = new TestJarFile(this.tempDir);
library.addClass("com/example/library/Library.class", ClassWithoutMainMethod.class);
return library.getFile();
}

View File

@@ -24,10 +24,10 @@ import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.jar.JarFile;
import java.util.jar.Manifest;
import org.junit.rules.TemporaryFolder;
import org.zeroturnaround.zip.FileSource;
import org.zeroturnaround.zip.ZipEntrySource;
import org.zeroturnaround.zip.ZipUtil;
@@ -40,15 +40,15 @@ public class TestJarFile {
private final byte[] buffer = new byte[4096];
private final TemporaryFolder temporaryFolder;
private final File temporaryFolder;
private final File jarSource;
private final List<ZipEntrySource> entries = new ArrayList<>();
public TestJarFile(TemporaryFolder temporaryFolder) throws IOException {
public TestJarFile(File temporaryFolder) throws IOException {
this.temporaryFolder = temporaryFolder;
this.jarSource = temporaryFolder.newFolder();
this.jarSource = new File(temporaryFolder, "jar-source");
}
public void addClass(String filename, Class<?> classToCopy) throws IOException {
@@ -120,8 +120,7 @@ public class TestJarFile {
}
public File getFile(String extension) throws IOException {
File file = this.temporaryFolder.newFile();
file = new File(file.getParent(), file.getName() + "." + extension);
File file = new File(this.temporaryFolder, UUID.randomUUID() + "." + extension);
ZipUtil.pack(this.entries.toArray(new ZipEntrySource[0]), file);
return file;
}

View File

@@ -24,16 +24,16 @@ package org.springframework.boot.loader.tools;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.springframework.boot.loader.tools.JarWriter.ZipHeaderPeekInputStream;
import static org.assertj.core.api.Assertions.assertThat;
public class ZipHeaderPeekInputStreamTests {
class ZipHeaderPeekInputStreamTests {
@Test
public void hasZipHeaderReturnsTrueWhenStreamStartsWithZipHeader() throws IOException {
void hasZipHeaderReturnsTrueWhenStreamStartsWithZipHeader() throws IOException {
try (ZipHeaderPeekInputStream in = new ZipHeaderPeekInputStream(
new ByteArrayInputStream(new byte[] { 0x50, 0x4b, 0x03, 0x04, 5, 6 }))) {
assertThat(in.hasZipHeader()).isTrue();
@@ -41,7 +41,7 @@ public class ZipHeaderPeekInputStreamTests {
}
@Test
public void hasZipHeaderReturnsFalseWhenStreamDoesNotStartWithZipHeader() throws IOException {
void hasZipHeaderReturnsFalseWhenStreamDoesNotStartWithZipHeader() throws IOException {
try (ZipHeaderPeekInputStream in = new ZipHeaderPeekInputStream(
new ByteArrayInputStream(new byte[] { 0, 1, 2, 3, 4, 5 }))) {
assertThat(in.hasZipHeader()).isFalse();
@@ -49,7 +49,7 @@ public class ZipHeaderPeekInputStreamTests {
}
@Test
public void readIndividualBytes() throws IOException {
void readIndividualBytes() throws IOException {
try (ZipHeaderPeekInputStream in = new ZipHeaderPeekInputStream(
new ByteArrayInputStream(new byte[] { 0, 1, 2, 3, 4, 5 }))) {
assertThat(in.read()).isEqualTo(0);
@@ -62,7 +62,7 @@ public class ZipHeaderPeekInputStreamTests {
}
@Test
public void readMultipleBytes() throws IOException {
void readMultipleBytes() throws IOException {
try (ZipHeaderPeekInputStream in = new ZipHeaderPeekInputStream(
new ByteArrayInputStream(new byte[] { 0, 1, 2, 3, 4, 5 }))) {
byte[] bytes = new byte[3];
@@ -75,7 +75,7 @@ public class ZipHeaderPeekInputStreamTests {
}
@Test
public void readingMoreThanEntireStreamReadsToEndOfStream() throws IOException {
void readingMoreThanEntireStreamReadsToEndOfStream() throws IOException {
try (ZipHeaderPeekInputStream in = new ZipHeaderPeekInputStream(
new ByteArrayInputStream(new byte[] { 0, 1, 2, 3, 4, 5 }))) {
byte[] bytes = new byte[8];
@@ -86,7 +86,7 @@ public class ZipHeaderPeekInputStreamTests {
}
@Test
public void readOfSomeOfTheHeaderThenMoreThanEntireStreamReadsToEndOfStream() throws IOException {
void readOfSomeOfTheHeaderThenMoreThanEntireStreamReadsToEndOfStream() throws IOException {
try (ZipHeaderPeekInputStream in = new ZipHeaderPeekInputStream(
new ByteArrayInputStream(new byte[] { 0, 1, 2, 3, 4, 5 }))) {
byte[] bytes = new byte[8];
@@ -98,7 +98,7 @@ public class ZipHeaderPeekInputStreamTests {
}
@Test
public void readMoreThanEntireStreamWhenStreamLengthIsLessThanZipHeaderLength() throws IOException {
void readMoreThanEntireStreamWhenStreamLengthIsLessThanZipHeaderLength() throws IOException {
try (ZipHeaderPeekInputStream in = new ZipHeaderPeekInputStream(new ByteArrayInputStream(new byte[] { 10 }))) {
byte[] bytes = new byte[8];
assertThat(in.read(bytes)).isEqualTo(1);
@@ -107,7 +107,7 @@ public class ZipHeaderPeekInputStreamTests {
}
@Test
public void readMoreThanEntireStreamWhenStreamLengthIsSameAsHeaderLength() throws IOException {
void readMoreThanEntireStreamWhenStreamLengthIsSameAsHeaderLength() throws IOException {
try (ZipHeaderPeekInputStream in = new ZipHeaderPeekInputStream(
new ByteArrayInputStream(new byte[] { 1, 2, 3, 4 }))) {
byte[] bytes = new byte[8];
@@ -117,7 +117,7 @@ public class ZipHeaderPeekInputStreamTests {
}
@Test
public void readMoreThanEntireStreamWhenStreamLengthIsZero() throws IOException {
void readMoreThanEntireStreamWhenStreamLengthIsZero() throws IOException {
try (ZipHeaderPeekInputStream in = new ZipHeaderPeekInputStream(new ByteArrayInputStream(new byte[0]))) {
byte[] bytes = new byte[8];
assertThat(in.read(bytes)).isEqualTo(-1);

View File

@@ -32,8 +32,7 @@ import java.util.jar.JarOutputStream;
import java.util.zip.CRC32;
import java.util.zip.ZipEntry;
import org.junit.Rule;
import org.junit.rules.TemporaryFolder;
import org.junit.jupiter.api.io.TempDir;
import org.springframework.boot.loader.archive.Archive;
import org.springframework.util.FileCopyUtils;
@@ -45,11 +44,11 @@ import org.springframework.util.FileCopyUtils;
*/
public abstract class AbstractExecutableArchiveLauncherTests {
@Rule
public TemporaryFolder temp = new TemporaryFolder();
@TempDir
File tempDir;
protected File createJarArchive(String name, String entryPrefix) throws IOException {
File archive = this.temp.newFile(name);
File archive = new File(this.tempDir, name);
JarOutputStream jarOutputStream = new JarOutputStream(new FileOutputStream(archive));
jarOutputStream.putNextEntry(new JarEntry(entryPrefix + "/"));
jarOutputStream.putNextEntry(new JarEntry(entryPrefix + "/classes/"));
@@ -69,7 +68,8 @@ public abstract class AbstractExecutableArchiveLauncherTests {
}
protected File explode(File archive) throws IOException {
File exploded = this.temp.newFolder("exploded");
File exploded = new File(this.tempDir, "exploded");
exploded.mkdirs();
JarFile jarFile = new JarFile(archive);
Enumeration<JarEntry> entries = jarFile.entries();
while (entries.hasMoreElements()) {

View File

@@ -20,7 +20,7 @@ import java.io.File;
import java.net.URL;
import java.util.List;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.springframework.boot.loader.archive.Archive;
import org.springframework.boot.loader.archive.ExplodedArchive;
@@ -33,10 +33,10 @@ import static org.assertj.core.api.Assertions.assertThat;
*
* @author Andy Wilkinson
*/
public class JarLauncherTests extends AbstractExecutableArchiveLauncherTests {
class JarLauncherTests extends AbstractExecutableArchiveLauncherTests {
@Test
public void explodedJarHasOnlyBootInfClassesAndContentsOfBootInfLibOnClasspath() throws Exception {
void explodedJarHasOnlyBootInfClassesAndContentsOfBootInfLibOnClasspath() throws Exception {
File explodedRoot = explode(createJarArchive("archive.jar", "BOOT-INF"));
JarLauncher launcher = new JarLauncher(new ExplodedArchive(explodedRoot, true));
List<Archive> archives = launcher.getClassPathArchives();
@@ -46,7 +46,7 @@ public class JarLauncherTests extends AbstractExecutableArchiveLauncherTests {
}
@Test
public void archivedJarHasOnlyBootInfClassesAndContentsOfBootInfLibOnClasspath() throws Exception {
void archivedJarHasOnlyBootInfClassesAndContentsOfBootInfLibOnClasspath() throws Exception {
File jarRoot = createJarArchive("archive.jar", "BOOT-INF");
JarLauncher launcher = new JarLauncher(new JarFileArchive(jarRoot));
List<Archive> archives = launcher.getClassPathArchives();

View File

@@ -19,9 +19,8 @@ package org.springframework.boot.loader;
import java.io.File;
import java.net.URL;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.springframework.boot.loader.jar.JarFile;
@@ -35,42 +34,42 @@ import static org.assertj.core.api.Assertions.assertThat;
* @author Andy Wilkinson
*/
@SuppressWarnings("resource")
public class LaunchedURLClassLoaderTests {
class LaunchedURLClassLoaderTests {
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
@TempDir
File tempDir;
@Test
public void resolveResourceFromArchive() throws Exception {
void resolveResourceFromArchive() throws Exception {
LaunchedURLClassLoader loader = new LaunchedURLClassLoader(
new URL[] { new URL("jar:file:src/test/resources/jars/app.jar!/") }, getClass().getClassLoader());
assertThat(loader.getResource("demo/Application.java")).isNotNull();
}
@Test
public void resolveResourcesFromArchive() throws Exception {
void resolveResourcesFromArchive() throws Exception {
LaunchedURLClassLoader loader = new LaunchedURLClassLoader(
new URL[] { new URL("jar:file:src/test/resources/jars/app.jar!/") }, getClass().getClassLoader());
assertThat(loader.getResources("demo/Application.java").hasMoreElements()).isTrue();
}
@Test
public void resolveRootPathFromArchive() throws Exception {
void resolveRootPathFromArchive() throws Exception {
LaunchedURLClassLoader loader = new LaunchedURLClassLoader(
new URL[] { new URL("jar:file:src/test/resources/jars/app.jar!/") }, getClass().getClassLoader());
assertThat(loader.getResource("")).isNotNull();
}
@Test
public void resolveRootResourcesFromArchive() throws Exception {
void resolveRootResourcesFromArchive() throws Exception {
LaunchedURLClassLoader loader = new LaunchedURLClassLoader(
new URL[] { new URL("jar:file:src/test/resources/jars/app.jar!/") }, getClass().getClassLoader());
assertThat(loader.getResources("").hasMoreElements()).isTrue();
}
@Test
public void resolveFromNested() throws Exception {
File file = this.temporaryFolder.newFile();
void resolveFromNested() throws Exception {
File file = new File(this.tempDir, "test.jar");
TestJarCreator.createTestJar(file);
JarFile jarFile = new JarFile(file);
URL url = jarFile.getUrl();
@@ -81,8 +80,8 @@ public class LaunchedURLClassLoaderTests {
}
@Test
public void resolveFromNestedWhileThreadIsInterrupted() throws Exception {
File file = this.temporaryFolder.newFile();
void resolveFromNestedWhileThreadIsInterrupted() throws Exception {
File file = new File(this.tempDir, "test.jar");
TestJarCreator.createTestJar(file);
JarFile jarFile = new JarFile(file);
URL url = jarFile.getUrl();

View File

@@ -28,16 +28,17 @@ import java.util.jar.Attributes;
import java.util.jar.Manifest;
import org.assertj.core.api.Condition;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
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.io.TempDir;
import org.springframework.boot.loader.archive.Archive;
import org.springframework.boot.loader.archive.ExplodedArchive;
import org.springframework.boot.loader.archive.JarFileArchive;
import org.springframework.boot.testsupport.rule.OutputCapture;
import org.springframework.boot.testsupport.system.CapturedOutput;
import org.springframework.boot.testsupport.system.OutputCaptureExtension;
import org.springframework.core.io.FileSystemResource;
import org.springframework.test.util.ReflectionTestUtils;
@@ -50,23 +51,24 @@ import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
* @author Dave Syer
* @author Andy Wilkinson
*/
public class PropertiesLauncherTests {
@ExtendWith(OutputCaptureExtension.class)
class PropertiesLauncherTests {
@Rule
public OutputCapture output = new OutputCapture();
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
@TempDir
File tempDir;
private ClassLoader contextClassLoader;
@Before
public void setup() {
private CapturedOutput capturedOutput;
@BeforeEach
public void setup(CapturedOutput capturedOutput) {
this.contextClassLoader = Thread.currentThread().getContextClassLoader();
System.setProperty("loader.home", new File("src/test/resources").getAbsolutePath());
this.capturedOutput = capturedOutput;
}
@After
@AfterEach
public void close() {
Thread.currentThread().setContextClassLoader(this.contextClassLoader);
System.clearProperty("loader.home");
@@ -79,14 +81,14 @@ public class PropertiesLauncherTests {
}
@Test
public void testDefaultHome() {
void testDefaultHome() {
System.clearProperty("loader.home");
PropertiesLauncher launcher = new PropertiesLauncher();
assertThat(launcher.getHomeDirectory()).isEqualTo(new File(System.getProperty("user.dir")));
}
@Test
public void testAlternateHome() throws Exception {
void testAlternateHome() throws Exception {
System.setProperty("loader.home", "src/test/resources/home");
PropertiesLauncher launcher = new PropertiesLauncher();
assertThat(launcher.getHomeDirectory()).isEqualTo(new File(System.getProperty("loader.home")));
@@ -94,21 +96,21 @@ public class PropertiesLauncherTests {
}
@Test
public void testNonExistentHome() {
void testNonExistentHome() {
System.setProperty("loader.home", "src/test/resources/nonexistent");
assertThatIllegalStateException().isThrownBy(PropertiesLauncher::new)
.withMessageContaining("Invalid source folder").withCauseInstanceOf(IllegalArgumentException.class);
}
@Test
public void testUserSpecifiedMain() throws Exception {
void testUserSpecifiedMain() throws Exception {
PropertiesLauncher launcher = new PropertiesLauncher();
assertThat(launcher.getMainClass()).isEqualTo("demo.Application");
assertThat(System.getProperty("loader.main")).isNull();
}
@Test
public void testUserSpecifiedConfigName() throws Exception {
void testUserSpecifiedConfigName() throws Exception {
System.setProperty("loader.config.name", "foo");
PropertiesLauncher launcher = new PropertiesLauncher();
assertThat(launcher.getMainClass()).isEqualTo("my.Application");
@@ -116,21 +118,21 @@ public class PropertiesLauncherTests {
}
@Test
public void testRootOfClasspathFirst() throws Exception {
void testRootOfClasspathFirst() throws Exception {
System.setProperty("loader.config.name", "bar");
PropertiesLauncher launcher = new PropertiesLauncher();
assertThat(launcher.getMainClass()).isEqualTo("my.BarApplication");
}
@Test
public void testUserSpecifiedDotPath() {
void testUserSpecifiedDotPath() {
System.setProperty("loader.path", ".");
PropertiesLauncher launcher = new PropertiesLauncher();
assertThat(ReflectionTestUtils.getField(launcher, "paths").toString()).isEqualTo("[.]");
}
@Test
public void testUserSpecifiedSlashPath() throws Exception {
void testUserSpecifiedSlashPath() throws Exception {
System.setProperty("loader.path", "jars/");
PropertiesLauncher launcher = new PropertiesLauncher();
assertThat(ReflectionTestUtils.getField(launcher, "paths").toString()).isEqualTo("[jars/]");
@@ -139,7 +141,7 @@ public class PropertiesLauncherTests {
}
@Test
public void testUserSpecifiedWildcardPath() throws Exception {
void testUserSpecifiedWildcardPath() throws Exception {
System.setProperty("loader.path", "jars/*");
System.setProperty("loader.main", "demo.Application");
PropertiesLauncher launcher = new PropertiesLauncher();
@@ -149,7 +151,7 @@ public class PropertiesLauncherTests {
}
@Test
public void testUserSpecifiedJarPath() throws Exception {
void testUserSpecifiedJarPath() throws Exception {
System.setProperty("loader.path", "jars/app.jar");
System.setProperty("loader.main", "demo.Application");
PropertiesLauncher launcher = new PropertiesLauncher();
@@ -159,7 +161,7 @@ public class PropertiesLauncherTests {
}
@Test
public void testUserSpecifiedRootOfJarPath() throws Exception {
void testUserSpecifiedRootOfJarPath() throws Exception {
System.setProperty("loader.path", "jar:file:./src/test/resources/nested-jars/app.jar!/");
PropertiesLauncher launcher = new PropertiesLauncher();
assertThat(ReflectionTestUtils.getField(launcher, "paths").toString())
@@ -170,7 +172,7 @@ public class PropertiesLauncherTests {
}
@Test
public void testUserSpecifiedRootOfJarPathWithDot() throws Exception {
void testUserSpecifiedRootOfJarPathWithDot() throws Exception {
System.setProperty("loader.path", "nested-jars/app.jar!/./");
PropertiesLauncher launcher = new PropertiesLauncher();
List<Archive> archives = launcher.getClassPathArchives();
@@ -179,7 +181,7 @@ public class PropertiesLauncherTests {
}
@Test
public void testUserSpecifiedRootOfJarPathWithDotAndJarPrefix() throws Exception {
void testUserSpecifiedRootOfJarPathWithDotAndJarPrefix() throws Exception {
System.setProperty("loader.path", "jar:file:./src/test/resources/nested-jars/app.jar!/./");
PropertiesLauncher launcher = new PropertiesLauncher();
List<Archive> archives = launcher.getClassPathArchives();
@@ -187,7 +189,7 @@ public class PropertiesLauncherTests {
}
@Test
public void testUserSpecifiedJarFileWithNestedArchives() throws Exception {
void testUserSpecifiedJarFileWithNestedArchives() throws Exception {
System.setProperty("loader.path", "nested-jars/app.jar");
System.setProperty("loader.main", "demo.Application");
PropertiesLauncher launcher = new PropertiesLauncher();
@@ -197,7 +199,7 @@ public class PropertiesLauncherTests {
}
@Test
public void testUserSpecifiedNestedJarPath() throws Exception {
void testUserSpecifiedNestedJarPath() throws Exception {
System.setProperty("loader.path", "nested-jars/app.jar!/foo.jar");
System.setProperty("loader.main", "demo.Application");
PropertiesLauncher launcher = new PropertiesLauncher();
@@ -206,7 +208,7 @@ public class PropertiesLauncherTests {
}
@Test
public void testUserSpecifiedDirectoryContainingJarFileWithNestedArchives() throws Exception {
void testUserSpecifiedDirectoryContainingJarFileWithNestedArchives() throws Exception {
System.setProperty("loader.path", "nested-jars");
System.setProperty("loader.main", "demo.Application");
PropertiesLauncher launcher = new PropertiesLauncher();
@@ -215,7 +217,7 @@ public class PropertiesLauncherTests {
}
@Test
public void testUserSpecifiedJarPathWithDot() throws Exception {
void testUserSpecifiedJarPathWithDot() throws Exception {
System.setProperty("loader.path", "./jars/app.jar");
System.setProperty("loader.main", "demo.Application");
PropertiesLauncher launcher = new PropertiesLauncher();
@@ -225,7 +227,7 @@ public class PropertiesLauncherTests {
}
@Test
public void testUserSpecifiedClassLoader() throws Exception {
void testUserSpecifiedClassLoader() throws Exception {
System.setProperty("loader.path", "jars/app.jar");
System.setProperty("loader.classLoader", URLClassLoader.class.getName());
PropertiesLauncher launcher = new PropertiesLauncher();
@@ -235,7 +237,7 @@ public class PropertiesLauncherTests {
}
@Test
public void testUserSpecifiedClassPathOrder() throws Exception {
void testUserSpecifiedClassPathOrder() throws Exception {
System.setProperty("loader.path", "more-jars/app.jar,jars/app.jar");
System.setProperty("loader.classLoader", URLClassLoader.class.getName());
PropertiesLauncher launcher = new PropertiesLauncher();
@@ -246,7 +248,7 @@ public class PropertiesLauncherTests {
}
@Test
public void testCustomClassLoaderCreation() throws Exception {
void testCustomClassLoaderCreation() throws Exception {
System.setProperty("loader.classLoader", TestLoader.class.getName());
PropertiesLauncher launcher = new PropertiesLauncher();
ClassLoader loader = launcher.createClassLoader(archives());
@@ -272,7 +274,7 @@ public class PropertiesLauncherTests {
}
@Test
public void testUserSpecifiedConfigPathWins() throws Exception {
void testUserSpecifiedConfigPathWins() throws Exception {
System.setProperty("loader.config.name", "foo");
System.setProperty("loader.config.location", "classpath:bar.properties");
@@ -281,21 +283,21 @@ public class PropertiesLauncherTests {
}
@Test
public void testSystemPropertySpecifiedMain() throws Exception {
void testSystemPropertySpecifiedMain() throws Exception {
System.setProperty("loader.main", "foo.Bar");
PropertiesLauncher launcher = new PropertiesLauncher();
assertThat(launcher.getMainClass()).isEqualTo("foo.Bar");
}
@Test
public void testSystemPropertiesSet() {
void testSystemPropertiesSet() {
System.setProperty("loader.system", "true");
new PropertiesLauncher();
assertThat(System.getProperty("loader.main")).isEqualTo("demo.Application");
}
@Test
public void testArgsEnhanced() throws Exception {
void testArgsEnhanced() throws Exception {
System.setProperty("loader.args", "foo");
PropertiesLauncher launcher = new PropertiesLauncher();
assertThat(Arrays.asList(launcher.getArgs("bar")).toString()).isEqualTo("[foo, bar]");
@@ -303,12 +305,12 @@ public class PropertiesLauncherTests {
@SuppressWarnings("unchecked")
@Test
public void testLoadPathCustomizedUsingManifest() throws Exception {
System.setProperty("loader.home", this.temporaryFolder.getRoot().getAbsolutePath());
void testLoadPathCustomizedUsingManifest() throws Exception {
System.setProperty("loader.home", this.tempDir.getAbsolutePath());
Manifest manifest = new Manifest();
manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
manifest.getMainAttributes().putValue("Loader-Path", "/foo.jar, /bar");
File manifestFile = new File(this.temporaryFolder.getRoot(), "META-INF/MANIFEST.MF");
File manifestFile = new File(this.tempDir, "META-INF/MANIFEST.MF");
manifestFile.getParentFile().mkdirs();
manifest.write(new FileOutputStream(manifestFile));
PropertiesLauncher launcher = new PropertiesLauncher();
@@ -316,15 +318,16 @@ public class PropertiesLauncherTests {
}
@Test
public void testManifestWithPlaceholders() throws Exception {
void testManifestWithPlaceholders() throws Exception {
System.setProperty("loader.home", "src/test/resources/placeholders");
PropertiesLauncher launcher = new PropertiesLauncher();
assertThat(launcher.getMainClass()).isEqualTo("demo.FooApplication");
}
@Test
public void encodedFileUrlLoaderPathIsHandledCorrectly() throws Exception {
File loaderPath = this.temporaryFolder.newFolder("loader path");
void encodedFileUrlLoaderPathIsHandledCorrectly() throws Exception {
File loaderPath = new File(this.tempDir, "loader path");
loaderPath.mkdir();
System.setProperty("loader.path", loaderPath.toURI().toURL().toString());
PropertiesLauncher launcher = new PropertiesLauncher();
List<Archive> archives = launcher.getClassPathArchives();
@@ -339,7 +342,7 @@ public class PropertiesLauncherTests {
while (!timeout && count < 100) {
count++;
Thread.sleep(50L);
timeout = this.output.toString().contains(value);
timeout = this.capturedOutput.toString().contains(value);
}
assertThat(timeout).as("Timed out waiting for (" + value + ")").isTrue();
}

View File

@@ -20,7 +20,7 @@ import java.io.File;
import java.net.URL;
import java.util.List;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.springframework.boot.loader.archive.Archive;
import org.springframework.boot.loader.archive.ExplodedArchive;
@@ -33,10 +33,10 @@ import static org.assertj.core.api.Assertions.assertThat;
*
* @author Andy Wilkinson
*/
public class WarLauncherTests extends AbstractExecutableArchiveLauncherTests {
class WarLauncherTests extends AbstractExecutableArchiveLauncherTests {
@Test
public void explodedWarHasOnlyWebInfClassesAndContentsOfWebInfLibOnClasspath() throws Exception {
void explodedWarHasOnlyWebInfClassesAndContentsOfWebInfLibOnClasspath() throws Exception {
File explodedRoot = explode(createJarArchive("archive.war", "WEB-INF"));
WarLauncher launcher = new WarLauncher(new ExplodedArchive(explodedRoot, true));
List<Archive> archives = launcher.getClassPathArchives();
@@ -46,7 +46,7 @@ public class WarLauncherTests extends AbstractExecutableArchiveLauncherTests {
}
@Test
public void archivedWarHasOnlyWebInfClassesAndContentsOWebInfLibOnClasspath() throws Exception {
void archivedWarHasOnlyWebInfClassesAndContentsOWebInfLibOnClasspath() throws Exception {
File jarRoot = createJarArchive("archive.war", "WEB-INF");
WarLauncher launcher = new WarLauncher(new JarFileArchive(jarRoot));
List<Archive> archives = launcher.getClassPathArchives();

View File

@@ -26,13 +26,13 @@ import java.net.URLClassLoader;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.springframework.boot.loader.TestJarCreator;
import org.springframework.boot.loader.archive.Archive.Entry;
@@ -47,16 +47,16 @@ import static org.assertj.core.api.Assertions.assertThat;
* @author Dave Syer
* @author Andy Wilkinson
*/
public class ExplodedArchiveTests {
class ExplodedArchiveTests {
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
@TempDir
File tempDir;
private File rootFolder;
private ExplodedArchive archive;
@Before
@BeforeEach
public void setup() throws Exception {
createArchive();
}
@@ -66,11 +66,11 @@ public class ExplodedArchiveTests {
}
private void createArchive(String folderName) throws Exception {
File file = this.temporaryFolder.newFile();
File file = new File(this.tempDir, "test.jar");
TestJarCreator.createTestJar(file);
this.rootFolder = (StringUtils.hasText(folderName) ? this.temporaryFolder.newFolder(folderName)
: this.temporaryFolder.newFolder());
this.rootFolder = (StringUtils.hasText(folderName) ? new File(this.tempDir, folderName)
: new File(this.tempDir, UUID.randomUUID().toString()));
JarFile jarFile = new JarFile(file);
Enumeration<JarEntry> entries = jarFile.entries();
while (entries.hasMoreElements()) {
@@ -98,36 +98,36 @@ public class ExplodedArchiveTests {
}
@Test
public void getManifest() throws Exception {
void getManifest() throws Exception {
assertThat(this.archive.getManifest().getMainAttributes().getValue("Built-By")).isEqualTo("j1");
}
@Test
public void getEntries() {
void getEntries() {
Map<String, Archive.Entry> entries = getEntriesMap(this.archive);
assertThat(entries.size()).isEqualTo(12);
}
@Test
public void getUrl() throws Exception {
void getUrl() throws Exception {
assertThat(this.archive.getUrl()).isEqualTo(this.rootFolder.toURI().toURL());
}
@Test
public void getUrlWithSpaceInPath() throws Exception {
void getUrlWithSpaceInPath() throws Exception {
createArchive("spaces in the name");
assertThat(this.archive.getUrl()).isEqualTo(this.rootFolder.toURI().toURL());
}
@Test
public void getNestedArchive() throws Exception {
void getNestedArchive() throws Exception {
Entry entry = getEntriesMap(this.archive).get("nested.jar");
Archive nested = this.archive.getNestedArchive(entry);
assertThat(nested.getUrl().toString()).isEqualTo(this.rootFolder.toURI() + "nested.jar");
}
@Test
public void nestedDirArchive() throws Exception {
void nestedDirArchive() throws Exception {
Entry entry = getEntriesMap(this.archive).get("d/");
Archive nested = this.archive.getNestedArchive(entry);
Map<String, Entry> nestedEntries = getEntriesMap(nested);
@@ -136,14 +136,14 @@ public class ExplodedArchiveTests {
}
@Test
public void getNonRecursiveEntriesForRoot() {
void getNonRecursiveEntriesForRoot() {
ExplodedArchive archive = new ExplodedArchive(new File("/"), false);
Map<String, Archive.Entry> entries = getEntriesMap(archive);
assertThat(entries.size()).isGreaterThan(1);
}
@Test
public void getNonRecursiveManifest() throws Exception {
void getNonRecursiveManifest() throws Exception {
ExplodedArchive archive = new ExplodedArchive(new File("src/test/resources/root"));
assertThat(archive.getManifest()).isNotNull();
Map<String, Archive.Entry> entries = getEntriesMap(archive);
@@ -151,7 +151,7 @@ public class ExplodedArchiveTests {
}
@Test
public void getNonRecursiveManifestEvenIfNonRecursive() throws Exception {
void getNonRecursiveManifestEvenIfNonRecursive() throws Exception {
ExplodedArchive archive = new ExplodedArchive(new File("src/test/resources/root"), false);
assertThat(archive.getManifest()).isNotNull();
Map<String, Archive.Entry> entries = getEntriesMap(archive);
@@ -159,7 +159,7 @@ public class ExplodedArchiveTests {
}
@Test
public void getResourceAsStream() throws Exception {
void getResourceAsStream() throws Exception {
ExplodedArchive archive = new ExplodedArchive(new File("src/test/resources/root"));
assertThat(archive.getManifest()).isNotNull();
URLClassLoader loader = new URLClassLoader(new URL[] { archive.getUrl() });
@@ -168,7 +168,7 @@ public class ExplodedArchiveTests {
}
@Test
public void getResourceAsStreamNonRecursive() throws Exception {
void getResourceAsStreamNonRecursive() throws Exception {
ExplodedArchive archive = new ExplodedArchive(new File("src/test/resources/root"), false);
assertThat(archive.getManifest()).isNotNull();
URLClassLoader loader = new URLClassLoader(new URL[] { archive.getUrl() });

View File

@@ -28,10 +28,9 @@ import java.util.jar.JarOutputStream;
import java.util.zip.CRC32;
import java.util.zip.ZipEntry;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.springframework.boot.loader.TestJarCreator;
import org.springframework.boot.loader.archive.Archive.Entry;
@@ -46,10 +45,10 @@ import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
* @author Phillip Webb
* @author Andy Wilkinson
*/
public class JarFileArchiveTests {
class JarFileArchiveTests {
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
@TempDir
File tempDir;
private File rootJarFile;
@@ -57,44 +56,44 @@ public class JarFileArchiveTests {
private String rootJarFileUrl;
@Before
@BeforeEach
public void setup() throws Exception {
setup(false);
}
private void setup(boolean unpackNested) throws Exception {
this.rootJarFile = this.temporaryFolder.newFile();
this.rootJarFile = new File(this.tempDir, "root.jar");
this.rootJarFileUrl = this.rootJarFile.toURI().toString();
TestJarCreator.createTestJar(this.rootJarFile, unpackNested);
this.archive = new JarFileArchive(this.rootJarFile);
}
@Test
public void getManifest() throws Exception {
void getManifest() throws Exception {
assertThat(this.archive.getManifest().getMainAttributes().getValue("Built-By")).isEqualTo("j1");
}
@Test
public void getEntries() {
void getEntries() {
Map<String, Archive.Entry> entries = getEntriesMap(this.archive);
assertThat(entries.size()).isEqualTo(12);
}
@Test
public void getUrl() throws Exception {
void getUrl() throws Exception {
URL url = this.archive.getUrl();
assertThat(url.toString()).isEqualTo(this.rootJarFileUrl);
}
@Test
public void getNestedArchive() throws Exception {
void getNestedArchive() throws Exception {
Entry entry = getEntriesMap(this.archive).get("nested.jar");
Archive nested = this.archive.getNestedArchive(entry);
assertThat(nested.getUrl().toString()).isEqualTo("jar:" + this.rootJarFileUrl + "!/nested.jar!/");
}
@Test
public void getNestedUnpackedArchive() throws Exception {
void getNestedUnpackedArchive() throws Exception {
setup(true);
Entry entry = getEntriesMap(this.archive).get("nested.jar");
Archive nested = this.archive.getNestedArchive(entry);
@@ -103,7 +102,7 @@ public class JarFileArchiveTests {
}
@Test
public void unpackedLocationsAreUniquePerArchive() throws Exception {
void unpackedLocationsAreUniquePerArchive() throws Exception {
setup(true);
Entry entry = getEntriesMap(this.archive).get("nested.jar");
URL firstNested = this.archive.getNestedArchive(entry).getUrl();
@@ -114,7 +113,7 @@ public class JarFileArchiveTests {
}
@Test
public void unpackedLocationsFromSameArchiveShareSameParent() throws Exception {
void unpackedLocationsFromSameArchiveShareSameParent() throws Exception {
setup(true);
File nested = new File(
this.archive.getNestedArchive(getEntriesMap(this.archive).get("nested.jar")).getUrl().toURI());
@@ -124,16 +123,16 @@ public class JarFileArchiveTests {
}
@Test
public void zip64ArchivesAreHandledGracefully() throws IOException {
File file = this.temporaryFolder.newFile("test.jar");
void zip64ArchivesAreHandledGracefully() throws IOException {
File file = new File(this.tempDir, "test.jar");
FileCopyUtils.copy(writeZip64Jar(), file);
assertThatIllegalStateException().isThrownBy(() -> new JarFileArchive(file))
.withMessageContaining("Zip64 archives are not supported");
}
@Test
public void nestedZip64ArchivesAreHandledGracefully() throws IOException {
File file = this.temporaryFolder.newFile("test.jar");
void nestedZip64ArchivesAreHandledGracefully() throws IOException {
File file = new File(this.tempDir, "test.jar");
JarOutputStream output = new JarOutputStream(new FileOutputStream(file));
JarEntry zip64JarEntry = new JarEntry("nested/zip64.jar");
output.putNextEntry(zip64JarEntry);

View File

@@ -27,11 +27,10 @@ import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
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.assertj.core.api.Assertions.assertThatExceptionOfType;
@@ -44,7 +43,7 @@ import static org.assertj.core.api.Assertions.assertThatNullPointerException;
* @author Phillip Webb
* @author Andy Wilkinson
*/
public class RandomAccessDataFileTests {
class RandomAccessDataFileTests {
private static final byte[] BYTES;
@@ -55,18 +54,15 @@ public class RandomAccessDataFileTests {
}
}
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
private File tempFile;
private RandomAccessDataFile file;
private InputStream inputStream;
@Before
public void setup() throws Exception {
this.tempFile = this.temporaryFolder.newFile();
@BeforeEach
public void setup(@TempDir File tempDir) throws Exception {
this.tempFile = new File(tempDir, "tempFile");
FileOutputStream outputStream = new FileOutputStream(this.tempFile);
outputStream.write(BYTES);
outputStream.close();
@@ -74,74 +70,74 @@ public class RandomAccessDataFileTests {
this.inputStream = this.file.getInputStream();
}
@After
@AfterEach
public void cleanup() throws Exception {
this.inputStream.close();
this.file.close();
}
@Test
public void fileNotNull() {
void fileNotNull() {
assertThatIllegalArgumentException().isThrownBy(() -> new RandomAccessDataFile(null))
.withMessageContaining("File must not be null");
}
@Test
public void fileExists() {
void fileExists() {
File file = new File("/does/not/exist");
assertThatIllegalArgumentException().isThrownBy(() -> new RandomAccessDataFile(file))
.withMessageContaining(String.format("File %s must exist", file.getAbsolutePath()));
}
@Test
public void readWithOffsetAndLengthShouldRead() throws Exception {
void readWithOffsetAndLengthShouldRead() throws Exception {
byte[] read = this.file.read(2, 3);
assertThat(read).isEqualTo(new byte[] { 2, 3, 4 });
}
@Test
public void readWhenOffsetIsBeyondEOFShouldThrowException() throws Exception {
void readWhenOffsetIsBeyondEOFShouldThrowException() throws Exception {
assertThatExceptionOfType(IndexOutOfBoundsException.class).isThrownBy(() -> this.file.read(257, 0));
}
@Test
public void readWhenOffsetIsBeyondEndOfSubsectionShouldThrowException() throws Exception {
void readWhenOffsetIsBeyondEndOfSubsectionShouldThrowException() throws Exception {
RandomAccessData subsection = this.file.getSubsection(0, 10);
assertThatExceptionOfType(IndexOutOfBoundsException.class).isThrownBy(() -> subsection.read(11, 0));
}
@Test
public void readWhenOffsetPlusLengthGreaterThanEOFShouldThrowException() throws Exception {
void readWhenOffsetPlusLengthGreaterThanEOFShouldThrowException() throws Exception {
assertThatExceptionOfType(EOFException.class).isThrownBy(() -> this.file.read(256, 1));
}
@Test
public void readWhenOffsetPlusLengthGreaterThanEndOfSubsectionShouldThrowException() throws Exception {
void readWhenOffsetPlusLengthGreaterThanEndOfSubsectionShouldThrowException() throws Exception {
RandomAccessData subsection = this.file.getSubsection(0, 10);
assertThatExceptionOfType(EOFException.class).isThrownBy(() -> subsection.read(10, 1));
}
@Test
public void inputStreamRead() throws Exception {
void inputStreamRead() throws Exception {
for (int i = 0; i <= 255; i++) {
assertThat(this.inputStream.read()).isEqualTo(i);
}
}
@Test
public void inputStreamReadNullBytes() throws Exception {
void inputStreamReadNullBytes() throws Exception {
assertThatNullPointerException().isThrownBy(() -> this.inputStream.read(null))
.withMessage("Bytes must not be null");
}
@Test
public void inputStreamReadNullBytesWithOffset() throws Exception {
void inputStreamReadNullBytesWithOffset() throws Exception {
assertThatNullPointerException().isThrownBy(() -> this.inputStream.read(null, 0, 1))
.withMessage("Bytes must not be null");
}
@Test
public void inputStreamReadBytes() throws Exception {
void inputStreamReadBytes() throws Exception {
byte[] b = new byte[256];
int amountRead = this.inputStream.read(b);
assertThat(b).isEqualTo(BYTES);
@@ -149,7 +145,7 @@ public class RandomAccessDataFileTests {
}
@Test
public void inputStreamReadOffsetBytes() throws Exception {
void inputStreamReadOffsetBytes() throws Exception {
byte[] b = new byte[7];
this.inputStream.skip(1);
int amountRead = this.inputStream.read(b, 2, 3);
@@ -158,7 +154,7 @@ public class RandomAccessDataFileTests {
}
@Test
public void inputStreamReadMoreBytesThanAvailable() throws Exception {
void inputStreamReadMoreBytesThanAvailable() throws Exception {
byte[] b = new byte[257];
int amountRead = this.inputStream.read(b);
assertThat(b).startsWith(BYTES);
@@ -166,7 +162,7 @@ public class RandomAccessDataFileTests {
}
@Test
public void inputStreamReadPastEnd() throws Exception {
void inputStreamReadPastEnd() throws Exception {
this.inputStream.skip(255);
assertThat(this.inputStream.read()).isEqualTo(0xFF);
assertThat(this.inputStream.read()).isEqualTo(-1);
@@ -174,7 +170,7 @@ public class RandomAccessDataFileTests {
}
@Test
public void inputStreamReadZeroLength() throws Exception {
void inputStreamReadZeroLength() throws Exception {
byte[] b = new byte[] { 0x0F };
int amountRead = this.inputStream.read(b, 0, 0);
assertThat(b).isEqualTo(new byte[] { 0x0F });
@@ -183,62 +179,62 @@ public class RandomAccessDataFileTests {
}
@Test
public void inputStreamSkip() throws Exception {
void inputStreamSkip() throws Exception {
long amountSkipped = this.inputStream.skip(4);
assertThat(this.inputStream.read()).isEqualTo(4);
assertThat(amountSkipped).isEqualTo(4L);
}
@Test
public void inputStreamSkipMoreThanAvailable() throws Exception {
void inputStreamSkipMoreThanAvailable() throws Exception {
long amountSkipped = this.inputStream.skip(257);
assertThat(this.inputStream.read()).isEqualTo(-1);
assertThat(amountSkipped).isEqualTo(256L);
}
@Test
public void inputStreamSkipPastEnd() throws Exception {
void inputStreamSkipPastEnd() throws Exception {
this.inputStream.skip(256);
long amountSkipped = this.inputStream.skip(1);
assertThat(amountSkipped).isEqualTo(0L);
}
@Test
public void subsectionNegativeOffset() {
void subsectionNegativeOffset() {
assertThatExceptionOfType(IndexOutOfBoundsException.class).isThrownBy(() -> this.file.getSubsection(-1, 1));
}
@Test
public void subsectionNegativeLength() {
void subsectionNegativeLength() {
assertThatExceptionOfType(IndexOutOfBoundsException.class).isThrownBy(() -> this.file.getSubsection(0, -1));
}
@Test
public void subsectionZeroLength() throws Exception {
void subsectionZeroLength() throws Exception {
RandomAccessData subsection = this.file.getSubsection(0, 0);
assertThat(subsection.getInputStream().read()).isEqualTo(-1);
}
@Test
public void subsectionTooBig() {
void subsectionTooBig() {
this.file.getSubsection(0, 256);
assertThatExceptionOfType(IndexOutOfBoundsException.class).isThrownBy(() -> this.file.getSubsection(0, 257));
}
@Test
public void subsectionTooBigWithOffset() {
void subsectionTooBigWithOffset() {
this.file.getSubsection(1, 255);
assertThatExceptionOfType(IndexOutOfBoundsException.class).isThrownBy(() -> this.file.getSubsection(1, 256));
}
@Test
public void subsection() throws Exception {
void subsection() throws Exception {
RandomAccessData subsection = this.file.getSubsection(1, 1);
assertThat(subsection.getInputStream().read()).isEqualTo(1);
}
@Test
public void inputStreamReadPastSubsection() throws Exception {
void inputStreamReadPastSubsection() throws Exception {
RandomAccessData subsection = this.file.getSubsection(1, 2);
InputStream inputStream = subsection.getInputStream();
assertThat(inputStream.read()).isEqualTo(1);
@@ -247,7 +243,7 @@ public class RandomAccessDataFileTests {
}
@Test
public void inputStreamReadBytesPastSubsection() throws Exception {
void inputStreamReadBytesPastSubsection() throws Exception {
RandomAccessData subsection = this.file.getSubsection(1, 2);
InputStream inputStream = subsection.getInputStream();
byte[] b = new byte[3];
@@ -257,7 +253,7 @@ public class RandomAccessDataFileTests {
}
@Test
public void inputStreamSkipPastSubsection() throws Exception {
void inputStreamSkipPastSubsection() throws Exception {
RandomAccessData subsection = this.file.getSubsection(1, 2);
InputStream inputStream = subsection.getInputStream();
assertThat(inputStream.skip(3)).isEqualTo(2L);
@@ -265,17 +261,17 @@ public class RandomAccessDataFileTests {
}
@Test
public void inputStreamSkipNegative() throws Exception {
void inputStreamSkipNegative() throws Exception {
assertThat(this.inputStream.skip(-1)).isEqualTo(0L);
}
@Test
public void getFile() {
void getFile() {
assertThat(this.file.getFile()).isEqualTo(this.tempFile);
}
@Test
public void concurrentReads() throws Exception {
void concurrentReads() throws Exception {
ExecutorService executorService = Executors.newFixedThreadPool(20);
List<Future<Boolean>> results = new ArrayList<>();
for (int i = 0; i < 100; i++) {

View File

@@ -16,7 +16,7 @@
package org.springframework.boot.loader.jar;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
@@ -27,30 +27,30 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
* @author Phillip Webb
* @author Andy Wilkinson
*/
public class AsciiBytesTests {
class AsciiBytesTests {
private static final char NO_SUFFIX = 0;
@Test
public void createFromBytes() {
void createFromBytes() {
AsciiBytes bytes = new AsciiBytes(new byte[] { 65, 66 });
assertThat(bytes.toString()).isEqualTo("AB");
}
@Test
public void createFromBytesWithOffset() {
void createFromBytesWithOffset() {
AsciiBytes bytes = new AsciiBytes(new byte[] { 65, 66, 67, 68 }, 1, 2);
assertThat(bytes.toString()).isEqualTo("BC");
}
@Test
public void createFromString() {
void createFromString() {
AsciiBytes bytes = new AsciiBytes("AB");
assertThat(bytes.toString()).isEqualTo("AB");
}
@Test
public void length() {
void length() {
AsciiBytes b1 = new AsciiBytes(new byte[] { 65, 66 });
AsciiBytes b2 = new AsciiBytes(new byte[] { 65, 66, 67, 68 }, 1, 2);
assertThat(b1.length()).isEqualTo(2);
@@ -58,7 +58,7 @@ public class AsciiBytesTests {
}
@Test
public void startWith() {
void startWith() {
AsciiBytes abc = new AsciiBytes(new byte[] { 65, 66, 67 });
AsciiBytes ab = new AsciiBytes(new byte[] { 65, 66 });
AsciiBytes bc = new AsciiBytes(new byte[] { 65, 66, 67 }, 1, 2);
@@ -70,7 +70,7 @@ public class AsciiBytesTests {
}
@Test
public void endsWith() {
void endsWith() {
AsciiBytes abc = new AsciiBytes(new byte[] { 65, 66, 67 });
AsciiBytes bc = new AsciiBytes(new byte[] { 65, 66, 67 }, 1, 2);
AsciiBytes ab = new AsciiBytes(new byte[] { 65, 66 });
@@ -82,7 +82,7 @@ public class AsciiBytesTests {
}
@Test
public void substringFromBeingIndex() {
void substringFromBeingIndex() {
AsciiBytes abcd = new AsciiBytes(new byte[] { 65, 66, 67, 68 });
assertThat(abcd.substring(0).toString()).isEqualTo("ABCD");
assertThat(abcd.substring(1).toString()).isEqualTo("BCD");
@@ -93,7 +93,7 @@ public class AsciiBytesTests {
}
@Test
public void substring() {
void substring() {
AsciiBytes abcd = new AsciiBytes(new byte[] { 65, 66, 67, 68 });
assertThat(abcd.substring(0, 4).toString()).isEqualTo("ABCD");
assertThat(abcd.substring(1, 3).toString()).isEqualTo("BC");
@@ -103,7 +103,7 @@ public class AsciiBytesTests {
}
@Test
public void hashCodeAndEquals() {
void hashCodeAndEquals() {
AsciiBytes abcd = new AsciiBytes(new byte[] { 65, 66, 67, 68 });
AsciiBytes bc = new AsciiBytes(new byte[] { 66, 67 });
AsciiBytes bc_substring = new AsciiBytes(new byte[] { 65, 66, 67, 68 }).substring(1, 3);
@@ -119,22 +119,22 @@ public class AsciiBytesTests {
}
@Test
public void hashCodeSameAsString() {
void hashCodeSameAsString() {
hashCodeSameAsString("abcABC123xyz!");
}
@Test
public void hashCodeSameAsStringWithSpecial() {
void hashCodeSameAsStringWithSpecial() {
hashCodeSameAsString("special/\u00EB.dat");
}
@Test
public void hashCodeSameAsStringWithCyrillicCharacters() {
void hashCodeSameAsStringWithCyrillicCharacters() {
hashCodeSameAsString("\u0432\u0435\u0441\u043D\u0430");
}
@Test
public void hashCodeSameAsStringWithEmoji() {
void hashCodeSameAsStringWithEmoji() {
hashCodeSameAsString("\ud83d\udca9");
}
@@ -143,22 +143,22 @@ public class AsciiBytesTests {
}
@Test
public void matchesSameAsString() {
void matchesSameAsString() {
matchesSameAsString("abcABC123xyz!");
}
@Test
public void matchesSameAsStringWithSpecial() {
void matchesSameAsStringWithSpecial() {
matchesSameAsString("special/\u00EB.dat");
}
@Test
public void matchesSameAsStringWithCyrillicCharacters() {
void matchesSameAsStringWithCyrillicCharacters() {
matchesSameAsString("\u0432\u0435\u0441\u043D\u0430");
}
@Test
public void matchesDifferentLengths() {
void matchesDifferentLengths() {
assertThat(new AsciiBytes("abc").matches("ab", NO_SUFFIX)).isFalse();
assertThat(new AsciiBytes("abc").matches("abcd", NO_SUFFIX)).isFalse();
assertThat(new AsciiBytes("abc").matches("abc", NO_SUFFIX)).isTrue();
@@ -168,23 +168,23 @@ public class AsciiBytesTests {
}
@Test
public void matchesSuffix() {
void matchesSuffix() {
assertThat(new AsciiBytes("ab").matches("a", 'b')).isTrue();
}
@Test
public void matchesSameAsStringWithEmoji() {
void matchesSameAsStringWithEmoji() {
matchesSameAsString("\ud83d\udca9");
}
@Test
public void hashCodeFromInstanceMatchesHashCodeFromString() {
void hashCodeFromInstanceMatchesHashCodeFromString() {
String name = "fonts/宋体/simsun.ttf";
assertThat(new AsciiBytes(name).hashCode()).isEqualTo(AsciiBytes.hashCode(name));
}
@Test
public void instanceCreatedFromCharSequenceMatchesSameCharSequence() {
void instanceCreatedFromCharSequenceMatchesSameCharSequence() {
String name = "fonts/宋体/simsun.ttf";
assertThat(new AsciiBytes(name).matches(name, NO_SUFFIX)).isTrue();
}

View File

@@ -21,10 +21,9 @@ import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.springframework.boot.loader.TestJarCreator;
import org.springframework.boot.loader.data.RandomAccessData;
@@ -37,24 +36,21 @@ import static org.assertj.core.api.Assertions.assertThat;
*
* @author Phillip Webb
*/
public class CentralDirectoryParserTests {
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
class CentralDirectoryParserTests {
private File jarFile;
private RandomAccessData jarData;
@Before
public void setup() throws Exception {
this.jarFile = this.temporaryFolder.newFile();
@BeforeEach
public void setup(@TempDir File tempDir) throws Exception {
this.jarFile = new File(tempDir, "test.jar");
TestJarCreator.createTestJar(this.jarFile);
this.jarData = new RandomAccessDataFile(this.jarFile);
}
@Test
public void visitsInOrder() throws Exception {
void visitsInOrder() throws Exception {
MockCentralDirectoryVisitor visitor = new MockCentralDirectoryVisitor();
CentralDirectoryParser parser = new CentralDirectoryParser();
parser.addVisitor(visitor);
@@ -64,7 +60,7 @@ public class CentralDirectoryParserTests {
}
@Test
public void visitRecords() throws Exception {
void visitRecords() throws Exception {
Collector collector = new Collector();
CentralDirectoryParser parser = new CentralDirectoryParser();
parser.addVisitor(collector);

View File

@@ -21,9 +21,8 @@ import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.springframework.boot.loader.TestJarCreator;
@@ -34,15 +33,12 @@ import static org.assertj.core.api.Assertions.assertThat;
*
* @author Andy Wilkinson
*/
public class HandlerTests {
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
class HandlerTests {
private final Handler handler = new Handler();
@Test
public void parseUrlWithJarRootContextAndAbsoluteSpecThatUsesContext() throws MalformedURLException {
void parseUrlWithJarRootContextAndAbsoluteSpecThatUsesContext() throws MalformedURLException {
String spec = "/entry.txt";
URL context = createUrl("file:example.jar!/");
this.handler.parseURL(context, spec, 0, spec.length());
@@ -50,7 +46,7 @@ public class HandlerTests {
}
@Test
public void parseUrlWithDirectoryEntryContextAndAbsoluteSpecThatUsesContext() throws MalformedURLException {
void parseUrlWithDirectoryEntryContextAndAbsoluteSpecThatUsesContext() throws MalformedURLException {
String spec = "/entry.txt";
URL context = createUrl("file:example.jar!/dir/");
this.handler.parseURL(context, spec, 0, spec.length());
@@ -58,7 +54,7 @@ public class HandlerTests {
}
@Test
public void parseUrlWithJarRootContextAndRelativeSpecThatUsesContext() throws MalformedURLException {
void parseUrlWithJarRootContextAndRelativeSpecThatUsesContext() throws MalformedURLException {
String spec = "entry.txt";
URL context = createUrl("file:example.jar!/");
this.handler.parseURL(context, spec, 0, spec.length());
@@ -66,7 +62,7 @@ public class HandlerTests {
}
@Test
public void parseUrlWithDirectoryEntryContextAndRelativeSpecThatUsesContext() throws MalformedURLException {
void parseUrlWithDirectoryEntryContextAndRelativeSpecThatUsesContext() throws MalformedURLException {
String spec = "entry.txt";
URL context = createUrl("file:example.jar!/dir/");
this.handler.parseURL(context, spec, 0, spec.length());
@@ -74,7 +70,7 @@ public class HandlerTests {
}
@Test
public void parseUrlWithFileEntryContextAndRelativeSpecThatUsesContext() throws MalformedURLException {
void parseUrlWithFileEntryContextAndRelativeSpecThatUsesContext() throws MalformedURLException {
String spec = "entry.txt";
URL context = createUrl("file:example.jar!/dir/file");
this.handler.parseURL(context, spec, 0, spec.length());
@@ -82,7 +78,7 @@ public class HandlerTests {
}
@Test
public void parseUrlWithSpecThatIgnoresContext() throws MalformedURLException {
void parseUrlWithSpecThatIgnoresContext() throws MalformedURLException {
JarFile.registerUrlProtocolHandler();
String spec = "jar:file:/other.jar!/nested!/entry.txt";
URL context = createUrl("file:example.jar!/dir/file");
@@ -91,73 +87,72 @@ public class HandlerTests {
}
@Test
public void sameFileReturnsFalseForUrlsWithDifferentProtocols() throws MalformedURLException {
void sameFileReturnsFalseForUrlsWithDifferentProtocols() throws MalformedURLException {
assertThat(this.handler.sameFile(new URL("jar:file:foo.jar!/content.txt"), new URL("file:/foo.jar"))).isFalse();
}
@Test
public void sameFileReturnsFalseForDifferentFileInSameJar() throws MalformedURLException {
void sameFileReturnsFalseForDifferentFileInSameJar() throws MalformedURLException {
assertThat(this.handler.sameFile(new URL("jar:file:foo.jar!/the/path/to/the/first/content.txt"),
new URL("jar:file:/foo.jar!/content.txt"))).isFalse();
}
@Test
public void sameFileReturnsFalseForSameFileInDifferentJars() throws MalformedURLException {
void sameFileReturnsFalseForSameFileInDifferentJars() throws MalformedURLException {
assertThat(this.handler.sameFile(new URL("jar:file:/the/path/to/the/first.jar!/content.txt"),
new URL("jar:file:/second.jar!/content.txt"))).isFalse();
}
@Test
public void sameFileReturnsTrueForSameFileInSameJar() throws MalformedURLException {
void sameFileReturnsTrueForSameFileInSameJar() throws MalformedURLException {
assertThat(this.handler.sameFile(new URL("jar:file:/the/path/to/the/first.jar!/content.txt"),
new URL("jar:file:/the/path/to/the/first.jar!/content.txt"))).isTrue();
}
@Test
public void sameFileReturnsTrueForUrlsThatReferenceSameFileViaNestedArchiveAndFromRootOfJar()
void sameFileReturnsTrueForUrlsThatReferenceSameFileViaNestedArchiveAndFromRootOfJar()
throws MalformedURLException {
assertThat(this.handler.sameFile(new URL("jar:file:/test.jar!/BOOT-INF/classes!/foo.txt"),
new URL("jar:file:/test.jar!/BOOT-INF/classes/foo.txt"))).isTrue();
}
@Test
public void hashCodesAreEqualForUrlsThatReferenceSameFileViaNestedArchiveAndFromRootOfJar()
throws MalformedURLException {
void hashCodesAreEqualForUrlsThatReferenceSameFileViaNestedArchiveAndFromRootOfJar() throws MalformedURLException {
assertThat(this.handler.hashCode(new URL("jar:file:/test.jar!/BOOT-INF/classes!/foo.txt")))
.isEqualTo(this.handler.hashCode(new URL("jar:file:/test.jar!/BOOT-INF/classes/foo.txt")));
}
@Test
public void urlWithSpecReferencingParentDirectory() throws MalformedURLException {
void urlWithSpecReferencingParentDirectory() throws MalformedURLException {
assertStandardAndCustomHandlerUrlsAreEqual("file:/test.jar!/BOOT-INF/classes!/xsd/folderA/a.xsd",
"../folderB/b.xsd");
}
@Test
public void urlWithSpecReferencingAncestorDirectoryOutsideJarStopsAtJarRoot() throws MalformedURLException {
void urlWithSpecReferencingAncestorDirectoryOutsideJarStopsAtJarRoot() throws MalformedURLException {
assertStandardAndCustomHandlerUrlsAreEqual("file:/test.jar!/BOOT-INF/classes!/xsd/folderA/a.xsd",
"../../../../../../folderB/b.xsd");
}
@Test
public void urlWithSpecReferencingCurrentDirectory() throws MalformedURLException {
void urlWithSpecReferencingCurrentDirectory() throws MalformedURLException {
assertStandardAndCustomHandlerUrlsAreEqual("file:/test.jar!/BOOT-INF/classes!/xsd/folderA/a.xsd",
"./folderB/./b.xsd");
}
@Test
public void urlWithRef() throws MalformedURLException {
void urlWithRef() throws MalformedURLException {
assertStandardAndCustomHandlerUrlsAreEqual("file:/test.jar!/BOOT-INF/classes", "!/foo.txt#alpha");
}
@Test
public void urlWithQuery() throws MalformedURLException {
void urlWithQuery() throws MalformedURLException {
assertStandardAndCustomHandlerUrlsAreEqual("file:/test.jar!/BOOT-INF/classes", "!/foo.txt?alpha");
}
@Test
public void fallbackToJdksJarUrlStreamHandler() throws Exception {
File testJar = this.temporaryFolder.newFile("test.jar");
void fallbackToJdksJarUrlStreamHandler(@TempDir File tempDir) throws Exception {
File testJar = new File(tempDir, "test.jar");
TestJarCreator.createTestJar(testJar);
URLConnection connection = new URL(null, "jar:file:" + testJar.getAbsolutePath() + "!/nested.jar!/",
this.handler).openConnection();

View File

@@ -32,10 +32,9 @@ import java.util.jar.Manifest;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.springframework.boot.loader.TestJarCreator;
import org.springframework.boot.loader.data.RandomAccessDataFile;
@@ -55,28 +54,28 @@ import static org.mockito.Mockito.verify;
* @author Martin Lau
* @author Andy Wilkinson
*/
public class JarFileTests {
class JarFileTests {
private static final String PROTOCOL_HANDLER = "java.protocol.handler.pkgs";
private static final String HANDLERS_PACKAGE = "org.springframework.boot.loader";
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
@TempDir
File tempDir;
private File rootJarFile;
private JarFile jarFile;
@Before
@BeforeEach
public void setup() throws Exception {
this.rootJarFile = this.temporaryFolder.newFile();
this.rootJarFile = new File(this.tempDir, "root.jar");
TestJarCreator.createTestJar(this.rootJarFile);
this.jarFile = new JarFile(this.rootJarFile);
}
@Test
public void jdkJarFile() throws Exception {
void jdkJarFile() throws Exception {
// Sanity checks to see how the default jar file operates
java.util.jar.JarFile jarFile = new java.util.jar.JarFile(this.rootJarFile);
Enumeration<java.util.jar.JarEntry> entries = jarFile.entries();
@@ -102,26 +101,26 @@ public class JarFileTests {
}
@Test
public void createFromFile() throws Exception {
void createFromFile() throws Exception {
JarFile jarFile = new JarFile(this.rootJarFile);
assertThat(jarFile.getName()).isNotNull();
jarFile.close();
}
@Test
public void getManifest() throws Exception {
void getManifest() throws Exception {
assertThat(this.jarFile.getManifest().getMainAttributes().getValue("Built-By")).isEqualTo("j1");
}
@Test
public void getManifestEntry() throws Exception {
void getManifestEntry() throws Exception {
ZipEntry entry = this.jarFile.getJarEntry("META-INF/MANIFEST.MF");
Manifest manifest = new Manifest(this.jarFile.getInputStream(entry));
assertThat(manifest.getMainAttributes().getValue("Built-By")).isEqualTo("j1");
}
@Test
public void getEntries() {
void getEntries() {
Enumeration<java.util.jar.JarEntry> entries = this.jarFile.entries();
assertThat(entries.nextElement().getName()).isEqualTo("META-INF/");
assertThat(entries.nextElement().getName()).isEqualTo("META-INF/MANIFEST.MF");
@@ -139,21 +138,21 @@ public class JarFileTests {
}
@Test
public void getSpecialResourceViaClassLoader() throws Exception {
void getSpecialResourceViaClassLoader() throws Exception {
URLClassLoader urlClassLoader = new URLClassLoader(new URL[] { this.jarFile.getUrl() });
assertThat(urlClassLoader.getResource("special/\u00EB.dat")).isNotNull();
urlClassLoader.close();
}
@Test
public void getJarEntry() {
void getJarEntry() {
java.util.jar.JarEntry entry = this.jarFile.getJarEntry("1.dat");
assertThat(entry).isNotNull();
assertThat(entry.getName()).isEqualTo("1.dat");
}
@Test
public void getInputStream() throws Exception {
void getInputStream() throws Exception {
InputStream inputStream = this.jarFile.getInputStream(this.jarFile.getEntry("1.dat"));
assertThat(inputStream.available()).isEqualTo(1);
assertThat(inputStream.read()).isEqualTo(1);
@@ -162,19 +161,19 @@ public class JarFileTests {
}
@Test
public void getName() {
void getName() {
assertThat(this.jarFile.getName()).isEqualTo(this.rootJarFile.getPath());
}
@Test
public void getSize() throws Exception {
void getSize() throws Exception {
try (ZipFile zip = new ZipFile(this.rootJarFile)) {
assertThat(this.jarFile.size()).isEqualTo(zip.size());
}
}
@Test
public void getEntryTime() throws Exception {
void getEntryTime() throws Exception {
java.util.jar.JarFile jdkJarFile = new java.util.jar.JarFile(this.rootJarFile);
assertThat(this.jarFile.getEntry("META-INF/MANIFEST.MF").getTime())
.isEqualTo(jdkJarFile.getEntry("META-INF/MANIFEST.MF").getTime());
@@ -182,7 +181,7 @@ public class JarFileTests {
}
@Test
public void close() throws Exception {
void close() throws Exception {
RandomAccessDataFile randomAccessDataFile = spy(new RandomAccessDataFile(this.rootJarFile));
JarFile jarFile = new JarFile(randomAccessDataFile);
jarFile.close();
@@ -190,7 +189,7 @@ public class JarFileTests {
}
@Test
public void getUrl() throws Exception {
void getUrl() throws Exception {
URL url = this.jarFile.getUrl();
assertThat(url.toString()).isEqualTo("jar:" + this.rootJarFile.toURI() + "!/");
JarURLConnection jarURLConnection = (JarURLConnection) url.openConnection();
@@ -203,7 +202,7 @@ public class JarFileTests {
}
@Test
public void createEntryUrl() throws Exception {
void createEntryUrl() throws Exception {
URL url = new URL(this.jarFile.getUrl(), "1.dat");
assertThat(url.toString()).isEqualTo("jar:" + this.rootJarFile.toURI() + "!/1.dat");
JarURLConnection jarURLConnection = (JarURLConnection) url.openConnection();
@@ -219,7 +218,7 @@ public class JarFileTests {
}
@Test
public void getMissingEntryUrl() throws Exception {
void getMissingEntryUrl() throws Exception {
URL url = new URL(this.jarFile.getUrl(), "missing.dat");
assertThat(url.toString()).isEqualTo("jar:" + this.rootJarFile.toURI() + "!/missing.dat");
assertThatExceptionOfType(FileNotFoundException.class)
@@ -227,14 +226,14 @@ public class JarFileTests {
}
@Test
public void getUrlStream() throws Exception {
void getUrlStream() throws Exception {
URL url = this.jarFile.getUrl();
url.openConnection();
assertThatIOException().isThrownBy(url::openStream);
}
@Test
public void getEntryUrlStream() throws Exception {
void getEntryUrlStream() throws Exception {
URL url = new URL(this.jarFile.getUrl(), "1.dat");
url.openConnection();
InputStream stream = url.openStream();
@@ -243,7 +242,7 @@ public class JarFileTests {
}
@Test
public void getNestedJarFile() throws Exception {
void getNestedJarFile() throws Exception {
JarFile nestedJarFile = this.jarFile.getNestedJarFile(this.jarFile.getEntry("nested.jar"));
Enumeration<java.util.jar.JarEntry> entries = nestedJarFile.entries();
@@ -276,7 +275,7 @@ public class JarFileTests {
}
@Test
public void getNestedJarDirectory() throws Exception {
void getNestedJarDirectory() throws Exception {
JarFile nestedJarFile = this.jarFile.getNestedJarFile(this.jarFile.getEntry("d/"));
Enumeration<java.util.jar.JarEntry> entries = nestedJarFile.entries();
@@ -293,7 +292,7 @@ public class JarFileTests {
}
@Test
public void getNestedJarEntryUrl() throws Exception {
void getNestedJarEntryUrl() throws Exception {
JarFile nestedJarFile = this.jarFile.getNestedJarFile(this.jarFile.getEntry("nested.jar"));
URL url = nestedJarFile.getJarEntry("3.dat").getUrl();
assertThat(url.toString()).isEqualTo("jar:" + this.rootJarFile.toURI() + "!/nested.jar!/3.dat");
@@ -303,7 +302,7 @@ public class JarFileTests {
}
@Test
public void createUrlFromString() throws Exception {
void createUrlFromString() throws Exception {
JarFile.registerUrlProtocolHandler();
String spec = "jar:" + this.rootJarFile.toURI() + "!/nested.jar!/3.dat";
URL url = new URL(spec);
@@ -318,12 +317,12 @@ public class JarFileTests {
}
@Test
public void createNonNestedUrlFromString() throws Exception {
void createNonNestedUrlFromString() throws Exception {
nonNestedJarFileFromString("jar:" + this.rootJarFile.toURI() + "!/2.dat");
}
@Test
public void createNonNestedUrlFromPathString() throws Exception {
void createNonNestedUrlFromPathString() throws Exception {
nonNestedJarFileFromString("jar:" + this.rootJarFile.toPath().toUri() + "!/2.dat");
}
@@ -341,28 +340,28 @@ public class JarFileTests {
}
@Test
public void getDirectoryInputStream() throws Exception {
void getDirectoryInputStream() throws Exception {
InputStream inputStream = this.jarFile.getInputStream(this.jarFile.getEntry("d/"));
assertThat(inputStream).isNotNull();
assertThat(inputStream.read()).isEqualTo(-1);
}
@Test
public void getDirectoryInputStreamWithoutSlash() throws Exception {
void getDirectoryInputStreamWithoutSlash() throws Exception {
InputStream inputStream = this.jarFile.getInputStream(this.jarFile.getEntry("d"));
assertThat(inputStream).isNotNull();
assertThat(inputStream.read()).isEqualTo(-1);
}
@Test
public void sensibleToString() throws Exception {
void sensibleToString() throws Exception {
assertThat(this.jarFile.toString()).isEqualTo(this.rootJarFile.getPath());
assertThat(this.jarFile.getNestedJarFile(this.jarFile.getEntry("nested.jar")).toString())
.isEqualTo(this.rootJarFile.getPath() + "!/nested.jar");
}
@Test
public void verifySignedJar() throws Exception {
void verifySignedJar() throws Exception {
String classpath = System.getProperty("java.class.path");
String[] entries = classpath.split(System.getProperty("path.separator"));
String signedJarFile = null;
@@ -389,8 +388,8 @@ public class JarFileTests {
}
@Test
public void jarFileWithScriptAtTheStart() throws Exception {
File file = this.temporaryFolder.newFile();
void jarFileWithScriptAtTheStart() throws Exception {
File file = new File(this.tempDir, "test.jar");
InputStream sourceJarContent = new FileInputStream(this.rootJarFile);
FileOutputStream outputStream = new FileOutputStream(file);
StreamUtils.copy("#/bin/bash", Charset.defaultCharset(), outputStream);
@@ -403,7 +402,7 @@ public class JarFileTests {
}
@Test
public void cannotLoadMissingJar() throws Exception {
void cannotLoadMissingJar() throws Exception {
// relates to gh-1070
JarFile nestedJarFile = this.jarFile.getNestedJarFile(this.jarFile.getEntry("nested.jar"));
URL nestedUrl = nestedJarFile.getUrl();
@@ -412,7 +411,7 @@ public class JarFileTests {
}
@Test
public void registerUrlProtocolHandlerWithNoExistingRegistration() {
void registerUrlProtocolHandlerWithNoExistingRegistration() {
String original = System.getProperty(PROTOCOL_HANDLER);
try {
System.clearProperty(PROTOCOL_HANDLER);
@@ -431,7 +430,7 @@ public class JarFileTests {
}
@Test
public void registerUrlProtocolHandlerAddsToExistingRegistration() {
void registerUrlProtocolHandlerAddsToExistingRegistration() {
String original = System.getProperty(PROTOCOL_HANDLER);
try {
System.setProperty(PROTOCOL_HANDLER, "com.example");
@@ -450,16 +449,16 @@ public class JarFileTests {
}
@Test
public void jarFileCanBeDeletedOnceItHasBeenClosed() throws Exception {
File temp = this.temporaryFolder.newFile();
TestJarCreator.createTestJar(temp);
JarFile jf = new JarFile(temp);
void jarFileCanBeDeletedOnceItHasBeenClosed() throws Exception {
File jar = new File(this.tempDir, "test.jar");
TestJarCreator.createTestJar(jar);
JarFile jf = new JarFile(jar);
jf.close();
assertThat(temp.delete()).isTrue();
assertThat(jar.delete()).isTrue();
}
@Test
public void createUrlFromStringWithContextWhenNotFound() throws Exception {
void createUrlFromStringWithContextWhenNotFound() throws Exception {
// gh-12483
JarURLConnection.setUseFastExceptions(true);
try {
@@ -477,7 +476,7 @@ public class JarFileTests {
}
@Test
public void multiReleaseEntry() throws Exception {
void multiReleaseEntry() throws Exception {
JarFile multiRelease = this.jarFile.getNestedJarFile(this.jarFile.getEntry("multi-release.jar"));
ZipEntry entry = multiRelease.getEntry("multi-release.dat");
assertThat(entry.getName()).isEqualTo("multi-release.dat");

View File

@@ -21,10 +21,9 @@ import java.io.File;
import java.io.FileNotFoundException;
import java.net.URL;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.springframework.boot.loader.TestJarCreator;
import org.springframework.boot.loader.jar.JarURLConnection.JarEntryName;
@@ -39,71 +38,68 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
* @author Phillip Webb
* @author Rostyslav Dudka
*/
public class JarURLConnectionTests {
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder(new File("target"));
class JarURLConnectionTests {
private File rootJarFile;
private JarFile jarFile;
@Before
public void setup() throws Exception {
this.rootJarFile = this.temporaryFolder.newFile();
@BeforeEach
public void setup(@TempDir File tempDir) throws Exception {
this.rootJarFile = new File(tempDir, "root.jar");
TestJarCreator.createTestJar(this.rootJarFile);
this.jarFile = new JarFile(this.rootJarFile);
}
@Test
public void connectionToRootUsingAbsoluteUrl() throws Exception {
void connectionToRootUsingAbsoluteUrl() throws Exception {
URL url = new URL("jar:file:" + getAbsolutePath() + "!/");
assertThat(JarURLConnection.get(url, this.jarFile).getContent()).isSameAs(this.jarFile);
}
@Test
public void connectionToRootUsingRelativeUrl() throws Exception {
void connectionToRootUsingRelativeUrl() throws Exception {
URL url = new URL("jar:file:" + getRelativePath() + "!/");
assertThat(JarURLConnection.get(url, this.jarFile).getContent()).isSameAs(this.jarFile);
}
@Test
public void connectionToEntryUsingAbsoluteUrl() throws Exception {
void connectionToEntryUsingAbsoluteUrl() throws Exception {
URL url = new URL("jar:file:" + getAbsolutePath() + "!/1.dat");
assertThat(JarURLConnection.get(url, this.jarFile).getInputStream())
.hasSameContentAs(new ByteArrayInputStream(new byte[] { 1 }));
}
@Test
public void connectionToEntryUsingRelativeUrl() throws Exception {
void connectionToEntryUsingRelativeUrl() throws Exception {
URL url = new URL("jar:file:" + getRelativePath() + "!/1.dat");
assertThat(JarURLConnection.get(url, this.jarFile).getInputStream())
.hasSameContentAs(new ByteArrayInputStream(new byte[] { 1 }));
}
@Test
public void connectionToEntryUsingAbsoluteUrlWithFileColonSlashSlashPrefix() throws Exception {
void connectionToEntryUsingAbsoluteUrlWithFileColonSlashSlashPrefix() throws Exception {
URL url = new URL("jar:file:/" + getAbsolutePath() + "!/1.dat");
assertThat(JarURLConnection.get(url, this.jarFile).getInputStream())
.hasSameContentAs(new ByteArrayInputStream(new byte[] { 1 }));
}
@Test
public void connectionToEntryUsingAbsoluteUrlForNestedEntry() throws Exception {
void connectionToEntryUsingAbsoluteUrlForNestedEntry() throws Exception {
URL url = new URL("jar:file:" + getAbsolutePath() + "!/nested.jar!/3.dat");
assertThat(JarURLConnection.get(url, this.jarFile).getInputStream())
.hasSameContentAs(new ByteArrayInputStream(new byte[] { 3 }));
}
@Test
public void connectionToEntryUsingRelativeUrlForNestedEntry() throws Exception {
void connectionToEntryUsingRelativeUrlForNestedEntry() throws Exception {
URL url = new URL("jar:file:" + getRelativePath() + "!/nested.jar!/3.dat");
assertThat(JarURLConnection.get(url, this.jarFile).getInputStream())
.hasSameContentAs(new ByteArrayInputStream(new byte[] { 3 }));
}
@Test
public void connectionToEntryUsingAbsoluteUrlForEntryFromNestedJarFile() throws Exception {
void connectionToEntryUsingAbsoluteUrlForEntryFromNestedJarFile() throws Exception {
URL url = new URL("jar:file:" + getAbsolutePath() + "!/nested.jar!/3.dat");
JarFile nested = this.jarFile.getNestedJarFile(this.jarFile.getEntry("nested.jar"));
assertThat(JarURLConnection.get(url, nested).getInputStream())
@@ -111,7 +107,7 @@ public class JarURLConnectionTests {
}
@Test
public void connectionToEntryUsingRelativeUrlForEntryFromNestedJarFile() throws Exception {
void connectionToEntryUsingRelativeUrlForEntryFromNestedJarFile() throws Exception {
URL url = new URL("jar:file:" + getRelativePath() + "!/nested.jar!/3.dat");
JarFile nested = this.jarFile.getNestedJarFile(this.jarFile.getEntry("nested.jar"));
assertThat(JarURLConnection.get(url, nested).getInputStream())
@@ -119,7 +115,7 @@ public class JarURLConnectionTests {
}
@Test
public void connectionToEntryInNestedJarFromUrlThatUsesExistingUrlAsContext() throws Exception {
void connectionToEntryInNestedJarFromUrlThatUsesExistingUrlAsContext() throws Exception {
URL url = new URL(new URL("jar", null, -1, "file:" + getAbsolutePath() + "!/nested.jar!/", new Handler()),
"/3.dat");
JarFile nested = this.jarFile.getNestedJarFile(this.jarFile.getEntry("nested.jar"));
@@ -128,21 +124,21 @@ public class JarURLConnectionTests {
}
@Test
public void connectionToEntryWithSpaceNestedEntry() throws Exception {
void connectionToEntryWithSpaceNestedEntry() throws Exception {
URL url = new URL("jar:file:" + getRelativePath() + "!/space nested.jar!/3.dat");
assertThat(JarURLConnection.get(url, this.jarFile).getInputStream())
.hasSameContentAs(new ByteArrayInputStream(new byte[] { 3 }));
}
@Test
public void connectionToEntryWithEncodedSpaceNestedEntry() throws Exception {
void connectionToEntryWithEncodedSpaceNestedEntry() throws Exception {
URL url = new URL("jar:file:" + getRelativePath() + "!/space%20nested.jar!/3.dat");
assertThat(JarURLConnection.get(url, this.jarFile).getInputStream())
.hasSameContentAs(new ByteArrayInputStream(new byte[] { 3 }));
}
@Test
public void connectionToEntryUsingWrongAbsoluteUrlForEntryFromNestedJarFile() throws Exception {
void connectionToEntryUsingWrongAbsoluteUrlForEntryFromNestedJarFile() throws Exception {
URL url = new URL("jar:file:" + getAbsolutePath() + "!/w.jar!/3.dat");
JarFile nested = this.jarFile.getNestedJarFile(this.jarFile.getEntry("nested.jar"));
assertThatExceptionOfType(FileNotFoundException.class)
@@ -150,43 +146,43 @@ public class JarURLConnectionTests {
}
@Test
public void getContentLengthReturnsLengthOfUnderlyingEntry() throws Exception {
void getContentLengthReturnsLengthOfUnderlyingEntry() throws Exception {
URL url = new URL(new URL("jar", null, -1, "file:" + getAbsolutePath() + "!/nested.jar!/", new Handler()),
"/3.dat");
assertThat(url.openConnection().getContentLength()).isEqualTo(1);
}
@Test
public void getContentLengthLongReturnsLengthOfUnderlyingEntry() throws Exception {
void getContentLengthLongReturnsLengthOfUnderlyingEntry() throws Exception {
URL url = new URL(new URL("jar", null, -1, "file:" + getAbsolutePath() + "!/nested.jar!/", new Handler()),
"/3.dat");
assertThat(url.openConnection().getContentLengthLong()).isEqualTo(1);
}
@Test
public void getLastModifiedReturnsLastModifiedTimeOfJarEntry() throws Exception {
void getLastModifiedReturnsLastModifiedTimeOfJarEntry() throws Exception {
URL url = new URL("jar:file:" + getAbsolutePath() + "!/1.dat");
JarURLConnection connection = JarURLConnection.get(url, this.jarFile);
assertThat(connection.getLastModified()).isEqualTo(connection.getJarEntry().getTime());
}
@Test
public void jarEntryBasicName() {
void jarEntryBasicName() {
assertThat(new JarEntryName(new StringSequence("a/b/C.class")).toString()).isEqualTo("a/b/C.class");
}
@Test
public void jarEntryNameWithSingleByteEncodedCharacters() {
void jarEntryNameWithSingleByteEncodedCharacters() {
assertThat(new JarEntryName(new StringSequence("%61/%62/%43.class")).toString()).isEqualTo("a/b/C.class");
}
@Test
public void jarEntryNameWithDoubleByteEncodedCharacters() {
void jarEntryNameWithDoubleByteEncodedCharacters() {
assertThat(new JarEntryName(new StringSequence("%c3%a1/b/C.class")).toString()).isEqualTo("\u00e1/b/C.class");
}
@Test
public void jarEntryNameWithMixtureOfEncodedAndUnencodedDoubleByteCharacters() {
void jarEntryNameWithMixtureOfEncodedAndUnencodedDoubleByteCharacters() {
assertThat(new JarEntryName(new StringSequence("%c3%a1/b/\u00c7.class")).toString())
.isEqualTo("\u00e1/b/\u00c7.class");
}

View File

@@ -16,7 +16,7 @@
package org.springframework.boot.loader.jar;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
@@ -27,55 +27,55 @@ import static org.assertj.core.api.Assertions.assertThatNullPointerException;
*
* @author Phillip Webb
*/
public class StringSequenceTests {
class StringSequenceTests {
@Test
public void createWhenSourceIsNullShouldThrowException() {
void createWhenSourceIsNullShouldThrowException() {
assertThatNullPointerException().isThrownBy(() -> new StringSequence(null))
.withMessage("Source must not be null");
}
@Test
public void createWithIndexWhenSourceIsNullShouldThrowException() {
void createWithIndexWhenSourceIsNullShouldThrowException() {
assertThatNullPointerException().isThrownBy(() -> new StringSequence(null, 0, 0))
.withMessage("Source must not be null");
}
@Test
public void createWhenStartIsLessThanZeroShouldThrowException() {
void createWhenStartIsLessThanZeroShouldThrowException() {
assertThatExceptionOfType(StringIndexOutOfBoundsException.class)
.isThrownBy(() -> new StringSequence("x", -1, 0));
}
@Test
public void createWhenEndIsGreaterThanLengthShouldThrowException() {
void createWhenEndIsGreaterThanLengthShouldThrowException() {
assertThatExceptionOfType(StringIndexOutOfBoundsException.class)
.isThrownBy(() -> new StringSequence("x", 0, 2));
}
@Test
public void createFromString() {
void createFromString() {
assertThat(new StringSequence("test").toString()).isEqualTo("test");
}
@Test
public void subSequenceWithJustStartShouldReturnSubSequence() {
void subSequenceWithJustStartShouldReturnSubSequence() {
assertThat(new StringSequence("smiles").subSequence(1).toString()).isEqualTo("miles");
}
@Test
public void subSequenceShouldReturnSubSequence() {
void subSequenceShouldReturnSubSequence() {
assertThat(new StringSequence("hamburger").subSequence(4, 8).toString()).isEqualTo("urge");
assertThat(new StringSequence("smiles").subSequence(1, 5).toString()).isEqualTo("mile");
}
@Test
public void subSequenceWhenCalledMultipleTimesShouldReturnSubSequence() {
void subSequenceWhenCalledMultipleTimesShouldReturnSubSequence() {
assertThat(new StringSequence("hamburger").subSequence(4, 8).subSequence(1, 3).toString()).isEqualTo("rg");
}
@Test
public void subSequenceWhenEndPastExistingEndShouldThrowException() {
void subSequenceWhenEndPastExistingEndShouldThrowException() {
StringSequence sequence = new StringSequence("abcde").subSequence(1, 4);
assertThat(sequence.toString()).isEqualTo("bcd");
assertThat(sequence.subSequence(2, 3).toString()).isEqualTo("d");
@@ -83,7 +83,7 @@ public class StringSequenceTests {
}
@Test
public void subSequenceWhenStartPastExistingEndShouldThrowException() {
void subSequenceWhenStartPastExistingEndShouldThrowException() {
StringSequence sequence = new StringSequence("abcde").subSequence(1, 4);
assertThat(sequence.toString()).isEqualTo("bcd");
assertThat(sequence.subSequence(2, 3).toString()).isEqualTo("d");
@@ -91,24 +91,24 @@ public class StringSequenceTests {
}
@Test
public void isEmptyWhenEmptyShouldReturnTrue() {
void isEmptyWhenEmptyShouldReturnTrue() {
assertThat(new StringSequence("").isEmpty()).isTrue();
}
@Test
public void isEmptyWhenNotEmptyShouldReturnFalse() {
void isEmptyWhenNotEmptyShouldReturnFalse() {
assertThat(new StringSequence("x").isEmpty()).isFalse();
}
@Test
public void lengthShouldReturnLength() {
void lengthShouldReturnLength() {
StringSequence sequence = new StringSequence("hamburger");
assertThat(sequence.length()).isEqualTo(9);
assertThat(sequence.subSequence(4, 8).length()).isEqualTo(4);
}
@Test
public void charAtShouldReturnChar() {
void charAtShouldReturnChar() {
StringSequence sequence = new StringSequence("hamburger");
assertThat(sequence.charAt(0)).isEqualTo('h');
assertThat(sequence.charAt(1)).isEqualTo('a');
@@ -117,7 +117,7 @@ public class StringSequenceTests {
}
@Test
public void indexOfCharShouldReturnIndexOf() {
void indexOfCharShouldReturnIndexOf() {
StringSequence sequence = new StringSequence("aabbaacc");
assertThat(sequence.indexOf('a')).isEqualTo(0);
assertThat(sequence.indexOf('b')).isEqualTo(2);
@@ -125,7 +125,7 @@ public class StringSequenceTests {
}
@Test
public void indexOfStringShouldReturnIndexOf() {
void indexOfStringShouldReturnIndexOf() {
StringSequence sequence = new StringSequence("aabbaacc");
assertThat(sequence.indexOf("a")).isEqualTo(0);
assertThat(sequence.indexOf("b")).isEqualTo(2);
@@ -133,7 +133,7 @@ public class StringSequenceTests {
}
@Test
public void indexOfStringFromIndexShouldReturnIndexOf() {
void indexOfStringFromIndexShouldReturnIndexOf() {
StringSequence sequence = new StringSequence("aabbaacc");
assertThat(sequence.indexOf("a", 2)).isEqualTo(4);
assertThat(sequence.indexOf("b", 3)).isEqualTo(3);
@@ -141,13 +141,13 @@ public class StringSequenceTests {
}
@Test
public void hashCodeShouldBeSameAsString() {
void hashCodeShouldBeSameAsString() {
assertThat(new StringSequence("hamburger").hashCode()).isEqualTo("hamburger".hashCode());
assertThat(new StringSequence("hamburger").subSequence(4, 8).hashCode()).isEqualTo("urge".hashCode());
}
@Test
public void equalsWhenSameContentShouldMatch() {
void equalsWhenSameContentShouldMatch() {
StringSequence a = new StringSequence("hamburger").subSequence(4, 8);
StringSequence b = new StringSequence("urge");
StringSequence c = new StringSequence("urgh");
@@ -155,50 +155,50 @@ public class StringSequenceTests {
}
@Test
public void notEqualsWhenSequencesOfDifferentLength() {
void notEqualsWhenSequencesOfDifferentLength() {
StringSequence a = new StringSequence("abcd");
StringSequence b = new StringSequence("ef");
assertThat(a).isNotEqualTo(b);
}
@Test
public void startsWithWhenExactMatch() {
void startsWithWhenExactMatch() {
assertThat(new StringSequence("abc").startsWith("abc")).isTrue();
}
@Test
public void startsWithWhenLongerAndStartsWith() {
void startsWithWhenLongerAndStartsWith() {
assertThat(new StringSequence("abcd").startsWith("abc")).isTrue();
}
@Test
public void startsWithWhenLongerAndDoesNotStartWith() {
void startsWithWhenLongerAndDoesNotStartWith() {
assertThat(new StringSequence("abcd").startsWith("abx")).isFalse();
}
@Test
public void startsWithWhenShorterAndDoesNotStartWith() {
void startsWithWhenShorterAndDoesNotStartWith() {
assertThat(new StringSequence("ab").startsWith("abc")).isFalse();
assertThat(new StringSequence("ab").startsWith("c")).isFalse();
}
@Test
public void startsWithOffsetWhenExactMatch() {
void startsWithOffsetWhenExactMatch() {
assertThat(new StringSequence("xabc").startsWith("abc", 1)).isTrue();
}
@Test
public void startsWithOffsetWhenLongerAndStartsWith() {
void startsWithOffsetWhenLongerAndStartsWith() {
assertThat(new StringSequence("xabcd").startsWith("abc", 1)).isTrue();
}
@Test
public void startsWithOffsetWhenLongerAndDoesNotStartWith() {
void startsWithOffsetWhenLongerAndDoesNotStartWith() {
assertThat(new StringSequence("xabcd").startsWith("abx", 1)).isFalse();
}
@Test
public void startsWithOffsetWhenShorterAndDoesNotStartWith() {
void startsWithOffsetWhenShorterAndDoesNotStartWith() {
assertThat(new StringSequence("xab").startsWith("abc", 1)).isFalse();
assertThat(new StringSequence("xab").startsWith("c", 1)).isFalse();
}

View File

@@ -16,9 +16,9 @@
package org.springframework.boot.loader.util;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
@@ -27,35 +27,35 @@ import static org.assertj.core.api.Assertions.assertThat;
*
* @author Dave Syer
*/
public class SystemPropertyUtilsTests {
class SystemPropertyUtilsTests {
@BeforeClass
public static void init() {
@BeforeEach
public void init() {
System.setProperty("foo", "bar");
}
@AfterClass
public static void close() {
@AfterEach
public void close() {
System.clearProperty("foo");
}
@Test
public void testVanillaPlaceholder() {
void testVanillaPlaceholder() {
assertThat(SystemPropertyUtils.resolvePlaceholders("${foo}")).isEqualTo("bar");
}
@Test
public void testDefaultValue() {
void testDefaultValue() {
assertThat(SystemPropertyUtils.resolvePlaceholders("${bar:foo}")).isEqualTo("foo");
}
@Test
public void testNestedPlaceholder() {
void testNestedPlaceholder() {
assertThat(SystemPropertyUtils.resolvePlaceholders("${bar:${spam:foo}}")).isEqualTo("foo");
}
@Test
public void testEnvVar() {
void testEnvVar() {
assertThat(SystemPropertyUtils.getProperty("lang")).isEqualTo(System.getenv("LANG"));
}

View File

@@ -26,8 +26,8 @@ import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.handler.ArtifactHandler;
import org.apache.maven.model.Dependency;
import org.apache.maven.plugin.logging.Log;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
@@ -48,7 +48,7 @@ import static org.mockito.Mockito.verify;
*
* @author Phillip Webb
*/
public class ArtifactsLibrariesTests {
class ArtifactsLibrariesTests {
@Mock
private Artifact artifact;
@@ -68,7 +68,7 @@ public class ArtifactsLibrariesTests {
@Captor
private ArgumentCaptor<Library> libraryCaptor;
@Before
@BeforeEach
public void setup() {
MockitoAnnotations.initMocks(this);
this.artifacts = Collections.singleton(this.artifact);
@@ -79,7 +79,7 @@ public class ArtifactsLibrariesTests {
}
@Test
public void callbackForJars() throws Exception {
void callbackForJars() throws Exception {
given(this.artifact.getType()).willReturn("jar");
given(this.artifact.getScope()).willReturn("compile");
this.libs.doWithLibraries(this.callback);
@@ -91,7 +91,7 @@ public class ArtifactsLibrariesTests {
}
@Test
public void callbackWithUnpack() throws Exception {
void callbackWithUnpack() throws Exception {
given(this.artifact.getGroupId()).willReturn("gid");
given(this.artifact.getArtifactId()).willReturn("aid");
given(this.artifact.getType()).willReturn("jar");
@@ -106,7 +106,7 @@ public class ArtifactsLibrariesTests {
}
@Test
public void renamesDuplicates() throws Exception {
void renamesDuplicates() throws Exception {
Artifact artifact1 = mock(Artifact.class);
Artifact artifact2 = mock(Artifact.class);
given(artifact1.getType()).willReturn("jar");

View File

@@ -26,7 +26,7 @@ import org.apache.maven.artifact.Artifact;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.shared.artifact.filter.collection.ArtifactsFilter;
import org.apache.maven.shared.artifact.filter.collection.ScopeFilter;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given;
@@ -37,10 +37,10 @@ import static org.mockito.Mockito.mock;
*
* @author Stephane Nicoll
*/
public class DependencyFilterMojoTests {
class DependencyFilterMojoTests {
@Test
public void filterDependencies() throws MojoExecutionException {
void filterDependencies() throws MojoExecutionException {
TestableDependencyFilterMojo mojo = new TestableDependencyFilterMojo(Collections.emptyList(), "com.foo");
Artifact artifact = createArtifact("com.bar", "one");
@@ -51,7 +51,7 @@ public class DependencyFilterMojoTests {
}
@Test
public void filterGroupIdExactMatch() throws MojoExecutionException {
void filterGroupIdExactMatch() throws MojoExecutionException {
TestableDependencyFilterMojo mojo = new TestableDependencyFilterMojo(Collections.emptyList(), "com.foo");
Artifact artifact = createArtifact("com.foo.bar", "one");
@@ -62,7 +62,7 @@ public class DependencyFilterMojoTests {
}
@Test
public void filterScopeKeepOrder() throws MojoExecutionException {
void filterScopeKeepOrder() throws MojoExecutionException {
TestableDependencyFilterMojo mojo = new TestableDependencyFilterMojo(Collections.emptyList(), "",
new ScopeFilter(null, Artifact.SCOPE_SYSTEM));
Artifact one = createArtifact("com.foo", "one");
@@ -73,7 +73,7 @@ public class DependencyFilterMojoTests {
}
@Test
public void filterGroupIdKeepOrder() throws MojoExecutionException {
void filterGroupIdKeepOrder() throws MojoExecutionException {
TestableDependencyFilterMojo mojo = new TestableDependencyFilterMojo(Collections.emptyList(), "com.foo");
Artifact one = createArtifact("com.foo", "one");
Artifact two = createArtifact("com.bar", "two");
@@ -84,7 +84,7 @@ public class DependencyFilterMojoTests {
}
@Test
public void filterExcludeKeepOrder() throws MojoExecutionException {
void filterExcludeKeepOrder() throws MojoExecutionException {
Exclude exclude = new Exclude();
exclude.setGroupId("com.bar");
exclude.setArtifactId("two");

View File

@@ -19,7 +19,7 @@ package org.springframework.boot.maven;
import java.util.LinkedHashMap;
import java.util.Map;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.entry;
@@ -29,22 +29,22 @@ import static org.assertj.core.api.Assertions.entry;
*
* @author Dmytro Nosan
*/
public class EnvVariablesTests {
class EnvVariablesTests {
@Test
public void asNull() {
void asNull() {
Map<String, String> args = new EnvVariables(null).asMap();
assertThat(args).isEmpty();
}
@Test
public void asArray() {
void asArray() {
assertThat(new EnvVariables(getTestArgs()).asArray()).contains("key=My Value", "key1= tt ", "key2= ",
"key3=");
}
@Test
public void asMap() {
void asMap() {
assertThat(new EnvVariables(getTestArgs()).asMap()).containsExactly(entry("key", "My Value"),
entry("key1", " tt "), entry("key2", " "), entry("key3", ""));
}

View File

@@ -23,7 +23,7 @@ import java.util.Set;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.shared.artifact.filter.collection.ArtifactFilterException;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given;
@@ -36,17 +36,17 @@ import static org.mockito.Mockito.mock;
* @author David Turanski
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public class ExcludeFilterTests {
class ExcludeFilterTests {
@Test
public void excludeSimple() throws ArtifactFilterException {
void excludeSimple() throws ArtifactFilterException {
ExcludeFilter filter = new ExcludeFilter(Arrays.asList(createExclude("com.foo", "bar")));
Set result = filter.filter(Collections.singleton(createArtifact("com.foo", "bar")));
assertThat(result).isEmpty();
}
@Test
public void excludeGroupIdNoMatch() throws ArtifactFilterException {
void excludeGroupIdNoMatch() throws ArtifactFilterException {
ExcludeFilter filter = new ExcludeFilter(Arrays.asList(createExclude("com.foo", "bar")));
Artifact artifact = createArtifact("com.baz", "bar");
Set result = filter.filter(Collections.singleton(artifact));
@@ -55,7 +55,7 @@ public class ExcludeFilterTests {
}
@Test
public void excludeArtifactIdNoMatch() throws ArtifactFilterException {
void excludeArtifactIdNoMatch() throws ArtifactFilterException {
ExcludeFilter filter = new ExcludeFilter(Arrays.asList(createExclude("com.foo", "bar")));
Artifact artifact = createArtifact("com.foo", "biz");
Set result = filter.filter(Collections.singleton(artifact));
@@ -64,14 +64,14 @@ public class ExcludeFilterTests {
}
@Test
public void excludeClassifier() throws ArtifactFilterException {
void excludeClassifier() throws ArtifactFilterException {
ExcludeFilter filter = new ExcludeFilter(Arrays.asList(createExclude("com.foo", "bar", "jdk5")));
Set result = filter.filter(Collections.singleton(createArtifact("com.foo", "bar", "jdk5")));
assertThat(result).isEmpty();
}
@Test
public void excludeClassifierNoTargetClassifier() throws ArtifactFilterException {
void excludeClassifierNoTargetClassifier() throws ArtifactFilterException {
ExcludeFilter filter = new ExcludeFilter(Arrays.asList(createExclude("com.foo", "bar", "jdk5")));
Artifact artifact = createArtifact("com.foo", "bar");
Set result = filter.filter(Collections.singleton(artifact));
@@ -80,7 +80,7 @@ public class ExcludeFilterTests {
}
@Test
public void excludeClassifierNoMatch() throws ArtifactFilterException {
void excludeClassifierNoMatch() throws ArtifactFilterException {
ExcludeFilter filter = new ExcludeFilter(Arrays.asList(createExclude("com.foo", "bar", "jdk5")));
Artifact artifact = createArtifact("com.foo", "bar", "jdk6");
Set result = filter.filter(Collections.singleton(artifact));
@@ -89,7 +89,7 @@ public class ExcludeFilterTests {
}
@Test
public void excludeMulti() throws ArtifactFilterException {
void excludeMulti() throws ArtifactFilterException {
ExcludeFilter filter = new ExcludeFilter(Arrays.asList(createExclude("com.foo", "bar"),
createExclude("com.foo", "bar2"), createExclude("org.acme", "app")));
Set<Artifact> artifacts = new HashSet<>();

View File

@@ -23,7 +23,7 @@ import java.util.Set;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.shared.artifact.filter.collection.ArtifactFilterException;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given;
@@ -35,10 +35,10 @@ import static org.mockito.Mockito.mock;
* @author David Turanski
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public class IncludeFilterTests {
class IncludeFilterTests {
@Test
public void includeSimple() throws ArtifactFilterException {
void includeSimple() throws ArtifactFilterException {
IncludeFilter filter = new IncludeFilter(Arrays.asList(createInclude("com.foo", "bar")));
Artifact artifact = createArtifact("com.foo", "bar");
Set result = filter.filter(Collections.singleton(artifact));
@@ -47,7 +47,7 @@ public class IncludeFilterTests {
}
@Test
public void includeGroupIdNoMatch() throws ArtifactFilterException {
void includeGroupIdNoMatch() throws ArtifactFilterException {
IncludeFilter filter = new IncludeFilter(Arrays.asList(createInclude("com.foo", "bar")));
Artifact artifact = createArtifact("com.baz", "bar");
Set result = filter.filter(Collections.singleton(artifact));
@@ -55,7 +55,7 @@ public class IncludeFilterTests {
}
@Test
public void includeArtifactIdNoMatch() throws ArtifactFilterException {
void includeArtifactIdNoMatch() throws ArtifactFilterException {
IncludeFilter filter = new IncludeFilter(Arrays.asList(createInclude("com.foo", "bar")));
Artifact artifact = createArtifact("com.foo", "biz");
Set result = filter.filter(Collections.singleton(artifact));
@@ -63,7 +63,7 @@ public class IncludeFilterTests {
}
@Test
public void includeClassifier() throws ArtifactFilterException {
void includeClassifier() throws ArtifactFilterException {
IncludeFilter filter = new IncludeFilter(Arrays.asList(createInclude("com.foo", "bar", "jdk5")));
Artifact artifact = createArtifact("com.foo", "bar", "jdk5");
Set result = filter.filter(Collections.singleton(artifact));
@@ -72,7 +72,7 @@ public class IncludeFilterTests {
}
@Test
public void includeClassifierNoTargetClassifier() throws ArtifactFilterException {
void includeClassifierNoTargetClassifier() throws ArtifactFilterException {
IncludeFilter filter = new IncludeFilter(Arrays.asList(createInclude("com.foo", "bar", "jdk5")));
Artifact artifact = createArtifact("com.foo", "bar");
Set result = filter.filter(Collections.singleton(artifact));
@@ -80,7 +80,7 @@ public class IncludeFilterTests {
}
@Test
public void includeClassifierNoMatch() throws ArtifactFilterException {
void includeClassifierNoMatch() throws ArtifactFilterException {
IncludeFilter filter = new IncludeFilter(Arrays.asList(createInclude("com.foo", "bar", "jdk5")));
Artifact artifact = createArtifact("com.foo", "bar", "jdk6");
Set result = filter.filter(Collections.singleton(artifact));
@@ -88,7 +88,7 @@ public class IncludeFilterTests {
}
@Test
public void includeMulti() throws ArtifactFilterException {
void includeMulti() throws ArtifactFilterException {
IncludeFilter filter = new IncludeFilter(Arrays.asList(createInclude("com.foo", "bar"),
createInclude("com.foo", "bar2"), createInclude("org.acme", "app")));
Set<Artifact> artifacts = new HashSet<>();

View File

@@ -20,7 +20,7 @@ import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.jar.JarOutputStream;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
@@ -29,26 +29,26 @@ import static org.assertj.core.api.Assertions.assertThat;
*
* @author Dave Syer
*/
public class PropertiesMergingResourceTransformerTests {
class PropertiesMergingResourceTransformerTests {
private final PropertiesMergingResourceTransformer transformer = new PropertiesMergingResourceTransformer();
@Test
public void testProcess() throws Exception {
void testProcess() throws Exception {
assertThat(this.transformer.hasTransformedResource()).isFalse();
this.transformer.processResource("foo", new ByteArrayInputStream("foo=bar".getBytes()), null);
assertThat(this.transformer.hasTransformedResource()).isTrue();
}
@Test
public void testMerge() throws Exception {
void testMerge() throws Exception {
this.transformer.processResource("foo", new ByteArrayInputStream("foo=bar".getBytes()), null);
this.transformer.processResource("bar", new ByteArrayInputStream("foo=spam".getBytes()), null);
assertThat(this.transformer.getData().getProperty("foo")).isEqualTo("bar,spam");
}
@Test
public void testOutput() throws Exception {
void testOutput() throws Exception {
this.transformer.setResource("foo");
this.transformer.processResource("foo", new ByteArrayInputStream("foo=bar".getBytes()), null);
ByteArrayOutputStream out = new ByteArrayOutputStream();

View File

@@ -16,7 +16,7 @@
package org.springframework.boot.maven;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
@@ -25,45 +25,45 @@ import static org.assertj.core.api.Assertions.assertThat;
*
* @author Stephane Nicoll
*/
public class RunArgumentsTests {
class RunArgumentsTests {
@Test
public void parseNull() {
void parseNull() {
String[] args = parseArgs(null);
assertThat(args).isNotNull();
assertThat(args.length).isEqualTo(0);
}
@Test
public void parseNullArray() {
void parseNullArray() {
String[] args = new RunArguments((String[]) null).asArray();
assertThat(args).isNotNull();
assertThat(args.length).isEqualTo(0);
}
@Test
public void parseArrayContainingNullValue() {
void parseArrayContainingNullValue() {
String[] args = new RunArguments(new String[] { "foo", null, "bar" }).asArray();
assertThat(args).isNotNull();
assertThat(args).containsOnly("foo", "bar");
}
@Test
public void parseArrayContainingEmptyValue() {
void parseArrayContainingEmptyValue() {
String[] args = new RunArguments(new String[] { "foo", "", "bar" }).asArray();
assertThat(args).isNotNull();
assertThat(args).containsOnly("foo", "", "bar");
}
@Test
public void parseEmpty() {
void parseEmpty() {
String[] args = parseArgs(" ");
assertThat(args).isNotNull();
assertThat(args.length).isEqualTo(0);
}
@Test
public void parseDebugFlags() {
void parseDebugFlags() {
String[] args = parseArgs("-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=5005");
assertThat(args.length).isEqualTo(2);
assertThat(args[0]).isEqualTo("-Xdebug");
@@ -71,7 +71,7 @@ public class RunArgumentsTests {
}
@Test
public void parseWithExtraSpaces() {
void parseWithExtraSpaces() {
String[] args = parseArgs(" -Dfoo=bar -Dfoo2=bar2 ");
assertThat(args.length).isEqualTo(2);
assertThat(args[0]).isEqualTo("-Dfoo=bar");
@@ -79,7 +79,7 @@ public class RunArgumentsTests {
}
@Test
public void parseWithNewLinesAndTabs() {
void parseWithNewLinesAndTabs() {
String[] args = parseArgs(" -Dfoo=bar \n" + "\t\t -Dfoo2=bar2 ");
assertThat(args.length).isEqualTo(2);
assertThat(args[0]).isEqualTo("-Dfoo=bar");
@@ -87,7 +87,7 @@ public class RunArgumentsTests {
}
@Test
public void quoteHandledProperly() {
void quoteHandledProperly() {
String[] args = parseArgs("-Dvalue=\"My Value\" ");
assertThat(args.length).isEqualTo(1);
assertThat(args[0]).isEqualTo("-Dvalue=My Value");

View File

@@ -16,7 +16,7 @@
package org.springframework.boot.maven;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.springframework.boot.maven.AbstractRunMojo.SystemPropertyFormatter;
@@ -25,30 +25,30 @@ import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link AbstractRunMojo.SystemPropertyFormatter}.
*/
public class SystemPropertyFormatterTests {
class SystemPropertyFormatterTests {
@Test
public void parseEmpty() {
void parseEmpty() {
assertThat(SystemPropertyFormatter.format(null, null)).isEqualTo("");
}
@Test
public void parseOnlyKey() {
void parseOnlyKey() {
assertThat(SystemPropertyFormatter.format("key1", null)).isEqualTo("-Dkey1");
}
@Test
public void parseKeyWithValue() {
void parseKeyWithValue() {
assertThat(SystemPropertyFormatter.format("key1", "value1")).isEqualTo("-Dkey1=\"value1\"");
}
@Test
public void parseKeyWithEmptyValue() {
void parseKeyWithEmptyValue() {
assertThat(SystemPropertyFormatter.format("key1", "")).isEqualTo("-Dkey1");
}
@Test
public void parseKeyWithOnlySpaces() {
void parseKeyWithOnlySpaces() {
assertThat(SystemPropertyFormatter.format("key1", " ")).isEqualTo("-Dkey1=\" \"");
}

View File

@@ -109,6 +109,11 @@
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>junit-jupiter</artifactId>
<optional>true</optional>
</dependency>
<!-- Provided -->
<dependency>
<groupId>junit</groupId>

View File

@@ -1,38 +0,0 @@
/*
* Copyright 2012-2017 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.testsupport;
import org.junit.AssumptionViolatedException;
import org.springframework.util.ClassUtils;
/**
* Provides utility methods that allow JUnit tests to {@link org.junit.Assume} certain
* conditions hold {@code true}. If the assumption fails, it means the test should be
* skipped.
*
* @author Stephane Nicoll
*/
public abstract class Assume {
public static void javaEight() {
if (ClassUtils.isPresent("java.security.cert.URICertStoreParameters", null)) {
throw new AssumptionViolatedException("Assumed Java 8 but got Java 9");
}
}
}

View File

@@ -29,8 +29,6 @@ import javax.tools.StandardJavaFileManager;
import javax.tools.StandardLocation;
import javax.tools.ToolProvider;
import org.junit.rules.TemporaryFolder;
/**
* Wrapper to make the {@link JavaCompiler} easier to use in tests.
*
@@ -51,14 +49,15 @@ public class TestCompiler {
private final File outputLocation;
public TestCompiler(TemporaryFolder temporaryFolder) throws IOException {
this(ToolProvider.getSystemJavaCompiler(), temporaryFolder);
public TestCompiler(File outputLocation) throws IOException {
this(ToolProvider.getSystemJavaCompiler(), outputLocation);
}
public TestCompiler(JavaCompiler compiler, TemporaryFolder temporaryFolder) throws IOException {
public TestCompiler(JavaCompiler compiler, File outputLocation) throws IOException {
this.compiler = compiler;
this.fileManager = compiler.getStandardFileManager(null, null, null);
this.outputLocation = temporaryFolder.newFolder();
this.outputLocation = outputLocation;
this.outputLocation.mkdirs();
Iterable<? extends File> temp = Arrays.asList(this.outputLocation);
this.fileManager.setLocation(StandardLocation.CLASS_OUTPUT, temp);
this.fileManager.setLocation(StandardLocation.SOURCE_OUTPUT, temp);

View File

@@ -20,7 +20,7 @@ import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.springframework.asm.Opcodes;
import org.springframework.beans.DirectFieldAccessor;

View File

@@ -1,156 +0,0 @@
/*
* Copyright 2012-2017 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.testsupport.rule;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.List;
import org.hamcrest.Matcher;
import org.junit.Assert;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
import static org.hamcrest.Matchers.allOf;
/**
* Internal JUnit {@code @Rule} to capture output from System.out and System.err.
*
* @author Phillip Webb
* @author Andy Wilkinson
*/
public class OutputCapture implements TestRule {
private CaptureOutputStream captureOut;
private CaptureOutputStream captureErr;
private ByteArrayOutputStream copy;
private List<Matcher<? super String>> matchers = new ArrayList<>();
@Override
public Statement apply(Statement base, Description description) {
return new Statement() {
@Override
public void evaluate() throws Throwable {
captureOutput();
try {
base.evaluate();
}
finally {
try {
if (!OutputCapture.this.matchers.isEmpty()) {
String output = OutputCapture.this.toString();
Assert.assertThat(output, allOf(OutputCapture.this.matchers));
}
}
finally {
releaseOutput();
}
}
}
};
}
protected void captureOutput() {
// FIXME AnsiOutput.setEnabled(Enabled.NEVER);
this.copy = new ByteArrayOutputStream();
this.captureOut = new CaptureOutputStream(System.out, this.copy);
this.captureErr = new CaptureOutputStream(System.err, this.copy);
System.setOut(new PrintStream(this.captureOut));
System.setErr(new PrintStream(this.captureErr));
}
protected void releaseOutput() {
// FIXME AnsiOutput.setEnabled(Enabled.DETECT);
System.setOut(this.captureOut.getOriginal());
System.setErr(this.captureErr.getOriginal());
this.copy = null;
}
public void flush() {
try {
this.captureOut.flush();
this.captureErr.flush();
}
catch (IOException ex) {
// ignore
}
}
@Override
public String toString() {
flush();
return this.copy.toString();
}
/**
* Verify that the output is matched by the supplied {@code matcher}. Verification is
* performed after the test method has executed.
* @param matcher the matcher
*/
public void expect(Matcher<? super String> matcher) {
this.matchers.add(matcher);
}
private static class CaptureOutputStream extends OutputStream {
private final PrintStream original;
private final OutputStream copy;
CaptureOutputStream(PrintStream original, OutputStream copy) {
this.original = original;
this.copy = copy;
}
@Override
public void write(int b) throws IOException {
this.copy.write(b);
this.original.write(b);
this.original.flush();
}
@Override
public void write(byte[] b) throws IOException {
write(b, 0, b.length);
}
@Override
public void write(byte[] b, int off, int len) throws IOException {
this.copy.write(b, off, len);
this.original.write(b, off, len);
}
public PrintStream getOriginal() {
return this.original;
}
@Override
public void flush() throws IOException {
this.copy.flush();
this.original.flush();
}
}
}

View File

@@ -1,20 +0,0 @@
/*
* Copyright 2012-2017 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.
*/
/**
* Internal JUnit rules used in Spring Boot tests.
*/
package org.springframework.boot.testsupport.rule;

View File

@@ -0,0 +1,71 @@
/*
* 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.testsupport.system;
/**
* Provides access to {@link System#out System.out} and {@link System#err System.err}
* output that has been capture by the {@link OutputCaptureExtension}. Can be used to
* apply assertions either using AssertJ or standard JUnit assertions. For example:
* <pre class="code">
* assertThat(output).contains("started"); // Checks all output
* assertThat(output.getErr()).contains("failed"); // Only checks System.err
* assertThat(output.getOut()).contains("ok"); // Only checks System.put
* </pre>
*
* @author Madhura Bhave
* @author Phillip Webb
* @author Andy Wilkinson
* @since 2.2.0
* @see OutputCaptureExtension
*/
public interface CapturedOutput extends CharSequence {
@Override
default int length() {
return toString().length();
}
@Override
default char charAt(int index) {
return toString().charAt(index);
}
@Override
default CharSequence subSequence(int start, int end) {
return toString().subSequence(start, end);
}
/**
* Return all content (both {@link System#out System.out} and {@link System#err
* System.err}) in the order that it was was captured.
* @return all captured output
*/
String getAll();
/**
* Return {@link System#out System.out} content in the order that it was was captured.
* @return {@link System#out System.out} captured output
*/
String getOut();
/**
* Return {@link System#err System.err} content in the order that it was was captured.
* @return {@link System#err System.err} captured output
*/
String getErr();
}

View File

@@ -0,0 +1,273 @@
/*
* 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.testsupport.system;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Predicate;
import org.springframework.util.Assert;
/**
* Provides support for capturing {@link System#out System.out} and {@link System#err
* System.err}.
*
* @author Madhura Bhave
* @author Phillip Webb
* @author Andy Wilkinson
* @see OutputCaptureExtension
* @see OutputCaptureRule
*/
class OutputCapture implements CapturedOutput {
private final Deque<SystemCapture> systemCaptures = new ArrayDeque<>();
/**
* Push a new system capture session onto the stack.
*/
final void push() {
this.systemCaptures.addLast(new SystemCapture());
}
/**
* Pop the last system capture session from the stack.
*/
final void pop() {
this.systemCaptures.removeLast().release();
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (obj instanceof CapturedOutput || obj instanceof CharSequence) {
return getAll().equals(obj.toString());
}
return false;
}
@Override
public int hashCode() {
return toString().hashCode();
}
@Override
public String toString() {
return getAll();
}
/**
* Return all content (both {@link System#out System.out} and {@link System#err
* System.err}) in the order that it was was captured.
* @return all captured output
*/
@Override
public String getAll() {
return get((type) -> true);
}
/**
* Return {@link System#out System.out} content in the order that it was was captured.
* @return {@link System#out System.out} captured output
*/
@Override
public String getOut() {
return get(Type.OUT::equals);
}
/**
* Return {@link System#err System.err} content in the order that it was was captured.
* @return {@link System#err System.err} captured output
*/
@Override
public String getErr() {
return get(Type.ERR::equals);
}
/**
* Resets the current capture session, clearing its captured output.
*/
void reset() {
this.systemCaptures.peek().reset();
}
private String get(Predicate<Type> filter) {
Assert.state(!this.systemCaptures.isEmpty(),
"No system captures found. Check that you have used @RegisterExtension "
+ "or @ExtendWith and the fields are not private");
StringBuilder builder = new StringBuilder();
for (SystemCapture systemCapture : this.systemCaptures) {
systemCapture.append(builder, filter);
}
return builder.toString();
}
/**
* A capture session that captures {@link System#out System.out} and {@link System#out
* System.err}.
*/
private static class SystemCapture {
private final PrintStreamCapture out;
private final PrintStreamCapture err;
private final Object monitor = new Object();
private final List<CapturedString> capturedStrings = new ArrayList<>();
SystemCapture() {
this.out = new PrintStreamCapture(System.out, this::captureOut);
this.err = new PrintStreamCapture(System.err, this::captureErr);
System.setOut(this.out);
System.setErr(this.err);
}
public void release() {
System.setOut(this.out.getParent());
System.setErr(this.err.getParent());
}
private void captureOut(String string) {
synchronized (this.monitor) {
this.capturedStrings.add(new CapturedString(Type.OUT, string));
}
}
private void captureErr(String string) {
synchronized (this.monitor) {
this.capturedStrings.add(new CapturedString(Type.ERR, string));
}
}
public void append(StringBuilder builder, Predicate<Type> filter) {
synchronized (this.monitor) {
for (CapturedString stringCapture : this.capturedStrings) {
if (filter.test(stringCapture.getType())) {
builder.append(stringCapture);
}
}
}
}
public void reset() {
synchronized (this.monitor) {
this.capturedStrings.clear();
}
}
}
/**
* A {@link PrintStream} implementation that captures written strings.
*/
private static class PrintStreamCapture extends PrintStream {
private final PrintStream parent;
PrintStreamCapture(PrintStream parent, Consumer<String> copy) {
super(new OutputStreamCapture(getSystemStream(parent), copy));
this.parent = parent;
}
public PrintStream getParent() {
return this.parent;
}
private static PrintStream getSystemStream(PrintStream printStream) {
while (printStream instanceof PrintStreamCapture) {
return ((PrintStreamCapture) printStream).getParent();
}
return printStream;
}
}
/**
* An {@link OutputStream} implementation that captures written strings.
*/
private static class OutputStreamCapture extends OutputStream {
private final PrintStream systemStream;
private final Consumer<String> copy;
OutputStreamCapture(PrintStream systemStream, Consumer<String> copy) {
this.systemStream = systemStream;
this.copy = copy;
}
@Override
public void write(int b) throws IOException {
write(new byte[] { (byte) (b & 0xFF) });
}
@Override
public void write(byte[] b, int off, int len) throws IOException {
this.copy.accept(new String(b, off, len));
this.systemStream.write(b, off, len);
}
@Override
public void flush() throws IOException {
this.systemStream.flush();
}
}
/**
* A captured string that forms part of the full output.
*/
private static class CapturedString {
private final Type type;
private final String string;
CapturedString(Type type, String string) {
this.type = type;
this.string = string;
}
public Type getType() {
return this.type;
}
@Override
public String toString() {
return this.string;
}
}
/**
* Types of content that can be captured.
*/
private enum Type {
OUT, ERR
}
}

View File

@@ -0,0 +1,98 @@
/*
* 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.testsupport.system;
import org.junit.jupiter.api.extension.AfterAllCallback;
import org.junit.jupiter.api.extension.AfterEachCallback;
import org.junit.jupiter.api.extension.BeforeAllCallback;
import org.junit.jupiter.api.extension.BeforeEachCallback;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.api.extension.ParameterContext;
import org.junit.jupiter.api.extension.ParameterResolutionException;
import org.junit.jupiter.api.extension.ParameterResolver;
/**
* Internal JUnit 5 {@code @Extension} to capture {@link System#out System.out} and
* {@link System#err System.err}. Can be used on a test class via
* {@link ExtendWith @ExtendWith}. This extension provides {@link ParameterResolver
* parameter resolution} for a {@link CapturedOutput} instance which can be used to assert
* that the correct output was written.
* <p>
* To use with {@link ExtendWith @ExtendWith}, inject the {@link CapturedOutput} as an
* argument to your test class constructor or test method:
*
* <pre class="code">
* &#064;ExtendWith(OutputExtension.class)
* class MyTest {
*
* &#064;Test
* void test(CapturedOutput output) {
* assertThat(output).contains("ok");
* }
*
* }
* </pre>
*
* @author Madhura Bhave
* @author Phillip Webb
* @author Andy Wilkinson
* @since 2.2.0
* @see CapturedOutput
*/
public class OutputCaptureExtension
implements BeforeAllCallback, AfterAllCallback, BeforeEachCallback, AfterEachCallback, ParameterResolver {
private final OutputCapture outputCapture = new OutputCapture();
OutputCaptureExtension() {
// Package private to prevent users from directly creating an instance.
}
@Override
public void beforeAll(ExtensionContext context) throws Exception {
this.outputCapture.push();
}
@Override
public void afterAll(ExtensionContext context) throws Exception {
this.outputCapture.pop();
}
@Override
public void beforeEach(ExtensionContext context) throws Exception {
this.outputCapture.push();
}
@Override
public void afterEach(ExtensionContext context) throws Exception {
this.outputCapture.pop();
}
@Override
public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext)
throws ParameterResolutionException {
return CapturedOutput.class.equals(parameterContext.getParameter().getType());
}
@Override
public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext)
throws ParameterResolutionException {
return this.outputCapture;
}
}

View File

@@ -0,0 +1,80 @@
/*
* 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.testsupport.system;
import java.util.ArrayList;
import java.util.List;
import org.hamcrest.Matcher;
import org.junit.Assert;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
import static org.hamcrest.Matchers.allOf;
/**
* Internal JUnit {@code @Rule} to capture output from System.out and System.err.
*
* @author Phillip Webb
* @author Andy Wilkinson
*/
public class OutputCaptureRule implements TestRule {
private final OutputCapture delegate = new OutputCapture();
private List<Matcher<? super String>> matchers = new ArrayList<>();
@Override
public Statement apply(Statement base, Description description) {
return new Statement() {
@Override
public void evaluate() throws Throwable {
OutputCaptureRule.this.delegate.push();
try {
base.evaluate();
}
finally {
try {
if (!OutputCaptureRule.this.matchers.isEmpty()) {
String output = OutputCaptureRule.this.delegate.toString();
Assert.assertThat(output, allOf(OutputCaptureRule.this.matchers));
}
}
finally {
OutputCaptureRule.this.delegate.pop();
}
}
}
};
}
@Override
public String toString() {
return this.delegate.toString();
}
/**
* Verify that the output is matched by the supplied {@code matcher}. Verification is
* performed after the test method has executed.
* @param matcher the matcher
*/
public void expect(Matcher<? super String> matcher) {
this.matchers.add(matcher);
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -15,6 +15,6 @@
*/
/**
* Support for integration testing with Testcontainers.
* Classes for {@link java.lang.System System}-related testing.
*/
package org.springframework.boot.testsupport.testcontainers;
package org.springframework.boot.testsupport.system;

View File

@@ -1,91 +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.testsupport.testcontainers;
import java.util.function.Consumer;
import java.util.function.Supplier;
import org.junit.jupiter.api.Assumptions;
import org.junit.rules.TestRule;
import org.testcontainers.DockerClientFactory;
import org.testcontainers.containers.GenericContainer;
import org.testcontainers.lifecycle.Startable;
/**
* {@link TestRule} for working with an optional Docker environment. Spins up a
* {@link GenericContainer} if a valid docker environment is found.
*
* @author Madhura Bhave
* @author Phillip Webb
*/
class Container implements Startable {
private final int port;
private final Supplier<GenericContainer<?>> containerFactory;
private GenericContainer<?> container;
<T extends GenericContainer<T>> Container(String dockerImageName, int port) {
this(dockerImageName, port, null);
}
@SuppressWarnings({ "unchecked", "resource" })
<T extends GenericContainer<T>> Container(String dockerImageName, int port, Consumer<T> customizer) {
this.port = port;
this.containerFactory = () -> {
T container = (T) new GenericContainer<>(dockerImageName).withExposedPorts(port);
if (customizer != null) {
customizer.accept(container);
}
return container;
};
}
public int getMappedPort() {
return this.container.getMappedPort(this.port);
}
protected GenericContainer<?> getContainer() {
return this.container;
}
@Override
public void start() {
Assumptions.assumeTrue(isDockerRunning(), "Could not find valid docker environment.");
this.container = this.containerFactory.get();
this.container.start();
}
private boolean isDockerRunning() {
try {
DockerClientFactory.instance().client();
return true;
}
catch (Throwable ex) {
return false;
}
}
@Override
public void stop() {
if (this.container != null) {
this.container.stop();
}
}
}

View File

@@ -0,0 +1,39 @@
/*
* 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.testsupport.testcontainers;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.junit.jupiter.api.extension.ExtendWith;
import org.testcontainers.junit.jupiter.Testcontainers;
/**
* Customization of {@link Testcontainers @Testcontainers} that disables the tests when
* Docker is not available.
*
* @author Andy Wilkinson
*/
@ExtendWith(DockerIsAvailableCondition.class)
@Testcontainers
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface DisabledWithoutDockerTestcontainers {
}

View File

@@ -0,0 +1,43 @@
/*
* 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.testsupport.testcontainers;
import org.junit.jupiter.api.extension.ConditionEvaluationResult;
import org.junit.jupiter.api.extension.ExecutionCondition;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.testcontainers.DockerClientFactory;
/**
* {@link ExecutionCondition} for
* {@link DisabledWithoutDockerTestcontainers @DisabledWithoutDockerTestcontainers}.
*
* @author Andy Wilkinson
*/
final class DockerIsAvailableCondition implements ExecutionCondition {
@Override
public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext context) {
try {
DockerClientFactory.instance().client();
return ConditionEvaluationResult.enabled("Docker is available");
}
catch (Throwable ex) {
return ConditionEvaluationResult.disabled("Docker is not available: " + ex.getMessage());
}
}
}

View File

@@ -1,53 +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.testsupport.testcontainers;
import java.time.Duration;
/**
* A {@link Container} for Elasticsearch.
*
* @author Andy Wilkinson
*/
public class ElasticsearchContainer extends Container {
public ElasticsearchContainer() {
super("elasticsearch:6.7.2", 9200, (container) -> container.withStartupTimeout(Duration.ofSeconds(120))
.withStartupAttempts(5).withEnv("discovery.type", "single-node").addExposedPorts(9200, 9300));
}
public int getMappedTransportPort() {
return getContainer().getMappedPort(9300);
}
public int getMappedHttpPort() {
return getContainer().getMappedPort(9200);
}
@Override
public void start() {
System.setProperty("es.set.netty.runtime.available.processors", "false");
super.start();
}
@Override
public void stop() {
System.clearProperty("es.set.netty.runtime.available.processors");
super.stop();
}
}

View File

@@ -24,10 +24,11 @@ import org.testcontainers.containers.GenericContainer;
* @author Andy Wilkinson
* @author Madhura Bhave
*/
public class RedisContainer extends Container {
public class RedisContainer extends GenericContainer<RedisContainer> {
public RedisContainer() {
super("redis:4.0.6", 6379);
super("redis:4.0.6");
addExposedPorts(6379);
}
}

View File

@@ -1,75 +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.testsupport.testcontainers;
import java.util.function.Supplier;
import org.junit.jupiter.api.Assumptions;
import org.testcontainers.DockerClientFactory;
import org.testcontainers.containers.GenericContainer;
import org.testcontainers.lifecycle.Startable;
/**
* A {@link GenericContainer} decorator that skips test execution when Docker is not
* available.
*
* @param <T> type of the underlying container
* @author Andy Wilkinson
* @author Madhura Bhave
*/
public class SkippableContainer<T extends GenericContainer<?>> implements Startable {
private final Supplier<T> containerFactory;
private T container;
public SkippableContainer(Supplier<T> containerFactory) {
this.containerFactory = containerFactory;
}
public T getContainer() {
if (this.container == null) {
throw new IllegalStateException("Container cannot be accessed prior to test invocation");
}
return this.container;
}
@Override
public void start() {
Assumptions.assumeTrue(isDockerRunning(), "Could not find valid docker environment.");
this.container = this.containerFactory.get();
this.container.start();
}
private boolean isDockerRunning() {
try {
DockerClientFactory.instance().client();
return true;
}
catch (Throwable ex) {
return false;
}
}
@Override
public void stop() {
if (this.container != null) {
this.container.stop();
}
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,7 +16,7 @@
package org.springframework.boot.testsupport.assertj;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
@@ -27,27 +27,27 @@ import static org.hamcrest.Matchers.startsWith;
*
* @author Phillip Webb
*/
public class MatchedTests {
class MatchedTests {
@Test
public void byMatcherMatches() {
void byMatcherMatches() {
assertThat("1234").is(Matched.by(startsWith("12")));
}
@Test
public void byMatcherDoesNotMatch() {
void byMatcherDoesNotMatch() {
assertThatExceptionOfType(AssertionError.class)
.isThrownBy(() -> assertThat("1234").is(Matched.by(startsWith("23"))))
.withMessageContaining("a string starting with \"23\"");
}
@Test
public void whenMatcherMatches() {
void whenMatcherMatches() {
assertThat("1234").is(Matched.when(startsWith("12")));
}
@Test
public void whenMatcherDoesNotMatch() {
void whenMatcherDoesNotMatch() {
assertThatExceptionOfType(AssertionError.class)
.isThrownBy(() -> assertThat("1234").is(Matched.when(startsWith("23"))))
.withMessageContaining("a string starting with \"23\"");