1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.apache.commons.text.lookup;
19
20 import java.util.HashMap;
21 import java.util.Map;
22 import java.util.concurrent.ConcurrentHashMap;
23 import java.util.function.BiFunction;
24
25 import org.apache.commons.lang3.StringUtils;
26 import org.junit.jupiter.api.Assertions;
27 import org.junit.jupiter.api.Test;
28
29
30
31
32 class BiFunctionStringLookupTest {
33
34 private static final String SEPARATOR = ".";
35
36 @SuppressWarnings("unchecked")
37 private final BiFunction<String, Map<String, Object>, Object> nestedMapBiFunction = (k, m) -> {
38 final String keyCandidate = StringUtils.substringBefore(k, SEPARATOR);
39 if (keyCandidate.isEmpty()) {
40 return m.get(k);
41 }
42 final Object value = m.get(keyCandidate);
43 if (value instanceof Map) {
44 return this.nestedMapBiFunction.apply(StringUtils.substringAfter(k, SEPARATOR),
45 (Map<String, Object>) value);
46 }
47 return value;
48 };
49
50 @Test
51 void testBiFunctionForNestedMap() {
52
53 final String subSubKey = "subsubkeyMap";
54 final String subSubValue = "subsubvalue";
55 final Map<String, String> subSubMap = new HashMap<>();
56 subSubMap.put(subSubKey, subSubValue);
57
58 final String subKey = "subkey";
59 final String subKeyMap = "subkeyMap";
60 final String subValue = "subvalue";
61 final Map<String, Object> rootSubMap = new HashMap<>();
62 rootSubMap.put(subKey, subValue);
63 rootSubMap.put(subKeyMap, subSubMap);
64
65 final String rootKey = "keyMap";
66 final String rootKey2 = "key2";
67 final String rootValue2 = "value2";
68 final Map<String, Object> rootMap = new HashMap<>();
69 rootMap.put(rootKey, rootSubMap);
70 rootMap.put(rootKey2, rootValue2);
71
72 final BiStringLookup<Map<String, Object>> stringLookup = StringLookupFactory.INSTANCE
73 .biFunctionStringLookup(nestedMapBiFunction);
74 Assertions.assertEquals(rootValue2, stringLookup.lookup(rootKey2, rootMap));
75 Assertions.assertEquals(subValue, stringLookup.lookup(rootKey + SEPARATOR + subKey, rootMap));
76 Assertions.assertEquals(subSubValue,
77 stringLookup.lookup(rootKey + SEPARATOR + subKeyMap + SEPARATOR + subSubKey, rootMap));
78 }
79
80 @Test
81 void testConcurrentHashMapNull() {
82 Assertions.assertNull(BiFunctionStringLookup.on(new ConcurrentHashMap<>()).apply(null));
83 }
84
85 @Test
86 void testHashMapNull() {
87 Assertions.assertNull(BiFunctionStringLookup.on(new HashMap<>()).apply(null));
88 }
89
90 @Test
91 void testNullBiFunction() {
92 Assertions.assertNull(BiFunctionStringLookup.on((BiFunction<String, Object, Object>) null).apply(null));
93 }
94
95 @Test
96 void testOne() {
97 final String key = "key";
98 final String value = "value";
99 final Map<String, String> map = new HashMap<>();
100 map.put(key, value);
101 Assertions.assertEquals(value, FunctionStringLookup.on(map).apply(key));
102 }
103
104 @Test
105 void testToString() {
106
107 Assertions.assertFalse(BiFunctionStringLookup.on(new HashMap<>()).toString().isEmpty());
108 }
109
110 }