Use AssertJ in spring-boot-tools

See gh-5083
pull/4188/merge
Phillip Webb 9 years ago
parent 7f9358f4d8
commit 00cfe1d054

@ -25,8 +25,7 @@ import org.junit.rules.ExpectedException;
import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource; import org.springframework.core.io.Resource;
import static org.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertNotNull;
/** /**
* Base for configuration meta-data tests. * Base for configuration meta-data tests.
@ -40,25 +39,25 @@ public abstract class AbstractConfigurationMetadataTests {
protected void assertSource(ConfigurationMetadataSource actual, String groupId, protected void assertSource(ConfigurationMetadataSource actual, String groupId,
String type, String sourceType) { String type, String sourceType) {
assertNotNull(actual); assertThat(actual).isNotNull();
assertEquals(groupId, actual.getGroupId()); assertThat(actual.getGroupId()).isEqualTo(groupId);
assertEquals(type, actual.getType()); assertThat(actual.getType()).isEqualTo(type);
assertEquals(sourceType, actual.getSourceType()); assertThat(actual.getSourceType()).isEqualTo(sourceType);
} }
protected void assertProperty(ConfigurationMetadataProperty actual, String id, protected void assertProperty(ConfigurationMetadataProperty actual, String id,
String name, Class<?> type, Object defaultValue) { String name, Class<?> type, Object defaultValue) {
assertNotNull(actual); assertThat(actual).isNotNull();
assertEquals(id, actual.getId()); assertThat(actual.getId()).isEqualTo(id);
assertEquals(name, actual.getName()); assertThat(actual.getName()).isEqualTo(name);
String typeName = type != null ? type.getName() : null; String typeName = type != null ? type.getName() : null;
assertEquals(typeName, actual.getType()); assertThat(actual.getType()).isEqualTo(typeName);
assertEquals(defaultValue, actual.getDefaultValue()); assertThat(actual.getDefaultValue()).isEqualTo(defaultValue);
} }
protected void assertItem(ConfigurationMetadataItem actual, String sourceType) { protected void assertItem(ConfigurationMetadataItem actual, String sourceType) {
assertNotNull(actual); assertThat(actual).isNotNull();
assertEquals(sourceType, actual.getSourceType()); assertThat(actual.getSourceType()).isEqualTo(sourceType);
} }
protected InputStream getInputStreamFor(String name) throws IOException { protected InputStream getInputStreamFor(String name) throws IOException {

@ -22,9 +22,7 @@ import java.util.Map;
import org.junit.Test; import org.junit.Test;
import static org.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
/** /**
* Tests for {@link ConfigurationMetadataRepository}. * Tests for {@link ConfigurationMetadataRepository}.
@ -47,10 +45,10 @@ public class ConfigurationMetadataRepositoryJsonBuilderTests
ConfigurationMetadataRepository repo = ConfigurationMetadataRepositoryJsonBuilder ConfigurationMetadataRepository repo = ConfigurationMetadataRepositoryJsonBuilder
.create(foo).build(); .create(foo).build();
validateFoo(repo); validateFoo(repo);
assertEquals(1, repo.getAllGroups().size()); assertThat(repo.getAllGroups()).hasSize(1);
contains(repo.getAllProperties(), "spring.foo.name", "spring.foo.description", contains(repo.getAllProperties(), "spring.foo.name", "spring.foo.description",
"spring.foo.counter"); "spring.foo.counter");
assertEquals(3, repo.getAllProperties().size()); assertThat(repo.getAllProperties()).hasSize(3);
} }
finally { finally {
foo.close(); foo.close();
@ -66,11 +64,11 @@ public class ConfigurationMetadataRepositoryJsonBuilderTests
.create(foo, bar).build(); .create(foo, bar).build();
validateFoo(repo); validateFoo(repo);
validateBar(repo); validateBar(repo);
assertEquals(2, repo.getAllGroups().size()); assertThat(repo.getAllGroups()).hasSize(2);
contains(repo.getAllProperties(), "spring.foo.name", "spring.foo.description", contains(repo.getAllProperties(), "spring.foo.name", "spring.foo.description",
"spring.foo.counter", "spring.bar.name", "spring.bar.description", "spring.foo.counter", "spring.bar.name", "spring.bar.description",
"spring.bar.counter"); "spring.bar.counter");
assertEquals(6, repo.getAllProperties().size()); assertThat(repo.getAllProperties()).hasSize(6);
} }
finally { finally {
foo.close(); foo.close();
@ -86,11 +84,11 @@ public class ConfigurationMetadataRepositoryJsonBuilderTests
ConfigurationMetadataRepository repo = ConfigurationMetadataRepositoryJsonBuilder ConfigurationMetadataRepository repo = ConfigurationMetadataRepositoryJsonBuilder
.create(foo, root).build(); .create(foo, root).build();
validateFoo(repo); validateFoo(repo);
assertEquals(2, repo.getAllGroups().size()); assertThat(repo.getAllGroups()).hasSize(2);
contains(repo.getAllProperties(), "spring.foo.name", "spring.foo.description", contains(repo.getAllProperties(), "spring.foo.name", "spring.foo.description",
"spring.foo.counter", "spring.root.name", "spring.root2.name"); "spring.foo.counter", "spring.root.name", "spring.root2.name");
assertEquals(5, repo.getAllProperties().size()); assertThat(repo.getAllProperties()).hasSize(5);
} }
finally { finally {
foo.close(); foo.close();
@ -105,17 +103,17 @@ public class ConfigurationMetadataRepositoryJsonBuilderTests
try { try {
ConfigurationMetadataRepository repo = ConfigurationMetadataRepositoryJsonBuilder ConfigurationMetadataRepository repo = ConfigurationMetadataRepositoryJsonBuilder
.create(foo, foo2).build(); .create(foo, foo2).build();
assertEquals(1, repo.getAllGroups().size()); assertThat(repo.getAllGroups()).hasSize(1);
ConfigurationMetadataGroup group = repo.getAllGroups().get("spring.foo"); ConfigurationMetadataGroup group = repo.getAllGroups().get("spring.foo");
contains(group.getSources(), "org.acme.Foo", "org.acme.Foo2", contains(group.getSources(), "org.acme.Foo", "org.acme.Foo2",
"org.springframework.boot.FooProperties"); "org.springframework.boot.FooProperties");
assertEquals(3, group.getSources().size()); assertThat(group.getSources()).hasSize(3);
contains(group.getProperties(), "spring.foo.name", "spring.foo.description", contains(group.getProperties(), "spring.foo.name", "spring.foo.description",
"spring.foo.counter", "spring.foo.enabled", "spring.foo.type"); "spring.foo.counter", "spring.foo.enabled", "spring.foo.type");
assertEquals(5, group.getProperties().size()); assertThat(group.getProperties()).hasSize(5);
contains(repo.getAllProperties(), "spring.foo.name", "spring.foo.description", contains(repo.getAllProperties(), "spring.foo.name", "spring.foo.description",
"spring.foo.counter", "spring.foo.enabled", "spring.foo.type"); "spring.foo.counter", "spring.foo.enabled", "spring.foo.type");
assertEquals(5, repo.getAllProperties().size()); assertThat(repo.getAllProperties()).hasSize(5);
} }
finally { finally {
foo.close(); foo.close();
@ -138,11 +136,11 @@ public class ConfigurationMetadataRepositoryJsonBuilderTests
validateFoo(secondRepo); validateFoo(secondRepo);
validateBar(secondRepo); validateBar(secondRepo);
// first repo not impacted by second build // first repo not impacted by second build
assertNotEquals(firstRepo, secondRepo); assertThat(secondRepo).isNotEqualTo(firstRepo);
assertEquals(1, firstRepo.getAllGroups().size()); assertThat(firstRepo.getAllGroups()).hasSize(1);
assertEquals(3, firstRepo.getAllProperties().size()); assertThat(firstRepo.getAllProperties()).hasSize(3);
assertEquals(2, secondRepo.getAllGroups().size()); assertThat(secondRepo.getAllGroups()).hasSize(2);
assertEquals(6, secondRepo.getAllProperties().size()); assertThat(secondRepo.getAllProperties()).hasSize(6);
} }
finally { finally {
foo.close(); foo.close();
@ -156,11 +154,11 @@ public class ConfigurationMetadataRepositoryJsonBuilderTests
"org.springframework.boot.FooProperties"); "org.springframework.boot.FooProperties");
ConfigurationMetadataSource source = group.getSources().get("org.acme.Foo"); ConfigurationMetadataSource source = group.getSources().get("org.acme.Foo");
contains(source.getProperties(), "spring.foo.name", "spring.foo.description"); contains(source.getProperties(), "spring.foo.name", "spring.foo.description");
assertEquals(2, source.getProperties().size()); assertThat(source.getProperties()).hasSize(2);
ConfigurationMetadataSource source2 = group.getSources() ConfigurationMetadataSource source2 = group.getSources()
.get("org.springframework.boot.FooProperties"); .get("org.springframework.boot.FooProperties");
contains(source2.getProperties(), "spring.foo.name", "spring.foo.counter"); contains(source2.getProperties(), "spring.foo.name", "spring.foo.counter");
assertEquals(2, source2.getProperties().size()); assertThat(source2.getProperties()).hasSize(2);
validatePropertyHints(repo.getAllProperties().get("spring.foo.name"), 0, 0); validatePropertyHints(repo.getAllProperties().get("spring.foo.name"), 0, 0);
validatePropertyHints(repo.getAllProperties().get("spring.foo.description"), 0, validatePropertyHints(repo.getAllProperties().get("spring.foo.description"), 0,
0); 0);
@ -173,11 +171,11 @@ public class ConfigurationMetadataRepositoryJsonBuilderTests
"org.springframework.boot.BarProperties"); "org.springframework.boot.BarProperties");
ConfigurationMetadataSource source = group.getSources().get("org.acme.Bar"); ConfigurationMetadataSource source = group.getSources().get("org.acme.Bar");
contains(source.getProperties(), "spring.bar.name", "spring.bar.description"); contains(source.getProperties(), "spring.bar.name", "spring.bar.description");
assertEquals(2, source.getProperties().size()); assertThat(source.getProperties()).hasSize(2);
ConfigurationMetadataSource source2 = group.getSources() ConfigurationMetadataSource source2 = group.getSources()
.get("org.springframework.boot.BarProperties"); .get("org.springframework.boot.BarProperties");
contains(source2.getProperties(), "spring.bar.name", "spring.bar.counter"); contains(source2.getProperties(), "spring.bar.name", "spring.bar.counter");
assertEquals(2, source2.getProperties().size()); assertThat(source2.getProperties()).hasSize(2);
validatePropertyHints(repo.getAllProperties().get("spring.bar.name"), 0, 0); validatePropertyHints(repo.getAllProperties().get("spring.bar.name"), 0, 0);
validatePropertyHints(repo.getAllProperties().get("spring.bar.description"), 2, validatePropertyHints(repo.getAllProperties().get("spring.bar.description"), 2,
2); 2);
@ -186,14 +184,13 @@ public class ConfigurationMetadataRepositoryJsonBuilderTests
private void validatePropertyHints(ConfigurationMetadataProperty property, private void validatePropertyHints(ConfigurationMetadataProperty property,
int valueHints, int valueProviders) { int valueHints, int valueProviders) {
assertEquals(valueHints, property.getValueHints().size()); assertThat(property.getValueHints().size()).isEqualTo(valueHints);
assertEquals(valueProviders, property.getValueHints().size()); assertThat(property.getValueHints().size()).isEqualTo(valueProviders);
} }
private void contains(Map<String, ?> source, String... keys) { private void contains(Map<String, ?> source, String... keys) {
for (String key : keys) { for (String key : keys) {
assertTrue("Item '" + key + "' not found. Got " + source.keySet(), assertThat(source).containsKey(key);
source.containsKey(key));
} }
} }

@ -18,7 +18,7 @@ package org.springframework.boot.configurationmetadata;
import org.junit.Test; import org.junit.Test;
import static org.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
/** /**
* Tests for {@link DescriptionExtractor}. * Tests for {@link DescriptionExtractor}.
@ -35,39 +35,39 @@ public class DescriptionExtractorTests {
public void extractShortDescription() { public void extractShortDescription() {
String description = this.extractor String description = this.extractor
.getShortDescription("My short " + "description. More stuff."); .getShortDescription("My short " + "description. More stuff.");
assertEquals("My short description.", description); assertThat(description).isEqualTo("My short description.");
} }
@Test @Test
public void extractShortDescriptionNewLineBeforeDot() { public void extractShortDescriptionNewLineBeforeDot() {
String description = this.extractor.getShortDescription( String description = this.extractor.getShortDescription(
"My short" + NEW_LINE + "description." + NEW_LINE + "More stuff."); "My short" + NEW_LINE + "description." + NEW_LINE + "More stuff.");
assertEquals("My short description.", description); assertThat(description).isEqualTo("My short description.");
} }
@Test @Test
public void extractShortDescriptionNewLineBeforeDotWithSpaces() { public void extractShortDescriptionNewLineBeforeDotWithSpaces() {
String description = this.extractor.getShortDescription( String description = this.extractor.getShortDescription(
"My short " + NEW_LINE + " description. " + NEW_LINE + "More stuff."); "My short " + NEW_LINE + " description. " + NEW_LINE + "More stuff.");
assertEquals("My short description.", description); assertThat(description).isEqualTo("My short description.");
} }
@Test @Test
public void extractShortDescriptionNoDot() { public void extractShortDescriptionNoDot() {
String description = this.extractor.getShortDescription("My short description"); String description = this.extractor.getShortDescription("My short description");
assertEquals("My short description", description); assertThat(description).isEqualTo("My short description");
} }
@Test @Test
public void extractShortDescriptionNoDotMultipleLines() { public void extractShortDescriptionNoDotMultipleLines() {
String description = this.extractor String description = this.extractor
.getShortDescription("My short description " + NEW_LINE + " More stuff"); .getShortDescription("My short description " + NEW_LINE + " More stuff");
assertEquals("My short description", description); assertThat(description).isEqualTo("My short description");
} }
@Test @Test
public void extractShortDescriptionNull() { public void extractShortDescriptionNull() {
assertEquals(null, this.extractor.getShortDescription(null)); assertThat(this.extractor.getShortDescription(null)).isEqualTo(null);
} }
} }

@ -23,10 +23,7 @@ import java.util.List;
import org.json.JSONException; import org.json.JSONException;
import org.junit.Test; import org.junit.Test;
import static org.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
/** /**
* Tests for {@link JsonReader} * Tests for {@link JsonReader}
@ -42,8 +39,8 @@ public class JsonReaderTests extends AbstractConfigurationMetadataTests {
@Test @Test
public void emptyMetadata() throws IOException { public void emptyMetadata() throws IOException {
RawConfigurationMetadata rawMetadata = readFor("empty"); RawConfigurationMetadata rawMetadata = readFor("empty");
assertEquals(0, rawMetadata.getSources().size()); assertThat(rawMetadata.getSources()).isEmpty();
assertEquals(0, rawMetadata.getItems().size()); assertThat(rawMetadata.getItems()).isEmpty();
} }
@Test @Test
@ -56,17 +53,17 @@ public class JsonReaderTests extends AbstractConfigurationMetadataTests {
public void simpleMetadata() throws IOException { public void simpleMetadata() throws IOException {
RawConfigurationMetadata rawMetadata = readFor("foo"); RawConfigurationMetadata rawMetadata = readFor("foo");
List<ConfigurationMetadataSource> sources = rawMetadata.getSources(); List<ConfigurationMetadataSource> sources = rawMetadata.getSources();
assertEquals(2, sources.size()); assertThat(sources).hasSize(2);
List<ConfigurationMetadataItem> items = rawMetadata.getItems(); List<ConfigurationMetadataItem> items = rawMetadata.getItems();
assertEquals(4, items.size()); assertThat(items).hasSize(4);
List<ConfigurationMetadataHint> hints = rawMetadata.getHints(); List<ConfigurationMetadataHint> hints = rawMetadata.getHints();
assertEquals(1, hints.size()); assertThat(hints).hasSize(1);
ConfigurationMetadataSource source = sources.get(0); ConfigurationMetadataSource source = sources.get(0);
assertSource(source, "spring.foo", "org.acme.Foo", "org.acme.config.FooApp"); assertSource(source, "spring.foo", "org.acme.Foo", "org.acme.config.FooApp");
assertEquals("foo()", source.getSourceMethod()); assertThat(source.getSourceMethod()).isEqualTo("foo()");
assertEquals("This is Foo.", source.getDescription()); assertThat(source.getDescription()).isEqualTo("This is Foo.");
assertEquals("This is Foo.", source.getShortDescription()); assertThat(source.getShortDescription()).isEqualTo("This is Foo.");
ConfigurationMetadataItem item = items.get(0); ConfigurationMetadataItem item = items.get(0);
assertProperty(item, "spring.foo.name", "name", String.class, null); assertProperty(item, "spring.foo.name", "name", String.class, null);
@ -74,61 +71,62 @@ public class JsonReaderTests extends AbstractConfigurationMetadataTests {
ConfigurationMetadataItem item2 = items.get(1); ConfigurationMetadataItem item2 = items.get(1);
assertProperty(item2, "spring.foo.description", "description", String.class, assertProperty(item2, "spring.foo.description", "description", String.class,
"FooBar"); "FooBar");
assertEquals("Foo description.", item2.getDescription()); assertThat(item2.getDescription()).isEqualTo("Foo description.");
assertEquals("Foo description.", item2.getShortDescription()); assertThat(item2.getShortDescription()).isEqualTo("Foo description.");
assertNull(item2.getSourceMethod()); assertThat(item2.getSourceMethod()).isNull();
assertItem(item2, "org.acme.Foo"); assertItem(item2, "org.acme.Foo");
ConfigurationMetadataHint hint = hints.get(0); ConfigurationMetadataHint hint = hints.get(0);
assertEquals("spring.foo.counter", hint.getId()); assertThat(hint.getId()).isEqualTo("spring.foo.counter");
assertEquals(1, hint.getValueHints().size()); assertThat(hint.getValueHints()).hasSize(1);
ValueHint valueHint = hint.getValueHints().get(0); ValueHint valueHint = hint.getValueHints().get(0);
assertEquals(42, valueHint.getValue()); assertThat(valueHint.getValue()).isEqualTo(42);
assertEquals("Because that's the answer to any question, choose it. \nReally.", assertThat(valueHint.getDescription()).isEqualTo(
valueHint.getDescription()); "Because that's the answer to any question, choose it. \nReally.");
assertEquals("Because that's the answer to any question, choose it.", assertThat(valueHint.getShortDescription())
valueHint.getShortDescription()); .isEqualTo("Because that's the answer to any question, choose it.");
assertEquals(1, hint.getValueProviders().size()); assertThat(hint.getValueProviders()).hasSize(1);
ValueProvider valueProvider = hint.getValueProviders().get(0); ValueProvider valueProvider = hint.getValueProviders().get(0);
assertEquals("handle-as", valueProvider.getName()); assertThat(valueProvider.getName()).isEqualTo("handle-as");
assertEquals(1, valueProvider.getParameters().size()); assertThat(valueProvider.getParameters()).hasSize(1);
assertEquals(Integer.class.getName(), assertThat(valueProvider.getParameters().get("target"))
valueProvider.getParameters().get("target")); .isEqualTo(Integer.class.getName());
} }
@Test @Test
public void metadataHints() throws IOException { public void metadataHints() throws IOException {
RawConfigurationMetadata rawMetadata = readFor("bar"); RawConfigurationMetadata rawMetadata = readFor("bar");
List<ConfigurationMetadataHint> hints = rawMetadata.getHints(); List<ConfigurationMetadataHint> hints = rawMetadata.getHints();
assertEquals(1, hints.size()); assertThat(hints).hasSize(1);
ConfigurationMetadataHint hint = hints.get(0); ConfigurationMetadataHint hint = hints.get(0);
assertEquals("spring.bar.description", hint.getId()); assertThat(hint.getId()).isEqualTo("spring.bar.description");
assertEquals(2, hint.getValueHints().size()); assertThat(hint.getValueHints()).hasSize(2);
ValueHint valueHint = hint.getValueHints().get(0); ValueHint valueHint = hint.getValueHints().get(0);
assertEquals("one", valueHint.getValue()); assertThat(valueHint.getValue()).isEqualTo("one");
assertEquals("One.", valueHint.getDescription()); assertThat(valueHint.getDescription()).isEqualTo("One.");
ValueHint valueHint2 = hint.getValueHints().get(1); ValueHint valueHint2 = hint.getValueHints().get(1);
assertEquals("two", valueHint2.getValue()); assertThat(valueHint2.getValue()).isEqualTo("two");
assertEquals(null, valueHint2.getDescription()); assertThat(valueHint2.getDescription()).isEqualTo(null);
assertEquals(2, hint.getValueProviders().size()); assertThat(hint.getValueProviders()).hasSize(2);
ValueProvider valueProvider = hint.getValueProviders().get(0); ValueProvider valueProvider = hint.getValueProviders().get(0);
assertEquals("handle-as", valueProvider.getName()); assertThat(valueProvider.getName()).isEqualTo("handle-as");
assertEquals(1, valueProvider.getParameters().size()); assertThat(valueProvider.getParameters()).hasSize(1);
assertEquals(String.class.getName(), valueProvider.getParameters().get("target")); assertThat(valueProvider.getParameters().get("target"))
.isEqualTo(String.class.getName());
ValueProvider valueProvider2 = hint.getValueProviders().get(1); ValueProvider valueProvider2 = hint.getValueProviders().get(1);
assertEquals("any", valueProvider2.getName()); assertThat(valueProvider2.getName()).isEqualTo("any");
assertEquals(0, valueProvider2.getParameters().size()); assertThat(valueProvider2.getParameters()).isEmpty();
} }
@Test @Test
public void rootMetadata() throws IOException { public void rootMetadata() throws IOException {
RawConfigurationMetadata rawMetadata = readFor("root"); RawConfigurationMetadata rawMetadata = readFor("root");
List<ConfigurationMetadataSource> sources = rawMetadata.getSources(); List<ConfigurationMetadataSource> sources = rawMetadata.getSources();
assertEquals(0, sources.size()); assertThat(sources).isEmpty();
List<ConfigurationMetadataItem> items = rawMetadata.getItems(); List<ConfigurationMetadataItem> items = rawMetadata.getItems();
assertEquals(2, items.size()); assertThat(items).hasSize(2);
ConfigurationMetadataItem item = items.get(0); ConfigurationMetadataItem item = items.get(0);
assertProperty(item, "spring.root.name", "spring.root.name", String.class, null); assertProperty(item, "spring.root.name", "spring.root.name", String.class, null);
} }
@ -137,27 +135,28 @@ public class JsonReaderTests extends AbstractConfigurationMetadataTests {
public void deprecatedMetadata() throws IOException { public void deprecatedMetadata() throws IOException {
RawConfigurationMetadata rawMetadata = readFor("deprecated"); RawConfigurationMetadata rawMetadata = readFor("deprecated");
List<ConfigurationMetadataItem> items = rawMetadata.getItems(); List<ConfigurationMetadataItem> items = rawMetadata.getItems();
assertEquals(3, items.size()); assertThat(items).hasSize(3);
ConfigurationMetadataItem item = items.get(0); ConfigurationMetadataItem item = items.get(0);
assertProperty(item, "server.port", "server.port", Integer.class, null); assertProperty(item, "server.port", "server.port", Integer.class, null);
assertTrue(item.isDeprecated()); assertThat(item.isDeprecated()).isTrue();
assertEquals("Server namespace has moved to spring.server", assertThat(item.getDeprecation().getReason())
item.getDeprecation().getReason()); .isEqualTo("Server namespace has moved to spring.server");
assertEquals("server.spring.port", item.getDeprecation().getReplacement()); assertThat(item.getDeprecation().getReplacement())
.isEqualTo("server.spring.port");
ConfigurationMetadataItem item2 = items.get(1); ConfigurationMetadataItem item2 = items.get(1);
assertProperty(item2, "server.cluster-name", "server.cluster-name", String.class, assertProperty(item2, "server.cluster-name", "server.cluster-name", String.class,
null); null);
assertTrue(item2.isDeprecated()); assertThat(item2.isDeprecated()).isTrue();
assertEquals(null, item2.getDeprecation().getReason()); assertThat(item2.getDeprecation().getReason()).isEqualTo(null);
assertEquals(null, item2.getDeprecation().getReplacement()); assertThat(item2.getDeprecation().getReplacement()).isEqualTo(null);
ConfigurationMetadataItem item3 = items.get(2); ConfigurationMetadataItem item3 = items.get(2);
assertProperty(item3, "spring.server.name", "spring.server.name", String.class, assertProperty(item3, "spring.server.name", "spring.server.name", String.class,
null); null);
assertFalse(item3.isDeprecated()); assertThat(item3.isDeprecated()).isFalse();
assertEquals(null, item3.getDeprecation()); assertThat(item3.getDeprecation()).isEqualTo(null);
} }
RawConfigurationMetadata readFor(String path) throws IOException { RawConfigurationMetadata readFor(String path) throws IOException {

@ -63,16 +63,7 @@ import org.springframework.boot.configurationsample.specific.InnerClassRootConfi
import org.springframework.boot.configurationsample.specific.SimplePojo; import org.springframework.boot.configurationsample.specific.SimplePojo;
import org.springframework.util.FileCopyUtils; import org.springframework.util.FileCopyUtils;
import static org.hamcrest.CoreMatchers.is; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.not;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.springframework.boot.configurationprocessor.ConfigurationMetadataMatchers.containsGroup;
import static org.springframework.boot.configurationprocessor.ConfigurationMetadataMatchers.containsHint;
import static org.springframework.boot.configurationprocessor.ConfigurationMetadataMatchers.containsProperty;
/** /**
* Tests for {@link ConfigurationMetadataAnnotationProcessor}. * Tests for {@link ConfigurationMetadataAnnotationProcessor}.
@ -100,80 +91,88 @@ public class ConfigurationMetadataAnnotationProcessorTests {
@Test @Test
public void notAnnotated() throws Exception { public void notAnnotated() throws Exception {
ConfigurationMetadata metadata = compile(NotAnnotated.class); ConfigurationMetadata metadata = compile(NotAnnotated.class);
assertThat("No config metadata file should have been generated when " assertThat(metadata.getItems()).isEmpty();
+ "no metadata is discovered", metadata.getItems(), empty());
} }
@Test @Test
public void simpleProperties() throws Exception { public void simpleProperties() throws Exception {
ConfigurationMetadata metadata = compile(SimpleProperties.class); ConfigurationMetadata metadata = compile(SimpleProperties.class);
assertThat(metadata, containsGroup("simple").fromSource(SimpleProperties.class)); assertThat(metadata)
assertThat(metadata, .has(Metadata.withGroup("simple").fromSource(SimpleProperties.class));
containsProperty("simple.the-name", String.class) assertThat(metadata).has(Metadata.withProperty("simple.the-name", String.class)
.fromSource(SimpleProperties.class) .fromSource(SimpleProperties.class)
.withDescription("The name of this simple properties.") .withDescription("The name of this simple properties.")
.withDefaultValue(is("boot")).withDeprecation(null, null)); .withDefaultValue("boot").withDeprecation(null, null));
assertThat(metadata, assertThat(metadata).has(Metadata.withProperty("simple.flag", Boolean.class)
containsProperty("simple.flag", Boolean.class) .fromSource(SimpleProperties.class).withDescription("A simple flag.")
.fromSource(SimpleProperties.class) .withDeprecation(null, null));
.withDescription("A simple flag.").withDeprecation(null, null)); assertThat(metadata).has(Metadata.withProperty("simple.comparator"));
assertThat(metadata, containsProperty("simple.comparator")); assertThat(metadata).doesNotHave(Metadata.withProperty("simple.counter"));
assertThat(metadata, not(containsProperty("simple.counter"))); assertThat(metadata).doesNotHave(Metadata.withProperty("simple.size"));
assertThat(metadata, not(containsProperty("simple.size")));
} }
@Test @Test
public void simplePrefixValueProperties() throws Exception { public void simplePrefixValueProperties() throws Exception {
ConfigurationMetadata metadata = compile(SimplePrefixValueProperties.class); ConfigurationMetadata metadata = compile(SimplePrefixValueProperties.class);
assertThat(metadata, assertThat(metadata).has(Metadata.withGroup("simple")
containsGroup("simple").fromSource(SimplePrefixValueProperties.class)); .fromSource(SimplePrefixValueProperties.class));
assertThat(metadata, containsProperty("simple.name", String.class) assertThat(metadata).has(Metadata.withProperty("simple.name", String.class)
.fromSource(SimplePrefixValueProperties.class)); .fromSource(SimplePrefixValueProperties.class));
} }
@Test @Test
public void simpleTypeProperties() throws Exception { public void simpleTypeProperties() throws Exception {
ConfigurationMetadata metadata = compile(SimpleTypeProperties.class); ConfigurationMetadata metadata = compile(SimpleTypeProperties.class);
assertThat(metadata, assertThat(metadata).has(
containsGroup("simple.type").fromSource(SimpleTypeProperties.class)); Metadata.withGroup("simple.type").fromSource(SimpleTypeProperties.class));
assertThat(metadata, containsProperty("simple.type.my-string", String.class)); assertThat(metadata)
assertThat(metadata, containsProperty("simple.type.my-byte", Byte.class)); .has(Metadata.withProperty("simple.type.my-string", String.class));
assertThat(metadata, assertThat(metadata)
containsProperty("simple.type.my-primitive-byte", Byte.class)); .has(Metadata.withProperty("simple.type.my-byte", Byte.class));
assertThat(metadata, containsProperty("simple.type.my-char", Character.class)); assertThat(metadata)
assertThat(metadata, .has(Metadata.withProperty("simple.type.my-primitive-byte", Byte.class));
containsProperty("simple.type.my-primitive-char", Character.class)); assertThat(metadata)
assertThat(metadata, containsProperty("simple.type.my-boolean", Boolean.class)); .has(Metadata.withProperty("simple.type.my-char", Character.class));
assertThat(metadata, assertThat(metadata).has(
containsProperty("simple.type.my-primitive-boolean", Boolean.class)); Metadata.withProperty("simple.type.my-primitive-char", Character.class));
assertThat(metadata, containsProperty("simple.type.my-short", Short.class)); assertThat(metadata)
assertThat(metadata, .has(Metadata.withProperty("simple.type.my-boolean", Boolean.class));
containsProperty("simple.type.my-primitive-short", Short.class)); assertThat(metadata).has(
assertThat(metadata, containsProperty("simple.type.my-integer", Integer.class)); Metadata.withProperty("simple.type.my-primitive-boolean", Boolean.class));
assertThat(metadata, assertThat(metadata)
containsProperty("simple.type.my-primitive-integer", Integer.class)); .has(Metadata.withProperty("simple.type.my-short", Short.class));
assertThat(metadata, containsProperty("simple.type.my-long", Long.class)); assertThat(metadata).has(
assertThat(metadata, Metadata.withProperty("simple.type.my-primitive-short", Short.class));
containsProperty("simple.type.my-primitive-long", Long.class)); assertThat(metadata)
assertThat(metadata, containsProperty("simple.type.my-double", Double.class)); .has(Metadata.withProperty("simple.type.my-integer", Integer.class));
assertThat(metadata, assertThat(metadata).has(
containsProperty("simple.type.my-primitive-double", Double.class)); Metadata.withProperty("simple.type.my-primitive-integer", Integer.class));
assertThat(metadata, containsProperty("simple.type.my-float", Float.class)); assertThat(metadata)
assertThat(metadata, .has(Metadata.withProperty("simple.type.my-long", Long.class));
containsProperty("simple.type.my-primitive-float", Float.class)); assertThat(metadata)
assertThat(metadata.getItems().size(), equalTo(18)); .has(Metadata.withProperty("simple.type.my-primitive-long", Long.class));
assertThat(metadata)
.has(Metadata.withProperty("simple.type.my-double", Double.class));
assertThat(metadata).has(
Metadata.withProperty("simple.type.my-primitive-double", Double.class));
assertThat(metadata)
.has(Metadata.withProperty("simple.type.my-float", Float.class));
assertThat(metadata).has(
Metadata.withProperty("simple.type.my-primitive-float", Float.class));
assertThat(metadata.getItems().size()).isEqualTo(18);
} }
@Test @Test
public void hierarchicalProperties() throws Exception { public void hierarchicalProperties() throws Exception {
ConfigurationMetadata metadata = compile(HierarchicalProperties.class); ConfigurationMetadata metadata = compile(HierarchicalProperties.class);
assertThat(metadata, assertThat(metadata).has(Metadata.withGroup("hierarchical")
containsGroup("hierarchical").fromSource(HierarchicalProperties.class));
assertThat(metadata, containsProperty("hierarchical.first", String.class)
.fromSource(HierarchicalProperties.class)); .fromSource(HierarchicalProperties.class));
assertThat(metadata, containsProperty("hierarchical.second", String.class) assertThat(metadata).has(Metadata.withProperty("hierarchical.first", String.class)
.fromSource(HierarchicalProperties.class)); .fromSource(HierarchicalProperties.class));
assertThat(metadata, containsProperty("hierarchical.third", String.class) assertThat(metadata)
.has(Metadata.withProperty("hierarchical.second", String.class)
.fromSource(HierarchicalProperties.class));
assertThat(metadata).has(Metadata.withProperty("hierarchical.third", String.class)
.fromSource(HierarchicalProperties.class)); .fromSource(HierarchicalProperties.class));
} }
@ -182,152 +181,157 @@ public class ConfigurationMetadataAnnotationProcessorTests {
public void deprecatedProperties() throws Exception { public void deprecatedProperties() throws Exception {
Class<?> type = org.springframework.boot.configurationsample.simple.DeprecatedProperties.class; Class<?> type = org.springframework.boot.configurationsample.simple.DeprecatedProperties.class;
ConfigurationMetadata metadata = compile(type); ConfigurationMetadata metadata = compile(type);
assertThat(metadata, containsGroup("deprecated").fromSource(type)); assertThat(metadata).has(Metadata.withGroup("deprecated").fromSource(type));
assertThat(metadata, containsProperty("deprecated.name", String.class) assertThat(metadata).has(Metadata.withProperty("deprecated.name", String.class)
.fromSource(type).withDeprecation(null, null));
assertThat(metadata, containsProperty("deprecated.description", String.class)
.fromSource(type).withDeprecation(null, null)); .fromSource(type).withDeprecation(null, null));
assertThat(metadata)
.has(Metadata.withProperty("deprecated.description", String.class)
.fromSource(type).withDeprecation(null, null));
} }
@Test @Test
public void singleDeprecatedProperty() throws Exception { public void singleDeprecatedProperty() throws Exception {
Class<?> type = DeprecatedSingleProperty.class; Class<?> type = DeprecatedSingleProperty.class;
ConfigurationMetadata metadata = compile(type); ConfigurationMetadata metadata = compile(type);
assertThat(metadata, containsGroup("singledeprecated").fromSource(type)); assertThat(metadata).has(Metadata.withGroup("singledeprecated").fromSource(type));
assertThat(metadata, containsProperty("singledeprecated.new-name", String.class) assertThat(metadata)
.fromSource(type)); .has(Metadata.withProperty("singledeprecated.new-name", String.class)
assertThat(metadata, .fromSource(type));
containsProperty("singledeprecated.name", String.class).fromSource(type) assertThat(metadata).has(Metadata
.withDeprecation("renamed", "singledeprecated.new-name")); .withProperty("singledeprecated.name", String.class).fromSource(type)
.withDeprecation("renamed", "singledeprecated.new-name"));
} }
@Test @Test
public void deprecatedOnUnrelatedSetter() throws Exception { public void deprecatedOnUnrelatedSetter() throws Exception {
Class<?> type = DeprecatedUnrelatedMethodPojo.class; Class<?> type = DeprecatedUnrelatedMethodPojo.class;
ConfigurationMetadata metadata = compile(type); ConfigurationMetadata metadata = compile(type);
assertThat(metadata, containsGroup("not.deprecated").fromSource(type)); assertThat(metadata).has(Metadata.withGroup("not.deprecated").fromSource(type));
assertThat(metadata, containsProperty("not.deprecated.counter", Integer.class) assertThat(metadata)
.withNoDeprecation().fromSource(type)); .has(Metadata.withProperty("not.deprecated.counter", Integer.class)
assertThat(metadata, containsProperty("not.deprecated.flag", Boolean.class) .withNoDeprecation().fromSource(type));
.withNoDeprecation().fromSource(type)); assertThat(metadata)
.has(Metadata.withProperty("not.deprecated.flag", Boolean.class)
.withNoDeprecation().fromSource(type));
} }
@Test @Test
public void boxingOnSetter() throws IOException { public void boxingOnSetter() throws IOException {
Class<?> type = BoxingPojo.class; Class<?> type = BoxingPojo.class;
ConfigurationMetadata metadata = compile(type); ConfigurationMetadata metadata = compile(type);
assertThat(metadata, containsGroup("boxing").fromSource(type)); assertThat(metadata).has(Metadata.withGroup("boxing").fromSource(type));
assertThat(metadata, assertThat(metadata).has(
containsProperty("boxing.flag", Boolean.class).fromSource(type)); Metadata.withProperty("boxing.flag", Boolean.class).fromSource(type));
assertThat(metadata, assertThat(metadata).has(
containsProperty("boxing.counter", Integer.class).fromSource(type)); Metadata.withProperty("boxing.counter", Integer.class).fromSource(type));
} }
@Test @Test
public void parseCollectionConfig() throws Exception { public void parseCollectionConfig() throws Exception {
ConfigurationMetadata metadata = compile(SimpleCollectionProperties.class); ConfigurationMetadata metadata = compile(SimpleCollectionProperties.class);
// getter and setter // getter and setter
assertThat(metadata, containsProperty("collection.integers-to-names", assertThat(metadata).has(Metadata.withProperty("collection.integers-to-names",
"java.util.Map<java.lang.Integer,java.lang.String>")); "java.util.Map<java.lang.Integer,java.lang.String>"));
assertThat(metadata, containsProperty("collection.longs", assertThat(metadata).has(Metadata.withProperty("collection.longs",
"java.util.Collection<java.lang.Long>")); "java.util.Collection<java.lang.Long>"));
assertThat(metadata, assertThat(metadata).has(Metadata.withProperty("collection.floats",
containsProperty("collection.floats", "java.util.List<java.lang.Float>")); "java.util.List<java.lang.Float>"));
// getter only // getter only
assertThat(metadata, containsProperty("collection.names-to-integers", assertThat(metadata).has(Metadata.withProperty("collection.names-to-integers",
"java.util.Map<java.lang.String,java.lang.Integer>")); "java.util.Map<java.lang.String,java.lang.Integer>"));
assertThat(metadata, containsProperty("collection.bytes", assertThat(metadata).has(Metadata.withProperty("collection.bytes",
"java.util.Collection<java.lang.Byte>")); "java.util.Collection<java.lang.Byte>"));
assertThat(metadata, containsProperty("collection.doubles", assertThat(metadata).has(Metadata.withProperty("collection.doubles",
"java.util.List<java.lang.Double>")); "java.util.List<java.lang.Double>"));
} }
@Test @Test
public void simpleMethodConfig() throws Exception { public void simpleMethodConfig() throws Exception {
ConfigurationMetadata metadata = compile(SimpleMethodConfig.class); ConfigurationMetadata metadata = compile(SimpleMethodConfig.class);
assertThat(metadata, containsGroup("foo").fromSource(SimpleMethodConfig.class)); assertThat(metadata)
assertThat(metadata, containsProperty("foo.name", String.class) .has(Metadata.withGroup("foo").fromSource(SimpleMethodConfig.class));
assertThat(metadata).has(Metadata.withProperty("foo.name", String.class)
.fromSource(SimpleMethodConfig.Foo.class)); .fromSource(SimpleMethodConfig.Foo.class));
assertThat(metadata, containsProperty("foo.flag", Boolean.class) assertThat(metadata).has(Metadata.withProperty("foo.flag", Boolean.class)
.fromSource(SimpleMethodConfig.Foo.class)); .fromSource(SimpleMethodConfig.Foo.class));
} }
@Test @Test
public void invalidMethodConfig() throws Exception { public void invalidMethodConfig() throws Exception {
ConfigurationMetadata metadata = compile(InvalidMethodConfig.class); ConfigurationMetadata metadata = compile(InvalidMethodConfig.class);
assertThat(metadata, containsProperty("something.name", String.class) assertThat(metadata).has(Metadata.withProperty("something.name", String.class)
.fromSource(InvalidMethodConfig.class)); .fromSource(InvalidMethodConfig.class));
assertThat(metadata, not(containsProperty("invalid.name"))); assertThat(metadata).isNotEqualTo(Metadata.withProperty("invalid.name"));
} }
@Test @Test
public void methodAndClassConfig() throws Exception { public void methodAndClassConfig() throws Exception {
ConfigurationMetadata metadata = compile(MethodAndClassConfig.class); ConfigurationMetadata metadata = compile(MethodAndClassConfig.class);
assertThat(metadata, containsProperty("conflict.name", String.class) assertThat(metadata).has(Metadata.withProperty("conflict.name", String.class)
.fromSource(MethodAndClassConfig.Foo.class)); .fromSource(MethodAndClassConfig.Foo.class));
assertThat(metadata, containsProperty("conflict.flag", Boolean.class) assertThat(metadata).has(Metadata.withProperty("conflict.flag", Boolean.class)
.fromSource(MethodAndClassConfig.Foo.class)); .fromSource(MethodAndClassConfig.Foo.class));
assertThat(metadata, containsProperty("conflict.value", String.class) assertThat(metadata).has(Metadata.withProperty("conflict.value", String.class)
.fromSource(MethodAndClassConfig.class)); .fromSource(MethodAndClassConfig.class));
} }
@Test @Test
public void emptyTypeMethodConfig() throws Exception { public void emptyTypeMethodConfig() throws Exception {
ConfigurationMetadata metadata = compile(EmptyTypeMethodConfig.class); ConfigurationMetadata metadata = compile(EmptyTypeMethodConfig.class);
assertThat(metadata, not(containsProperty("something.foo"))); assertThat(metadata).isNotEqualTo(Metadata.withProperty("something.foo"));
} }
@Test @Test
public void innerClassRootConfig() throws Exception { public void innerClassRootConfig() throws Exception {
ConfigurationMetadata metadata = compile(InnerClassRootConfig.class); ConfigurationMetadata metadata = compile(InnerClassRootConfig.class);
assertThat(metadata, containsProperty("config.name")); assertThat(metadata).has(Metadata.withProperty("config.name"));
} }
@Test @Test
public void innerClassProperties() throws Exception { public void innerClassProperties() throws Exception {
ConfigurationMetadata metadata = compile(InnerClassProperties.class); ConfigurationMetadata metadata = compile(InnerClassProperties.class);
assertThat(metadata, assertThat(metadata)
containsGroup("config").fromSource(InnerClassProperties.class)); .has(Metadata.withGroup("config").fromSource(InnerClassProperties.class));
assertThat(metadata, assertThat(metadata).has(
containsGroup("config.first").ofType(InnerClassProperties.Foo.class) Metadata.withGroup("config.first").ofType(InnerClassProperties.Foo.class)
.fromSource(InnerClassProperties.class)); .fromSource(InnerClassProperties.class));
assertThat(metadata, containsProperty("config.first.name")); assertThat(metadata).has(Metadata.withProperty("config.first.name"));
assertThat(metadata, containsProperty("config.first.bar.name")); assertThat(metadata).has(Metadata.withProperty("config.first.bar.name"));
assertThat(metadata, assertThat(metadata).has(
containsGroup("config.the-second", InnerClassProperties.Foo.class) Metadata.withGroup("config.the-second", InnerClassProperties.Foo.class)
.fromSource(InnerClassProperties.class)); .fromSource(InnerClassProperties.class));
assertThat(metadata, containsProperty("config.the-second.name")); assertThat(metadata).has(Metadata.withProperty("config.the-second.name"));
assertThat(metadata, containsProperty("config.the-second.bar.name")); assertThat(metadata).has(Metadata.withProperty("config.the-second.bar.name"));
assertThat(metadata, containsGroup("config.third").ofType(SimplePojo.class) assertThat(metadata).has(Metadata.withGroup("config.third")
.fromSource(InnerClassProperties.class)); .ofType(SimplePojo.class).fromSource(InnerClassProperties.class));
assertThat(metadata, containsProperty("config.third.value")); assertThat(metadata).has(Metadata.withProperty("config.third.value"));
assertThat(metadata, containsProperty("config.fourth")); assertThat(metadata).has(Metadata.withProperty("config.fourth"));
assertThat(metadata, not(containsGroup("config.fourth"))); assertThat(metadata).isNotEqualTo(Metadata.withGroup("config.fourth"));
} }
@Test @Test
public void innerClassAnnotatedGetterConfig() throws Exception { public void innerClassAnnotatedGetterConfig() throws Exception {
ConfigurationMetadata metadata = compile(InnerClassAnnotatedGetterConfig.class); ConfigurationMetadata metadata = compile(InnerClassAnnotatedGetterConfig.class);
assertThat(metadata, containsProperty("specific.value")); assertThat(metadata).has(Metadata.withProperty("specific.value"));
assertThat(metadata, containsProperty("foo.name")); assertThat(metadata).has(Metadata.withProperty("foo.name"));
assertThat(metadata, not(containsProperty("specific.foo"))); assertThat(metadata).isNotEqualTo(Metadata.withProperty("specific.foo"));
} }
@Test @Test
public void builderPojo() throws IOException { public void builderPojo() throws IOException {
ConfigurationMetadata metadata = compile(BuilderPojo.class); ConfigurationMetadata metadata = compile(BuilderPojo.class);
assertThat(metadata, containsProperty("builder.name")); assertThat(metadata).has(Metadata.withProperty("builder.name"));
} }
@Test @Test
public void excludedTypesPojo() throws IOException { public void excludedTypesPojo() throws IOException {
ConfigurationMetadata metadata = compile(ExcludedTypesPojo.class); ConfigurationMetadata metadata = compile(ExcludedTypesPojo.class);
assertThat(metadata, containsProperty("excluded.name")); assertThat(metadata).has(Metadata.withProperty("excluded.name"));
assertThat(metadata, not(containsProperty("excluded.class-loader"))); assertThat(metadata).isNotEqualTo(Metadata.withProperty("excluded.class-loader"));
assertThat(metadata, not(containsProperty("excluded.data-source"))); assertThat(metadata).isNotEqualTo(Metadata.withProperty("excluded.data-source"));
assertThat(metadata, not(containsProperty("excluded.print-writer"))); assertThat(metadata).isNotEqualTo(Metadata.withProperty("excluded.print-writer"));
assertThat(metadata, not(containsProperty("excluded.writer"))); assertThat(metadata).isNotEqualTo(Metadata.withProperty("excluded.writer"));
assertThat(metadata, not(containsProperty("excluded.writer-array"))); assertThat(metadata).isNotEqualTo(Metadata.withProperty("excluded.writer-array"));
} }
@Test @Test
@ -352,28 +356,29 @@ public class ConfigurationMetadataAnnotationProcessorTests {
@Test @Test
public void lombokInnerClassProperties() throws Exception { public void lombokInnerClassProperties() throws Exception {
ConfigurationMetadata metadata = compile(LombokInnerClassProperties.class); ConfigurationMetadata metadata = compile(LombokInnerClassProperties.class);
assertThat(metadata, assertThat(metadata).has(Metadata.withGroup("config")
containsGroup("config").fromSource(LombokInnerClassProperties.class)); .fromSource(LombokInnerClassProperties.class));
assertThat(metadata, assertThat(metadata).has(Metadata.withGroup("config.first")
containsGroup("config.first").ofType(LombokInnerClassProperties.Foo.class) .ofType(LombokInnerClassProperties.Foo.class)
.fromSource(LombokInnerClassProperties.class));
assertThat(metadata).has(Metadata.withProperty("config.first.name"));
assertThat(metadata).has(Metadata.withProperty("config.first.bar.name"));
assertThat(metadata).has(
Metadata.withGroup("config.second", LombokInnerClassProperties.Foo.class)
.fromSource(LombokInnerClassProperties.class)); .fromSource(LombokInnerClassProperties.class));
assertThat(metadata, containsProperty("config.first.name")); assertThat(metadata).has(Metadata.withProperty("config.second.name"));
assertThat(metadata, containsProperty("config.first.bar.name")); assertThat(metadata).has(Metadata.withProperty("config.second.bar.name"));
assertThat(metadata, assertThat(metadata)
containsGroup("config.second", LombokInnerClassProperties.Foo.class) .has(Metadata.withGroup("config.third").ofType(SimpleLombokPojo.class)
.fromSource(LombokInnerClassProperties.class)); .fromSource(LombokInnerClassProperties.class));
assertThat(metadata, containsProperty("config.second.name"));
assertThat(metadata, containsProperty("config.second.bar.name"));
assertThat(metadata, containsGroup("config.third").ofType(SimpleLombokPojo.class)
.fromSource(LombokInnerClassProperties.class));
// For some reason the annotation processor resolves a type for SimpleLombokPojo // For some reason the annotation processor resolves a type for SimpleLombokPojo
// that is resolved (compiled) and the source annotations are gone. Because we // that is resolved (compiled) and the source annotations are gone. Because we
// don't see the @Data annotation anymore, no field is harvested. What is crazy is // don't see the @Data annotation anymore, no field is harvested. What is crazy is
// that a sample project works fine so this seem to be related to the unit test // that a sample project works fine so this seem to be related to the unit test
// environment for some reason. assertThat(metadata, // environment for some reason. assertThat(metadata,
// containsProperty("config.third.value")); // containsProperty("config.third.value"));
assertThat(metadata, containsProperty("config.fourth")); assertThat(metadata).has(Metadata.withProperty("config.fourth"));
assertThat(metadata, not(containsGroup("config.fourth"))); assertThat(metadata).isNotEqualTo(Metadata.withGroup("config.fourth"));
} }
@Test @Test
@ -382,8 +387,8 @@ public class ConfigurationMetadataAnnotationProcessorTests {
AdditionalMetadata.class.getName(), null, null, null, null); AdditionalMetadata.class.getName(), null, null, null, null);
writeAdditionalMetadata(property); writeAdditionalMetadata(property);
ConfigurationMetadata metadata = compile(SimpleProperties.class); ConfigurationMetadata metadata = compile(SimpleProperties.class);
assertThat(metadata, containsProperty("simple.comparator")); assertThat(metadata).has(Metadata.withProperty("simple.comparator"));
assertThat(metadata, containsProperty("foo", String.class) assertThat(metadata).has(Metadata.withProperty("foo", String.class)
.fromSource(AdditionalMetadata.class)); .fromSource(AdditionalMetadata.class));
} }
@ -393,10 +398,10 @@ public class ConfigurationMetadataAnnotationProcessorTests {
null, null, true, null); null, null, true, null);
writeAdditionalMetadata(property); writeAdditionalMetadata(property);
ConfigurationMetadata metadata = compile(SimpleProperties.class); ConfigurationMetadata metadata = compile(SimpleProperties.class);
assertThat(metadata, containsProperty("simple.flag", Boolean.class) assertThat(metadata).has(Metadata.withProperty("simple.flag", Boolean.class)
.fromSource(SimpleProperties.class).withDescription("A simple flag.") .fromSource(SimpleProperties.class).withDescription("A simple flag.")
.withDeprecation(null, null).withDefaultValue(is(true))); .withDeprecation(null, null).withDefaultValue(true));
assertThat(metadata.getItems().size(), is(4)); assertThat(metadata.getItems()).hasSize(4);
} }
@Test @Test
@ -405,11 +410,11 @@ public class ConfigurationMetadataAnnotationProcessorTests {
null, null, "A nice comparator.", null, null); null, null, "A nice comparator.", null, null);
writeAdditionalMetadata(property); writeAdditionalMetadata(property);
ConfigurationMetadata metadata = compile(SimpleProperties.class); ConfigurationMetadata metadata = compile(SimpleProperties.class);
assertThat(metadata, assertThat(metadata)
containsProperty("simple.comparator", "java.util.Comparator<?>") .has(Metadata.withProperty("simple.comparator", "java.util.Comparator<?>")
.fromSource(SimpleProperties.class) .fromSource(SimpleProperties.class)
.withDescription("A nice comparator.")); .withDescription("A nice comparator."));
assertThat(metadata.getItems().size(), is(4)); assertThat(metadata.getItems()).hasSize(4);
} }
@Test @Test
@ -419,11 +424,11 @@ public class ConfigurationMetadataAnnotationProcessorTests {
new ItemDeprecation("Don't use this.", "simple.complex-comparator")); new ItemDeprecation("Don't use this.", "simple.complex-comparator"));
writeAdditionalMetadata(property); writeAdditionalMetadata(property);
ConfigurationMetadata metadata = compile(SimpleProperties.class); ConfigurationMetadata metadata = compile(SimpleProperties.class);
assertThat(metadata, assertThat(metadata)
containsProperty("simple.comparator", "java.util.Comparator<?>") .has(Metadata.withProperty("simple.comparator", "java.util.Comparator<?>")
.fromSource(SimpleProperties.class) .fromSource(SimpleProperties.class)
.withDeprecation("Don't use this.", "simple.complex-comparator")); .withDeprecation("Don't use this.", "simple.complex-comparator"));
assertThat(metadata.getItems().size(), is(4)); assertThat(metadata.getItems()).hasSize(4);
} }
@Test @Test
@ -433,11 +438,11 @@ public class ConfigurationMetadataAnnotationProcessorTests {
new ItemDeprecation("Don't use this.", "single.name")); new ItemDeprecation("Don't use this.", "single.name"));
writeAdditionalMetadata(property); writeAdditionalMetadata(property);
ConfigurationMetadata metadata = compile(DeprecatedSingleProperty.class); ConfigurationMetadata metadata = compile(DeprecatedSingleProperty.class);
assertThat(metadata, assertThat(metadata).has(
containsProperty("singledeprecated.name", String.class.getName()) Metadata.withProperty("singledeprecated.name", String.class.getName())
.fromSource(DeprecatedSingleProperty.class) .fromSource(DeprecatedSingleProperty.class)
.withDeprecation("Don't use this.", "single.name")); .withDeprecation("Don't use this.", "single.name"));
assertThat(metadata.getItems().size(), is(3)); assertThat(metadata.getItems()).hasSize(3);
} }
@Test @Test
@ -456,12 +461,11 @@ public class ConfigurationMetadataAnnotationProcessorTests {
new ItemHint.ValueHint("boot", "Bla bla"), new ItemHint.ValueHint("boot", "Bla bla"),
new ItemHint.ValueHint("spring", null))); new ItemHint.ValueHint("spring", null)));
ConfigurationMetadata metadata = compile(SimpleProperties.class); ConfigurationMetadata metadata = compile(SimpleProperties.class);
assertThat(metadata, assertThat(metadata).has(Metadata.withProperty("simple.the-name", String.class)
containsProperty("simple.the-name", String.class) .fromSource(SimpleProperties.class)
.fromSource(SimpleProperties.class) .withDescription("The name of this simple properties.")
.withDescription("The name of this simple properties.") .withDefaultValue("boot").withDeprecation(null, null));
.withDefaultValue(is("boot")).withDeprecation(null, null)); assertThat(metadata).has(Metadata.withHint("simple.the-name")
assertThat(metadata, containsHint("simple.the-name")
.withValue(0, "boot", "Bla bla").withValue(1, "spring", null)); .withValue(0, "boot", "Bla bla").withValue(1, "spring", null));
} }
@ -470,13 +474,12 @@ public class ConfigurationMetadataAnnotationProcessorTests {
writeAdditionalHints(ItemHint.newHint("simple.theName", writeAdditionalHints(ItemHint.newHint("simple.theName",
new ItemHint.ValueHint("boot", "Bla bla"))); new ItemHint.ValueHint("boot", "Bla bla")));
ConfigurationMetadata metadata = compile(SimpleProperties.class); ConfigurationMetadata metadata = compile(SimpleProperties.class);
assertThat(metadata, assertThat(metadata).has(Metadata.withProperty("simple.the-name", String.class)
containsProperty("simple.the-name", String.class) .fromSource(SimpleProperties.class)
.fromSource(SimpleProperties.class) .withDescription("The name of this simple properties.")
.withDescription("The name of this simple properties.") .withDefaultValue("boot").withDeprecation(null, null));
.withDefaultValue(is("boot")).withDeprecation(null, null)); assertThat(metadata).has(
assertThat(metadata, Metadata.withHint("simple.the-name").withValue(0, "boot", "Bla bla"));
containsHint("simple.the-name").withValue(0, "boot", "Bla bla"));
} }
@Test @Test
@ -489,12 +492,11 @@ public class ConfigurationMetadataAnnotationProcessorTests {
"org.foo")), "org.foo")),
new ItemHint.ValueProvider("second", null)))); new ItemHint.ValueProvider("second", null))));
ConfigurationMetadata metadata = compile(SimpleProperties.class); ConfigurationMetadata metadata = compile(SimpleProperties.class);
assertThat(metadata, assertThat(metadata).has(Metadata.withProperty("simple.the-name", String.class)
containsProperty("simple.the-name", String.class) .fromSource(SimpleProperties.class)
.fromSource(SimpleProperties.class) .withDescription("The name of this simple properties.")
.withDescription("The name of this simple properties.") .withDefaultValue("boot").withDeprecation(null, null));
.withDefaultValue(is("boot")).withDeprecation(null, null)); assertThat(metadata).has(Metadata.withHint("simple.the-name")
assertThat(metadata, containsHint("simple.the-name")
.withProvider("first", "target", "org.foo").withProvider("second")); .withProvider("first", "target", "org.foo").withProvider("second"));
} }
@ -504,7 +506,7 @@ public class ConfigurationMetadataAnnotationProcessorTests {
"java.lang.String", null, null, null, null, "java.lang.String", null, null, null, null,
new ItemDeprecation("Lame name.", "simple.the-name"))); new ItemDeprecation("Lame name.", "simple.the-name")));
ConfigurationMetadata metadata = compile(SimpleProperties.class); ConfigurationMetadata metadata = compile(SimpleProperties.class);
assertThat(metadata, containsProperty("simple.wrong-name", String.class) assertThat(metadata).has(Metadata.withProperty("simple.wrong-name", String.class)
.withDeprecation("Lame name.", "simple.the-name")); .withDeprecation("Lame name.", "simple.the-name"));
} }
@ -527,8 +529,8 @@ public class ConfigurationMetadataAnnotationProcessorTests {
additionalMetadata.write(writer); additionalMetadata.write(writer);
writer.flush(); writer.flush();
ConfigurationMetadata metadata = compile(SimpleProperties.class); ConfigurationMetadata metadata = compile(SimpleProperties.class);
assertThat(metadata, containsProperty("simple.comparator")); assertThat(metadata).has(Metadata.withProperty("simple.comparator"));
assertThat(metadata, containsProperty("foo", String.class) assertThat(metadata).has(Metadata.withProperty("foo", String.class)
.fromSource(AdditionalMetadata.class)); .fromSource(AdditionalMetadata.class));
} }
@ -536,29 +538,29 @@ public class ConfigurationMetadataAnnotationProcessorTests {
public void incrementalBuild() throws Exception { public void incrementalBuild() throws Exception {
TestProject project = new TestProject(this.temporaryFolder, FooProperties.class, TestProject project = new TestProject(this.temporaryFolder, FooProperties.class,
BarProperties.class); BarProperties.class);
assertFalse(project.getOutputFile(MetadataStore.METADATA_PATH).exists()); assertThat(project.getOutputFile(MetadataStore.METADATA_PATH).exists()).isFalse();
ConfigurationMetadata metadata = project.fullBuild(); ConfigurationMetadata metadata = project.fullBuild();
assertTrue(project.getOutputFile(MetadataStore.METADATA_PATH).exists()); assertThat(project.getOutputFile(MetadataStore.METADATA_PATH).exists()).isTrue();
assertThat(metadata, assertThat(metadata).has(
containsProperty("foo.counter").fromSource(FooProperties.class)); Metadata.withProperty("foo.counter").fromSource(FooProperties.class));
assertThat(metadata, assertThat(metadata).has(
containsProperty("bar.counter").fromSource(BarProperties.class)); Metadata.withProperty("bar.counter").fromSource(BarProperties.class));
metadata = project.incrementalBuild(BarProperties.class); metadata = project.incrementalBuild(BarProperties.class);
assertThat(metadata, assertThat(metadata).has(
containsProperty("foo.counter").fromSource(FooProperties.class)); Metadata.withProperty("foo.counter").fromSource(FooProperties.class));
assertThat(metadata, assertThat(metadata).has(
containsProperty("bar.counter").fromSource(BarProperties.class)); Metadata.withProperty("bar.counter").fromSource(BarProperties.class));
project.addSourceCode(BarProperties.class, project.addSourceCode(BarProperties.class,
BarProperties.class.getResourceAsStream("BarProperties.snippet")); BarProperties.class.getResourceAsStream("BarProperties.snippet"));
metadata = project.incrementalBuild(BarProperties.class); metadata = project.incrementalBuild(BarProperties.class);
assertThat(metadata, containsProperty("bar.extra")); assertThat(metadata).has(Metadata.withProperty("bar.extra"));
assertThat(metadata, containsProperty("foo.counter")); assertThat(metadata).has(Metadata.withProperty("foo.counter"));
assertThat(metadata, containsProperty("bar.counter")); assertThat(metadata).has(Metadata.withProperty("bar.counter"));
project.revert(BarProperties.class); project.revert(BarProperties.class);
metadata = project.incrementalBuild(BarProperties.class); metadata = project.incrementalBuild(BarProperties.class);
assertThat(metadata, not(containsProperty("bar.extra"))); assertThat(metadata).isNotEqualTo(Metadata.withProperty("bar.extra"));
assertThat(metadata, containsProperty("foo.counter")); assertThat(metadata).has(Metadata.withProperty("foo.counter"));
assertThat(metadata, containsProperty("bar.counter")); assertThat(metadata).has(Metadata.withProperty("bar.counter"));
} }
@Test @Test
@ -566,13 +568,13 @@ public class ConfigurationMetadataAnnotationProcessorTests {
TestProject project = new TestProject(this.temporaryFolder, FooProperties.class, TestProject project = new TestProject(this.temporaryFolder, FooProperties.class,
BarProperties.class); BarProperties.class);
ConfigurationMetadata metadata = project.fullBuild(); ConfigurationMetadata metadata = project.fullBuild();
assertThat(metadata, containsProperty("foo.counter")); assertThat(metadata).has(Metadata.withProperty("foo.counter"));
assertThat(metadata, containsProperty("bar.counter")); assertThat(metadata).has(Metadata.withProperty("bar.counter"));
project.replaceText(BarProperties.class, "@ConfigurationProperties", project.replaceText(BarProperties.class, "@ConfigurationProperties",
"//@ConfigurationProperties"); "//@ConfigurationProperties");
metadata = project.incrementalBuild(BarProperties.class); metadata = project.incrementalBuild(BarProperties.class);
assertThat(metadata, containsProperty("foo.counter")); assertThat(metadata).has(Metadata.withProperty("foo.counter"));
assertThat(metadata, not(containsProperty("bar.counter"))); assertThat(metadata).isNotEqualTo(Metadata.withProperty("bar.counter"));
} }
@Test @Test
@ -580,35 +582,35 @@ public class ConfigurationMetadataAnnotationProcessorTests {
TestProject project = new TestProject(this.temporaryFolder, FooProperties.class, TestProject project = new TestProject(this.temporaryFolder, FooProperties.class,
BarProperties.class); BarProperties.class);
ConfigurationMetadata metadata = project.fullBuild(); ConfigurationMetadata metadata = project.fullBuild();
assertThat(metadata, assertThat(metadata).has(
containsProperty("foo.counter").fromSource(FooProperties.class)); Metadata.withProperty("foo.counter").fromSource(FooProperties.class));
assertThat(metadata, assertThat(metadata).has(
containsProperty("bar.counter").fromSource(BarProperties.class)); Metadata.withProperty("bar.counter").fromSource(BarProperties.class));
assertThat(metadata, not( assertThat(metadata).doesNotHave(Metadata.withProperty("bar.counter")
containsProperty("bar.counter").fromSource(RenamedBarProperties.class))); .fromSource(RenamedBarProperties.class));
project.delete(BarProperties.class); project.delete(BarProperties.class);
project.add(RenamedBarProperties.class); project.add(RenamedBarProperties.class);
metadata = project.incrementalBuild(RenamedBarProperties.class); metadata = project.incrementalBuild(RenamedBarProperties.class);
assertThat(metadata, assertThat(metadata).has(
containsProperty("foo.counter").fromSource(FooProperties.class)); Metadata.withProperty("foo.counter").fromSource(FooProperties.class));
assertThat(metadata, assertThat(metadata).doesNotHave(
not(containsProperty("bar.counter").fromSource(BarProperties.class))); Metadata.withProperty("bar.counter").fromSource(BarProperties.class));
assertThat(metadata, assertThat(metadata).has(Metadata.withProperty("bar.counter")
containsProperty("bar.counter").fromSource(RenamedBarProperties.class)); .fromSource(RenamedBarProperties.class));
} }
private void assertSimpleLombokProperties(ConfigurationMetadata metadata, private void assertSimpleLombokProperties(ConfigurationMetadata metadata,
Class<?> source, String prefix) { Class<?> source, String prefix) {
assertThat(metadata, containsGroup(prefix).fromSource(source)); assertThat(metadata).has(Metadata.withGroup(prefix).fromSource(source));
assertThat(metadata, not(containsProperty(prefix + ".id"))); assertThat(metadata).doesNotHave(Metadata.withProperty(prefix + ".id"));
assertThat(metadata, containsProperty(prefix + ".name", String.class) assertThat(metadata).has(Metadata.withProperty(prefix + ".name", String.class)
.fromSource(source).withDescription("Name description.")); .fromSource(source).withDescription("Name description."));
assertThat(metadata, containsProperty(prefix + ".description")); assertThat(metadata).has(Metadata.withProperty(prefix + ".description"));
assertThat(metadata, containsProperty(prefix + ".counter")); assertThat(metadata).has(Metadata.withProperty(prefix + ".counter"));
assertThat(metadata, containsProperty(prefix + ".number").fromSource(source) assertThat(metadata).has(Metadata.withProperty(prefix + ".number")
.withDefaultValue(is(0)).withDeprecation(null, null)); .fromSource(source).withDefaultValue(0).withDeprecation(null, null));
assertThat(metadata, containsProperty(prefix + ".items")); assertThat(metadata).has(Metadata.withProperty(prefix + ".items"));
assertThat(metadata, not(containsProperty(prefix + ".ignored"))); assertThat(metadata).doesNotHave(Metadata.withProperty(prefix + ".ignored"));
} }
private ConfigurationMetadata compile(Class<?>... types) throws IOException { private ConfigurationMetadata compile(Class<?>... types) throws IOException {

@ -1,416 +0,0 @@
/*
* Copyright 2012-2015 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
*
* http://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.configurationprocessor;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import org.hamcrest.BaseMatcher;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.collection.IsMapContaining;
import org.springframework.boot.configurationprocessor.metadata.ConfigurationMetadata;
import org.springframework.boot.configurationprocessor.metadata.ItemDeprecation;
import org.springframework.boot.configurationprocessor.metadata.ItemHint;
import org.springframework.boot.configurationprocessor.metadata.ItemMetadata;
import org.springframework.boot.configurationprocessor.metadata.ItemMetadata.ItemType;
/**
* Hamcrest {@link Matcher} to help test {@link ConfigurationMetadata}.
*
* @author Phillip Webb
* @author Stephane Nicoll
*/
public final class ConfigurationMetadataMatchers {
private ConfigurationMetadataMatchers() {
}
public static ContainsItemMatcher containsGroup(String name) {
return new ContainsItemMatcher(ItemType.GROUP, name);
}
public static ContainsItemMatcher containsGroup(String name, Class<?> type) {
return new ContainsItemMatcher(ItemType.GROUP, name).ofType(type);
}
public static ContainsItemMatcher containsGroup(String name, String type) {
return new ContainsItemMatcher(ItemType.GROUP, name).ofType(type);
}
public static ContainsItemMatcher containsProperty(String name) {
return new ContainsItemMatcher(ItemType.PROPERTY, name);
}
public static ContainsItemMatcher containsProperty(String name, Class<?> type) {
return new ContainsItemMatcher(ItemType.PROPERTY, name).ofType(type);
}
public static ContainsItemMatcher containsProperty(String name, String type) {
return new ContainsItemMatcher(ItemType.PROPERTY, name).ofType(type);
}
public static ContainsHintMatcher containsHint(String name) {
return new ContainsHintMatcher(name);
}
public static class ContainsItemMatcher extends BaseMatcher<ConfigurationMetadata> {
private final ItemType itemType;
private final String name;
private final String type;
private final Class<?> sourceType;
private final String description;
private final Matcher<?> defaultValue;
private final ItemDeprecation deprecation;
public ContainsItemMatcher(ItemType itemType, String name) {
this(itemType, name, null, null, null, null, null);
}
public ContainsItemMatcher(ItemType itemType, String name, String type,
Class<?> sourceType, String description, Matcher<?> defaultValue,
ItemDeprecation deprecation) {
this.itemType = itemType;
this.name = name;
this.type = type;
this.sourceType = sourceType;
this.description = description;
this.defaultValue = defaultValue;
this.deprecation = deprecation;
}
@Override
public boolean matches(Object item) {
ConfigurationMetadata metadata = (ConfigurationMetadata) item;
ItemMetadata itemMetadata = getFirstItemWithName(metadata, this.name);
if (itemMetadata == null) {
return false;
}
if (this.type != null && !this.type.equals(itemMetadata.getType())) {
return false;
}
if (this.sourceType != null
&& !this.sourceType.getName().equals(itemMetadata.getSourceType())) {
return false;
}
if (this.defaultValue != null
&& !this.defaultValue.matches(itemMetadata.getDefaultValue())) {
return false;
}
if (this.description != null
&& !this.description.equals(itemMetadata.getDescription())) {
return false;
}
if (this.deprecation == null && itemMetadata.getDeprecation() != null) {
return false;
}
if (this.deprecation != null
&& !this.deprecation.equals(itemMetadata.getDeprecation())) {
return false;
}
return true;
}
@Override
public void describeMismatch(Object item, Description description) {
ConfigurationMetadata metadata = (ConfigurationMetadata) item;
ItemMetadata property = getFirstItemWithName(metadata, this.name);
if (property == null) {
description.appendText("missing " + this.itemType.toString().toLowerCase()
+ " " + this.name);
}
else {
description
.appendText("was " + this.itemType.toString().toLowerCase() + " ")
.appendValue(property);
}
}
@Override
public void describeTo(Description description) {
description.appendText("metadata containing " + this.name);
if (this.type != null) {
description.appendText(" dataType ").appendValue(this.type);
}
if (this.sourceType != null) {
description.appendText(" sourceType ").appendValue(this.sourceType);
}
if (this.defaultValue != null) {
description.appendText(" defaultValue ").appendValue(this.defaultValue);
}
if (this.description != null) {
description.appendText(" description ").appendValue(this.description);
}
if (this.deprecation != null) {
description.appendText(" deprecation ").appendValue(this.deprecation);
}
}
public ContainsItemMatcher ofType(Class<?> dataType) {
return new ContainsItemMatcher(this.itemType, this.name, dataType.getName(),
this.sourceType, this.description, this.defaultValue,
this.deprecation);
}
public ContainsItemMatcher ofType(String dataType) {
return new ContainsItemMatcher(this.itemType, this.name, dataType,
this.sourceType, this.description, this.defaultValue,
this.deprecation);
}
public ContainsItemMatcher fromSource(Class<?> sourceType) {
return new ContainsItemMatcher(this.itemType, this.name, this.type,
sourceType, this.description, this.defaultValue, this.deprecation);
}
public ContainsItemMatcher withDescription(String description) {
return new ContainsItemMatcher(this.itemType, this.name, this.type,
this.sourceType, description, this.defaultValue, this.deprecation);
}
public ContainsItemMatcher withDefaultValue(Matcher<?> defaultValue) {
return new ContainsItemMatcher(this.itemType, this.name, this.type,
this.sourceType, this.description, defaultValue, this.deprecation);
}
public ContainsItemMatcher withDeprecation(String reason, String replacement) {
return new ContainsItemMatcher(this.itemType, this.name, this.type,
this.sourceType, this.description, this.defaultValue,
new ItemDeprecation(reason, replacement));
}
public ContainsItemMatcher withNoDeprecation() {
return new ContainsItemMatcher(this.itemType, this.name, this.type,
this.sourceType, this.description, this.defaultValue, null);
}
private ItemMetadata getFirstItemWithName(ConfigurationMetadata metadata,
String name) {
for (ItemMetadata item : metadata.getItems()) {
if (item.isOfItemType(this.itemType) && name.equals(item.getName())) {
return item;
}
}
return null;
}
}
public static class ContainsHintMatcher extends BaseMatcher<ConfigurationMetadata> {
private final String name;
private final List<ValueHintMatcher> values;
private final List<ValueProviderMatcher> providers;
public ContainsHintMatcher(String name) {
this(name, new ArrayList<ValueHintMatcher>(),
new ArrayList<ValueProviderMatcher>());
}
public ContainsHintMatcher(String name, List<ValueHintMatcher> values,
List<ValueProviderMatcher> providers) {
this.name = name;
this.values = values;
this.providers = providers;
}
@Override
public boolean matches(Object item) {
ConfigurationMetadata metadata = (ConfigurationMetadata) item;
ItemHint itemHint = getFirstHintWithName(metadata, this.name);
if (itemHint == null) {
return false;
}
for (ValueHintMatcher value : this.values) {
if (!value.matches(itemHint)) {
return false;
}
}
for (ValueProviderMatcher provider : this.providers) {
if (!provider.matches(itemHint)) {
return false;
}
}
return true;
}
@Override
public void describeMismatch(Object item, Description description) {
ConfigurationMetadata metadata = (ConfigurationMetadata) item;
ItemHint itemHint = getFirstHintWithName(metadata, this.name);
if (itemHint == null) {
description.appendText("missing hint " + this.name);
}
else {
description.appendText("was hint ").appendValue(itemHint);
}
}
@Override
public void describeTo(Description description) {
description.appendText("hints for " + this.name);
if (this.values != null) {
description.appendText(" values ").appendValue(this.values);
}
if (this.providers != null) {
description.appendText(" providers ").appendValue(this.providers);
}
}
public ContainsHintMatcher withValue(int index, Object value,
String description) {
List<ValueHintMatcher> values = new ArrayList<ValueHintMatcher>(this.values);
values.add(new ValueHintMatcher(index, value, description));
return new ContainsHintMatcher(this.name, values, this.providers);
}
public ContainsHintMatcher withProvider(int index, String provider,
Map<String, Object> parameters) {
List<ValueProviderMatcher> providers = new ArrayList<ValueProviderMatcher>(
this.providers);
providers.add(new ValueProviderMatcher(index, provider, parameters));
return new ContainsHintMatcher(this.name, this.values, providers);
}
public ContainsHintMatcher withProvider(String provider, String key,
Object value) {
return withProvider(this.providers.size(), provider,
Collections.singletonMap(key, value));
}
public ContainsHintMatcher withProvider(String provider) {
return withProvider(this.providers.size(), provider, null);
}
private ItemHint getFirstHintWithName(ConfigurationMetadata metadata,
String name) {
for (ItemHint hint : metadata.getHints()) {
if (name.equals(hint.getName())) {
return hint;
}
}
return null;
}
}
public static class ValueHintMatcher extends BaseMatcher<ItemHint> {
private final int index;
private final Object value;
private final String description;
public ValueHintMatcher(int index, Object value, String description) {
this.index = index;
this.value = value;
this.description = description;
}
@Override
public boolean matches(Object item) {
ItemHint hint = (ItemHint) item;
if (this.index + 1 > hint.getValues().size()) {
return false;
}
ItemHint.ValueHint valueHint = hint.getValues().get(this.index);
if (this.value != null && !this.value.equals(valueHint.getValue())) {
return false;
}
if (this.description != null
&& !this.description.equals(valueHint.getDescription())) {
return false;
}
return true;
}
@Override
public void describeTo(Description description) {
description.appendText("value hint at index '" + this.index + "'");
if (this.value != null) {
description.appendText(" value ").appendValue(this.value);
}
if (this.description != null) {
description.appendText(" description ").appendValue(this.description);
}
}
}
public static class ValueProviderMatcher extends BaseMatcher<ItemHint> {
private final int index;
private final String name;
private final Map<String, Object> parameters;
public ValueProviderMatcher(int index, String name,
Map<String, Object> parameters) {
this.index = index;
this.name = name;
this.parameters = parameters;
}
@Override
public boolean matches(Object item) {
ItemHint hint = (ItemHint) item;
if (this.index + 1 > hint.getProviders().size()) {
return false;
}
ItemHint.ValueProvider valueProvider = hint.getProviders().get(this.index);
if (this.name != null && !this.name.equals(valueProvider.getName())) {
return false;
}
if (this.parameters != null) {
for (Map.Entry<String, Object> entry : this.parameters.entrySet()) {
if (!IsMapContaining.hasEntry(entry.getKey(), entry.getValue())
.matches(valueProvider.getParameters())) {
return false;
}
}
}
return true;
}
@Override
public void describeTo(Description description) {
description.appendText("value provider ");
if (this.name != null) {
description.appendText(" name ").appendValue(this.name);
}
if (this.parameters != null) {
description.appendText(" parameters ").appendValue(this.parameters);
}
}
}
}

@ -0,0 +1,401 @@
/*
* Copyright 2012-2015 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
*
* http://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.configurationprocessor;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import org.assertj.core.api.Condition;
import org.hamcrest.collection.IsMapContaining;
import org.springframework.boot.configurationprocessor.metadata.ConfigurationMetadata;
import org.springframework.boot.configurationprocessor.metadata.ItemDeprecation;
import org.springframework.boot.configurationprocessor.metadata.ItemHint;
import org.springframework.boot.configurationprocessor.metadata.ItemMetadata;
import org.springframework.boot.configurationprocessor.metadata.ItemMetadata.ItemType;
import org.springframework.util.ObjectUtils;
/**
* AssertJ {@link Condition} to help test {@link ConfigurationMetadata}.
*
* @author Phillip Webb
* @author Stephane Nicoll
*/
public final class Metadata {
private Metadata() {
}
public static MetadataItemCondition withGroup(String name) {
return new MetadataItemCondition(ItemType.GROUP, name);
}
public static MetadataItemCondition withGroup(String name, Class<?> type) {
return new MetadataItemCondition(ItemType.GROUP, name).ofType(type);
}
public static MetadataItemCondition withGroup(String name, String type) {
return new MetadataItemCondition(ItemType.GROUP, name).ofType(type);
}
public static MetadataItemCondition withProperty(String name) {
return new MetadataItemCondition(ItemType.PROPERTY, name);
}
public static MetadataItemCondition withProperty(String name, Class<?> type) {
return new MetadataItemCondition(ItemType.PROPERTY, name).ofType(type);
}
public static MetadataItemCondition withProperty(String name, String type) {
return new MetadataItemCondition(ItemType.PROPERTY, name).ofType(type);
}
public static MetadataHintCondition withHint(String name) {
return new MetadataHintCondition(name);
}
public static class MetadataItemCondition extends Condition<ConfigurationMetadata> {
private final ItemType itemType;
private final String name;
private final String type;
private final Class<?> sourceType;
private final String description;
private final Object defaultValue;
private final ItemDeprecation deprecation;
public MetadataItemCondition(ItemType itemType, String name) {
this(itemType, name, null, null, null, null, null);
}
public MetadataItemCondition(ItemType itemType, String name, String type,
Class<?> sourceType, String description, Object defaultValue,
ItemDeprecation deprecation) {
this.itemType = itemType;
this.name = name;
this.type = type;
this.sourceType = sourceType;
this.description = description;
this.defaultValue = defaultValue;
this.deprecation = deprecation;
describedAs(createDescription());
}
private String createDescription() {
StringBuilder description = new StringBuilder();
description.append("an item named '" + this.name + "'");
if (this.type != null) {
description.append(" with dataType:").append(this.type);
}
if (this.sourceType != null) {
description.append(" with sourceType:").append(this.sourceType);
}
if (this.defaultValue != null) {
description.append(" with defaultValue:").append(this.defaultValue);
}
if (this.description != null) {
description.append(" with description:").append(this.description);
}
if (this.deprecation != null) {
description.append(" with deprecation:").append(this.deprecation);
}
return description.toString();
}
@Override
public boolean matches(ConfigurationMetadata value) {
ItemMetadata itemMetadata = getFirstItemWithName(value, this.name);
if (itemMetadata == null) {
return false;
}
if (this.type != null && !this.type.equals(itemMetadata.getType())) {
return false;
}
if (this.sourceType != null
&& !this.sourceType.getName().equals(itemMetadata.getSourceType())) {
return false;
}
if (this.defaultValue != null && !ObjectUtils
.nullSafeEquals(this.defaultValue, itemMetadata.getDefaultValue())) {
return false;
}
if (this.description != null
&& !this.description.equals(itemMetadata.getDescription())) {
return false;
}
if (this.deprecation == null && itemMetadata.getDeprecation() != null) {
return false;
}
if (this.deprecation != null
&& !this.deprecation.equals(itemMetadata.getDeprecation())) {
return false;
}
return true;
}
public MetadataItemCondition ofType(Class<?> dataType) {
return new MetadataItemCondition(this.itemType, this.name, dataType.getName(),
this.sourceType, this.description, this.defaultValue,
this.deprecation);
}
public MetadataItemCondition ofType(String dataType) {
return new MetadataItemCondition(this.itemType, this.name, dataType,
this.sourceType, this.description, this.defaultValue,
this.deprecation);
}
public MetadataItemCondition fromSource(Class<?> sourceType) {
return new MetadataItemCondition(this.itemType, this.name, this.type,
sourceType, this.description, this.defaultValue, this.deprecation);
}
public MetadataItemCondition withDescription(String description) {
return new MetadataItemCondition(this.itemType, this.name, this.type,
this.sourceType, description, this.defaultValue, this.deprecation);
}
public MetadataItemCondition withDefaultValue(Object defaultValue) {
return new MetadataItemCondition(this.itemType, this.name, this.type,
this.sourceType, this.description, defaultValue, this.deprecation);
}
public MetadataItemCondition withDeprecation(String reason, String replacement) {
return new MetadataItemCondition(this.itemType, this.name, this.type,
this.sourceType, this.description, this.defaultValue,
new ItemDeprecation(reason, replacement));
}
public MetadataItemCondition withNoDeprecation() {
return new MetadataItemCondition(this.itemType, this.name, this.type,
this.sourceType, this.description, this.defaultValue, null);
}
private ItemMetadata getFirstItemWithName(ConfigurationMetadata metadata,
String name) {
for (ItemMetadata item : metadata.getItems()) {
if (item.isOfItemType(this.itemType) && name.equals(item.getName())) {
return item;
}
}
return null;
}
}
public static class MetadataHintCondition extends Condition<ConfigurationMetadata> {
private final String name;
private final List<ItemHintValueCondition> valueConditions;
private final List<ItemHintProviderCondition> providerConditions;
public MetadataHintCondition(String name) {
this.name = name;
this.valueConditions = Collections.emptyList();
this.providerConditions = Collections.emptyList();
}
public MetadataHintCondition(String name,
List<ItemHintValueCondition> valueConditions,
List<ItemHintProviderCondition> providerConditions) {
this.name = name;
this.valueConditions = valueConditions;
this.providerConditions = providerConditions;
describedAs(createDescription());
}
private String createDescription() {
StringBuilder description = new StringBuilder();
description.append("a hints name '" + this.name + "'");
if (!this.valueConditions.isEmpty()) {
description.append(" with values:").append(this.valueConditions);
}
if (!this.providerConditions.isEmpty()) {
description.append(" with providers:").append(this.providerConditions);
}
return description.toString();
}
@Override
public boolean matches(ConfigurationMetadata metadata) {
ItemHint itemHint = getFirstHintWithName(metadata, this.name);
if (itemHint == null) {
return false;
}
return matches(itemHint, this.valueConditions)
&& matches(itemHint, this.providerConditions);
}
private boolean matches(ItemHint itemHint,
List<? extends Condition<ItemHint>> conditions) {
for (Condition<ItemHint> condition : conditions) {
if (!condition.matches(itemHint)) {
return false;
}
}
return true;
}
private ItemHint getFirstHintWithName(ConfigurationMetadata metadata,
String name) {
for (ItemHint hint : metadata.getHints()) {
if (name.equals(hint.getName())) {
return hint;
}
}
return null;
}
public MetadataHintCondition withValue(int index, Object value,
String description) {
return new MetadataHintCondition(this.name,
add(this.valueConditions,
new ItemHintValueCondition(index, value, description)),
this.providerConditions);
}
public MetadataHintCondition withProvider(String provider) {
return withProvider(this.providerConditions.size(), provider, null);
}
public MetadataHintCondition withProvider(String provider, String key,
Object value) {
return withProvider(this.providerConditions.size(), provider,
Collections.singletonMap(key, value));
}
public MetadataHintCondition withProvider(int index, String provider,
Map<String, Object> parameters) {
return new MetadataHintCondition(this.name, this.valueConditions,
add(this.providerConditions,
new ItemHintProviderCondition(index, provider, parameters)));
}
private <T> List<T> add(List<T> items, T item) {
List<T> result = new ArrayList<T>(items);
result.add(item);
return result;
}
}
private static class ItemHintValueCondition extends Condition<ItemHint> {
private final int index;
private final Object value;
private final String description;
ItemHintValueCondition(int index, Object value, String description) {
this.index = index;
this.value = value;
this.description = description;
describedAs(createDescription());
}
private String createDescription() {
StringBuilder description = new StringBuilder();
description.append("value hint at index '" + this.index + "'");
if (this.value != null) {
description.append(" with value:").append(this.value);
}
if (this.description != null) {
description.append(" with description:").append(this.description);
}
return description.toString();
}
@Override
public boolean matches(ItemHint value) {
if (this.index + 1 > value.getValues().size()) {
return false;
}
ItemHint.ValueHint valueHint = value.getValues().get(this.index);
if (this.value != null && !this.value.equals(valueHint.getValue())) {
return false;
}
if (this.description != null
&& !this.description.equals(valueHint.getDescription())) {
return false;
}
return true;
}
}
private static class ItemHintProviderCondition extends Condition<ItemHint> {
private final int index;
private final String name;
private final Map<String, Object> parameters;
ItemHintProviderCondition(int index, String name,
Map<String, Object> parameters) {
this.index = index;
this.name = name;
this.parameters = parameters;
describedAs(createDescription());
}
public String createDescription() {
StringBuilder description = new StringBuilder();
description.append("value provider");
if (this.name != null) {
description.append(" with name:").append(this.name);
}
if (this.parameters != null) {
description.append(" with parameters:").append(this.parameters);
}
return description.toString();
}
@Override
public boolean matches(ItemHint hint) {
if (this.index + 1 > hint.getProviders().size()) {
return false;
}
ItemHint.ValueProvider valueProvider = hint.getProviders().get(this.index);
if (this.name != null && !this.name.equals(valueProvider.getName())) {
return false;
}
if (this.parameters != null) {
for (Map.Entry<String, Object> entry : this.parameters.entrySet()) {
if (!IsMapContaining.hasEntry(entry.getKey(), entry.getValue())
.matches(valueProvider.getParameters())) {
return false;
}
}
}
return true;
}
}
}

@ -28,6 +28,8 @@ import org.springframework.boot.configurationprocessor.metadata.ConfigurationMet
import org.springframework.boot.configurationprocessor.metadata.JsonMarshaller; import org.springframework.boot.configurationprocessor.metadata.JsonMarshaller;
/** /**
* Test {@link ConfigurationMetadataAnnotationProcessor}.
*
* @author Stephane Nicoll * @author Stephane Nicoll
* @author Phillip Webb * @author Phillip Webb
* @author Andy Wilkinson * @author Andy Wilkinson

@ -29,7 +29,6 @@ import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element; import javax.lang.model.element.Element;
import javax.lang.model.element.TypeElement; import javax.lang.model.element.TypeElement;
import org.hamcrest.Matcher;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.TemporaryFolder; import org.junit.rules.TemporaryFolder;
@ -37,9 +36,7 @@ import org.junit.rules.TemporaryFolder;
import org.springframework.boot.configurationprocessor.TestCompiler; import org.springframework.boot.configurationprocessor.TestCompiler;
import org.springframework.boot.configurationsample.fieldvalues.FieldValues; import org.springframework.boot.configurationsample.fieldvalues.FieldValues;
import static org.hamcrest.Matchers.equalTo; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.Assert.assertThat;
/** /**
* Abstract base class for {@link FieldValuesParser} tests. * Abstract base class for {@link FieldValuesParser} tests.
@ -60,43 +57,37 @@ public abstract class AbstractFieldValuesProcessorTests {
TestCompiler compiler = new TestCompiler(this.temporaryFolder); TestCompiler compiler = new TestCompiler(this.temporaryFolder);
compiler.getTask(FieldValues.class).call(processor); compiler.getTask(FieldValues.class).call(processor);
Map<String, Object> values = processor.getValues(); Map<String, Object> values = processor.getValues();
assertThat(values.get("string"), equalToObject("1")); assertThat(values.get("string")).isEqualTo("1");
assertThat(values.get("stringNone"), nullValue()); assertThat(values.get("stringNone")).isNull();
assertThat(values.get("stringConst"), equalToObject("c")); assertThat(values.get("stringConst")).isEqualTo("c");
assertThat(values.get("bool"), equalToObject(true)); assertThat(values.get("bool")).isEqualTo(true);
assertThat(values.get("boolNone"), equalToObject(false)); assertThat(values.get("boolNone")).isEqualTo(false);
assertThat(values.get("boolConst"), equalToObject(true)); assertThat(values.get("boolConst")).isEqualTo(true);
assertThat(values.get("boolObject"), equalToObject(true)); assertThat(values.get("boolObject")).isEqualTo(true);
assertThat(values.get("boolObjectNone"), nullValue()); assertThat(values.get("boolObjectNone")).isNull();
assertThat(values.get("boolObjectConst"), equalToObject(true)); assertThat(values.get("boolObjectConst")).isEqualTo(true);
assertThat(values.get("integer"), equalToObject(1)); assertThat(values.get("integer")).isEqualTo(1);
assertThat(values.get("integerNone"), equalToObject(0)); assertThat(values.get("integerNone")).isEqualTo(0);
assertThat(values.get("integerConst"), equalToObject(2)); assertThat(values.get("integerConst")).isEqualTo(2);
assertThat(values.get("integerObject"), equalToObject(3)); assertThat(values.get("integerObject")).isEqualTo(3);
assertThat(values.get("integerObjectNone"), nullValue()); assertThat(values.get("integerObjectNone")).isNull();
assertThat(values.get("integerObjectConst"), equalToObject(4)); assertThat(values.get("integerObjectConst")).isEqualTo(4);
assertThat(values.get("charset"), equalToObject("US-ASCII")); assertThat(values.get("charset")).isEqualTo("US-ASCII");
assertThat(values.get("charsetConst"), equalToObject("UTF-8")); assertThat(values.get("charsetConst")).isEqualTo("UTF-8");
assertThat(values.get("mimeType"), equalToObject("text/html")); assertThat(values.get("mimeType")).isEqualTo("text/html");
assertThat(values.get("mimeTypeConst"), equalToObject("text/plain")); assertThat(values.get("mimeTypeConst")).isEqualTo("text/plain");
assertThat(values.get("object"), equalToObject(123)); assertThat(values.get("object")).isEqualTo(123);
assertThat(values.get("objectNone"), nullValue()); assertThat(values.get("objectNone")).isNull();
assertThat(values.get("objectConst"), equalToObject("c")); assertThat(values.get("objectConst")).isEqualTo("c");
assertThat(values.get("objectInstance"), nullValue()); assertThat(values.get("objectInstance")).isNull();
assertThat(values.get("stringArray"), assertThat(values.get("stringArray")).isEqualTo(new Object[] { "FOO", "BAR" });
equalToObject(new Object[] { "FOO", "BAR" })); assertThat(values.get("stringArrayNone")).isNull();
assertThat(values.get("stringArrayNone"), nullValue()); assertThat(values.get("stringEmptyArray")).isEqualTo(new Object[0]);
assertThat(values.get("stringEmptyArray"), equalToObject(new Object[0])); assertThat(values.get("stringArrayConst")).isEqualTo(new Object[] { "OK", "KO" });
assertThat(values.get("stringArrayConst"), assertThat(values.get("stringArrayConstElements"))
equalToObject(new Object[] { "OK", "KO" })); .isEqualTo(new Object[] { "c" });
assertThat(values.get("stringArrayConstElements"), assertThat(values.get("integerArray")).isEqualTo(new Object[] { 42, 24 });
equalToObject(new Object[] { "c" })); assertThat(values.get("unknownArray")).isNull();
assertThat(values.get("integerArray"), equalToObject(new Object[] { 42, 24 }));
assertThat(values.get("unknownArray"), nullValue());
}
private Matcher<Object> equalToObject(Object object) {
return equalTo(object);
} }
@SupportedAnnotationTypes({ @SupportedAnnotationTypes({

@ -18,8 +18,7 @@ package org.springframework.boot.configurationprocessor.metadata;
import org.junit.Test; import org.junit.Test;
import static org.hamcrest.CoreMatchers.is; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertThat;
/** /**
* Tests for {@link ConfigurationMetadata}. * Tests for {@link ConfigurationMetadata}.
@ -30,43 +29,44 @@ public class ConfigurationMetadataTests {
@Test @Test
public void toDashedCaseCamelCase() { public void toDashedCaseCamelCase() {
assertThat(toDashedCase("simpleCamelCase"), is("simple-camel-case")); assertThat(toDashedCase("simpleCamelCase")).isEqualTo("simple-camel-case");
} }
@Test @Test
public void toDashedCaseWordsUnderscore() { public void toDashedCaseWordsUnderscore() {
assertThat(toDashedCase("Word_With_underscore"), is("word_with_underscore")); assertThat(toDashedCase("Word_With_underscore"))
.isEqualTo("word_with_underscore");
} }
@Test @Test
public void toDashedCaseWordsSeveralUnderscores() { public void toDashedCaseWordsSeveralUnderscores() {
assertThat(toDashedCase("Word___With__underscore"), assertThat(toDashedCase("Word___With__underscore"))
is("word___with__underscore")); .isEqualTo("word___with__underscore");
} }
@Test @Test
public void toDashedCaseLowerCaseUnderscore() { public void toDashedCaseLowerCaseUnderscore() {
assertThat(toDashedCase("lower_underscore"), is("lower_underscore")); assertThat(toDashedCase("lower_underscore")).isEqualTo("lower_underscore");
} }
@Test @Test
public void toDashedCaseUpperUnderscore() { public void toDashedCaseUpperUnderscore() {
assertThat(toDashedCase("UPPER_UNDERSCORE"), is("upper_underscore")); assertThat(toDashedCase("UPPER_UNDERSCORE")).isEqualTo("upper_underscore");
} }
@Test @Test
public void toDashedCaseMultipleUnderscores() { public void toDashedCaseMultipleUnderscores() {
assertThat(toDashedCase("super___crazy"), is("super___crazy")); assertThat(toDashedCase("super___crazy")).isEqualTo("super___crazy");
} }
@Test @Test
public void toDashedCaseUppercase() { public void toDashedCaseUppercase() {
assertThat(toDashedCase("UPPERCASE"), is("uppercase")); assertThat(toDashedCase("UPPERCASE")).isEqualTo("uppercase");
} }
@Test @Test
public void toDashedCaseLowercase() { public void toDashedCaseLowercase() {
assertThat(toDashedCase("lowercase"), is("lowercase")); assertThat(toDashedCase("lowercase")).isEqualTo("lowercase");
} }
private String toDashedCase(String name) { private String toDashedCase(String name) {

@ -25,11 +25,9 @@ import java.util.Collections;
import org.junit.Test; import org.junit.Test;
import static org.hamcrest.CoreMatchers.is; import org.springframework.boot.configurationprocessor.Metadata;
import static org.junit.Assert.assertThat;
import static org.springframework.boot.configurationprocessor.ConfigurationMetadataMatchers.containsGroup; import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.boot.configurationprocessor.ConfigurationMetadataMatchers.containsHint;
import static org.springframework.boot.configurationprocessor.ConfigurationMetadataMatchers.containsProperty;
/** /**
* Tests for {@link JsonMarshaller}. * Tests for {@link JsonMarshaller}.
@ -70,22 +68,21 @@ public class JsonMarshallerTests {
marshaller.write(metadata, outputStream); marshaller.write(metadata, outputStream);
ConfigurationMetadata read = marshaller ConfigurationMetadata read = marshaller
.read(new ByteArrayInputStream(outputStream.toByteArray())); .read(new ByteArrayInputStream(outputStream.toByteArray()));
assertThat(read, assertThat(read).has(Metadata.withProperty("a.b", StringBuffer.class)
containsProperty("a.b", StringBuffer.class).fromSource(InputStream.class) .fromSource(InputStream.class).withDescription("desc")
.withDescription("desc").withDefaultValue(is("x")) .withDefaultValue("x").withDeprecation("Deprecation comment", "b.c.d"));
.withDeprecation("Deprecation comment", "b.c.d")); assertThat(read).has(Metadata.withProperty("b.c.d"));
assertThat(read, containsProperty("b.c.d")); assertThat(read).has(Metadata.withProperty("c").withDefaultValue(123));
assertThat(read, containsProperty("c").withDefaultValue(is(123))); assertThat(read).has(Metadata.withProperty("d").withDefaultValue(true));
assertThat(read, containsProperty("d").withDefaultValue(is(true))); assertThat(read).has(
assertThat(read, Metadata.withProperty("e").withDefaultValue(new String[] { "y", "n" }));
containsProperty("e").withDefaultValue(is(new String[] { "y", "n" }))); assertThat(read).has(Metadata.withProperty("f")
assertThat(read, containsProperty("f") .withDefaultValue(new Object[] { true, false }));
.withDefaultValue(is(new boolean[] { true, false }))); assertThat(read).has(Metadata.withGroup("d"));
assertThat(read, containsGroup("d")); assertThat(read).has(Metadata.withHint("a.b"));
assertThat(read, containsHint("a.b")); assertThat(read).has(
assertThat(read, Metadata.withHint("c").withValue(0, 123, "hey").withValue(1, 456, null));
containsHint("c").withValue(0, 123, "hey").withValue(1, 456, null)); assertThat(read).has(Metadata.withHint("d").withProvider("first", "target", "foo")
assertThat(read, containsHint("d").withProvider("first", "target", "foo")
.withProvider("second")); .withProvider("second"));
} }

@ -26,9 +26,7 @@ import org.junit.rules.TemporaryFolder;
import org.springframework.util.FileCopyUtils; import org.springframework.util.FileCopyUtils;
import static org.hamcrest.Matchers.containsString; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;
/** /**
* Tests for {@link DefaultLaunchScript}. * Tests for {@link DefaultLaunchScript}.
@ -45,7 +43,7 @@ public class DefaultLaunchScriptTests {
public void loadsDefaultScript() throws Exception { public void loadsDefaultScript() throws Exception {
DefaultLaunchScript script = new DefaultLaunchScript(null, null); DefaultLaunchScript script = new DefaultLaunchScript(null, null);
String content = new String(script.toByteArray()); String content = new String(script.toByteArray());
assertThat(content, containsString("Spring Boot Startup Script")); assertThat(content).contains("Spring Boot Startup Script");
} }
@Test @Test
@ -82,14 +80,14 @@ public class DefaultLaunchScriptTests {
public void defaultForUseStartStopDaemonIsTrue() throws Exception { public void defaultForUseStartStopDaemonIsTrue() throws Exception {
DefaultLaunchScript script = new DefaultLaunchScript(null, null); DefaultLaunchScript script = new DefaultLaunchScript(null, null);
String content = new String(script.toByteArray()); String content = new String(script.toByteArray());
assertThat(content, containsString("USE_START_STOP_DAEMON=\"true\"")); assertThat(content).contains("USE_START_STOP_DAEMON=\"true\"");
} }
@Test @Test
public void defaultForModeIsAuto() throws Exception { public void defaultForModeIsAuto() throws Exception {
DefaultLaunchScript script = new DefaultLaunchScript(null, null); DefaultLaunchScript script = new DefaultLaunchScript(null, null);
String content = new String(script.toByteArray()); String content = new String(script.toByteArray());
assertThat(content, containsString("MODE=\"auto\"")); assertThat(content).contains("MODE=\"auto\"");
} }
@Test @Test
@ -98,7 +96,7 @@ public class DefaultLaunchScriptTests {
FileCopyUtils.copy("ABC".getBytes(), file); FileCopyUtils.copy("ABC".getBytes(), file);
DefaultLaunchScript script = new DefaultLaunchScript(file, null); DefaultLaunchScript script = new DefaultLaunchScript(file, null);
String content = new String(script.toByteArray()); String content = new String(script.toByteArray());
assertThat(content, equalTo("ABC")); assertThat(content).isEqualTo("ABC");
} }
@Test @Test
@ -108,7 +106,7 @@ public class DefaultLaunchScriptTests {
DefaultLaunchScript script = new DefaultLaunchScript(file, DefaultLaunchScript script = new DefaultLaunchScript(file,
createProperties("a:e", "b:o")); createProperties("a:e", "b:o"));
String content = new String(script.toByteArray()); String content = new String(script.toByteArray());
assertThat(content, equalTo("hello")); assertThat(content).isEqualTo("hello");
} }
@Test @Test
@ -118,7 +116,7 @@ public class DefaultLaunchScriptTests {
DefaultLaunchScript script = new DefaultLaunchScript(file, DefaultLaunchScript script = new DefaultLaunchScript(file,
createProperties("a:e", "b:o")); createProperties("a:e", "b:o"));
String content = new String(script.toByteArray()); String content = new String(script.toByteArray());
assertThat(content, equalTo("hel\nlo")); assertThat(content).isEqualTo("hel\nlo");
} }
@Test @Test
@ -127,7 +125,7 @@ public class DefaultLaunchScriptTests {
FileCopyUtils.copy("h{{a:e}}ll{{b:o}}".getBytes(), file); FileCopyUtils.copy("h{{a:e}}ll{{b:o}}".getBytes(), file);
DefaultLaunchScript script = new DefaultLaunchScript(file, null); DefaultLaunchScript script = new DefaultLaunchScript(file, null);
String content = new String(script.toByteArray()); String content = new String(script.toByteArray());
assertThat(content, equalTo("hello")); assertThat(content).isEqualTo("hello");
} }
@Test @Test
@ -137,7 +135,7 @@ public class DefaultLaunchScriptTests {
DefaultLaunchScript script = new DefaultLaunchScript(file, DefaultLaunchScript script = new DefaultLaunchScript(file,
createProperties("a:a")); createProperties("a:a"));
String content = new String(script.toByteArray()); String content = new String(script.toByteArray());
assertThat(content, equalTo("hallo")); assertThat(content).isEqualTo("hallo");
} }
@Test @Test
@ -146,14 +144,14 @@ public class DefaultLaunchScriptTests {
FileCopyUtils.copy("h{{a}}ll{{b}}".getBytes(), file); FileCopyUtils.copy("h{{a}}ll{{b}}".getBytes(), file);
DefaultLaunchScript script = new DefaultLaunchScript(file, null); DefaultLaunchScript script = new DefaultLaunchScript(file, null);
String content = new String(script.toByteArray()); String content = new String(script.toByteArray());
assertThat(content, equalTo("h{{a}}ll{{b}}")); assertThat(content).isEqualTo("h{{a}}ll{{b}}");
} }
private void assertThatPlaceholderCanBeReplaced(String placeholder) throws Exception { private void assertThatPlaceholderCanBeReplaced(String placeholder) throws Exception {
DefaultLaunchScript script = new DefaultLaunchScript(null, DefaultLaunchScript script = new DefaultLaunchScript(null,
createProperties(placeholder + ":__test__")); createProperties(placeholder + ":__test__"));
String content = new String(script.toByteArray()); String content = new String(script.toByteArray());
assertThat(content, containsString("__test__")); assertThat(content).contains("__test__");
} }
private Map<?, ?> createProperties(String... pairs) { private Map<?, ?> createProperties(String... pairs) {

@ -28,10 +28,7 @@ import org.junit.rules.TemporaryFolder;
import org.springframework.util.FileSystemUtils; import org.springframework.util.FileSystemUtils;
import static org.hamcrest.Matchers.equalTo; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
/** /**
* Tests for {@link FileUtils}. * Tests for {@link FileUtils}.
@ -65,31 +62,31 @@ public class FileUtilsTests {
new File(this.originDirectory, "logback.xml").createNewFile(); new File(this.originDirectory, "logback.xml").createNewFile();
FileUtils.removeDuplicatesFromOutputDirectory(this.outputDirectory, FileUtils.removeDuplicatesFromOutputDirectory(this.outputDirectory,
this.originDirectory); this.originDirectory);
assertFalse(file.exists()); assertThat(file.exists()).isFalse();
} }
@Test @Test
public void nestedDuplicateFile() throws IOException { public void nestedDuplicateFile() throws IOException {
assertTrue(new File(this.outputDirectory, "sub").mkdirs()); assertThat(new File(this.outputDirectory, "sub").mkdirs()).isTrue();
assertTrue(new File(this.originDirectory, "sub").mkdirs()); assertThat(new File(this.originDirectory, "sub").mkdirs()).isTrue();
File file = new File(this.outputDirectory, "sub/logback.xml"); File file = new File(this.outputDirectory, "sub/logback.xml");
file.createNewFile(); file.createNewFile();
new File(this.originDirectory, "sub/logback.xml").createNewFile(); new File(this.originDirectory, "sub/logback.xml").createNewFile();
FileUtils.removeDuplicatesFromOutputDirectory(this.outputDirectory, FileUtils.removeDuplicatesFromOutputDirectory(this.outputDirectory,
this.originDirectory); this.originDirectory);
assertFalse(file.exists()); assertThat(file.exists()).isFalse();
} }
@Test @Test
public void nestedNonDuplicateFile() throws IOException { public void nestedNonDuplicateFile() throws IOException {
assertTrue(new File(this.outputDirectory, "sub").mkdirs()); assertThat(new File(this.outputDirectory, "sub").mkdirs()).isTrue();
assertTrue(new File(this.originDirectory, "sub").mkdirs()); assertThat(new File(this.originDirectory, "sub").mkdirs()).isTrue();
File file = new File(this.outputDirectory, "sub/logback.xml"); File file = new File(this.outputDirectory, "sub/logback.xml");
file.createNewFile(); file.createNewFile();
new File(this.originDirectory, "sub/different.xml").createNewFile(); new File(this.originDirectory, "sub/different.xml").createNewFile();
FileUtils.removeDuplicatesFromOutputDirectory(this.outputDirectory, FileUtils.removeDuplicatesFromOutputDirectory(this.outputDirectory,
this.originDirectory); this.originDirectory);
assertTrue(file.exists()); assertThat(file.exists()).isTrue();
} }
@Test @Test
@ -99,7 +96,7 @@ public class FileUtilsTests {
new File(this.originDirectory, "different.xml").createNewFile(); new File(this.originDirectory, "different.xml").createNewFile();
FileUtils.removeDuplicatesFromOutputDirectory(this.outputDirectory, FileUtils.removeDuplicatesFromOutputDirectory(this.outputDirectory,
this.originDirectory); this.originDirectory);
assertTrue(file.exists()); assertThat(file.exists()).isTrue();
} }
@Test @Test
@ -112,8 +109,8 @@ public class FileUtilsTests {
finally { finally {
outputStream.close(); outputStream.close();
} }
assertThat(FileUtils.sha1Hash(file), assertThat(FileUtils.sha1Hash(file))
equalTo("7037807198c22a7d2b0807371d763779a84fdfcf")); .isEqualTo("7037807198c22a7d2b0807371d763779a84fdfcf");
} }
} }

@ -21,9 +21,7 @@ import java.net.URL;
import org.junit.Test; import org.junit.Test;
import static org.hamcrest.Matchers.endsWith; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;
/** /**
* Tests for {@link JvmUtils}. * Tests for {@link JvmUtils}.
@ -36,8 +34,8 @@ public class JvmUtilsTests {
public void getToolsJar() throws Exception { public void getToolsJar() throws Exception {
URL jarUrl = JvmUtils.getToolsJarUrl(); URL jarUrl = JvmUtils.getToolsJarUrl();
// System.out.println(jarUrl); // System.out.println(jarUrl);
assertThat(jarUrl.toString(), endsWith(".jar")); assertThat(jarUrl.toString()).endsWith(".jar");
assertThat(new File(jarUrl.toURI()).exists(), equalTo(true)); assertThat(new File(jarUrl.toURI()).exists()).isTrue();
} }
} }

@ -22,10 +22,7 @@ import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException; import org.junit.rules.ExpectedException;
import static org.hamcrest.Matchers.equalTo; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.Assert.assertThat;
/** /**
* Tests for {@link Layouts}. * Tests for {@link Layouts}.
@ -40,18 +37,20 @@ public class LayoutsTests {
@Test @Test
public void jarFile() throws Exception { public void jarFile() throws Exception {
assertThat(Layouts.forFile(new File("test.jar")), instanceOf(Layouts.Jar.class)); assertThat(Layouts.forFile(new File("test.jar"))).isInstanceOf(Layouts.Jar.class);
assertThat(Layouts.forFile(new File("test.JAR")), instanceOf(Layouts.Jar.class)); assertThat(Layouts.forFile(new File("test.JAR"))).isInstanceOf(Layouts.Jar.class);
assertThat(Layouts.forFile(new File("test.jAr")), instanceOf(Layouts.Jar.class)); assertThat(Layouts.forFile(new File("test.jAr"))).isInstanceOf(Layouts.Jar.class);
assertThat(Layouts.forFile(new File("te.st.jar")), instanceOf(Layouts.Jar.class)); assertThat(Layouts.forFile(new File("te.st.jar")))
.isInstanceOf(Layouts.Jar.class);
} }
@Test @Test
public void warFile() throws Exception { public void warFile() throws Exception {
assertThat(Layouts.forFile(new File("test.war")), instanceOf(Layouts.War.class)); assertThat(Layouts.forFile(new File("test.war"))).isInstanceOf(Layouts.War.class);
assertThat(Layouts.forFile(new File("test.WAR")), instanceOf(Layouts.War.class)); assertThat(Layouts.forFile(new File("test.WAR"))).isInstanceOf(Layouts.War.class);
assertThat(Layouts.forFile(new File("test.wAr")), instanceOf(Layouts.War.class)); assertThat(Layouts.forFile(new File("test.wAr"))).isInstanceOf(Layouts.War.class);
assertThat(Layouts.forFile(new File("te.st.war")), instanceOf(Layouts.War.class)); assertThat(Layouts.forFile(new File("te.st.war")))
.isInstanceOf(Layouts.War.class);
} }
@Test @Test
@ -64,40 +63,40 @@ public class LayoutsTests {
@Test @Test
public void jarLayout() throws Exception { public void jarLayout() throws Exception {
Layout layout = new Layouts.Jar(); Layout layout = new Layouts.Jar();
assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.COMPILE), assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.COMPILE))
equalTo("lib/")); .isEqualTo("lib/");
assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.CUSTOM), assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.CUSTOM))
equalTo("lib/")); .isEqualTo("lib/");
assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.PROVIDED), assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.PROVIDED))
equalTo("lib/")); .isEqualTo("lib/");
assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.RUNTIME), assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.RUNTIME))
equalTo("lib/")); .isEqualTo("lib/");
} }
@Test @Test
public void warLayout() throws Exception { public void warLayout() throws Exception {
Layout layout = new Layouts.War(); Layout layout = new Layouts.War();
assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.COMPILE), assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.COMPILE))
equalTo("WEB-INF/lib/")); .isEqualTo("WEB-INF/lib/");
assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.CUSTOM), assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.CUSTOM))
equalTo("WEB-INF/lib/")); .isEqualTo("WEB-INF/lib/");
assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.PROVIDED), assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.PROVIDED))
equalTo("WEB-INF/lib-provided/")); .isEqualTo("WEB-INF/lib-provided/");
assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.RUNTIME), assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.RUNTIME))
equalTo("WEB-INF/lib/")); .isEqualTo("WEB-INF/lib/");
} }
@Test @Test
public void moduleLayout() throws Exception { public void moduleLayout() throws Exception {
Layout layout = new Layouts.Module(); Layout layout = new Layouts.Module();
assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.COMPILE), assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.COMPILE))
equalTo("lib/")); .isEqualTo("lib/");
assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.PROVIDED), assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.PROVIDED))
nullValue()); .isNull();
assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.RUNTIME), assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.RUNTIME))
equalTo("lib/")); .isEqualTo("lib/");
assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.CUSTOM), assertThat(layout.getLibraryDestination("lib.jar", LibraryScope.CUSTOM))
equalTo("lib/")); .isEqualTo("lib/");
} }
} }

@ -30,8 +30,7 @@ import org.springframework.boot.loader.tools.MainClassFinder.ClassNameCallback;
import org.springframework.boot.loader.tools.sample.ClassWithMainMethod; import org.springframework.boot.loader.tools.sample.ClassWithMainMethod;
import org.springframework.boot.loader.tools.sample.ClassWithoutMainMethod; import org.springframework.boot.loader.tools.sample.ClassWithoutMainMethod;
import static org.hamcrest.Matchers.equalTo; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertThat;
/** /**
* Tests for {@link MainClassFinder}. * Tests for {@link MainClassFinder}.
@ -58,7 +57,7 @@ public class MainClassFinderTests {
this.testJarFile.addClass("B.class", ClassWithMainMethod.class); this.testJarFile.addClass("B.class", ClassWithMainMethod.class);
this.testJarFile.addClass("A.class", ClassWithoutMainMethod.class); this.testJarFile.addClass("A.class", ClassWithoutMainMethod.class);
String actual = MainClassFinder.findMainClass(this.testJarFile.getJarFile(), ""); String actual = MainClassFinder.findMainClass(this.testJarFile.getJarFile(), "");
assertThat(actual, equalTo("B")); assertThat(actual).isEqualTo("B");
} }
@Test @Test
@ -67,7 +66,7 @@ public class MainClassFinderTests {
this.testJarFile.addClass("a/b/c/E.class", ClassWithoutMainMethod.class); this.testJarFile.addClass("a/b/c/E.class", ClassWithoutMainMethod.class);
this.testJarFile.addClass("a/b/F.class", ClassWithoutMainMethod.class); this.testJarFile.addClass("a/b/F.class", ClassWithoutMainMethod.class);
String actual = MainClassFinder.findMainClass(this.testJarFile.getJarFile(), ""); String actual = MainClassFinder.findMainClass(this.testJarFile.getJarFile(), "");
assertThat(actual, equalTo("a.b.c.D")); assertThat(actual).isEqualTo("a.b.c.D");
} }
@Test @Test
@ -75,7 +74,7 @@ public class MainClassFinderTests {
this.testJarFile.addClass("a/B.class", ClassWithMainMethod.class); this.testJarFile.addClass("a/B.class", ClassWithMainMethod.class);
this.testJarFile.addClass("a/b/c/E.class", ClassWithMainMethod.class); this.testJarFile.addClass("a/b/c/E.class", ClassWithMainMethod.class);
String actual = MainClassFinder.findMainClass(this.testJarFile.getJarFile(), ""); String actual = MainClassFinder.findMainClass(this.testJarFile.getJarFile(), "");
assertThat(actual, equalTo("a.B")); assertThat(actual).isEqualTo("a.B");
} }
@Test @Test
@ -94,7 +93,7 @@ public class MainClassFinderTests {
this.testJarFile.addClass("a/b/c/E.class", ClassWithMainMethod.class); this.testJarFile.addClass("a/b/c/E.class", ClassWithMainMethod.class);
String actual = MainClassFinder.findMainClass(this.testJarFile.getJarFile(), String actual = MainClassFinder.findMainClass(this.testJarFile.getJarFile(),
"a/"); "a/");
assertThat(actual, equalTo("B")); assertThat(actual).isEqualTo("B");
} }
@ -103,7 +102,7 @@ public class MainClassFinderTests {
this.testJarFile.addClass("B.class", ClassWithMainMethod.class); this.testJarFile.addClass("B.class", ClassWithMainMethod.class);
this.testJarFile.addClass("A.class", ClassWithoutMainMethod.class); this.testJarFile.addClass("A.class", ClassWithoutMainMethod.class);
String actual = MainClassFinder.findMainClass(this.testJarFile.getJarSource()); String actual = MainClassFinder.findMainClass(this.testJarFile.getJarSource());
assertThat(actual, equalTo("B")); assertThat(actual).isEqualTo("B");
} }
@Test @Test
@ -112,7 +111,7 @@ public class MainClassFinderTests {
this.testJarFile.addClass("a/b/c/E.class", ClassWithoutMainMethod.class); this.testJarFile.addClass("a/b/c/E.class", ClassWithoutMainMethod.class);
this.testJarFile.addClass("a/b/F.class", ClassWithoutMainMethod.class); this.testJarFile.addClass("a/b/F.class", ClassWithoutMainMethod.class);
String actual = MainClassFinder.findMainClass(this.testJarFile.getJarSource()); String actual = MainClassFinder.findMainClass(this.testJarFile.getJarSource());
assertThat(actual, equalTo("a.b.c.D")); assertThat(actual).isEqualTo("a.b.c.D");
} }
@Test @Test
@ -120,7 +119,7 @@ public class MainClassFinderTests {
this.testJarFile.addClass("a/B.class", ClassWithMainMethod.class); this.testJarFile.addClass("a/B.class", ClassWithMainMethod.class);
this.testJarFile.addClass("a/b/c/E.class", ClassWithMainMethod.class); this.testJarFile.addClass("a/b/c/E.class", ClassWithMainMethod.class);
String actual = MainClassFinder.findMainClass(this.testJarFile.getJarSource()); String actual = MainClassFinder.findMainClass(this.testJarFile.getJarSource());
assertThat(actual, equalTo("a.B")); assertThat(actual).isEqualTo("a.B");
} }
@Test @Test
@ -141,7 +140,7 @@ public class MainClassFinderTests {
this.testJarFile.addClass("a/b/G.class", ClassWithMainMethod.class); this.testJarFile.addClass("a/b/G.class", ClassWithMainMethod.class);
ClassNameCollector callback = new ClassNameCollector(); ClassNameCollector callback = new ClassNameCollector();
MainClassFinder.doWithMainClasses(this.testJarFile.getJarSource(), callback); MainClassFinder.doWithMainClasses(this.testJarFile.getJarSource(), callback);
assertThat(callback.getClassNames().toString(), equalTo("[a.b.G, a.b.c.D]")); assertThat(callback.getClassNames().toString()).isEqualTo("[a.b.G, a.b.c.D]");
} }
@Test @Test
@ -152,7 +151,7 @@ public class MainClassFinderTests {
this.testJarFile.addClass("a/b/G.class", ClassWithMainMethod.class); this.testJarFile.addClass("a/b/G.class", ClassWithMainMethod.class);
ClassNameCollector callback = new ClassNameCollector(); ClassNameCollector callback = new ClassNameCollector();
MainClassFinder.doWithMainClasses(this.testJarFile.getJarFile(), "", callback); MainClassFinder.doWithMainClasses(this.testJarFile.getJarFile(), "", callback);
assertThat(callback.getClassNames().toString(), equalTo("[a.b.G, a.b.c.D]")); assertThat(callback.getClassNames().toString()).isEqualTo("[a.b.G, a.b.c.D]");
} }
private static class ClassNameCollector implements ClassNameCallback<Object> { private static class ClassNameCollector implements ClassNameCallback<Object> {

@ -38,10 +38,7 @@ import org.springframework.boot.loader.tools.sample.ClassWithMainMethod;
import org.springframework.boot.loader.tools.sample.ClassWithoutMainMethod; import org.springframework.boot.loader.tools.sample.ClassWithoutMainMethod;
import org.springframework.util.FileCopyUtils; import org.springframework.util.FileCopyUtils;
import static org.hamcrest.Matchers.equalTo; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.startsWith;
import static org.junit.Assert.assertThat;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq; import static org.mockito.Matchers.eq;
@ -112,11 +109,11 @@ public class RepackagerTests {
repackager.setMainClass("a.b.C"); repackager.setMainClass("a.b.C");
repackager.repackage(NO_LIBRARIES); repackager.repackage(NO_LIBRARIES);
Manifest actualManifest = getManifest(file); Manifest actualManifest = getManifest(file);
assertThat(actualManifest.getMainAttributes().getValue("Main-Class"), assertThat(actualManifest.getMainAttributes().getValue("Main-Class"))
equalTo("org.springframework.boot.loader.JarLauncher")); .isEqualTo("org.springframework.boot.loader.JarLauncher");
assertThat(actualManifest.getMainAttributes().getValue("Start-Class"), assertThat(actualManifest.getMainAttributes().getValue("Start-Class"))
equalTo("a.b.C")); .isEqualTo("a.b.C");
assertThat(hasLauncherClasses(file), equalTo(true)); assertThat(hasLauncherClasses(file)).isTrue();
} }
@Test @Test
@ -130,11 +127,11 @@ public class RepackagerTests {
Repackager repackager = new Repackager(file); Repackager repackager = new Repackager(file);
repackager.repackage(NO_LIBRARIES); repackager.repackage(NO_LIBRARIES);
Manifest actualManifest = getManifest(file); Manifest actualManifest = getManifest(file);
assertThat(actualManifest.getMainAttributes().getValue("Main-Class"), assertThat(actualManifest.getMainAttributes().getValue("Main-Class"))
equalTo("org.springframework.boot.loader.JarLauncher")); .isEqualTo("org.springframework.boot.loader.JarLauncher");
assertThat(actualManifest.getMainAttributes().getValue("Start-Class"), assertThat(actualManifest.getMainAttributes().getValue("Start-Class"))
equalTo("a.b.C")); .isEqualTo("a.b.C");
assertThat(hasLauncherClasses(file), equalTo(true)); assertThat(hasLauncherClasses(file)).isTrue();
} }
@Test @Test
@ -144,11 +141,11 @@ public class RepackagerTests {
Repackager repackager = new Repackager(file); Repackager repackager = new Repackager(file);
repackager.repackage(NO_LIBRARIES); repackager.repackage(NO_LIBRARIES);
Manifest actualManifest = getManifest(file); Manifest actualManifest = getManifest(file);
assertThat(actualManifest.getMainAttributes().getValue("Main-Class"), assertThat(actualManifest.getMainAttributes().getValue("Main-Class"))
equalTo("org.springframework.boot.loader.JarLauncher")); .isEqualTo("org.springframework.boot.loader.JarLauncher");
assertThat(actualManifest.getMainAttributes().getValue("Start-Class"), assertThat(actualManifest.getMainAttributes().getValue("Start-Class"))
equalTo("a.b.C")); .isEqualTo("a.b.C");
assertThat(hasLauncherClasses(file), equalTo(true)); assertThat(hasLauncherClasses(file)).isTrue();
} }
@Test @Test
@ -159,11 +156,11 @@ public class RepackagerTests {
repackager.repackage(NO_LIBRARIES); repackager.repackage(NO_LIBRARIES);
repackager.repackage(NO_LIBRARIES); repackager.repackage(NO_LIBRARIES);
Manifest actualManifest = getManifest(file); Manifest actualManifest = getManifest(file);
assertThat(actualManifest.getMainAttributes().getValue("Main-Class"), assertThat(actualManifest.getMainAttributes().getValue("Main-Class"))
equalTo("org.springframework.boot.loader.JarLauncher")); .isEqualTo("org.springframework.boot.loader.JarLauncher");
assertThat(actualManifest.getMainAttributes().getValue("Start-Class"), assertThat(actualManifest.getMainAttributes().getValue("Start-Class"))
equalTo("a.b.C")); .isEqualTo("a.b.C");
assertThat(hasLauncherClasses(file), equalTo(true)); assertThat(hasLauncherClasses(file)).isTrue();
} }
@Test @Test
@ -194,9 +191,9 @@ public class RepackagerTests {
repackager.setLayout(new Layouts.None()); repackager.setLayout(new Layouts.None());
repackager.repackage(file, NO_LIBRARIES); repackager.repackage(file, NO_LIBRARIES);
Manifest actualManifest = getManifest(file); Manifest actualManifest = getManifest(file);
assertThat(actualManifest.getMainAttributes().getValue("Main-Class"), assertThat(actualManifest.getMainAttributes().getValue("Main-Class"))
equalTo("a.b.C")); .isEqualTo("a.b.C");
assertThat(hasLauncherClasses(file), equalTo(false)); assertThat(hasLauncherClasses(file)).isFalse();
} }
@Test @Test
@ -207,9 +204,9 @@ public class RepackagerTests {
repackager.setLayout(new Layouts.None()); repackager.setLayout(new Layouts.None());
repackager.repackage(file, NO_LIBRARIES); repackager.repackage(file, NO_LIBRARIES);
Manifest actualManifest = getManifest(file); Manifest actualManifest = getManifest(file);
assertThat(actualManifest.getMainAttributes().getValue("Main-Class"), assertThat(actualManifest.getMainAttributes().getValue("Main-Class"))
equalTo(null)); .isEqualTo(null);
assertThat(hasLauncherClasses(file), equalTo(false)); assertThat(hasLauncherClasses(file)).isFalse();
} }
@Test @Test
@ -218,9 +215,8 @@ public class RepackagerTests {
File file = this.testJarFile.getFile(); File file = this.testJarFile.getFile();
Repackager repackager = new Repackager(file); Repackager repackager = new Repackager(file);
repackager.repackage(NO_LIBRARIES); repackager.repackage(NO_LIBRARIES);
assertThat(new File(file.getParent(), file.getName() + ".original").exists(), assertThat(new File(file.getParent(), file.getName() + ".original")).exists();
equalTo(true)); assertThat(hasLauncherClasses(file)).isTrue();
assertThat(hasLauncherClasses(file), equalTo(true));
} }
@Test @Test
@ -230,9 +226,9 @@ public class RepackagerTests {
Repackager repackager = new Repackager(file); Repackager repackager = new Repackager(file);
repackager.setBackupSource(false); repackager.setBackupSource(false);
repackager.repackage(NO_LIBRARIES); repackager.repackage(NO_LIBRARIES);
assertThat(new File(file.getParent(), file.getName() + ".original").exists(), assertThat(new File(file.getParent(), file.getName() + ".original"))
equalTo(false)); .doesNotExist();
assertThat(hasLauncherClasses(file), equalTo(true)); assertThat(hasLauncherClasses(file)).isTrue();
} }
@Test @Test
@ -242,10 +238,10 @@ public class RepackagerTests {
File dest = this.temporaryFolder.newFile("different.jar"); File dest = this.temporaryFolder.newFile("different.jar");
Repackager repackager = new Repackager(source); Repackager repackager = new Repackager(source);
repackager.repackage(dest, NO_LIBRARIES); repackager.repackage(dest, NO_LIBRARIES);
assertThat(new File(source.getParent(), source.getName() + ".original").exists(), assertThat(new File(source.getParent(), source.getName() + ".original"))
equalTo(false)); .doesNotExist();
assertThat(hasLauncherClasses(source), equalTo(false)); assertThat(hasLauncherClasses(source)).isFalse();
assertThat(hasLauncherClasses(dest), equalTo(true)); assertThat(hasLauncherClasses(dest)).isTrue();
} }
@Test @Test
@ -273,7 +269,7 @@ public class RepackagerTests {
File dest = this.temporaryFolder.newFile("dest.jar"); File dest = this.temporaryFolder.newFile("dest.jar");
dest.createNewFile(); dest.createNewFile();
repackager.repackage(dest, NO_LIBRARIES); repackager.repackage(dest, NO_LIBRARIES);
assertThat(hasLauncherClasses(dest), equalTo(true)); assertThat(hasLauncherClasses(dest)).isTrue();
} }
@Test @Test
@ -309,14 +305,14 @@ public class RepackagerTests {
callback.library(new Library(libNonJarFile, LibraryScope.COMPILE)); callback.library(new Library(libNonJarFile, LibraryScope.COMPILE));
} }
}); });
assertThat(hasEntry(file, "lib/" + libJarFile.getName()), equalTo(true)); assertThat(hasEntry(file, "lib/" + libJarFile.getName())).isTrue();
assertThat(hasEntry(file, "lib/" + libJarFileToUnpack.getName()), equalTo(true)); assertThat(hasEntry(file, "lib/" + libJarFileToUnpack.getName())).isTrue();
assertThat(hasEntry(file, "lib/" + libNonJarFile.getName()), equalTo(false)); assertThat(hasEntry(file, "lib/" + libNonJarFile.getName())).isFalse();
JarEntry entry = getEntry(file, "lib/" + libJarFile.getName()); JarEntry entry = getEntry(file, "lib/" + libJarFile.getName());
assertThat(entry.getTime(), equalTo(JAN_1_1985)); assertThat(entry.getTime()).isEqualTo(JAN_1_1985);
entry = getEntry(file, "lib/" + libJarFileToUnpack.getName()); entry = getEntry(file, "lib/" + libJarFileToUnpack.getName());
assertThat(entry.getComment(), startsWith("UNPACK:")); assertThat(entry.getComment()).startsWith("UNPACK:");
assertThat(entry.getComment().length(), equalTo(47)); assertThat(entry.getComment().length()).isEqualTo(47);
} }
@Test @Test
@ -357,9 +353,9 @@ public class RepackagerTests {
callback.library(new Library(libJarFile, scope)); callback.library(new Library(libJarFile, scope));
} }
}); });
assertThat(hasEntry(file, "test/" + libJarFile.getName()), equalTo(true)); assertThat(hasEntry(file, "test/" + libJarFile.getName())).isTrue();
assertThat(getManifest(file).getMainAttributes().getValue("Main-Class"), assertThat(getManifest(file).getMainAttributes().getValue("Main-Class"))
equalTo("testLauncher")); .isEqualTo("testLauncher");
} }
@Test @Test
@ -369,8 +365,8 @@ public class RepackagerTests {
Repackager repackager = new Repackager(file); Repackager repackager = new Repackager(file);
repackager.repackage(NO_LIBRARIES); repackager.repackage(NO_LIBRARIES);
Manifest actualManifest = getManifest(file); Manifest actualManifest = getManifest(file);
assertThat(actualManifest.getMainAttributes() assertThat(actualManifest.getMainAttributes())
.containsKey(new Attributes.Name("Spring-Boot-Version")), equalTo(true)); .containsKey(new Attributes.Name("Spring-Boot-Version"));
} }
@Test @Test
@ -399,10 +395,10 @@ public class RepackagerTests {
}); });
JarFile jarFile = new JarFile(file); JarFile jarFile = new JarFile(file);
try { try {
assertThat(jarFile.getEntry("lib/" + nestedFile.getName()).getMethod(), assertThat(jarFile.getEntry("lib/" + nestedFile.getName()).getMethod())
equalTo(ZipEntry.STORED)); .isEqualTo(ZipEntry.STORED);
assertThat(jarFile.getEntry("test/nested.jar").getMethod(), assertThat(jarFile.getEntry("test/nested.jar").getMethod())
equalTo(ZipEntry.STORED)); .isEqualTo(ZipEntry.STORED);
} }
finally { finally {
jarFile.close(); jarFile.close();
@ -418,12 +414,12 @@ public class RepackagerTests {
LaunchScript script = new MockLauncherScript("ABC"); LaunchScript script = new MockLauncherScript("ABC");
repackager.repackage(dest, NO_LIBRARIES, script); repackager.repackage(dest, NO_LIBRARIES, script);
byte[] bytes = FileCopyUtils.copyToByteArray(dest); byte[] bytes = FileCopyUtils.copyToByteArray(dest);
assertThat(new String(bytes), startsWith("ABC")); assertThat(new String(bytes)).startsWith("ABC");
assertThat(hasLauncherClasses(source), equalTo(false)); assertThat(hasLauncherClasses(source)).isFalse();
assertThat(hasLauncherClasses(dest), equalTo(true)); assertThat(hasLauncherClasses(dest)).isTrue();
try { try {
assertThat(Files.getPosixFilePermissions(dest.toPath()), assertThat(Files.getPosixFilePermissions(dest.toPath()))
hasItem(PosixFilePermission.OWNER_EXECUTE)); .contains(PosixFilePermission.OWNER_EXECUTE);
} }
catch (UnsupportedOperationException ex) { catch (UnsupportedOperationException ex) {
// Probably running the test on Windows // Probably running the test on Windows
@ -450,8 +446,8 @@ public class RepackagerTests {
}); });
JarFile jarFile = new JarFile(file); JarFile jarFile = new JarFile(file);
try { try {
assertThat(jarFile.getEntry("lib/" + nestedFile.getName()).getComment(), assertThat(jarFile.getEntry("lib/" + nestedFile.getName()).getComment())
startsWith("UNPACK:")); .startsWith("UNPACK:");
} }
finally { finally {
jarFile.close(); jarFile.close();
@ -482,8 +478,8 @@ public class RepackagerTests {
}); });
JarFile jarFile = new JarFile(file); JarFile jarFile = new JarFile(file);
try { try {
assertThat(jarFile.getEntry("lib/" + nestedFile.getName()).getSize(), assertThat(jarFile.getEntry("lib/" + nestedFile.getName()).getSize())
equalTo(sourceLength)); .isEqualTo(sourceLength);
} }
finally { finally {
jarFile.close(); jarFile.close();

@ -28,8 +28,7 @@ import org.mockito.MockitoAnnotations;
import org.springframework.boot.loader.archive.Archive.Entry; import org.springframework.boot.loader.archive.Archive.Entry;
import static org.junit.Assert.assertArrayEquals; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertTrue;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
/** /**
@ -87,8 +86,8 @@ public class ExecutableArchiveLauncherTests {
} }
private void assertClassLoaderUrls(ClassLoader classLoader, URL[] urls) { private void assertClassLoaderUrls(ClassLoader classLoader, URL[] urls) {
assertTrue(classLoader instanceof URLClassLoader); assertThat(classLoader).isInstanceOf(URLClassLoader.class);
assertArrayEquals(urls, ((URLClassLoader) classLoader).getURLs()); assertThat(((URLClassLoader) classLoader).getURLs()).isEqualTo(urls);
} }
private void doWithTccl(ClassLoader classLoader, Callable<?> action) private void doWithTccl(ClassLoader classLoader, Callable<?> action)

@ -23,8 +23,7 @@ import java.util.Arrays;
import org.junit.Test; import org.junit.Test;
import static org.junit.Assert.assertFalse; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertTrue;
/** /**
* Tests for {@link InputArgumentsJavaAgentDetector} * Tests for {@link InputArgumentsJavaAgentDetector}
@ -38,24 +37,25 @@ public class InputArgumentsJavaAgentDetectorTests {
throws MalformedURLException, IOException { throws MalformedURLException, IOException {
InputArgumentsJavaAgentDetector detector = new InputArgumentsJavaAgentDetector( InputArgumentsJavaAgentDetector detector = new InputArgumentsJavaAgentDetector(
Arrays.asList("-javaagent:my-agent.jar")); Arrays.asList("-javaagent:my-agent.jar"));
assertFalse(detector.isJavaAgentJar( assertThat(detector.isJavaAgentJar(
new File("something-else.jar").getCanonicalFile().toURI().toURL())); new File("something-else.jar").getCanonicalFile().toURI().toURL()))
.isFalse();
} }
@Test @Test
public void singleJavaAgent() throws MalformedURLException, IOException { public void singleJavaAgent() throws MalformedURLException, IOException {
InputArgumentsJavaAgentDetector detector = new InputArgumentsJavaAgentDetector( InputArgumentsJavaAgentDetector detector = new InputArgumentsJavaAgentDetector(
Arrays.asList("-javaagent:my-agent.jar")); Arrays.asList("-javaagent:my-agent.jar"));
assertTrue(detector.isJavaAgentJar( assertThat(detector.isJavaAgentJar(
new File("my-agent.jar").getCanonicalFile().toURI().toURL())); new File("my-agent.jar").getCanonicalFile().toURI().toURL())).isTrue();
} }
@Test @Test
public void singleJavaAgentWithOptions() throws MalformedURLException, IOException { public void singleJavaAgentWithOptions() throws MalformedURLException, IOException {
InputArgumentsJavaAgentDetector detector = new InputArgumentsJavaAgentDetector( InputArgumentsJavaAgentDetector detector = new InputArgumentsJavaAgentDetector(
Arrays.asList("-javaagent:my-agent.jar=a=alpha,b=bravo")); Arrays.asList("-javaagent:my-agent.jar=a=alpha,b=bravo"));
assertTrue(detector.isJavaAgentJar( assertThat(detector.isJavaAgentJar(
new File("my-agent.jar").getCanonicalFile().toURI().toURL())); new File("my-agent.jar").getCanonicalFile().toURI().toURL())).isTrue();
} }
@Test @Test
@ -63,10 +63,11 @@ public class InputArgumentsJavaAgentDetectorTests {
InputArgumentsJavaAgentDetector detector = new InputArgumentsJavaAgentDetector( InputArgumentsJavaAgentDetector detector = new InputArgumentsJavaAgentDetector(
Arrays.asList("-javaagent:my-agent.jar", Arrays.asList("-javaagent:my-agent.jar",
"-javaagent:my-other-agent.jar")); "-javaagent:my-other-agent.jar"));
assertTrue(detector.isJavaAgentJar( assertThat(detector.isJavaAgentJar(
new File("my-agent.jar").getCanonicalFile().toURI().toURL())); new File("my-agent.jar").getCanonicalFile().toURI().toURL())).isTrue();
assertTrue(detector.isJavaAgentJar( assertThat(detector.isJavaAgentJar(
new File("my-other-agent.jar").getCanonicalFile().toURI().toURL())); new File("my-other-agent.jar").getCanonicalFile().toURI().toURL()))
.isTrue();
} }
} }

@ -25,11 +25,7 @@ import org.junit.rules.TemporaryFolder;
import org.springframework.boot.loader.jar.JarFile; import org.springframework.boot.loader.jar.JarFile;
import static org.hamcrest.Matchers.equalTo; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
/** /**
* Tests for {@link LaunchedURLClassLoader}. * Tests for {@link LaunchedURLClassLoader}.
@ -47,13 +43,13 @@ public class LaunchedURLClassLoaderTests {
public void resolveResourceFromWindowsFilesystem() throws Exception { public void resolveResourceFromWindowsFilesystem() throws Exception {
// This path is invalid - it should return null even on Windows. // This path is invalid - it should return null even on Windows.
// A regular URLClassLoader will deal with it gracefully. // A regular URLClassLoader will deal with it gracefully.
assertNull(getClass().getClassLoader() assertThat(getClass().getClassLoader()
.getResource("c:\\Users\\user\\bar.properties")); .getResource("c:\\Users\\user\\bar.properties")).isNull();
LaunchedURLClassLoader loader = new LaunchedURLClassLoader( LaunchedURLClassLoader loader = new LaunchedURLClassLoader(
new URL[] { new URL("jar:file:src/test/resources/jars/app.jar!/") }, new URL[] { new URL("jar:file:src/test/resources/jars/app.jar!/") },
getClass().getClassLoader()); getClass().getClassLoader());
// So we should too... // So we should too...
assertNull(loader.getResource("c:\\Users\\user\\bar.properties")); assertThat(loader.getResource("c:\\Users\\user\\bar.properties")).isNull();
} }
@Test @Test
@ -61,7 +57,7 @@ public class LaunchedURLClassLoaderTests {
LaunchedURLClassLoader loader = new LaunchedURLClassLoader( LaunchedURLClassLoader loader = new LaunchedURLClassLoader(
new URL[] { new URL("jar:file:src/test/resources/jars/app.jar!/") }, new URL[] { new URL("jar:file:src/test/resources/jars/app.jar!/") },
getClass().getClassLoader()); getClass().getClassLoader());
assertNotNull(loader.getResource("demo/Application.java")); assertThat(loader.getResource("demo/Application.java")).isNotNull();
} }
@Test @Test
@ -69,7 +65,8 @@ public class LaunchedURLClassLoaderTests {
LaunchedURLClassLoader loader = new LaunchedURLClassLoader( LaunchedURLClassLoader loader = new LaunchedURLClassLoader(
new URL[] { new URL("jar:file:src/test/resources/jars/app.jar!/") }, new URL[] { new URL("jar:file:src/test/resources/jars/app.jar!/") },
getClass().getClassLoader()); getClass().getClassLoader());
assertTrue(loader.getResources("demo/Application.java").hasMoreElements()); assertThat(loader.getResources("demo/Application.java").hasMoreElements())
.isTrue();
} }
@Test @Test
@ -77,7 +74,7 @@ public class LaunchedURLClassLoaderTests {
LaunchedURLClassLoader loader = new LaunchedURLClassLoader( LaunchedURLClassLoader loader = new LaunchedURLClassLoader(
new URL[] { new URL("jar:file:src/test/resources/jars/app.jar!/") }, new URL[] { new URL("jar:file:src/test/resources/jars/app.jar!/") },
getClass().getClassLoader()); getClass().getClassLoader());
assertNotNull(loader.getResource("")); assertThat(loader.getResource("")).isNotNull();
} }
@Test @Test
@ -85,7 +82,7 @@ public class LaunchedURLClassLoaderTests {
LaunchedURLClassLoader loader = new LaunchedURLClassLoader( LaunchedURLClassLoader loader = new LaunchedURLClassLoader(
new URL[] { new URL("jar:file:src/test/resources/jars/app.jar!/") }, new URL[] { new URL("jar:file:src/test/resources/jars/app.jar!/") },
getClass().getClassLoader()); getClass().getClassLoader());
assertTrue(loader.getResources("").hasMoreElements()); assertThat(loader.getResources("").hasMoreElements()).isTrue();
} }
@Test @Test
@ -97,8 +94,8 @@ public class LaunchedURLClassLoaderTests {
LaunchedURLClassLoader loader = new LaunchedURLClassLoader(new URL[] { url }, LaunchedURLClassLoader loader = new LaunchedURLClassLoader(new URL[] { url },
null); null);
URL resource = loader.getResource("nested.jar!/3.dat"); URL resource = loader.getResource("nested.jar!/3.dat");
assertThat(resource.toString(), equalTo(url + "nested.jar!/3.dat")); assertThat(resource.toString()).isEqualTo(url + "nested.jar!/3.dat");
assertThat(resource.openConnection().getInputStream().read(), equalTo(3)); assertThat(resource.openConnection().getInputStream().read()).isEqualTo(3);
} }
} }

@ -34,13 +34,7 @@ import org.mockito.MockitoAnnotations;
import org.springframework.boot.loader.archive.Archive; import org.springframework.boot.loader.archive.Archive;
import org.springframework.test.util.ReflectionTestUtils; import org.springframework.test.util.ReflectionTestUtils;
import static org.hamcrest.Matchers.equalTo; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verify;
@ -78,31 +72,32 @@ public class PropertiesLauncherTests {
@Test @Test
public void testDefaultHome() { public void testDefaultHome() {
PropertiesLauncher launcher = new PropertiesLauncher(); PropertiesLauncher launcher = new PropertiesLauncher();
assertEquals(new File(System.getProperty("loader.home")), assertThat(launcher.getHomeDirectory())
launcher.getHomeDirectory()); .isEqualTo(new File(System.getProperty("loader.home")));
} }
@Test @Test
public void testUserSpecifiedMain() throws Exception { public void testUserSpecifiedMain() throws Exception {
PropertiesLauncher launcher = new PropertiesLauncher(); PropertiesLauncher launcher = new PropertiesLauncher();
assertEquals("demo.Application", launcher.getMainClass()); assertThat(launcher.getMainClass()).isEqualTo("demo.Application");
assertNull(System.getProperty("loader.main")); assertThat(System.getProperty("loader.main")).isNull();
} }
@Test @Test
public void testUserSpecifiedConfigName() throws Exception { public void testUserSpecifiedConfigName() throws Exception {
System.setProperty("loader.config.name", "foo"); System.setProperty("loader.config.name", "foo");
PropertiesLauncher launcher = new PropertiesLauncher(); PropertiesLauncher launcher = new PropertiesLauncher();
assertEquals("my.Application", launcher.getMainClass()); assertThat(launcher.getMainClass()).isEqualTo("my.Application");
assertEquals("[etc/]", assertThat(ReflectionTestUtils.getField(launcher, "paths").toString())
ReflectionTestUtils.getField(launcher, "paths").toString()); .isEqualTo("[etc/]");
} }
@Test @Test
public void testUserSpecifiedDotPath() throws Exception { public void testUserSpecifiedDotPath() throws Exception {
System.setProperty("loader.path", "."); System.setProperty("loader.path", ".");
PropertiesLauncher launcher = new PropertiesLauncher(); PropertiesLauncher launcher = new PropertiesLauncher();
assertEquals("[.]", ReflectionTestUtils.getField(launcher, "paths").toString()); assertThat(ReflectionTestUtils.getField(launcher, "paths").toString())
.isEqualTo("[.]");
} }
@Test @Test
@ -110,8 +105,8 @@ public class PropertiesLauncherTests {
System.setProperty("loader.path", "jars/*"); System.setProperty("loader.path", "jars/*");
System.setProperty("loader.main", "demo.Application"); System.setProperty("loader.main", "demo.Application");
PropertiesLauncher launcher = new PropertiesLauncher(); PropertiesLauncher launcher = new PropertiesLauncher();
assertEquals("[jars/]", assertThat(ReflectionTestUtils.getField(launcher, "paths").toString())
ReflectionTestUtils.getField(launcher, "paths").toString()); .isEqualTo("[jars/]");
launcher.launch(new String[0]); launcher.launch(new String[0]);
waitFor("Hello World"); waitFor("Hello World");
} }
@ -121,8 +116,8 @@ public class PropertiesLauncherTests {
System.setProperty("loader.path", "jars/app.jar"); System.setProperty("loader.path", "jars/app.jar");
System.setProperty("loader.main", "demo.Application"); System.setProperty("loader.main", "demo.Application");
PropertiesLauncher launcher = new PropertiesLauncher(); PropertiesLauncher launcher = new PropertiesLauncher();
assertEquals("[jars/app.jar]", assertThat(ReflectionTestUtils.getField(launcher, "paths").toString())
ReflectionTestUtils.getField(launcher, "paths").toString()); .isEqualTo("[jars/app.jar]");
launcher.launch(new String[0]); launcher.launch(new String[0]);
waitFor("Hello World"); waitFor("Hello World");
} }
@ -132,8 +127,8 @@ public class PropertiesLauncherTests {
System.setProperty("loader.path", "./jars/app.jar"); System.setProperty("loader.path", "./jars/app.jar");
System.setProperty("loader.main", "demo.Application"); System.setProperty("loader.main", "demo.Application");
PropertiesLauncher launcher = new PropertiesLauncher(); PropertiesLauncher launcher = new PropertiesLauncher();
assertEquals("[jars/app.jar]", assertThat(ReflectionTestUtils.getField(launcher, "paths").toString())
ReflectionTestUtils.getField(launcher, "paths").toString()); .isEqualTo("[jars/app.jar]");
launcher.launch(new String[0]); launcher.launch(new String[0]);
waitFor("Hello World"); waitFor("Hello World");
} }
@ -143,8 +138,8 @@ public class PropertiesLauncherTests {
System.setProperty("loader.path", "jars/app.jar"); System.setProperty("loader.path", "jars/app.jar");
System.setProperty("loader.classLoader", URLClassLoader.class.getName()); System.setProperty("loader.classLoader", URLClassLoader.class.getName());
PropertiesLauncher launcher = new PropertiesLauncher(); PropertiesLauncher launcher = new PropertiesLauncher();
assertEquals("[jars/app.jar]", assertThat(ReflectionTestUtils.getField(launcher, "paths").toString())
ReflectionTestUtils.getField(launcher, "paths").toString()); .isEqualTo("[jars/app.jar]");
launcher.launch(new String[0]); launcher.launch(new String[0]);
waitFor("Hello World"); waitFor("Hello World");
} }
@ -154,8 +149,8 @@ public class PropertiesLauncherTests {
System.setProperty("loader.path", "more-jars/app.jar,jars/app.jar"); System.setProperty("loader.path", "more-jars/app.jar,jars/app.jar");
System.setProperty("loader.classLoader", URLClassLoader.class.getName()); System.setProperty("loader.classLoader", URLClassLoader.class.getName());
PropertiesLauncher launcher = new PropertiesLauncher(); PropertiesLauncher launcher = new PropertiesLauncher();
assertEquals("[more-jars/app.jar, jars/app.jar]", assertThat(ReflectionTestUtils.getField(launcher, "paths").toString())
ReflectionTestUtils.getField(launcher, "paths").toString()); .isEqualTo("[more-jars/app.jar, jars/app.jar]");
launcher.launch(new String[0]); launcher.launch(new String[0]);
waitFor("Hello Other World"); waitFor("Hello Other World");
} }
@ -165,8 +160,8 @@ public class PropertiesLauncherTests {
System.setProperty("loader.classLoader", TestLoader.class.getName()); System.setProperty("loader.classLoader", TestLoader.class.getName());
PropertiesLauncher launcher = new PropertiesLauncher(); PropertiesLauncher launcher = new PropertiesLauncher();
ClassLoader loader = launcher.createClassLoader(Collections.<Archive>emptyList()); ClassLoader loader = launcher.createClassLoader(Collections.<Archive>emptyList());
assertNotNull(loader); assertThat(loader).isNotNull();
assertEquals(TestLoader.class.getName(), loader.getClass().getName()); assertThat(loader.getClass().getName()).isEqualTo(TestLoader.class.getName());
} }
@Test @Test
@ -175,28 +170,29 @@ public class PropertiesLauncherTests {
System.setProperty("loader.config.name", "foo"); System.setProperty("loader.config.name", "foo");
System.setProperty("loader.config.location", "classpath:bar.properties"); System.setProperty("loader.config.location", "classpath:bar.properties");
PropertiesLauncher launcher = new PropertiesLauncher(); PropertiesLauncher launcher = new PropertiesLauncher();
assertEquals("my.BarApplication", launcher.getMainClass()); assertThat(launcher.getMainClass()).isEqualTo("my.BarApplication");
} }
@Test @Test
public void testSystemPropertySpecifiedMain() throws Exception { public void testSystemPropertySpecifiedMain() throws Exception {
System.setProperty("loader.main", "foo.Bar"); System.setProperty("loader.main", "foo.Bar");
PropertiesLauncher launcher = new PropertiesLauncher(); PropertiesLauncher launcher = new PropertiesLauncher();
assertEquals("foo.Bar", launcher.getMainClass()); assertThat(launcher.getMainClass()).isEqualTo("foo.Bar");
} }
@Test @Test
public void testSystemPropertiesSet() throws Exception { public void testSystemPropertiesSet() throws Exception {
System.setProperty("loader.system", "true"); System.setProperty("loader.system", "true");
new PropertiesLauncher(); new PropertiesLauncher();
assertEquals("demo.Application", System.getProperty("loader.main")); assertThat(System.getProperty("loader.main")).isEqualTo("demo.Application");
} }
@Test @Test
public void testArgsEnhanced() throws Exception { public void testArgsEnhanced() throws Exception {
System.setProperty("loader.args", "foo"); System.setProperty("loader.args", "foo");
PropertiesLauncher launcher = new PropertiesLauncher(); PropertiesLauncher launcher = new PropertiesLauncher();
assertEquals("[foo, bar]", Arrays.asList(launcher.getArgs("bar")).toString()); assertThat(Arrays.asList(launcher.getArgs("bar")).toString())
.isEqualTo("[foo, bar]");
} }
@Test @Test
@ -208,8 +204,7 @@ public class PropertiesLauncherTests {
} }
List<Archive> nonAgentArchives = new PropertiesLauncher(this.javaAgentDetector) List<Archive> nonAgentArchives = new PropertiesLauncher(this.javaAgentDetector)
.getClassPathArchives(); .getClassPathArchives();
assertThat(nonAgentArchives.size(), assertThat(nonAgentArchives).hasSize(allArchives.size() - parentUrls.length);
is(equalTo(allArchives.size() - parentUrls.length)));
for (URL url : parentUrls) { for (URL url : parentUrls) {
verify(this.javaAgentDetector).isJavaAgentJar(url); verify(this.javaAgentDetector).isJavaAgentJar(url);
} }
@ -223,7 +218,7 @@ public class PropertiesLauncherTests {
Thread.sleep(50L); Thread.sleep(50L);
timeout = this.output.toString().contains(value); timeout = this.output.toString().contains(value);
} }
assertTrue("Timed out waiting for (" + value + ")", timeout); assertThat(timeout).as("Timed out waiting for (" + value + ")").isTrue();
} }
public static class TestLoader extends URLClassLoader { public static class TestLoader extends URLClassLoader {

@ -38,9 +38,7 @@ import org.springframework.boot.loader.archive.ExplodedArchive;
import org.springframework.boot.loader.archive.JarFileArchive; import org.springframework.boot.loader.archive.JarFileArchive;
import org.springframework.util.FileSystemUtils; import org.springframework.util.FileSystemUtils;
import static org.hamcrest.Matchers.hasItems; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
/** /**
* Tests for {@link WarLauncher} * Tests for {@link WarLauncher}
@ -61,28 +59,23 @@ public class WarLauncherTests {
webInfLib.mkdirs(); webInfLib.mkdirs();
File webInfLibFoo = new File(webInfLib, "foo.jar"); File webInfLibFoo = new File(webInfLib, "foo.jar");
new JarOutputStream(new FileOutputStream(webInfLibFoo)).close(); new JarOutputStream(new FileOutputStream(webInfLibFoo)).close();
WarLauncher launcher = new WarLauncher(new ExplodedArchive(warRoot, true)); WarLauncher launcher = new WarLauncher(new ExplodedArchive(warRoot, true));
List<Archive> archives = launcher.getClassPathArchives(); List<Archive> archives = launcher.getClassPathArchives();
assertEquals(2, archives.size()); assertThat(archives).hasSize(2);
assertThat(getUrls(archives)).containsOnly(webInfClasses.toURI().toURL(),
assertThat(getUrls(archives), hasItems(webInfClasses.toURI().toURL(), new URL("jar:" + webInfLibFoo.toURI().toURL() + "!/"));
new URL("jar:" + webInfLibFoo.toURI().toURL() + "!/")));
} }
@Test @Test
public void archivedWarHasOnlyWebInfClassesAndContentsOfWebInfLibOnClasspath() public void archivedWarHasOnlyWebInfClassesAndContentsOfWebInfLibOnClasspath()
throws Exception { throws Exception {
File warRoot = createWarArchive(); File warRoot = createWarArchive();
WarLauncher launcher = new WarLauncher(new JarFileArchive(warRoot)); WarLauncher launcher = new WarLauncher(new JarFileArchive(warRoot));
List<Archive> archives = launcher.getClassPathArchives(); List<Archive> archives = launcher.getClassPathArchives();
assertEquals(2, archives.size()); assertThat(archives).hasSize(2);
assertThat(getUrls(archives)).containsOnly(
assertThat(getUrls(archives), new URL("jar:" + warRoot.toURI().toURL() + "!/WEB-INF/classes!/"),
hasItems(new URL("jar:" + warRoot.toURI().toURL() new URL("jar:" + warRoot.toURI().toURL() + "!/WEB-INF/lib/foo.jar!/"));
+ "!/WEB-INF/classes!/"),
new URL("jar:" + warRoot.toURI().toURL() + "!/WEB-INF/lib/foo.jar!/")));
} }
private Set<URL> getUrls(List<Archive> archives) throws MalformedURLException { private Set<URL> getUrls(List<Archive> archives) throws MalformedURLException {
@ -96,14 +89,11 @@ public class WarLauncherTests {
private File createWarArchive() throws IOException, FileNotFoundException { private File createWarArchive() throws IOException, FileNotFoundException {
File warRoot = new File("target/archive.war"); File warRoot = new File("target/archive.war");
warRoot.delete(); warRoot.delete();
JarOutputStream jarOutputStream = new JarOutputStream( JarOutputStream jarOutputStream = new JarOutputStream(
new FileOutputStream(warRoot)); new FileOutputStream(warRoot));
jarOutputStream.putNextEntry(new JarEntry("WEB-INF/")); jarOutputStream.putNextEntry(new JarEntry("WEB-INF/"));
jarOutputStream.putNextEntry(new JarEntry("WEB-INF/classes/")); jarOutputStream.putNextEntry(new JarEntry("WEB-INF/classes/"));
jarOutputStream.putNextEntry(new JarEntry("WEB-INF/lib/")); jarOutputStream.putNextEntry(new JarEntry("WEB-INF/lib/"));
JarEntry webInfLibFoo = new JarEntry("WEB-INF/lib/foo.jar"); JarEntry webInfLibFoo = new JarEntry("WEB-INF/lib/foo.jar");
webInfLibFoo.setMethod(ZipEntry.STORED); webInfLibFoo.setMethod(ZipEntry.STORED);
ByteArrayOutputStream fooJarStream = new ByteArrayOutputStream(); ByteArrayOutputStream fooJarStream = new ByteArrayOutputStream();
@ -114,7 +104,6 @@ public class WarLauncherTests {
webInfLibFoo.setCrc(crc32.getValue()); webInfLibFoo.setCrc(crc32.getValue());
jarOutputStream.putNextEntry(webInfLibFoo); jarOutputStream.putNextEntry(webInfLibFoo);
jarOutputStream.write(fooJarStream.toByteArray()); jarOutputStream.write(fooJarStream.toByteArray());
jarOutputStream.close(); jarOutputStream.close();
return warRoot; return warRoot;
} }

@ -38,10 +38,7 @@ import org.junit.rules.TemporaryFolder;
import org.springframework.boot.loader.TestJarCreator; import org.springframework.boot.loader.TestJarCreator;
import org.springframework.boot.loader.archive.Archive.Entry; import org.springframework.boot.loader.archive.Archive.Entry;
import static org.hamcrest.Matchers.equalTo; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.greaterThan;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
/** /**
* Tests for {@link ExplodedArchive}. * Tests for {@link ExplodedArchive}.
@ -93,29 +90,29 @@ public class ExplodedArchiveTests {
@Test @Test
public void getManifest() throws Exception { public void getManifest() throws Exception {
assertThat(this.archive.getManifest().getMainAttributes().getValue("Built-By"), assertThat(this.archive.getManifest().getMainAttributes().getValue("Built-By"))
equalTo("j1")); .isEqualTo("j1");
} }
@Test @Test
public void getEntries() throws Exception { public void getEntries() throws Exception {
Map<String, Archive.Entry> entries = getEntriesMap(this.archive); Map<String, Archive.Entry> entries = getEntriesMap(this.archive);
assertThat(entries.size(), equalTo(10)); assertThat(entries.size()).isEqualTo(10);
} }
@Test @Test
public void getUrl() throws Exception { public void getUrl() throws Exception {
URL url = this.archive.getUrl(); URL url = this.archive.getUrl();
assertThat(new File(URLDecoder.decode(url.getFile(), "UTF-8")), assertThat(new File(URLDecoder.decode(url.getFile(), "UTF-8")))
equalTo(this.rootFolder)); .isEqualTo(this.rootFolder);
} }
@Test @Test
public void getNestedArchive() throws Exception { public void getNestedArchive() throws Exception {
Entry entry = getEntriesMap(this.archive).get("nested.jar"); Entry entry = getEntriesMap(this.archive).get("nested.jar");
Archive nested = this.archive.getNestedArchive(entry); Archive nested = this.archive.getNestedArchive(entry);
assertThat(nested.getUrl().toString(), assertThat(nested.getUrl().toString())
equalTo("jar:" + this.rootFolder.toURI() + "nested.jar!/")); .isEqualTo("jar:" + this.rootFolder.toURI() + "nested.jar!/");
} }
@Test @Test
@ -123,43 +120,44 @@ public class ExplodedArchiveTests {
Entry entry = getEntriesMap(this.archive).get("d/"); Entry entry = getEntriesMap(this.archive).get("d/");
Archive nested = this.archive.getNestedArchive(entry); Archive nested = this.archive.getNestedArchive(entry);
Map<String, Entry> nestedEntries = getEntriesMap(nested); Map<String, Entry> nestedEntries = getEntriesMap(nested);
assertThat(nestedEntries.size(), equalTo(1)); assertThat(nestedEntries.size()).isEqualTo(1);
assertThat(nested.getUrl().toString(), assertThat(nested.getUrl().toString())
equalTo("file:" + this.rootFolder.toURI().getPath() + "d/")); .isEqualTo("file:" + this.rootFolder.toURI().getPath() + "d/");
} }
@Test @Test
public void getNonRecursiveEntriesForRoot() throws Exception { public void getNonRecursiveEntriesForRoot() throws Exception {
ExplodedArchive archive = new ExplodedArchive(new File("/"), false); ExplodedArchive archive = new ExplodedArchive(new File("/"), false);
Map<String, Archive.Entry> entries = getEntriesMap(archive); Map<String, Archive.Entry> entries = getEntriesMap(archive);
assertThat(entries.size(), greaterThan(1)); assertThat(entries.size()).isGreaterThan(1);
} }
@Test @Test
public void getNonRecursiveManifest() throws Exception { public void getNonRecursiveManifest() throws Exception {
ExplodedArchive archive = new ExplodedArchive( ExplodedArchive archive = new ExplodedArchive(
new File("src/test/resources/root")); new File("src/test/resources/root"));
assertNotNull(archive.getManifest()); assertThat(archive.getManifest()).isNotNull();
Map<String, Archive.Entry> entries = getEntriesMap(archive); Map<String, Archive.Entry> entries = getEntriesMap(archive);
assertThat(entries.size(), equalTo(4)); assertThat(entries.size()).isEqualTo(4);
} }
@Test @Test
public void getNonRecursiveManifestEvenIfNonRecursive() throws Exception { public void getNonRecursiveManifestEvenIfNonRecursive() throws Exception {
ExplodedArchive archive = new ExplodedArchive(new File("src/test/resources/root"), ExplodedArchive archive = new ExplodedArchive(new File("src/test/resources/root"),
false); false);
assertNotNull(archive.getManifest()); assertThat(archive.getManifest()).isNotNull();
Map<String, Archive.Entry> entries = getEntriesMap(archive); Map<String, Archive.Entry> entries = getEntriesMap(archive);
assertThat(entries.size(), equalTo(3)); assertThat(entries.size()).isEqualTo(3);
} }
@Test @Test
public void getResourceAsStream() throws Exception { public void getResourceAsStream() throws Exception {
ExplodedArchive archive = new ExplodedArchive( ExplodedArchive archive = new ExplodedArchive(
new File("src/test/resources/root")); new File("src/test/resources/root"));
assertNotNull(archive.getManifest()); assertThat(archive.getManifest()).isNotNull();
URLClassLoader loader = new URLClassLoader(new URL[] { archive.getUrl() }); URLClassLoader loader = new URLClassLoader(new URL[] { archive.getUrl() });
assertNotNull(loader.getResourceAsStream("META-INF/spring/application.xml")); assertThat(loader.getResourceAsStream("META-INF/spring/application.xml"))
.isNotNull();
loader.close(); loader.close();
} }
@ -167,9 +165,10 @@ public class ExplodedArchiveTests {
public void getResourceAsStreamNonRecursive() throws Exception { public void getResourceAsStreamNonRecursive() throws Exception {
ExplodedArchive archive = new ExplodedArchive(new File("src/test/resources/root"), ExplodedArchive archive = new ExplodedArchive(new File("src/test/resources/root"),
false); false);
assertNotNull(archive.getManifest()); assertThat(archive.getManifest()).isNotNull();
URLClassLoader loader = new URLClassLoader(new URL[] { archive.getUrl() }); URLClassLoader loader = new URLClassLoader(new URL[] { archive.getUrl() });
assertNotNull(loader.getResourceAsStream("META-INF/spring/application.xml")); assertThat(loader.getResourceAsStream("META-INF/spring/application.xml"))
.isNotNull();
loader.close(); loader.close();
} }
@ -180,4 +179,5 @@ public class ExplodedArchiveTests {
} }
return entries; return entries;
} }
} }

@ -29,12 +29,7 @@ import org.junit.rules.TemporaryFolder;
import org.springframework.boot.loader.TestJarCreator; import org.springframework.boot.loader.TestJarCreator;
import org.springframework.boot.loader.archive.Archive.Entry; import org.springframework.boot.loader.archive.Archive.Entry;
import static org.hamcrest.Matchers.endsWith; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.startsWith;
import static org.junit.Assert.assertThat;
/** /**
* Tests for {@link JarFileArchive}. * Tests for {@link JarFileArchive}.
@ -67,28 +62,28 @@ public class JarFileArchiveTests {
@Test @Test
public void getManifest() throws Exception { public void getManifest() throws Exception {
assertThat(this.archive.getManifest().getMainAttributes().getValue("Built-By"), assertThat(this.archive.getManifest().getMainAttributes().getValue("Built-By"))
equalTo("j1")); .isEqualTo("j1");
} }
@Test @Test
public void getEntries() throws Exception { public void getEntries() throws Exception {
Map<String, Archive.Entry> entries = getEntriesMap(this.archive); Map<String, Archive.Entry> entries = getEntriesMap(this.archive);
assertThat(entries.size(), equalTo(10)); assertThat(entries.size()).isEqualTo(10);
} }
@Test @Test
public void getUrl() throws Exception { public void getUrl() throws Exception {
URL url = this.archive.getUrl(); URL url = this.archive.getUrl();
assertThat(url.toString(), equalTo("jar:" + this.rootJarFileUrl + "!/")); assertThat(url.toString()).isEqualTo("jar:" + this.rootJarFileUrl + "!/");
} }
@Test @Test
public void getNestedArchive() throws Exception { public void getNestedArchive() throws Exception {
Entry entry = getEntriesMap(this.archive).get("nested.jar"); Entry entry = getEntriesMap(this.archive).get("nested.jar");
Archive nested = this.archive.getNestedArchive(entry); Archive nested = this.archive.getNestedArchive(entry);
assertThat(nested.getUrl().toString(), assertThat(nested.getUrl().toString())
equalTo("jar:" + this.rootJarFileUrl + "!/nested.jar!/")); .isEqualTo("jar:" + this.rootJarFileUrl + "!/nested.jar!/");
} }
@Test @Test
@ -96,8 +91,8 @@ public class JarFileArchiveTests {
setup(true); setup(true);
Entry entry = getEntriesMap(this.archive).get("nested.jar"); Entry entry = getEntriesMap(this.archive).get("nested.jar");
Archive nested = this.archive.getNestedArchive(entry); Archive nested = this.archive.getNestedArchive(entry);
assertThat(nested.getUrl().toString(), startsWith("file:")); assertThat(nested.getUrl().toString()).startsWith("file:");
assertThat(nested.getUrl().toString(), endsWith("/nested.jar")); assertThat(nested.getUrl().toString()).endsWith("/nested.jar");
} }
@Test @Test
@ -108,7 +103,7 @@ public class JarFileArchiveTests {
setup(true); setup(true);
entry = getEntriesMap(this.archive).get("nested.jar"); entry = getEntriesMap(this.archive).get("nested.jar");
URL secondNested = this.archive.getNestedArchive(entry).getUrl(); URL secondNested = this.archive.getNestedArchive(entry).getUrl();
assertThat(secondNested, is(not(equalTo(firstNested)))); assertThat(secondNested).isNotEqualTo(firstNested);
} }
@Test @Test
@ -122,7 +117,7 @@ public class JarFileArchiveTests {
.getNestedArchive( .getNestedArchive(
getEntriesMap(this.archive).get("another-nested.jar")) getEntriesMap(this.archive).get("another-nested.jar"))
.getUrl().toURI()); .getUrl().toURI());
assertThat(nested.getParent(), is(equalTo(anotherNested.getParent()))); assertThat(nested.getParent()).isEqualTo(anotherNested.getParent());
} }
private Map<String, Archive.Entry> getEntriesMap(Archive archive) { private Map<String, Archive.Entry> getEntriesMap(Archive archive) {
@ -132,4 +127,5 @@ public class JarFileArchiveTests {
} }
return entries; return entries;
} }
} }

@ -16,13 +16,14 @@
package org.springframework.boot.loader.data; package org.springframework.boot.loader.data;
import java.io.InputStream;
import org.junit.Test; import org.junit.Test;
import org.springframework.boot.loader.data.RandomAccessData.ResourceAccess; import org.springframework.boot.loader.data.RandomAccessData.ResourceAccess;
import org.springframework.util.FileCopyUtils; import org.springframework.util.FileCopyUtils;
import static org.hamcrest.Matchers.equalTo; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertThat;
/** /**
* Tests for {@link ByteArrayRandomAccessData}. * Tests for {@link ByteArrayRandomAccessData}.
@ -35,9 +36,9 @@ public class ByteArrayRandomAccessDataTests {
public void testGetInputStream() throws Exception { public void testGetInputStream() throws Exception {
byte[] bytes = new byte[] { 0, 1, 2, 3, 4, 5 }; byte[] bytes = new byte[] { 0, 1, 2, 3, 4, 5 };
RandomAccessData data = new ByteArrayRandomAccessData(bytes); RandomAccessData data = new ByteArrayRandomAccessData(bytes);
assertThat(FileCopyUtils.copyToByteArray( InputStream inputStream = data.getInputStream(ResourceAccess.PER_READ);
data.getInputStream(ResourceAccess.PER_READ)), equalTo(bytes)); assertThat(FileCopyUtils.copyToByteArray(inputStream)).isEqualTo(bytes);
assertThat(data.getSize(), equalTo((long) bytes.length)); assertThat(data.getSize()).isEqualTo(bytes.length);
} }
@Test @Test
@ -45,10 +46,10 @@ public class ByteArrayRandomAccessDataTests {
byte[] bytes = new byte[] { 0, 1, 2, 3, 4, 5 }; byte[] bytes = new byte[] { 0, 1, 2, 3, 4, 5 };
RandomAccessData data = new ByteArrayRandomAccessData(bytes); RandomAccessData data = new ByteArrayRandomAccessData(bytes);
data = data.getSubsection(1, 4).getSubsection(1, 2); data = data.getSubsection(1, 4).getSubsection(1, 2);
assertThat( InputStream inputStream = data.getInputStream(ResourceAccess.PER_READ);
FileCopyUtils assertThat(FileCopyUtils.copyToByteArray(inputStream))
.copyToByteArray(data.getInputStream(ResourceAccess.PER_READ)), .isEqualTo(new byte[] { 2, 3 });
equalTo(new byte[] { 2, 3 })); assertThat(data.getSize()).isEqualTo(2L);
assertThat(data.getSize(), equalTo(2L));
} }
} }

@ -29,7 +29,6 @@ import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
import java.util.concurrent.Future; import java.util.concurrent.Future;
import org.hamcrest.Matcher;
import org.junit.After; import org.junit.After;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule; import org.junit.Rule;
@ -37,11 +36,9 @@ import org.junit.Test;
import org.junit.rules.ExpectedException; import org.junit.rules.ExpectedException;
import org.junit.rules.TemporaryFolder; import org.junit.rules.TemporaryFolder;
import org.springframework.boot.loader.ByteArrayStartsWith;
import org.springframework.boot.loader.data.RandomAccessData.ResourceAccess; import org.springframework.boot.loader.data.RandomAccessData.ResourceAccess;
import static org.hamcrest.Matchers.equalTo; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertThat;
/** /**
* Tests for {@link RandomAccessDataFile}. * Tests for {@link RandomAccessDataFile}.
@ -118,7 +115,7 @@ public class RandomAccessDataFileTests {
@Test @Test
public void inputStreamRead() throws Exception { public void inputStreamRead() throws Exception {
for (int i = 0; i <= 255; i++) { for (int i = 0; i <= 255; i++) {
assertThat(this.inputStream.read(), equalTo(i)); assertThat(this.inputStream.read()).isEqualTo(i);
} }
} }
@ -140,8 +137,8 @@ public class RandomAccessDataFileTests {
public void inputStreamReadBytes() throws Exception { public void inputStreamReadBytes() throws Exception {
byte[] b = new byte[256]; byte[] b = new byte[256];
int amountRead = this.inputStream.read(b); int amountRead = this.inputStream.read(b);
assertThat(b, equalTo(BYTES)); assertThat(b).isEqualTo(BYTES);
assertThat(amountRead, equalTo(256)); assertThat(amountRead).isEqualTo(256);
} }
@Test @Test
@ -149,54 +146,54 @@ public class RandomAccessDataFileTests {
byte[] b = new byte[7]; byte[] b = new byte[7];
this.inputStream.skip(1); this.inputStream.skip(1);
int amountRead = this.inputStream.read(b, 2, 3); int amountRead = this.inputStream.read(b, 2, 3);
assertThat(b, equalTo(new byte[] { 0, 0, 1, 2, 3, 0, 0 })); assertThat(b).isEqualTo(new byte[] { 0, 0, 1, 2, 3, 0, 0 });
assertThat(amountRead, equalTo(3)); assertThat(amountRead).isEqualTo(3);
} }
@Test @Test
public void inputStreamReadMoreBytesThanAvailable() throws Exception { public void inputStreamReadMoreBytesThanAvailable() throws Exception {
byte[] b = new byte[257]; byte[] b = new byte[257];
int amountRead = this.inputStream.read(b); int amountRead = this.inputStream.read(b);
assertThat(b, startsWith(BYTES)); assertThat(b).startsWith(BYTES);
assertThat(amountRead, equalTo(256)); assertThat(amountRead).isEqualTo(256);
} }
@Test @Test
public void inputStreamReadPastEnd() throws Exception { public void inputStreamReadPastEnd() throws Exception {
this.inputStream.skip(255); this.inputStream.skip(255);
assertThat(this.inputStream.read(), equalTo(0xFF)); assertThat(this.inputStream.read()).isEqualTo(0xFF);
assertThat(this.inputStream.read(), equalTo(-1)); assertThat(this.inputStream.read()).isEqualTo(-1);
assertThat(this.inputStream.read(), equalTo(-1)); assertThat(this.inputStream.read()).isEqualTo(-1);
} }
@Test @Test
public void inputStreamReadZeroLength() throws Exception { public void inputStreamReadZeroLength() throws Exception {
byte[] b = new byte[] { 0x0F }; byte[] b = new byte[] { 0x0F };
int amountRead = this.inputStream.read(b, 0, 0); int amountRead = this.inputStream.read(b, 0, 0);
assertThat(b, equalTo(new byte[] { 0x0F })); assertThat(b).isEqualTo(new byte[] { 0x0F });
assertThat(amountRead, equalTo(0)); assertThat(amountRead).isEqualTo(0);
assertThat(this.inputStream.read(), equalTo(0)); assertThat(this.inputStream.read()).isEqualTo(0);
} }
@Test @Test
public void inputStreamSkip() throws Exception { public void inputStreamSkip() throws Exception {
long amountSkipped = this.inputStream.skip(4); long amountSkipped = this.inputStream.skip(4);
assertThat(this.inputStream.read(), equalTo(4)); assertThat(this.inputStream.read()).isEqualTo(4);
assertThat(amountSkipped, equalTo(4L)); assertThat(amountSkipped).isEqualTo(4L);
} }
@Test @Test
public void inputStreamSkipMoreThanAvailable() throws Exception { public void inputStreamSkipMoreThanAvailable() throws Exception {
long amountSkipped = this.inputStream.skip(257); long amountSkipped = this.inputStream.skip(257);
assertThat(this.inputStream.read(), equalTo(-1)); assertThat(this.inputStream.read()).isEqualTo(-1);
assertThat(amountSkipped, equalTo(256L)); assertThat(amountSkipped).isEqualTo(256L);
} }
@Test @Test
public void inputStreamSkipPastEnd() throws Exception { public void inputStreamSkipPastEnd() throws Exception {
this.inputStream.skip(256); this.inputStream.skip(256);
long amountSkipped = this.inputStream.skip(1); long amountSkipped = this.inputStream.skip(1);
assertThat(amountSkipped, equalTo(0L)); assertThat(amountSkipped).isEqualTo(0L);
} }
@Test @Test
@ -214,8 +211,8 @@ public class RandomAccessDataFileTests {
@Test @Test
public void subsectionZeroLength() throws Exception { public void subsectionZeroLength() throws Exception {
RandomAccessData subsection = this.file.getSubsection(0, 0); RandomAccessData subsection = this.file.getSubsection(0, 0);
assertThat(subsection.getInputStream(ResourceAccess.PER_READ).read(), assertThat(subsection.getInputStream(ResourceAccess.PER_READ).read())
equalTo(-1)); .isEqualTo(-1);
} }
@Test @Test
@ -235,16 +232,17 @@ public class RandomAccessDataFileTests {
@Test @Test
public void subsection() throws Exception { public void subsection() throws Exception {
RandomAccessData subsection = this.file.getSubsection(1, 1); RandomAccessData subsection = this.file.getSubsection(1, 1);
assertThat(subsection.getInputStream(ResourceAccess.PER_READ).read(), equalTo(1)); assertThat(subsection.getInputStream(ResourceAccess.PER_READ).read())
.isEqualTo(1);
} }
@Test @Test
public void inputStreamReadPastSubsection() throws Exception { public void inputStreamReadPastSubsection() throws Exception {
RandomAccessData subsection = this.file.getSubsection(1, 2); RandomAccessData subsection = this.file.getSubsection(1, 2);
InputStream inputStream = subsection.getInputStream(ResourceAccess.PER_READ); InputStream inputStream = subsection.getInputStream(ResourceAccess.PER_READ);
assertThat(inputStream.read(), equalTo(1)); assertThat(inputStream.read()).isEqualTo(1);
assertThat(inputStream.read(), equalTo(2)); assertThat(inputStream.read()).isEqualTo(2);
assertThat(inputStream.read(), equalTo(-1)); assertThat(inputStream.read()).isEqualTo(-1);
} }
@Test @Test
@ -253,26 +251,26 @@ public class RandomAccessDataFileTests {
InputStream inputStream = subsection.getInputStream(ResourceAccess.PER_READ); InputStream inputStream = subsection.getInputStream(ResourceAccess.PER_READ);
byte[] b = new byte[3]; byte[] b = new byte[3];
int amountRead = inputStream.read(b); int amountRead = inputStream.read(b);
assertThat(b, equalTo(new byte[] { 1, 2, 0 })); assertThat(b).isEqualTo(new byte[] { 1, 2, 0 });
assertThat(amountRead, equalTo(2)); assertThat(amountRead).isEqualTo(2);
} }
@Test @Test
public void inputStreamSkipPastSubsection() throws Exception { public void inputStreamSkipPastSubsection() throws Exception {
RandomAccessData subsection = this.file.getSubsection(1, 2); RandomAccessData subsection = this.file.getSubsection(1, 2);
InputStream inputStream = subsection.getInputStream(ResourceAccess.PER_READ); InputStream inputStream = subsection.getInputStream(ResourceAccess.PER_READ);
assertThat(inputStream.skip(3), equalTo(2L)); assertThat(inputStream.skip(3)).isEqualTo(2L);
assertThat(inputStream.read(), equalTo(-1)); assertThat(inputStream.read()).isEqualTo(-1);
} }
@Test @Test
public void inputStreamSkipNegative() throws Exception { public void inputStreamSkipNegative() throws Exception {
assertThat(this.inputStream.skip(-1), equalTo(0L)); assertThat(this.inputStream.skip(-1)).isEqualTo(0L);
} }
@Test @Test
public void getFile() throws Exception { public void getFile() throws Exception {
assertThat(this.file.getFile(), equalTo(this.tempFile)); assertThat(this.file.getFile()).isEqualTo(this.tempFile);
} }
@Test @Test
@ -294,7 +292,7 @@ public class RandomAccessDataFileTests {
})); }));
} }
for (Future<Boolean> future : results) { for (Future<Boolean> future : results) {
assertThat(future.get(), equalTo(true)); assertThat(future.get()).isTrue();
} }
} }
@ -308,11 +306,7 @@ public class RandomAccessDataFileTests {
Field filesField = filePool.getClass().getDeclaredField("files"); Field filesField = filePool.getClass().getDeclaredField("files");
filesField.setAccessible(true); filesField.setAccessible(true);
Queue<?> queue = (Queue<?>) filesField.get(filePool); Queue<?> queue = (Queue<?>) filesField.get(filePool);
assertThat(queue.size(), equalTo(0)); assertThat(queue.size()).isEqualTo(0);
}
private static Matcher<? super byte[]> startsWith(byte[] bytes) {
return new ByteArrayStartsWith(bytes);
} }
} }

@ -20,9 +20,7 @@ import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException; import org.junit.rules.ExpectedException;
import static org.hamcrest.Matchers.equalTo; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.not;
import static org.junit.Assert.assertThat;
/** /**
* Tests for {@link AsciiBytes}. * Tests for {@link AsciiBytes}.
@ -37,27 +35,27 @@ public class AsciiBytesTests {
@Test @Test
public void createFromBytes() throws Exception { public void createFromBytes() throws Exception {
AsciiBytes bytes = new AsciiBytes(new byte[] { 65, 66 }); AsciiBytes bytes = new AsciiBytes(new byte[] { 65, 66 });
assertThat(bytes.toString(), equalTo("AB")); assertThat(bytes.toString()).isEqualTo("AB");
} }
@Test @Test
public void createFromBytesWithOffset() throws Exception { public void createFromBytesWithOffset() throws Exception {
AsciiBytes bytes = new AsciiBytes(new byte[] { 65, 66, 67, 68 }, 1, 2); AsciiBytes bytes = new AsciiBytes(new byte[] { 65, 66, 67, 68 }, 1, 2);
assertThat(bytes.toString(), equalTo("BC")); assertThat(bytes.toString()).isEqualTo("BC");
} }
@Test @Test
public void createFromString() throws Exception { public void createFromString() throws Exception {
AsciiBytes bytes = new AsciiBytes("AB"); AsciiBytes bytes = new AsciiBytes("AB");
assertThat(bytes.toString(), equalTo("AB")); assertThat(bytes.toString()).isEqualTo("AB");
} }
@Test @Test
public void length() throws Exception { public void length() throws Exception {
AsciiBytes b1 = new AsciiBytes(new byte[] { 65, 66 }); AsciiBytes b1 = new AsciiBytes(new byte[] { 65, 66 });
AsciiBytes b2 = new AsciiBytes(new byte[] { 65, 66, 67, 68 }, 1, 2); AsciiBytes b2 = new AsciiBytes(new byte[] { 65, 66, 67, 68 }, 1, 2);
assertThat(b1.length(), equalTo(2)); assertThat(b1.length()).isEqualTo(2);
assertThat(b2.length(), equalTo(2)); assertThat(b2.length()).isEqualTo(2);
} }
@Test @Test
@ -66,10 +64,10 @@ public class AsciiBytesTests {
AsciiBytes ab = new AsciiBytes(new byte[] { 65, 66 }); AsciiBytes ab = new AsciiBytes(new byte[] { 65, 66 });
AsciiBytes bc = new AsciiBytes(new byte[] { 65, 66, 67 }, 1, 2); AsciiBytes bc = new AsciiBytes(new byte[] { 65, 66, 67 }, 1, 2);
AsciiBytes abcd = new AsciiBytes(new byte[] { 65, 66, 67, 68 }); AsciiBytes abcd = new AsciiBytes(new byte[] { 65, 66, 67, 68 });
assertThat(abc.startsWith(abc), equalTo(true)); assertThat(abc.startsWith(abc)).isTrue();
assertThat(abc.startsWith(ab), equalTo(true)); assertThat(abc.startsWith(ab)).isTrue();
assertThat(abc.startsWith(bc), equalTo(false)); assertThat(abc.startsWith(bc)).isFalse();
assertThat(abc.startsWith(abcd), equalTo(false)); assertThat(abc.startsWith(abcd)).isFalse();
} }
@Test @Test
@ -78,20 +76,20 @@ public class AsciiBytesTests {
AsciiBytes bc = new AsciiBytes(new byte[] { 65, 66, 67 }, 1, 2); AsciiBytes bc = new AsciiBytes(new byte[] { 65, 66, 67 }, 1, 2);
AsciiBytes ab = new AsciiBytes(new byte[] { 65, 66 }); AsciiBytes ab = new AsciiBytes(new byte[] { 65, 66 });
AsciiBytes aabc = new AsciiBytes(new byte[] { 65, 65, 66, 67 }); AsciiBytes aabc = new AsciiBytes(new byte[] { 65, 65, 66, 67 });
assertThat(abc.endsWith(abc), equalTo(true)); assertThat(abc.endsWith(abc)).isTrue();
assertThat(abc.endsWith(bc), equalTo(true)); assertThat(abc.endsWith(bc)).isTrue();
assertThat(abc.endsWith(ab), equalTo(false)); assertThat(abc.endsWith(ab)).isFalse();
assertThat(abc.endsWith(aabc), equalTo(false)); assertThat(abc.endsWith(aabc)).isFalse();
} }
@Test @Test
public void substringFromBeingIndex() throws Exception { public void substringFromBeingIndex() throws Exception {
AsciiBytes abcd = new AsciiBytes(new byte[] { 65, 66, 67, 68 }); AsciiBytes abcd = new AsciiBytes(new byte[] { 65, 66, 67, 68 });
assertThat(abcd.substring(0).toString(), equalTo("ABCD")); assertThat(abcd.substring(0).toString()).isEqualTo("ABCD");
assertThat(abcd.substring(1).toString(), equalTo("BCD")); assertThat(abcd.substring(1).toString()).isEqualTo("BCD");
assertThat(abcd.substring(2).toString(), equalTo("CD")); assertThat(abcd.substring(2).toString()).isEqualTo("CD");
assertThat(abcd.substring(3).toString(), equalTo("D")); assertThat(abcd.substring(3).toString()).isEqualTo("D");
assertThat(abcd.substring(4).toString(), equalTo("")); assertThat(abcd.substring(4).toString()).isEqualTo("");
this.thrown.expect(IndexOutOfBoundsException.class); this.thrown.expect(IndexOutOfBoundsException.class);
abcd.substring(5); abcd.substring(5);
} }
@ -99,10 +97,10 @@ public class AsciiBytesTests {
@Test @Test
public void substring() throws Exception { public void substring() throws Exception {
AsciiBytes abcd = new AsciiBytes(new byte[] { 65, 66, 67, 68 }); AsciiBytes abcd = new AsciiBytes(new byte[] { 65, 66, 67, 68 });
assertThat(abcd.substring(0, 4).toString(), equalTo("ABCD")); assertThat(abcd.substring(0, 4).toString()).isEqualTo("ABCD");
assertThat(abcd.substring(1, 3).toString(), equalTo("BC")); assertThat(abcd.substring(1, 3).toString()).isEqualTo("BC");
assertThat(abcd.substring(3, 4).toString(), equalTo("D")); assertThat(abcd.substring(3, 4).toString()).isEqualTo("D");
assertThat(abcd.substring(3, 3).toString(), equalTo("")); assertThat(abcd.substring(3, 3).toString()).isEqualTo("");
this.thrown.expect(IndexOutOfBoundsException.class); this.thrown.expect(IndexOutOfBoundsException.class);
abcd.substring(3, 5); abcd.substring(3, 5);
} }
@ -111,16 +109,16 @@ public class AsciiBytesTests {
public void appendString() throws Exception { public void appendString() throws Exception {
AsciiBytes bc = new AsciiBytes(new byte[] { 65, 66, 67, 68 }, 1, 2); AsciiBytes bc = new AsciiBytes(new byte[] { 65, 66, 67, 68 }, 1, 2);
AsciiBytes appended = bc.append("D"); AsciiBytes appended = bc.append("D");
assertThat(bc.toString(), equalTo("BC")); assertThat(bc.toString()).isEqualTo("BC");
assertThat(appended.toString(), equalTo("BCD")); assertThat(appended.toString()).isEqualTo("BCD");
} }
@Test @Test
public void appendBytes() throws Exception { public void appendBytes() throws Exception {
AsciiBytes bc = new AsciiBytes(new byte[] { 65, 66, 67, 68 }, 1, 2); AsciiBytes bc = new AsciiBytes(new byte[] { 65, 66, 67, 68 }, 1, 2);
AsciiBytes appended = bc.append(new byte[] { 68 }); AsciiBytes appended = bc.append(new byte[] { 68 });
assertThat(bc.toString(), equalTo("BC")); assertThat(bc.toString()).isEqualTo("BC");
assertThat(appended.toString(), equalTo("BCD")); assertThat(appended.toString()).isEqualTo("BCD");
} }
@Test @Test
@ -130,28 +128,28 @@ public class AsciiBytesTests {
AsciiBytes bc_substring = new AsciiBytes(new byte[] { 65, 66, 67, 68 }) AsciiBytes bc_substring = new AsciiBytes(new byte[] { 65, 66, 67, 68 })
.substring(1, 3); .substring(1, 3);
AsciiBytes bc_string = new AsciiBytes("BC"); AsciiBytes bc_string = new AsciiBytes("BC");
assertThat(bc.hashCode(), equalTo(bc.hashCode())); assertThat(bc.hashCode()).isEqualTo(bc.hashCode());
assertThat(bc.hashCode(), equalTo(bc_substring.hashCode())); assertThat(bc.hashCode()).isEqualTo(bc_substring.hashCode());
assertThat(bc.hashCode(), equalTo(bc_string.hashCode())); assertThat(bc.hashCode()).isEqualTo(bc_string.hashCode());
assertThat(bc, equalTo(bc)); assertThat(bc).isEqualTo(bc);
assertThat(bc, equalTo(bc_substring)); assertThat(bc).isEqualTo(bc_substring);
assertThat(bc, equalTo(bc_string)); assertThat(bc).isEqualTo(bc_string);
assertThat(bc.hashCode(), not(equalTo(abcd.hashCode()))); assertThat(bc.hashCode()).isNotEqualTo(abcd.hashCode());
assertThat(bc, not(equalTo(abcd))); assertThat(bc).isNotEqualTo(abcd);
} }
@Test @Test
public void hashCodeSameAsString() throws Exception { public void hashCodeSameAsString() throws Exception {
String s = "abcABC123xyz!"; String s = "abcABC123xyz!";
AsciiBytes a = new AsciiBytes(s); AsciiBytes a = new AsciiBytes(s);
assertThat(s.hashCode(), equalTo(a.hashCode())); assertThat(s.hashCode()).isEqualTo(a.hashCode());
} }
@Test @Test
public void hashCodeSameAsStringWithSpecial() throws Exception { public void hashCodeSameAsStringWithSpecial() throws Exception {
String s = "special/\u00EB.dat"; String s = "special/\u00EB.dat";
AsciiBytes a = new AsciiBytes(s); AsciiBytes a = new AsciiBytes(s);
assertThat(s.hashCode(), equalTo(a.hashCode())); assertThat(s.hashCode()).isEqualTo(a.hashCode());
} }
} }

@ -31,8 +31,7 @@ import org.springframework.boot.loader.TestJarCreator;
import org.springframework.boot.loader.data.RandomAccessData; import org.springframework.boot.loader.data.RandomAccessData;
import org.springframework.boot.loader.data.RandomAccessDataFile; import org.springframework.boot.loader.data.RandomAccessDataFile;
import static org.hamcrest.Matchers.equalTo; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertThat;
import static org.mockito.Matchers.any; import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyInt; import static org.mockito.Matchers.anyInt;
import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.atLeastOnce;
@ -62,7 +61,7 @@ public class CentralDirectoryParserTests {
@Test @Test
public void visitsInOrder() throws Exception { public void visitsInOrder() throws Exception {
CentralDirectoryVisitor visitor = mock(CentralDirectoryVisitor.class); CentralDirectoryVisitor visitor = mock(TestCentralDirectoryVisitor.class);
CentralDirectoryParser parser = new CentralDirectoryParser(); CentralDirectoryParser parser = new CentralDirectoryParser();
parser.addVisitor(visitor); parser.addVisitor(visitor);
parser.parse(this.jarData, false); parser.parse(this.jarData, false);
@ -81,17 +80,17 @@ public class CentralDirectoryParserTests {
parser.addVisitor(collector); parser.addVisitor(collector);
parser.parse(this.jarData, false); parser.parse(this.jarData, false);
Iterator<CentralDirectoryFileHeader> headers = collector.getHeaders().iterator(); Iterator<CentralDirectoryFileHeader> headers = collector.getHeaders().iterator();
assertThat(headers.next().getName().toString(), equalTo("META-INF/")); assertThat(headers.next().getName().toString()).isEqualTo("META-INF/");
assertThat(headers.next().getName().toString(), equalTo("META-INF/MANIFEST.MF")); assertThat(headers.next().getName().toString()).isEqualTo("META-INF/MANIFEST.MF");
assertThat(headers.next().getName().toString(), equalTo("1.dat")); assertThat(headers.next().getName().toString()).isEqualTo("1.dat");
assertThat(headers.next().getName().toString(), equalTo("2.dat")); assertThat(headers.next().getName().toString()).isEqualTo("2.dat");
assertThat(headers.next().getName().toString(), equalTo("d/")); assertThat(headers.next().getName().toString()).isEqualTo("d/");
assertThat(headers.next().getName().toString(), equalTo("d/9.dat")); assertThat(headers.next().getName().toString()).isEqualTo("d/9.dat");
assertThat(headers.next().getName().toString(), equalTo("special/")); assertThat(headers.next().getName().toString()).isEqualTo("special/");
assertThat(headers.next().getName().toString(), equalTo("special/\u00EB.dat")); assertThat(headers.next().getName().toString()).isEqualTo("special/\u00EB.dat");
assertThat(headers.next().getName().toString(), equalTo("nested.jar")); assertThat(headers.next().getName().toString()).isEqualTo("nested.jar");
assertThat(headers.next().getName().toString(), equalTo("another-nested.jar")); assertThat(headers.next().getName().toString()).isEqualTo("another-nested.jar");
assertThat(headers.hasNext(), equalTo(false)); assertThat(headers.hasNext()).isFalse();
} }
private static class Collector implements CentralDirectoryVisitor { private static class Collector implements CentralDirectoryVisitor {
@ -119,4 +118,8 @@ public class CentralDirectoryParserTests {
} }
public interface TestCentralDirectoryVisitor extends CentralDirectoryVisitor {
}
} }

@ -41,14 +41,7 @@ import org.springframework.boot.loader.data.RandomAccessDataFile;
import org.springframework.util.FileCopyUtils; import org.springframework.util.FileCopyUtils;
import org.springframework.util.StreamUtils; import org.springframework.util.StreamUtils;
import static org.hamcrest.Matchers.equalTo; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
import static org.hamcrest.Matchers.sameInstance;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.spy; import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verify;
@ -82,21 +75,21 @@ public class JarFileTests {
// Sanity checks to see how the default jar file operates // Sanity checks to see how the default jar file operates
java.util.jar.JarFile jarFile = new java.util.jar.JarFile(this.rootJarFile); java.util.jar.JarFile jarFile = new java.util.jar.JarFile(this.rootJarFile);
Enumeration<java.util.jar.JarEntry> entries = jarFile.entries(); Enumeration<java.util.jar.JarEntry> entries = jarFile.entries();
assertThat(entries.nextElement().getName(), equalTo("META-INF/")); assertThat(entries.nextElement().getName()).isEqualTo("META-INF/");
assertThat(entries.nextElement().getName(), equalTo("META-INF/MANIFEST.MF")); assertThat(entries.nextElement().getName()).isEqualTo("META-INF/MANIFEST.MF");
assertThat(entries.nextElement().getName(), equalTo("1.dat")); assertThat(entries.nextElement().getName()).isEqualTo("1.dat");
assertThat(entries.nextElement().getName(), equalTo("2.dat")); assertThat(entries.nextElement().getName()).isEqualTo("2.dat");
assertThat(entries.nextElement().getName(), equalTo("d/")); assertThat(entries.nextElement().getName()).isEqualTo("d/");
assertThat(entries.nextElement().getName(), equalTo("d/9.dat")); assertThat(entries.nextElement().getName()).isEqualTo("d/9.dat");
assertThat(entries.nextElement().getName(), equalTo("special/")); assertThat(entries.nextElement().getName()).isEqualTo("special/");
assertThat(entries.nextElement().getName(), equalTo("special/\u00EB.dat")); assertThat(entries.nextElement().getName()).isEqualTo("special/\u00EB.dat");
assertThat(entries.nextElement().getName(), equalTo("nested.jar")); assertThat(entries.nextElement().getName()).isEqualTo("nested.jar");
assertThat(entries.nextElement().getName(), equalTo("another-nested.jar")); assertThat(entries.nextElement().getName()).isEqualTo("another-nested.jar");
assertThat(entries.hasMoreElements(), equalTo(false)); assertThat(entries.hasMoreElements()).isFalse();
URL jarUrl = new URL("jar:" + this.rootJarFile.toURI() + "!/"); URL jarUrl = new URL("jar:" + this.rootJarFile.toURI() + "!/");
URLClassLoader urlClassLoader = new URLClassLoader(new URL[] { jarUrl }); URLClassLoader urlClassLoader = new URLClassLoader(new URL[] { jarUrl });
assertThat(urlClassLoader.getResource("special/\u00EB.dat"), notNullValue()); assertThat(urlClassLoader.getResource("special/\u00EB.dat")).isNotNull();
assertThat(urlClassLoader.getResource("d/9.dat"), notNullValue()); assertThat(urlClassLoader.getResource("d/9.dat")).isNotNull();
jarFile.close(); jarFile.close();
urlClassLoader.close(); urlClassLoader.close();
} }
@ -104,79 +97,79 @@ public class JarFileTests {
@Test @Test
public void createFromFile() throws Exception { public void createFromFile() throws Exception {
JarFile jarFile = new JarFile(this.rootJarFile); JarFile jarFile = new JarFile(this.rootJarFile);
assertThat(jarFile.getName(), notNullValue(String.class)); assertThat(jarFile.getName()).isNotNull();
jarFile.close(); jarFile.close();
} }
@Test @Test
public void getManifest() throws Exception { public void getManifest() throws Exception {
assertThat(this.jarFile.getManifest().getMainAttributes().getValue("Built-By"), assertThat(this.jarFile.getManifest().getMainAttributes().getValue("Built-By"))
equalTo("j1")); .isEqualTo("j1");
} }
@Test @Test
public void getManifestEntry() throws Exception { public void getManifestEntry() throws Exception {
ZipEntry entry = this.jarFile.getJarEntry("META-INF/MANIFEST.MF"); ZipEntry entry = this.jarFile.getJarEntry("META-INF/MANIFEST.MF");
Manifest manifest = new Manifest(this.jarFile.getInputStream(entry)); Manifest manifest = new Manifest(this.jarFile.getInputStream(entry));
assertThat(manifest.getMainAttributes().getValue("Built-By"), equalTo("j1")); assertThat(manifest.getMainAttributes().getValue("Built-By")).isEqualTo("j1");
} }
@Test @Test
public void getEntries() throws Exception { public void getEntries() throws Exception {
Enumeration<java.util.jar.JarEntry> entries = this.jarFile.entries(); Enumeration<java.util.jar.JarEntry> entries = this.jarFile.entries();
assertThat(entries.nextElement().getName(), equalTo("META-INF/")); assertThat(entries.nextElement().getName()).isEqualTo("META-INF/");
assertThat(entries.nextElement().getName(), equalTo("META-INF/MANIFEST.MF")); assertThat(entries.nextElement().getName()).isEqualTo("META-INF/MANIFEST.MF");
assertThat(entries.nextElement().getName(), equalTo("1.dat")); assertThat(entries.nextElement().getName()).isEqualTo("1.dat");
assertThat(entries.nextElement().getName(), equalTo("2.dat")); assertThat(entries.nextElement().getName()).isEqualTo("2.dat");
assertThat(entries.nextElement().getName(), equalTo("d/")); assertThat(entries.nextElement().getName()).isEqualTo("d/");
assertThat(entries.nextElement().getName(), equalTo("d/9.dat")); assertThat(entries.nextElement().getName()).isEqualTo("d/9.dat");
assertThat(entries.nextElement().getName(), equalTo("special/")); assertThat(entries.nextElement().getName()).isEqualTo("special/");
assertThat(entries.nextElement().getName(), equalTo("special/\u00EB.dat")); assertThat(entries.nextElement().getName()).isEqualTo("special/\u00EB.dat");
assertThat(entries.nextElement().getName(), equalTo("nested.jar")); assertThat(entries.nextElement().getName()).isEqualTo("nested.jar");
assertThat(entries.nextElement().getName(), equalTo("another-nested.jar")); assertThat(entries.nextElement().getName()).isEqualTo("another-nested.jar");
assertThat(entries.hasMoreElements(), equalTo(false)); assertThat(entries.hasMoreElements()).isFalse();
} }
@Test @Test
public void getSpecialResourceViaClassLoader() throws Exception { public void getSpecialResourceViaClassLoader() throws Exception {
URLClassLoader urlClassLoader = new URLClassLoader( URLClassLoader urlClassLoader = new URLClassLoader(
new URL[] { this.jarFile.getUrl() }); new URL[] { this.jarFile.getUrl() });
assertThat(urlClassLoader.getResource("special/\u00EB.dat"), notNullValue()); assertThat(urlClassLoader.getResource("special/\u00EB.dat")).isNotNull();
urlClassLoader.close(); urlClassLoader.close();
} }
@Test @Test
public void getJarEntry() throws Exception { public void getJarEntry() throws Exception {
java.util.jar.JarEntry entry = this.jarFile.getJarEntry("1.dat"); java.util.jar.JarEntry entry = this.jarFile.getJarEntry("1.dat");
assertThat(entry, notNullValue(ZipEntry.class)); assertThat(entry).isNotNull();
assertThat(entry.getName(), equalTo("1.dat")); assertThat(entry.getName()).isEqualTo("1.dat");
} }
@Test @Test
public void getInputStream() throws Exception { public void getInputStream() throws Exception {
InputStream inputStream = this.jarFile InputStream inputStream = this.jarFile
.getInputStream(this.jarFile.getEntry("1.dat")); .getInputStream(this.jarFile.getEntry("1.dat"));
assertThat(inputStream.available(), equalTo(1)); assertThat(inputStream.available()).isEqualTo(1);
assertThat(inputStream.read(), equalTo(1)); assertThat(inputStream.read()).isEqualTo(1);
assertThat(inputStream.available(), equalTo(0)); assertThat(inputStream.available()).isEqualTo(0);
assertThat(inputStream.read(), equalTo(-1)); assertThat(inputStream.read()).isEqualTo(-1);
} }
@Test @Test
public void getName() throws Exception { public void getName() throws Exception {
assertThat(this.jarFile.getName(), equalTo(this.rootJarFile.getPath())); assertThat(this.jarFile.getName()).isEqualTo(this.rootJarFile.getPath());
} }
@Test @Test
public void getSize() throws Exception { public void getSize() throws Exception {
assertThat(this.jarFile.size(), equalTo((int) this.rootJarFile.length())); assertThat(this.jarFile.size()).isEqualTo((int) this.rootJarFile.length());
} }
@Test @Test
public void getEntryTime() throws Exception { public void getEntryTime() throws Exception {
java.util.jar.JarFile jdkJarFile = new java.util.jar.JarFile(this.rootJarFile); java.util.jar.JarFile jdkJarFile = new java.util.jar.JarFile(this.rootJarFile);
assertThat(this.jarFile.getEntry("META-INF/MANIFEST.MF").getTime(), assertThat(this.jarFile.getEntry("META-INF/MANIFEST.MF").getTime())
equalTo(jdkJarFile.getEntry("META-INF/MANIFEST.MF").getTime())); .isEqualTo(jdkJarFile.getEntry("META-INF/MANIFEST.MF").getTime());
jdkJarFile.close(); jdkJarFile.close();
} }
@ -192,36 +185,36 @@ public class JarFileTests {
@Test @Test
public void getUrl() throws Exception { public void getUrl() throws Exception {
URL url = this.jarFile.getUrl(); URL url = this.jarFile.getUrl();
assertThat(url.toString(), equalTo("jar:" + this.rootJarFile.toURI() + "!/")); assertThat(url.toString()).isEqualTo("jar:" + this.rootJarFile.toURI() + "!/");
JarURLConnection jarURLConnection = (JarURLConnection) url.openConnection(); JarURLConnection jarURLConnection = (JarURLConnection) url.openConnection();
assertThat(jarURLConnection.getJarFile(), sameInstance(this.jarFile)); assertThat(jarURLConnection.getJarFile()).isSameAs(this.jarFile);
assertThat(jarURLConnection.getJarEntry(), nullValue()); assertThat(jarURLConnection.getJarEntry()).isNull();
assertThat(jarURLConnection.getContentLength(), greaterThan(1)); assertThat(jarURLConnection.getContentLength()).isGreaterThan(1);
assertThat(jarURLConnection.getContent(), sameInstance((Object) this.jarFile)); assertThat(jarURLConnection.getContent()).isSameAs(this.jarFile);
assertThat(jarURLConnection.getContentType(), equalTo("x-java/jar")); assertThat(jarURLConnection.getContentType()).isEqualTo("x-java/jar");
assertThat(jarURLConnection.getJarFileURL().toURI(), assertThat(jarURLConnection.getJarFileURL().toURI())
equalTo(this.rootJarFile.toURI())); .isEqualTo(this.rootJarFile.toURI());
} }
@Test @Test
public void createEntryUrl() throws Exception { public void createEntryUrl() throws Exception {
URL url = new URL(this.jarFile.getUrl(), "1.dat"); URL url = new URL(this.jarFile.getUrl(), "1.dat");
assertThat(url.toString(), assertThat(url.toString())
equalTo("jar:" + this.rootJarFile.toURI() + "!/1.dat")); .isEqualTo("jar:" + this.rootJarFile.toURI() + "!/1.dat");
JarURLConnection jarURLConnection = (JarURLConnection) url.openConnection(); JarURLConnection jarURLConnection = (JarURLConnection) url.openConnection();
assertThat(jarURLConnection.getJarFile(), sameInstance(this.jarFile)); assertThat(jarURLConnection.getJarFile()).isSameAs(this.jarFile);
assertThat(jarURLConnection.getJarEntry(), assertThat(jarURLConnection.getJarEntry())
sameInstance(this.jarFile.getJarEntry("1.dat"))); .isSameAs(this.jarFile.getJarEntry("1.dat"));
assertThat(jarURLConnection.getContentLength(), equalTo(1)); assertThat(jarURLConnection.getContentLength()).isEqualTo(1);
assertThat(jarURLConnection.getContent(), instanceOf(InputStream.class)); assertThat(jarURLConnection.getContent()).isInstanceOf(InputStream.class);
assertThat(jarURLConnection.getContentType(), equalTo("content/unknown")); assertThat(jarURLConnection.getContentType()).isEqualTo("content/unknown");
} }
@Test @Test
public void getMissingEntryUrl() throws Exception { public void getMissingEntryUrl() throws Exception {
URL url = new URL(this.jarFile.getUrl(), "missing.dat"); URL url = new URL(this.jarFile.getUrl(), "missing.dat");
assertThat(url.toString(), assertThat(url.toString())
equalTo("jar:" + this.rootJarFile.toURI() + "!/missing.dat")); .isEqualTo("jar:" + this.rootJarFile.toURI() + "!/missing.dat");
this.thrown.expect(FileNotFoundException.class); this.thrown.expect(FileNotFoundException.class);
((JarURLConnection) url.openConnection()).getJarEntry(); ((JarURLConnection) url.openConnection()).getJarEntry();
} }
@ -239,8 +232,8 @@ public class JarFileTests {
URL url = new URL(this.jarFile.getUrl(), "1.dat"); URL url = new URL(this.jarFile.getUrl(), "1.dat");
url.openConnection(); url.openConnection();
InputStream stream = url.openStream(); InputStream stream = url.openStream();
assertThat(stream.read(), equalTo(1)); assertThat(stream.read()).isEqualTo(1);
assertThat(stream.read(), equalTo(-1)); assertThat(stream.read()).isEqualTo(-1);
} }
@Test @Test
@ -249,25 +242,25 @@ public class JarFileTests {
.getNestedJarFile(this.jarFile.getEntry("nested.jar")); .getNestedJarFile(this.jarFile.getEntry("nested.jar"));
Enumeration<java.util.jar.JarEntry> entries = nestedJarFile.entries(); Enumeration<java.util.jar.JarEntry> entries = nestedJarFile.entries();
assertThat(entries.nextElement().getName(), equalTo("META-INF/")); assertThat(entries.nextElement().getName()).isEqualTo("META-INF/");
assertThat(entries.nextElement().getName(), equalTo("META-INF/MANIFEST.MF")); assertThat(entries.nextElement().getName()).isEqualTo("META-INF/MANIFEST.MF");
assertThat(entries.nextElement().getName(), equalTo("3.dat")); assertThat(entries.nextElement().getName()).isEqualTo("3.dat");
assertThat(entries.nextElement().getName(), equalTo("4.dat")); assertThat(entries.nextElement().getName()).isEqualTo("4.dat");
assertThat(entries.nextElement().getName(), equalTo("\u00E4.dat")); assertThat(entries.nextElement().getName()).isEqualTo("\u00E4.dat");
assertThat(entries.hasMoreElements(), equalTo(false)); assertThat(entries.hasMoreElements()).isFalse();
InputStream inputStream = nestedJarFile InputStream inputStream = nestedJarFile
.getInputStream(nestedJarFile.getEntry("3.dat")); .getInputStream(nestedJarFile.getEntry("3.dat"));
assertThat(inputStream.read(), equalTo(3)); assertThat(inputStream.read()).isEqualTo(3);
assertThat(inputStream.read(), equalTo(-1)); assertThat(inputStream.read()).isEqualTo(-1);
URL url = nestedJarFile.getUrl(); URL url = nestedJarFile.getUrl();
assertThat(url.toString(), assertThat(url.toString())
equalTo("jar:" + this.rootJarFile.toURI() + "!/nested.jar!/")); .isEqualTo("jar:" + this.rootJarFile.toURI() + "!/nested.jar!/");
JarURLConnection conn = (JarURLConnection) url.openConnection(); JarURLConnection conn = (JarURLConnection) url.openConnection();
assertThat(conn.getJarFile(), sameInstance(nestedJarFile)); assertThat(conn.getJarFile()).isSameAs(nestedJarFile);
assertThat(conn.getJarFileURL().toString(), assertThat(conn.getJarFileURL().toString())
equalTo("jar:" + this.rootJarFile.toURI() + "!/nested.jar")); .isEqualTo("jar:" + this.rootJarFile.toURI() + "!/nested.jar");
} }
@Test @Test
@ -276,18 +269,18 @@ public class JarFileTests {
.getNestedJarFile(this.jarFile.getEntry("d/")); .getNestedJarFile(this.jarFile.getEntry("d/"));
Enumeration<java.util.jar.JarEntry> entries = nestedJarFile.entries(); Enumeration<java.util.jar.JarEntry> entries = nestedJarFile.entries();
assertThat(entries.nextElement().getName(), equalTo("9.dat")); assertThat(entries.nextElement().getName()).isEqualTo("9.dat");
assertThat(entries.hasMoreElements(), equalTo(false)); assertThat(entries.hasMoreElements()).isFalse();
InputStream inputStream = nestedJarFile InputStream inputStream = nestedJarFile
.getInputStream(nestedJarFile.getEntry("9.dat")); .getInputStream(nestedJarFile.getEntry("9.dat"));
assertThat(inputStream.read(), equalTo(9)); assertThat(inputStream.read()).isEqualTo(9);
assertThat(inputStream.read(), equalTo(-1)); assertThat(inputStream.read()).isEqualTo(-1);
URL url = nestedJarFile.getUrl(); URL url = nestedJarFile.getUrl();
assertThat(url.toString(), equalTo("jar:" + this.rootJarFile.toURI() + "!/d!/")); assertThat(url.toString()).isEqualTo("jar:" + this.rootJarFile.toURI() + "!/d!/");
assertThat(((JarURLConnection) url.openConnection()).getJarFile(), assertThat(((JarURLConnection) url.openConnection()).getJarFile())
sameInstance(nestedJarFile)); .isSameAs(nestedJarFile);
} }
@Test @Test
@ -295,11 +288,11 @@ public class JarFileTests {
JarFile nestedJarFile = this.jarFile JarFile nestedJarFile = this.jarFile
.getNestedJarFile(this.jarFile.getEntry("nested.jar")); .getNestedJarFile(this.jarFile.getEntry("nested.jar"));
URL url = nestedJarFile.getJarEntry("3.dat").getUrl(); URL url = nestedJarFile.getJarEntry("3.dat").getUrl();
assertThat(url.toString(), assertThat(url.toString())
equalTo("jar:" + this.rootJarFile.toURI() + "!/nested.jar!/3.dat")); .isEqualTo("jar:" + this.rootJarFile.toURI() + "!/nested.jar!/3.dat");
InputStream inputStream = url.openStream(); InputStream inputStream = url.openStream();
assertThat(inputStream, notNullValue()); assertThat(inputStream).isNotNull();
assertThat(inputStream.read(), equalTo(3)); assertThat(inputStream.read()).isEqualTo(3);
} }
@Test @Test
@ -307,15 +300,15 @@ public class JarFileTests {
JarFile.registerUrlProtocolHandler(); JarFile.registerUrlProtocolHandler();
String spec = "jar:" + this.rootJarFile.toURI() + "!/nested.jar!/3.dat"; String spec = "jar:" + this.rootJarFile.toURI() + "!/nested.jar!/3.dat";
URL url = new URL(spec); URL url = new URL(spec);
assertThat(url.toString(), equalTo(spec)); assertThat(url.toString()).isEqualTo(spec);
InputStream inputStream = url.openStream(); InputStream inputStream = url.openStream();
assertThat(inputStream, notNullValue()); assertThat(inputStream).isNotNull();
assertThat(inputStream.read(), equalTo(3)); assertThat(inputStream.read()).isEqualTo(3);
JarURLConnection connection = (JarURLConnection) url.openConnection(); JarURLConnection connection = (JarURLConnection) url.openConnection();
assertThat(connection.getURL().toString(), equalTo(spec)); assertThat(connection.getURL().toString()).isEqualTo(spec);
assertThat(connection.getJarFileURL().toString(), assertThat(connection.getJarFileURL().toString())
equalTo("jar:" + this.rootJarFile.toURI() + "!/nested.jar")); .isEqualTo("jar:" + this.rootJarFile.toURI() + "!/nested.jar");
assertThat(connection.getEntryName(), equalTo("3.dat")); assertThat(connection.getEntryName()).isEqualTo("3.dat");
} }
@Test @Test
@ -323,38 +316,37 @@ public class JarFileTests {
JarFile.registerUrlProtocolHandler(); JarFile.registerUrlProtocolHandler();
String spec = "jar:" + this.rootJarFile.toURI() + "!/2.dat"; String spec = "jar:" + this.rootJarFile.toURI() + "!/2.dat";
URL url = new URL(spec); URL url = new URL(spec);
assertThat(url.toString(), equalTo(spec)); assertThat(url.toString()).isEqualTo(spec);
InputStream inputStream = url.openStream(); InputStream inputStream = url.openStream();
assertThat(inputStream, notNullValue()); assertThat(inputStream).isNotNull();
assertThat(inputStream.read(), equalTo(2)); assertThat(inputStream.read()).isEqualTo(2);
JarURLConnection connection = (JarURLConnection) url.openConnection(); JarURLConnection connection = (JarURLConnection) url.openConnection();
assertThat(connection.getURL().toString(), equalTo(spec)); assertThat(connection.getURL().toString()).isEqualTo(spec);
assertThat(connection.getJarFileURL().toURI(), equalTo(this.rootJarFile.toURI())); assertThat(connection.getJarFileURL().toURI())
assertThat(connection.getEntryName(), equalTo("2.dat")); .isEqualTo(this.rootJarFile.toURI());
assertThat(connection.getEntryName()).isEqualTo("2.dat");
} }
@Test @Test
public void getDirectoryInputStream() throws Exception { public void getDirectoryInputStream() throws Exception {
InputStream inputStream = this.jarFile InputStream inputStream = this.jarFile
.getInputStream(this.jarFile.getEntry("d/")); .getInputStream(this.jarFile.getEntry("d/"));
assertThat(inputStream, notNullValue()); assertThat(inputStream).isNotNull();
assertThat(inputStream.read(), equalTo(-1)); assertThat(inputStream.read()).isEqualTo(-1);
} }
@Test @Test
public void getDirectoryInputStreamWithoutSlash() throws Exception { public void getDirectoryInputStreamWithoutSlash() throws Exception {
InputStream inputStream = this.jarFile.getInputStream(this.jarFile.getEntry("d")); InputStream inputStream = this.jarFile.getInputStream(this.jarFile.getEntry("d"));
assertThat(inputStream, notNullValue()); assertThat(inputStream).isNotNull();
assertThat(inputStream.read(), equalTo(-1)); assertThat(inputStream.read()).isEqualTo(-1);
} }
@Test @Test
public void sensibleToString() throws Exception { public void sensibleToString() throws Exception {
assertThat(this.jarFile.toString(), equalTo(this.rootJarFile.getPath())); assertThat(this.jarFile.toString()).isEqualTo(this.rootJarFile.getPath());
assertThat( assertThat(this.jarFile.getNestedJarFile(this.jarFile.getEntry("nested.jar"))
this.jarFile.getNestedJarFile(this.jarFile.getEntry("nested.jar")) .toString()).isEqualTo(this.rootJarFile.getPath() + "!/nested.jar");
.toString(),
equalTo(this.rootJarFile.getPath() + "!/nested.jar"));
} }
@Test @Test
@ -367,7 +359,7 @@ public class JarFileTests {
signedJarFile = entry; signedJarFile = entry;
} }
} }
assertNotNull(signedJarFile); assertThat(signedJarFile).isNotNull();
java.util.jar.JarFile jarFile = new JarFile(new File(signedJarFile)); java.util.jar.JarFile jarFile = new JarFile(new File(signedJarFile));
jarFile.getManifest(); jarFile.getManifest();
Enumeration<JarEntry> jarEntries = jarFile.entries(); Enumeration<JarEntry> jarEntries = jarFile.entries();
@ -378,8 +370,7 @@ public class JarFileTests {
inputStream.close(); inputStream.close();
if (!jarEntry.getName().startsWith("META-INF") && !jarEntry.isDirectory() if (!jarEntry.getName().startsWith("META-INF") && !jarEntry.isDirectory()
&& !jarEntry.getName().endsWith("TigerDigest.class")) { && !jarEntry.getName().endsWith("TigerDigest.class")) {
assertNotNull("Missing cert " + jarEntry.getName(), assertThat(jarEntry.getCertificates()).isNotNull();
jarEntry.getCertificates());
} }
} }
jarFile.close(); jarFile.close();

@ -20,9 +20,11 @@ import org.junit.AfterClass;
import org.junit.BeforeClass; import org.junit.BeforeClass;
import org.junit.Test; import org.junit.Test;
import static org.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
/** /**
* Tests for {@link SystemPropertyUtils}.
*
* @author Dave Syer * @author Dave Syer
*/ */
public class SystemPropertyUtilsTests { public class SystemPropertyUtilsTests {
@ -39,23 +41,25 @@ public class SystemPropertyUtilsTests {
@Test @Test
public void testVanillaPlaceholder() { public void testVanillaPlaceholder() {
assertEquals("bar", SystemPropertyUtils.resolvePlaceholders("${foo}")); assertThat(SystemPropertyUtils.resolvePlaceholders("${foo}")).isEqualTo("bar");
} }
@Test @Test
public void testDefaultValue() { public void testDefaultValue() {
assertEquals("foo", SystemPropertyUtils.resolvePlaceholders("${bar:foo}")); assertThat(SystemPropertyUtils.resolvePlaceholders("${bar:foo}"))
.isEqualTo("foo");
} }
@Test @Test
public void testNestedPlaceholder() { public void testNestedPlaceholder() {
assertEquals("foo", assertThat(SystemPropertyUtils.resolvePlaceholders("${bar:${spam:foo}}"))
SystemPropertyUtils.resolvePlaceholders("${bar:${spam:foo}}")); .isEqualTo("foo");
} }
@Test @Test
public void testEnvVar() { public void testEnvVar() {
assertEquals(System.getenv("LANG"), SystemPropertyUtils.getProperty("lang")); assertThat(SystemPropertyUtils.getProperty("lang"))
.isEqualTo(System.getenv("LANG"));
} }
} }

@ -36,8 +36,7 @@ import org.springframework.boot.loader.tools.Library;
import org.springframework.boot.loader.tools.LibraryCallback; import org.springframework.boot.loader.tools.LibraryCallback;
import org.springframework.boot.loader.tools.LibraryScope; import org.springframework.boot.loader.tools.LibraryScope;
import static org.hamcrest.Matchers.equalTo; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertThat;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times; import static org.mockito.Mockito.times;
@ -80,9 +79,9 @@ public class ArtifactsLibrariesTests {
this.libs.doWithLibraries(this.callback); this.libs.doWithLibraries(this.callback);
verify(this.callback).library(this.libraryCaptor.capture()); verify(this.callback).library(this.libraryCaptor.capture());
Library library = this.libraryCaptor.getValue(); Library library = this.libraryCaptor.getValue();
assertThat(library.getFile(), equalTo(this.file)); assertThat(library.getFile()).isEqualTo(this.file);
assertThat(library.getScope(), equalTo(LibraryScope.COMPILE)); assertThat(library.getScope()).isEqualTo(LibraryScope.COMPILE);
assertThat(library.isUnpackRequired(), equalTo(false)); assertThat(library.isUnpackRequired()).isFalse();
} }
@Test @Test
@ -98,7 +97,7 @@ public class ArtifactsLibrariesTests {
mock(Log.class)); mock(Log.class));
this.libs.doWithLibraries(this.callback); this.libs.doWithLibraries(this.callback);
verify(this.callback).library(this.libraryCaptor.capture()); verify(this.callback).library(this.libraryCaptor.capture());
assertThat(this.libraryCaptor.getValue().isUnpackRequired(), equalTo(true)); assertThat(this.libraryCaptor.getValue().isUnpackRequired()).isTrue();
} }
@Test @Test
@ -117,8 +116,8 @@ public class ArtifactsLibrariesTests {
this.libs = new ArtifactsLibraries(this.artifacts, null, mock(Log.class)); this.libs = new ArtifactsLibraries(this.artifacts, null, mock(Log.class));
this.libs.doWithLibraries(this.callback); this.libs.doWithLibraries(this.callback);
verify(this.callback, times(2)).library(this.libraryCaptor.capture()); verify(this.callback, times(2)).library(this.libraryCaptor.capture());
assertThat(this.libraryCaptor.getAllValues().get(0).getName(), equalTo("g1-a")); assertThat(this.libraryCaptor.getAllValues().get(0).getName()).isEqualTo("g1-a");
assertThat(this.libraryCaptor.getAllValues().get(1).getName(), equalTo("g2-a")); assertThat(this.libraryCaptor.getAllValues().get(1).getName()).isEqualTo("g2-a");
} }
} }

@ -27,8 +27,7 @@ import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugin.MojoFailureException;
import org.junit.Test; import org.junit.Test;
import static org.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertSame;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
@ -48,8 +47,8 @@ public class DependencyFilterMojoTests {
Set<Artifact> artifacts = mojo.filterDependencies( Set<Artifact> artifacts = mojo.filterDependencies(
createArtifact("com.foo", "one"), createArtifact("com.foo", "two"), createArtifact("com.foo", "one"), createArtifact("com.foo", "two"),
createArtifact("com.bar", "exclude-id"), artifact); createArtifact("com.bar", "exclude-id"), artifact);
assertEquals("wrong filtering of artifacts", 1, artifacts.size()); assertThat(artifacts).hasSize(1);
assertSame("Wrong filtered artifact", artifact, artifacts.iterator().next()); assertThat(artifacts.iterator().next()).isSameAs(artifact);
} }
@Test @Test
@ -61,8 +60,8 @@ public class DependencyFilterMojoTests {
Set<Artifact> artifacts = mojo.filterDependencies( Set<Artifact> artifacts = mojo.filterDependencies(
createArtifact("com.foo", "one"), createArtifact("com.foo", "two"), createArtifact("com.foo", "one"), createArtifact("com.foo", "two"),
artifact); artifact);
assertEquals("wrong filtering of artifacts", 1, artifacts.size()); assertThat(artifacts).hasSize(1);
assertSame("Wrong filtered artifact", artifact, artifacts.iterator().next()); assertThat(artifacts.iterator().next()).isSameAs(artifact);
} }
private Artifact createArtifact(String groupId, String artifactId) { private Artifact createArtifact(String groupId, String artifactId) {

@ -25,8 +25,7 @@ import org.apache.maven.artifact.Artifact;
import org.apache.maven.shared.artifact.filter.collection.ArtifactFilterException; import org.apache.maven.shared.artifact.filter.collection.ArtifactFilterException;
import org.junit.Test; import org.junit.Test;
import static org.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertSame;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
@ -36,7 +35,7 @@ import static org.mockito.Mockito.mock;
* @author Stephane Nicoll * @author Stephane Nicoll
* @author David Turanski * @author David Turanski
*/ */
@SuppressWarnings("rawtypes") @SuppressWarnings({ "rawtypes", "unchecked" })
public class ExcludeFilterTests { public class ExcludeFilterTests {
@Test @Test
@ -45,7 +44,7 @@ public class ExcludeFilterTests {
Arrays.asList(createExclude("com.foo", "bar"))); Arrays.asList(createExclude("com.foo", "bar")));
Set result = filter Set result = filter
.filter(Collections.singleton(createArtifact("com.foo", "bar"))); .filter(Collections.singleton(createArtifact("com.foo", "bar")));
assertEquals("Should have been filtered", 0, result.size()); assertThat(result).isEmpty();
} }
@Test @Test
@ -54,8 +53,8 @@ public class ExcludeFilterTests {
Arrays.asList(createExclude("com.foo", "bar"))); Arrays.asList(createExclude("com.foo", "bar")));
Artifact artifact = createArtifact("com.baz", "bar"); Artifact artifact = createArtifact("com.baz", "bar");
Set result = filter.filter(Collections.singleton(artifact)); Set result = filter.filter(Collections.singleton(artifact));
assertEquals("Should not have been filtered", 1, result.size()); assertThat(result).hasSize(1);
assertSame(artifact, result.iterator().next()); assertThat(result.iterator().next()).isSameAs(artifact);
} }
@Test @Test
@ -64,8 +63,8 @@ public class ExcludeFilterTests {
Arrays.asList(createExclude("com.foo", "bar"))); Arrays.asList(createExclude("com.foo", "bar")));
Artifact artifact = createArtifact("com.foo", "biz"); Artifact artifact = createArtifact("com.foo", "biz");
Set result = filter.filter(Collections.singleton(artifact)); Set result = filter.filter(Collections.singleton(artifact));
assertEquals("Should not have been filtered", 1, result.size()); assertThat(result).hasSize(1);
assertSame(artifact, result.iterator().next()); assertThat(result.iterator().next()).isSameAs(artifact);
} }
@Test @Test
@ -74,7 +73,7 @@ public class ExcludeFilterTests {
Arrays.asList(createExclude("com.foo", "bar", "jdk5"))); Arrays.asList(createExclude("com.foo", "bar", "jdk5")));
Set result = filter Set result = filter
.filter(Collections.singleton(createArtifact("com.foo", "bar", "jdk5"))); .filter(Collections.singleton(createArtifact("com.foo", "bar", "jdk5")));
assertEquals("Should have been filtered", 0, result.size()); assertThat(result).isEmpty();
} }
@Test @Test
@ -83,8 +82,8 @@ public class ExcludeFilterTests {
Arrays.asList(createExclude("com.foo", "bar", "jdk5"))); Arrays.asList(createExclude("com.foo", "bar", "jdk5")));
Artifact artifact = createArtifact("com.foo", "bar"); Artifact artifact = createArtifact("com.foo", "bar");
Set result = filter.filter(Collections.singleton(artifact)); Set result = filter.filter(Collections.singleton(artifact));
assertEquals("Should not have been filtered", 1, result.size()); assertThat(result).hasSize(1);
assertSame(artifact, result.iterator().next()); assertThat(result.iterator().next()).isSameAs(artifact);
} }
@Test @Test
@ -93,8 +92,8 @@ public class ExcludeFilterTests {
Arrays.asList(createExclude("com.foo", "bar", "jdk5"))); Arrays.asList(createExclude("com.foo", "bar", "jdk5")));
Artifact artifact = createArtifact("com.foo", "bar", "jdk6"); Artifact artifact = createArtifact("com.foo", "bar", "jdk6");
Set result = filter.filter(Collections.singleton(artifact)); Set result = filter.filter(Collections.singleton(artifact));
assertEquals("Should not have been filtered", 1, result.size()); assertThat(result).hasSize(1);
assertSame(artifact, result.iterator().next()); assertThat(result.iterator().next()).isSameAs(artifact);
} }
@Test @Test
@ -108,8 +107,8 @@ public class ExcludeFilterTests {
Artifact anotherAcme = createArtifact("org.acme", "another-app"); Artifact anotherAcme = createArtifact("org.acme", "another-app");
artifacts.add(anotherAcme); artifacts.add(anotherAcme);
Set result = filter.filter(artifacts); Set result = filter.filter(artifacts);
assertEquals("Two dependencies should have been filtered", 1, result.size()); assertThat(result).hasSize(1);
assertSame(anotherAcme, result.iterator().next()); assertThat(result.iterator().next()).isSameAs(anotherAcme);
} }
private Exclude createExclude(String groupId, String artifactId) { private Exclude createExclude(String groupId, String artifactId) {

@ -25,8 +25,7 @@ import org.apache.maven.artifact.Artifact;
import org.apache.maven.shared.artifact.filter.collection.ArtifactFilterException; import org.apache.maven.shared.artifact.filter.collection.ArtifactFilterException;
import org.junit.Test; import org.junit.Test;
import static org.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertSame;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
@ -35,7 +34,7 @@ import static org.mockito.Mockito.mock;
* *
* @author David Turanski * @author David Turanski
*/ */
@SuppressWarnings("rawtypes") @SuppressWarnings({ "rawtypes", "unchecked" })
public class IncludeFilterTests { public class IncludeFilterTests {
@Test @Test
@ -44,8 +43,8 @@ public class IncludeFilterTests {
Arrays.asList(createInclude("com.foo", "bar"))); Arrays.asList(createInclude("com.foo", "bar")));
Artifact artifact = createArtifact("com.foo", "bar"); Artifact artifact = createArtifact("com.foo", "bar");
Set result = filter.filter(Collections.singleton(artifact)); Set result = filter.filter(Collections.singleton(artifact));
assertEquals("Should not have been filtered", 1, result.size()); assertThat(result).hasSize(1);
assertSame(artifact, result.iterator().next()); assertThat(result.iterator().next()).isSameAs(artifact);
} }
@Test @Test
@ -54,7 +53,7 @@ public class IncludeFilterTests {
Arrays.asList(createInclude("com.foo", "bar"))); Arrays.asList(createInclude("com.foo", "bar")));
Artifact artifact = createArtifact("com.baz", "bar"); Artifact artifact = createArtifact("com.baz", "bar");
Set result = filter.filter(Collections.singleton(artifact)); Set result = filter.filter(Collections.singleton(artifact));
assertEquals("Should have been filtered", 0, result.size()); assertThat(result).isEmpty();
} }
@Test @Test
@ -63,7 +62,7 @@ public class IncludeFilterTests {
Arrays.asList(createInclude("com.foo", "bar"))); Arrays.asList(createInclude("com.foo", "bar")));
Artifact artifact = createArtifact("com.foo", "biz"); Artifact artifact = createArtifact("com.foo", "biz");
Set result = filter.filter(Collections.singleton(artifact)); Set result = filter.filter(Collections.singleton(artifact));
assertEquals("Should have been filtered", 0, result.size()); assertThat(result).isEmpty();
} }
@Test @Test
@ -72,8 +71,8 @@ public class IncludeFilterTests {
Arrays.asList(createInclude("com.foo", "bar", "jdk5"))); Arrays.asList(createInclude("com.foo", "bar", "jdk5")));
Artifact artifact = createArtifact("com.foo", "bar", "jdk5"); Artifact artifact = createArtifact("com.foo", "bar", "jdk5");
Set result = filter.filter(Collections.singleton(artifact)); Set result = filter.filter(Collections.singleton(artifact));
assertEquals("Should not have been filtered", 1, result.size()); assertThat(result).hasSize(1);
assertSame(artifact, result.iterator().next()); assertThat(result.iterator().next()).isSameAs(artifact);
} }
@Test @Test
@ -82,7 +81,7 @@ public class IncludeFilterTests {
Arrays.asList(createInclude("com.foo", "bar", "jdk5"))); Arrays.asList(createInclude("com.foo", "bar", "jdk5")));
Artifact artifact = createArtifact("com.foo", "bar"); Artifact artifact = createArtifact("com.foo", "bar");
Set result = filter.filter(Collections.singleton(artifact)); Set result = filter.filter(Collections.singleton(artifact));
assertEquals("Should have been filtered", 0, result.size()); assertThat(result).isEmpty();
} }
@Test @Test
@ -91,7 +90,7 @@ public class IncludeFilterTests {
Arrays.asList(createInclude("com.foo", "bar", "jdk5"))); Arrays.asList(createInclude("com.foo", "bar", "jdk5")));
Artifact artifact = createArtifact("com.foo", "bar", "jdk6"); Artifact artifact = createArtifact("com.foo", "bar", "jdk6");
Set result = filter.filter(Collections.singleton(artifact)); Set result = filter.filter(Collections.singleton(artifact));
assertEquals("Should have been filtered", 0, result.size()); assertThat(result).isEmpty();
} }
@Test @Test
@ -105,7 +104,7 @@ public class IncludeFilterTests {
Artifact anotherAcme = createArtifact("org.acme", "another-app"); Artifact anotherAcme = createArtifact("org.acme", "another-app");
artifacts.add(anotherAcme); artifacts.add(anotherAcme);
Set result = filter.filter(artifacts); Set result = filter.filter(artifacts);
assertEquals("One dependency should have been filtered", 2, result.size()); assertThat(result).hasSize(2);
} }
private Include createInclude(String groupId, String artifactId) { private Include createInclude(String groupId, String artifactId) {

@ -22,10 +22,7 @@ import java.util.jar.JarOutputStream;
import org.junit.Test; import org.junit.Test;
import static org.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
/** /**
* Tests for {@link PropertiesMergingResourceTransformer}. * Tests for {@link PropertiesMergingResourceTransformer}.
@ -38,10 +35,10 @@ public class PropertiesMergingResourceTransformerTests {
@Test @Test
public void testProcess() throws Exception { public void testProcess() throws Exception {
assertFalse(this.transformer.hasTransformedResource()); assertThat(this.transformer.hasTransformedResource()).isFalse();
this.transformer.processResource("foo", this.transformer.processResource("foo",
new ByteArrayInputStream("foo=bar".getBytes()), null); new ByteArrayInputStream("foo=bar".getBytes()), null);
assertTrue(this.transformer.hasTransformedResource()); assertThat(this.transformer.hasTransformedResource()).isTrue();
} }
@Test @Test
@ -50,7 +47,7 @@ public class PropertiesMergingResourceTransformerTests {
new ByteArrayInputStream("foo=bar".getBytes()), null); new ByteArrayInputStream("foo=bar".getBytes()), null);
this.transformer.processResource("bar", this.transformer.processResource("bar",
new ByteArrayInputStream("foo=spam".getBytes()), null); new ByteArrayInputStream("foo=spam".getBytes()), null);
assertEquals("bar,spam", this.transformer.getData().getProperty("foo")); assertThat(this.transformer.getData().getProperty("foo")).isEqualTo("bar,spam");
} }
@Test @Test
@ -63,8 +60,8 @@ public class PropertiesMergingResourceTransformerTests {
this.transformer.modifyOutputStream(os); this.transformer.modifyOutputStream(os);
os.flush(); os.flush();
os.close(); os.close();
assertNotNull(out.toByteArray()); assertThat(out.toByteArray()).isNotNull();
assertTrue(out.toByteArray().length > 0); assertThat(out.toByteArray().length > 0).isTrue();
} }
} }

@ -18,8 +18,7 @@ package org.springframework.boot.maven;
import org.junit.Test; import org.junit.Test;
import static org.junit.Assert.assertEquals; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertNotNull;
/** /**
* Tests for {@link RunArguments}. * Tests for {@link RunArguments}.
@ -31,48 +30,48 @@ public class RunArgumentsTests {
@Test @Test
public void parseNull() { public void parseNull() {
String[] args = parseArgs(null); String[] args = parseArgs(null);
assertNotNull(args); assertThat(args).isNotNull();
assertEquals(0, args.length); assertThat(args.length).isEqualTo(0);
} }
@Test @Test
public void parseEmpty() { public void parseEmpty() {
String[] args = parseArgs(" "); String[] args = parseArgs(" ");
assertNotNull(args); assertThat(args).isNotNull();
assertEquals(0, args.length); assertThat(args.length).isEqualTo(0);
} }
@Test @Test
public void parseDebugFlags() { public void parseDebugFlags() {
String[] args = parseArgs( String[] args = parseArgs(
"-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=5005"); "-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=5005");
assertEquals(2, args.length); assertThat(args.length).isEqualTo(2);
assertEquals("-Xdebug", args[0]); assertThat(args[0]).isEqualTo("-Xdebug");
assertEquals("-Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=5005", assertThat(args[1]).isEqualTo(
args[1]); "-Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=5005");
} }
@Test @Test
public void parseWithExtraSpaces() { public void parseWithExtraSpaces() {
String[] args = parseArgs(" -Dfoo=bar -Dfoo2=bar2 "); String[] args = parseArgs(" -Dfoo=bar -Dfoo2=bar2 ");
assertEquals(2, args.length); assertThat(args.length).isEqualTo(2);
assertEquals("-Dfoo=bar", args[0]); assertThat(args[0]).isEqualTo("-Dfoo=bar");
assertEquals("-Dfoo2=bar2", args[1]); assertThat(args[1]).isEqualTo("-Dfoo2=bar2");
} }
@Test @Test
public void parseWithNewLinesAndTabs() { public void parseWithNewLinesAndTabs() {
String[] args = parseArgs(" -Dfoo=bar \n" + "\t\t -Dfoo2=bar2 "); String[] args = parseArgs(" -Dfoo=bar \n" + "\t\t -Dfoo2=bar2 ");
assertEquals(2, args.length); assertThat(args.length).isEqualTo(2);
assertEquals("-Dfoo=bar", args[0]); assertThat(args[0]).isEqualTo("-Dfoo=bar");
assertEquals("-Dfoo2=bar2", args[1]); assertThat(args[1]).isEqualTo("-Dfoo2=bar2");
} }
@Test @Test
public void quoteHandledProperly() { public void quoteHandledProperly() {
String[] args = parseArgs("-Dvalue=\"My Value\" "); String[] args = parseArgs("-Dvalue=\"My Value\" ");
assertEquals(1, args.length); assertThat(args.length).isEqualTo(1);
assertEquals("-Dvalue=My Value", args[0]); assertThat(args[0]).isEqualTo("-Dvalue=My Value");
} }
private String[] parseArgs(String args) { private String[] parseArgs(String args) {

@ -28,11 +28,7 @@ import java.util.zip.ZipFile;
import org.springframework.util.FileCopyUtils; import org.springframework.util.FileCopyUtils;
import static org.hamcrest.Matchers.containsString; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
/** /**
* Verification utility for use with maven-invoker-plugin verification scripts. * Verification utility for use with maven-invoker-plugin verification scripts.
@ -107,13 +103,15 @@ public final class Verify {
} }
public void assertHasNonUnpackEntry(String entryName) { public void assertHasNonUnpackEntry(String entryName) {
assertTrue("Entry starting with " + entryName + " was an UNPACK entry", assertThat(hasNonUnpackEntry(entryName))
hasNonUnpackEntry(entryName)); .as("Entry starting with " + entryName + " was an UNPACK entry")
.isTrue();
} }
public void assertHasUnpackEntry(String entryName) { public void assertHasUnpackEntry(String entryName) {
assertTrue("Entry starting with " + entryName + " was not an UNPACK entry", assertThat(hasUnpackEntry(entryName))
hasUnpackEntry(entryName)); .as("Entry starting with " + entryName + " was not an UNPACK entry")
.isTrue();
} }
private boolean hasNonUnpackEntry(String entryName) { private boolean hasNonUnpackEntry(String entryName) {
@ -167,22 +165,21 @@ public final class Verify {
public void verify(boolean executable, String... scriptContents) public void verify(boolean executable, String... scriptContents)
throws Exception { throws Exception {
assertTrue("Archive missing", this.file.exists()); assertThat(this.file).exists().isFile();
assertTrue("Archive not a file", this.file.isFile());
if (scriptContents.length > 0 && executable) { if (scriptContents.length > 0 && executable) {
String contents = new String(FileCopyUtils.copyToByteArray(this.file)); String contents = new String(FileCopyUtils.copyToByteArray(this.file));
contents = contents.substring(0, contents contents = contents.substring(0, contents
.indexOf(new String(new byte[] { 0x50, 0x4b, 0x03, 0x04 }))); .indexOf(new String(new byte[] { 0x50, 0x4b, 0x03, 0x04 })));
for (String content : scriptContents) { for (String content : scriptContents) {
assertThat(contents, containsString(content)); assertThat(contents).contains(content);
} }
} }
if (!executable) { if (!executable) {
String contents = new String(FileCopyUtils.copyToByteArray(this.file)); String contents = new String(FileCopyUtils.copyToByteArray(this.file));
assertTrue("Is executable", contents assertThat(contents).as("Is executable")
.startsWith(new String(new byte[] { 0x50, 0x4b, 0x03, 0x04 }))); .startsWith(new String(new byte[] { 0x50, 0x4b, 0x03, 0x04 }));
} }
ZipFile zipFile = new ZipFile(this.file); ZipFile zipFile = new ZipFile(this.file);
@ -224,18 +221,21 @@ public final class Verify {
verifier.assertHasEntryNameStartingWith("lib/spring-context"); verifier.assertHasEntryNameStartingWith("lib/spring-context");
verifier.assertHasEntryNameStartingWith("lib/spring-core"); verifier.assertHasEntryNameStartingWith("lib/spring-core");
verifier.assertHasEntryNameStartingWith("lib/javax.servlet-api-3"); verifier.assertHasEntryNameStartingWith("lib/javax.servlet-api-3");
assertTrue("Unpacked launcher classes", verifier assertThat(verifier
.hasEntry("org/" + "springframework/boot/loader/JarLauncher.class")); .hasEntry("org/" + "springframework/boot/loader/JarLauncher.class"))
assertTrue("Own classes", .as("Unpacked launcher classes").isTrue();
verifier.hasEntry("org/" + "test/SampleApplication.class")); assertThat(verifier.hasEntry("org/" + "test/SampleApplication.class"))
.as("Own classes").isTrue();
} }
@Override @Override
protected void verifyManifest(Manifest manifest) throws Exception { protected void verifyManifest(Manifest manifest) throws Exception {
assertEquals("org.springframework.boot.loader.JarLauncher", assertThat(manifest.getMainAttributes().getValue("Main-Class"))
manifest.getMainAttributes().getValue("Main-Class")); .isEqualTo("org.springframework.boot.loader.JarLauncher");
assertEquals(this.main, manifest.getMainAttributes().getValue("Start-Class")); assertThat(manifest.getMainAttributes().getValue("Start-Class"))
assertEquals("Foo", manifest.getMainAttributes().getValue("Not-Used")); .isEqualTo(this.main);
assertThat(manifest.getMainAttributes().getValue("Not-Used"))
.isEqualTo("Foo");
} }
} }
@ -252,20 +252,23 @@ public final class Verify {
verifier.assertHasEntryNameStartingWith("WEB-INF/lib/spring-core"); verifier.assertHasEntryNameStartingWith("WEB-INF/lib/spring-core");
verifier.assertHasEntryNameStartingWith( verifier.assertHasEntryNameStartingWith(
"WEB-INF/lib-provided/javax.servlet-api-3"); "WEB-INF/lib-provided/javax.servlet-api-3");
assertTrue("Unpacked launcher classes", verifier assertThat(verifier
.hasEntry("org/" + "springframework/boot/loader/JarLauncher.class")); .hasEntry("org/" + "springframework/boot/loader/JarLauncher.class"))
assertTrue("Own classes", verifier .as("Unpacked launcher classes").isTrue();
.hasEntry("WEB-INF/classes/org/" + "test/SampleApplication.class")); assertThat(verifier
assertTrue("Web content", verifier.hasEntry("index.html")); .hasEntry("WEB-INF/classes/org/" + "test/SampleApplication.class"))
.as("Own classes").isTrue();
assertThat(verifier.hasEntry("index.html")).as("Web content").isTrue();
} }
@Override @Override
protected void verifyManifest(Manifest manifest) throws Exception { protected void verifyManifest(Manifest manifest) throws Exception {
assertEquals("org.springframework.boot.loader.WarLauncher", assertThat(manifest.getMainAttributes().getValue("Main-Class"))
manifest.getMainAttributes().getValue("Main-Class")); .isEqualTo("org.springframework.boot.loader.WarLauncher");
assertEquals("org.test.SampleApplication", assertThat(manifest.getMainAttributes().getValue("Start-Class"))
manifest.getMainAttributes().getValue("Start-Class")); .isEqualTo("org.test.SampleApplication");
assertEquals("Foo", manifest.getMainAttributes().getValue("Not-Used")); assertThat(manifest.getMainAttributes().getValue("Not-Used"))
.isEqualTo("Foo");
} }
} }
@ -277,11 +280,12 @@ public final class Verify {
@Override @Override
protected void verifyManifest(Manifest manifest) throws Exception { protected void verifyManifest(Manifest manifest) throws Exception {
assertEquals("org.springframework.boot.loader.PropertiesLauncher", assertThat(manifest.getMainAttributes().getValue("Main-Class"))
manifest.getMainAttributes().getValue("Main-Class")); .isEqualTo("org.springframework.boot.loader.PropertiesLauncher");
assertEquals("org.test.SampleApplication", assertThat(manifest.getMainAttributes().getValue("Start-Class"))
manifest.getMainAttributes().getValue("Start-Class")); .isEqualTo("org.test.SampleApplication");
assertEquals("Foo", manifest.getMainAttributes().getValue("Not-Used")); assertThat(manifest.getMainAttributes().getValue("Not-Used"))
.isEqualTo("Foo");
} }
} }
@ -297,10 +301,11 @@ public final class Verify {
verifier.assertHasEntryNameStartingWith("lib/spring-context"); verifier.assertHasEntryNameStartingWith("lib/spring-context");
verifier.assertHasEntryNameStartingWith("lib/spring-core"); verifier.assertHasEntryNameStartingWith("lib/spring-core");
verifier.assertHasNoEntryNameStartingWith("lib/javax.servlet-api-3"); verifier.assertHasNoEntryNameStartingWith("lib/javax.servlet-api-3");
assertFalse("Unpacked launcher classes", verifier assertThat(verifier
.hasEntry("org/" + "springframework/boot/loader/JarLauncher.class")); .hasEntry("org/" + "springframework/boot/loader/JarLauncher.class"))
assertTrue("Own classes", .as("Unpacked launcher classes").isFalse();
verifier.hasEntry("org/" + "test/SampleModule.class")); assertThat(verifier.hasEntry("org/" + "test/SampleModule.class"))
.as("Own classes").isTrue();
} }
@Override @Override

Loading…
Cancel
Save