Skip to content

Commit daa2ba3

Browse files
authored
Fixed flaky test UnsignedLongFieldBlockLoaderTests (elastic#141559)
* Fixed flaky test UnsignedLongFieldBlockLoaderTests * Addressed feedback
1 parent be794c6 commit daa2ba3

File tree

1 file changed

+44
-12
lines changed

1 file changed

+44
-12
lines changed

test/framework/src/main/java/org/elasticsearch/index/mapper/NumberFieldBlockLoaderTestCase.java

Lines changed: 44 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111

1212
import org.elasticsearch.datageneration.FieldType;
1313

14+
import java.math.BigDecimal;
1415
import java.util.List;
1516
import java.util.Map;
1617
import java.util.Objects;
@@ -48,21 +49,52 @@ protected Object expected(Map<String, Object> fieldMapping, Object value, TestCo
4849
return maybeFoldList(resultList);
4950
}
5051

51-
@SuppressWarnings("unchecked")
5252
private T convert(Object value, T nullValue, Map<String, Object> fieldMapping) {
53-
if (value == null) {
54-
return nullValue;
55-
}
56-
// String coercion is true by default
57-
if (value instanceof String s && s.isEmpty()) {
58-
return nullValue;
59-
}
60-
if (value instanceof Number n) {
61-
return convert(n, fieldMapping);
53+
switch (value) {
54+
case null -> {
55+
return nullValue;
56+
}
57+
58+
// String coercion is true by default
59+
case String s -> {
60+
if (s.isEmpty()) {
61+
return nullValue;
62+
}
63+
// Attempt to parse the string as a number. If that fails, the string is malformed, so return null
64+
Number parsed = tryParseString(s);
65+
if (parsed != null) {
66+
return convert(parsed, fieldMapping);
67+
}
68+
return null;
69+
}
70+
71+
case Number n -> {
72+
return convert(n, fieldMapping);
73+
}
74+
75+
default -> {
76+
// Malformed values are excluded
77+
return null;
78+
}
6279
}
80+
}
6381

64-
// Malformed values are excluded
65-
return null;
82+
/**
83+
* Tries to parse a string as a number, matching the behavior of UnsignedLongFieldMapper.parseUnsignedLong().
84+
* Returns null if the string cannot be parsed as a valid number.
85+
*/
86+
private Number tryParseString(String s) {
87+
try {
88+
return Long.parseUnsignedLong(s);
89+
} catch (NumberFormatException ex1) {
90+
try {
91+
BigDecimal bd = new BigDecimal(s);
92+
return bd.toBigIntegerExact();
93+
} catch (NumberFormatException | ArithmeticException ex2) {
94+
// not a valid number
95+
return null;
96+
}
97+
}
6698
}
6799

68100
protected abstract T convert(Number value, Map<String, Object> fieldMapping);

0 commit comments

Comments
 (0)