Skip to content

Commit fe3bfd1

Browse files
committed
Cover optional case
1 parent 16a9e6f commit fe3bfd1

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed

src/test/java/org/primeframework/mvc/test/BodyToolsTest.java

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717

1818
import java.nio.file.Paths;
1919
import java.util.Map;
20+
import java.util.Optional;
2021

2122
import org.testng.annotations.Test;
2223
import static org.testng.Assert.assertEquals;
@@ -55,6 +56,36 @@ public void processTemplateWithMap_functions() throws Exception {
5556
assertEquals(result, "missing");
5657
}
5758

59+
@Test
60+
public void processTemplateWithMap_optional_variable_unused() throws Exception {
61+
// arrange
62+
DetectionMap values = new DetectionMap();
63+
values.putAll(Map.of("message", "howdy", "othervariable", Optional.of("value")));
64+
65+
// act
66+
String result = BodyTools.processTemplateWithMap(Paths.get("src/test/web/templates/echo.ftl"),
67+
values,
68+
false);
69+
70+
// assert
71+
assertEquals(result, "howdy");
72+
}
73+
74+
@Test
75+
public void processTemplateWithMap_optional_variable_used() throws Exception {
76+
// arrange
77+
DetectionMap values = new DetectionMap();
78+
values.put("message", Optional.of("howdy"));
79+
80+
// act
81+
String result = BodyTools.processTemplateWithMap(Paths.get("src/test/web/templates/echo.ftl"),
82+
values,
83+
false);
84+
85+
// assert
86+
assertEquals(result, "howdy");
87+
}
88+
5889
@Test
5990
public void processTemplateWithMap_unused_variables() throws Exception {
6091
// arrange

src/test/java/org/primeframework/mvc/test/DetectionMap.java

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717

1818
import java.util.HashMap;
1919
import java.util.HashSet;
20+
import java.util.Optional;
2021
import java.util.Set;
2122
import java.util.stream.Collectors;
2223

@@ -50,6 +51,17 @@ public Set<Object> getUnusedVariables(String excludePrefix,
5051
Set<String> excludeKeySet = Set.of(excludeKeys);
5152
return keySet().stream()
5253
.filter(key -> !variablesAccessed.contains(key) && !key.startsWith(excludePrefix) && !excludeKeySet.contains(key))
54+
// optional variables do not have to be used in the template
55+
.filter(key -> !(super.get(key) instanceof Optional<?>))
5356
.collect(Collectors.toSet());
5457
}
58+
59+
@Override
60+
public Object put(String key, Object value) {
61+
// go ahead and evaluate optional values for FreeMarker
62+
if (value instanceof Optional<?> opt && opt.isPresent()) {
63+
value = opt.get();
64+
}
65+
return super.put(key, value);
66+
}
5567
}

0 commit comments

Comments
 (0)