Skip to content

Commit

Permalink
#18 Comments on beans: Add tests, revise Javadoc
Browse files Browse the repository at this point in the history
  • Loading branch information
ljacqu committed Aug 3, 2023
1 parent a427c1c commit 96881d2
Show file tree
Hide file tree
Showing 15 changed files with 918 additions and 32 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,13 @@ public class BeanDescriptionFactoryImpl implements BeanDescriptionFactory {
comments);
}

/**
* Returns the comments that are defined on the property. Comments are found by looking for an @{@link Comment}
* annotation on a field with the same name as the property.
*
* @param descriptor the property descriptor
* @return comments for the property (never null)
*/
protected @NotNull List<String> getComments(@NotNull PropertyDescriptor descriptor) {
try {
Field field = descriptor.getWriteMethod().getDeclaringClass().getDeclaredField(descriptor.getName());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,9 @@ public interface BeanPropertyDescription {
*/
@Nullable Object getValue(@NotNull Object bean);

/**
* @return the comments to add when this property is exported
*/
@NotNull List<String> getComments();

}
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,9 @@ public interface SnakeYamlNodeBuilder {
* but we do not want the comments to appear between the key and the value in the YAML. Therefore, this method is
* called before producing YAML as to move the comments from the value to the key node.
*
* @implNote Only considers {@link Node#getBlockComments() block comments} on the nodes because it's the only type
* of comment that this builder sets.
*
* @param valueNode the value node to remove the comments from
* @param keyNode the key node to set the comments to
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
import org.yaml.snakeyaml.nodes.SequenceNode;
import org.yaml.snakeyaml.nodes.Tag;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
Expand Down Expand Up @@ -55,7 +56,7 @@ public class SnakeYamlNodeBuilderImpl implements SnakeYamlNodeBuilder {
node = createSequenceNode(stream, path, configurationData);
} else {
throw new IllegalArgumentException("Unsupported value of type: "
+ (value == null ? null : value.getClass()));
+ (value == null ? null : value.getClass().getName()));
}

List<CommentLine> commentLines = collectComments(obj, path, configurationData, numberOfNewLines);
Expand All @@ -78,7 +79,7 @@ public class SnakeYamlNodeBuilderImpl implements SnakeYamlNodeBuilder {

@Override
public void transferComments(@NotNull Node valueNode, @NotNull Node keyNode) {
if (!valueNode.getBlockComments().isEmpty()) {
if (valueNode.getBlockComments() != null && !valueNode.getBlockComments().isEmpty()) {
keyNode.setBlockComments(valueNode.getBlockComments());
valueNode.setBlockComments(Collections.emptyList());
}
Expand All @@ -89,7 +90,9 @@ public void transferComments(@NotNull Node valueNode, @NotNull Node keyNode) {
}

protected @NotNull Node createNumberNode(@NotNull Number value) {
Tag tag = (value instanceof Double || value instanceof Float) ? Tag.FLOAT : Tag.INT;
Tag tag = (value instanceof Double || value instanceof Float || value instanceof BigDecimal)
? Tag.FLOAT
: Tag.INT;
return new ScalarNode(tag, value.toString(), null, null, DumperOptions.ScalarStyle.PLAIN);
}

Expand Down Expand Up @@ -128,6 +131,16 @@ public void transferComments(@NotNull Node valueNode, @NotNull Node keyNode) {
return new MappingNode(Tag.MAP, nodeEntries, DumperOptions.FlowStyle.BLOCK);
}

/**
* Creates comments based on all possible sources (number of empty lines, configuration data,
* {@link ValueWithComments}) and returns them as SnakeYAML comment lines.
*
* @param value the export value
* @param path the path the value is located at
* @param configurationData the configuration data instance
* @param numberOfNewLines number of new lines to add to the beginning of the comments
* @return comment lines representing all defined comments
*/
protected @NotNull List<CommentLine> collectComments(@NotNull Object value, @NotNull String path,
@NotNull ConfigurationData configurationData,
int numberOfNewLines) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ public SnakeYamlNodeContainerImpl(@NotNull List<String> comments) {
@NotNull Supplier<List<String>> commentsSupplier) {
Object value = values.computeIfAbsent(name, k -> new SnakeYamlNodeContainerImpl(commentsSupplier.get()));
if (!(value instanceof SnakeYamlNodeContainer)) {
throw new IllegalStateException("Unexpectedly found " + value.getClass() + " in '" + name + "'");
throw new IllegalStateException("Unexpectedly found " + value.getClass().getName() + " in '" + name + "'");
}
return (SnakeYamlNodeContainer) value;
}
Expand Down
10 changes: 0 additions & 10 deletions src/test/java/ch/jalu/configme/TestUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -119,16 +119,6 @@ public static <E> Matcher<Iterable<? extends E>> containsAll(Iterable<E> element
// Exception verification
// -------------

/**
* Verifies that the provided executable throws an exception of the given type.
*
* @param executable the executable to check
* @param exceptionType the expected type of the exception
*/
public static void verifyException(Executable executable, Class<? extends Exception> exceptionType) {
verifyException(executable, exceptionType, "");
}

/**
* Verifies that the provided executable throws an exception of the given type whose message contains
* the provided message excerpt.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,13 @@
import ch.jalu.configme.beanmapper.command.Command;
import ch.jalu.configme.beanmapper.command.CommandConfig;
import ch.jalu.configme.beanmapper.command.ExecutionDetails;
import ch.jalu.configme.beanmapper.command.Executor;
import ch.jalu.configme.properties.convertresult.ValueWithComments;
import org.junit.jupiter.api.Test;

import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;

import static ch.jalu.configme.beanmapper.command.Executor.CONSOLE;
Expand All @@ -30,11 +28,11 @@ class MapperExportValueTest {
@Test
void shouldCreatePropertyEntriesForCommandConfig() {
// given
ExecutionDetails kickExecution = createExecution(CONSOLE, 0.4, true, "player.kick", "is.admin");
ExecutionDetails kickExecution = new ExecutionDetails(CONSOLE, 0.4, true, "player.kick", "is.admin");
Command kickCommand = createCommand("kick", kickExecution, "name");
ExecutionDetails msgExecution = createExecution(USER, 1.0, false, "player.msg");
ExecutionDetails msgExecution = new ExecutionDetails(USER, 1.0, false, "player.msg");
Command msgCommand = createCommand("msg", msgExecution, "name", "message");
ExecutionDetails vanishExecution = createExecution(USER, 0.1, true, "player.vanish");
ExecutionDetails vanishExecution = new ExecutionDetails(USER, 0.1, true, "player.vanish");
Command vanishCommand = createCommand("vanish", vanishExecution);

CommandConfig config = new CommandConfig();
Expand Down Expand Up @@ -131,14 +129,4 @@ private static Command createCommand(String name, ExecutionDetails executionDeta
command.setArguments(Arrays.asList(arguments));
return command;
}

private static ExecutionDetails createExecution(Executor executor, double importance, boolean isOptional,
String... privileges) {
ExecutionDetails execution = new ExecutionDetails();
execution.setImportance(importance);
execution.setOptional(isOptional);
execution.setExecutor(executor);
execution.setPrivileges(new LinkedHashSet<>(Arrays.asList(privileges)));
return execution;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

import ch.jalu.configme.Comment;

import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.Set;

/**
Expand All @@ -15,6 +17,16 @@ public class ExecutionDetails {
private Double importance;
private Set<String> privileges;

public ExecutionDetails() {
}

public ExecutionDetails(Executor executor, double importance, boolean isOptional, String... privileges) {
this.executor = executor;
this.optional = isOptional;
this.importance = importance;
this.privileges = new LinkedHashSet<>(Arrays.asList(privileges));
}

public Executor getExecutor() {
return executor;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package ch.jalu.configme.beanmapper.propertydescription;


import ch.jalu.configme.Comment;
import ch.jalu.configme.beanmapper.ConfigMeMapperException;
import ch.jalu.configme.samples.beanannotations.AnnotatedEntry;
import ch.jalu.configme.samples.beanannotations.BeanWithEmptyName;
Expand Down Expand Up @@ -40,8 +41,14 @@ void shouldReturnWritableProperties() {

// then
assertThat(descriptions, hasSize(2));
assertThat(getDescription("size", descriptions).getTypeInformation(), equalTo(new TypeInformation(int.class)));
assertThat(getDescription("name", descriptions).getTypeInformation(), equalTo(new TypeInformation(String.class)));

BeanPropertyDescription sizeProperty = getDescription("size", descriptions);
assertThat(sizeProperty.getTypeInformation(), equalTo(new TypeInformation(int.class)));
assertThat(sizeProperty.getComments(), contains("Size of this entry (cm)"));

BeanPropertyDescription nameProperty = getDescription("name", descriptions);
assertThat(nameProperty.getTypeInformation(), equalTo(new TypeInformation(String.class)));
assertThat(nameProperty.getComments(), empty());
}

@Test
Expand Down Expand Up @@ -162,6 +169,7 @@ private static BeanPropertyDescription getDescription(String name,
private static final class SampleBean {

private String name;
@Comment("Size of this entry (cm)")
private int size;
private long longField; // static "getter" method
private UUID uuid = UUID.randomUUID(); // no setter
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,14 @@

import ch.jalu.configme.beanmapper.ConfigMeMapperException;
import ch.jalu.configme.samples.beanannotations.AnnotatedEntry;
import ch.jalu.configme.utils.TypeInformation;
import org.junit.jupiter.api.Test;

import java.lang.reflect.Method;
import java.util.Collection;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.jupiter.api.Assertions.assertThrows;

Expand Down Expand Up @@ -71,6 +74,22 @@ void shouldHaveAppropriateStringRepresentation() {
+ "'public boolean ch.jalu.configme.samples.beanannotations.AnnotatedEntry.getHasId()'"));
}

@Test
void shouldCreateValuesWithLegacyConstructor() throws NoSuchMethodException {
// given
Method sizeGetter = SampleBean.class.getDeclaredMethod("getSize");
Method sizeSetter = SampleBean.class.getDeclaredMethod("setSize", int.class);

// when
BeanPropertyDescriptionImpl property =
new BeanPropertyDescriptionImpl("name", new TypeInformation(String.class), sizeGetter, sizeSetter);

// then
assertThat(property.getName(), equalTo("name"));
assertThat(property.getTypeInformation(), equalTo(new TypeInformation(String.class)));
assertThat(property.getComments(), empty());
}

private static BeanPropertyDescription getDescriptor(String name, Class<?> clazz) {
return new BeanDescriptionFactoryImpl().collectAllProperties(clazz)
.stream()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.anyDouble;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.BDDMockito.given;
Expand Down Expand Up @@ -53,7 +54,8 @@ void shouldHaveImmutablePropertyList() {
ConfigurationData configData = new ConfigurationDataImpl(properties, Collections.emptyMap());

// when / then
verifyException(() -> configData.getProperties().remove(0), UnsupportedOperationException.class);
assertThrows(UnsupportedOperationException.class,
() -> configData.getProperties().remove(0));
}

@Test
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package ch.jalu.configme.properties.convertresult;

import org.junit.jupiter.api.Test;

import java.util.Arrays;
import java.util.concurrent.TimeUnit;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.nullValue;

/**
* Test for {@link ValueWithComments}.
*/
class ValueWithCommentsTest {

@Test
void shouldUnwrapValue() {
// given
Object object1 = new ValueWithComments("test", Arrays.asList("Explanatory", "comments"));
Object object2 = TimeUnit.SECONDS;

// when / then
assertThat(ValueWithComments.unwrapValue(object1), equalTo("test"));
assertThat(ValueWithComments.unwrapValue(object2), equalTo(TimeUnit.SECONDS));
assertThat(ValueWithComments.unwrapValue(null), nullValue());
}
}
Loading

0 comments on commit 96881d2

Please sign in to comment.