aboutsummaryrefslogtreecommitdiff
path: root/src/test/java/com/fasterxml/jackson/databind/convert/CoerceToBooleanTest.java
blob: f78c14db147d0665dba201ab28af22cbacbdc050 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
package com.fasterxml.jackson.databind.convert;

import java.io.IOException;
import java.util.concurrent.atomic.AtomicBoolean;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;

import com.fasterxml.jackson.databind.BaseMapTest;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectReader;
import com.fasterxml.jackson.databind.cfg.CoercionAction;
import com.fasterxml.jackson.databind.cfg.CoercionInputShape;
import com.fasterxml.jackson.databind.exc.MismatchedInputException;
import com.fasterxml.jackson.databind.type.LogicalType;

public class CoerceToBooleanTest extends BaseMapTest
{
    static class BooleanPOJO {
        public boolean value;
    }

    private final ObjectMapper DEFAULT_MAPPER = sharedMapper();

    private final ObjectMapper LEGACY_NONCOERCING_MAPPER = jsonMapperBuilder()
            .disable(MapperFeature.ALLOW_COERCION_OF_SCALARS)
            .build();

    private final ObjectMapper MAPPER_TO_EMPTY; {
        MAPPER_TO_EMPTY = newJsonMapper();
        MAPPER_TO_EMPTY.coercionConfigFor(LogicalType.Boolean)
            .setCoercion(CoercionInputShape.Integer, CoercionAction.AsEmpty);
    }

    private final ObjectMapper MAPPER_TRY_CONVERT; {
        MAPPER_TRY_CONVERT = newJsonMapper();
        MAPPER_TRY_CONVERT.coercionConfigFor(LogicalType.Boolean)
            .setCoercion(CoercionInputShape.Integer, CoercionAction.TryConvert);
    }

    private final ObjectMapper MAPPER_TO_NULL; {
        MAPPER_TO_NULL = newJsonMapper();
        MAPPER_TO_NULL.coercionConfigFor(LogicalType.Boolean)
            .setCoercion(CoercionInputShape.Integer, CoercionAction.AsNull);
    }

    private final ObjectMapper MAPPER_TO_FAIL; {
        MAPPER_TO_FAIL = newJsonMapper();
        MAPPER_TO_FAIL.coercionConfigFor(LogicalType.Boolean)
            .setCoercion(CoercionInputShape.Integer, CoercionAction.Fail);
    }

    private final static String DOC_WITH_0 = aposToQuotes("{'value':0}");
    private final static String DOC_WITH_1 = aposToQuotes("{'value':1}");

    /*
    /**********************************************************
    /* Unit tests: default, legacy configuration
    /**********************************************************
     */

    public void testToBooleanCoercionSuccessPojo() throws Exception
    {        
        BooleanPOJO p;
        final ObjectReader r = DEFAULT_MAPPER.readerFor(BooleanPOJO.class);

        p = r.readValue(DOC_WITH_0);
        assertEquals(false, p.value);
        p = r.readValue(utf8Bytes(DOC_WITH_0));
        assertEquals(false, p.value);

        p = r.readValue(DOC_WITH_1);
        assertEquals(true, p.value);
        p = r.readValue(utf8Bytes(DOC_WITH_1));
        assertEquals(true, p.value);
    }

    public void testToBooleanCoercionSuccessRoot() throws Exception
    {        
        final ObjectReader br = DEFAULT_MAPPER.readerFor(Boolean.class);

        assertEquals(Boolean.FALSE, br.readValue(" 0"));
        assertEquals(Boolean.FALSE, br.readValue(utf8Bytes(" 0")));
        assertEquals(Boolean.TRUE, br.readValue(" -1"));
        assertEquals(Boolean.TRUE, br.readValue(utf8Bytes(" -1")));

        final ObjectReader atomicR = DEFAULT_MAPPER.readerFor(AtomicBoolean.class);

        AtomicBoolean ab;
        
        ab = atomicR.readValue(" 0");
        ab = atomicR.readValue(utf8Bytes(" 0"));
        assertEquals(false, ab.get());

        ab = atomicR.readValue(" 111");
        assertEquals(true, ab.get());
        ab = atomicR.readValue(utf8Bytes(" 111"));
        assertEquals(true, ab.get());
    }

    public void testToBooleanCoercionFailBytes() throws Exception
    {
        _verifyBooleanCoerceFail(aposToQuotes("{'value':1}"), true, JsonToken.VALUE_NUMBER_INT, "1", BooleanPOJO.class);

        _verifyBooleanCoerceFail("1", true, JsonToken.VALUE_NUMBER_INT, "1", Boolean.TYPE);
        _verifyBooleanCoerceFail("1", true, JsonToken.VALUE_NUMBER_INT, "1", Boolean.class);
    }

    public void testToBooleanCoercionFailChars() throws Exception
    {
        _verifyBooleanCoerceFail(aposToQuotes("{'value':1}"), false, JsonToken.VALUE_NUMBER_INT, "1", BooleanPOJO.class);

        _verifyBooleanCoerceFail("1", false, JsonToken.VALUE_NUMBER_INT, "1", Boolean.TYPE);
        _verifyBooleanCoerceFail("1", false, JsonToken.VALUE_NUMBER_INT, "1", Boolean.class);
    }

    /*
    /**********************************************************
    /* Unit tests: new CoercionConfig, as-null, as-empty, try-coerce
    /**********************************************************
     */

    public void testIntToNullCoercion() throws Exception
    {
        assertNull(MAPPER_TO_NULL.readValue("0", Boolean.class));
        assertNull(MAPPER_TO_NULL.readValue("1", Boolean.class));

        // but due to coercion to `boolean`, can not return null here -- however,
        // goes "1 -> false (no null for primitive) -> Boolean.FALSE
        assertEquals(Boolean.FALSE, MAPPER_TO_NULL.readValue("0", Boolean.TYPE));
        assertEquals(Boolean.FALSE, MAPPER_TO_NULL.readValue("1", Boolean.TYPE));

        // As to AtomicBoolean: that type itself IS nullable since it's of LogicalType.Boolean so
        assertNull(MAPPER_TO_NULL.readValue("0", AtomicBoolean.class));
        assertNull(MAPPER_TO_NULL.readValue("1", AtomicBoolean.class));

        BooleanPOJO p;
        p = MAPPER_TO_NULL.readValue(DOC_WITH_0, BooleanPOJO.class);
        assertFalse(p.value);
        p = MAPPER_TO_NULL.readValue(DOC_WITH_1, BooleanPOJO.class);
        assertFalse(p.value);
    }

    public void testIntToEmptyCoercion() throws Exception
    {
        // "empty" value for Boolean/boolean is False/false

        assertEquals(Boolean.FALSE, MAPPER_TO_EMPTY.readValue("0", Boolean.class));
        assertEquals(Boolean.FALSE, MAPPER_TO_EMPTY.readValue("1", Boolean.class));

        assertEquals(Boolean.FALSE, MAPPER_TO_EMPTY.readValue("0", Boolean.TYPE));
        assertEquals(Boolean.FALSE, MAPPER_TO_EMPTY.readValue("1", Boolean.TYPE));

        AtomicBoolean ab;
        ab = MAPPER_TO_EMPTY.readValue("0", AtomicBoolean.class);
        assertFalse(ab.get());
        ab = MAPPER_TO_EMPTY.readValue("1", AtomicBoolean.class);
        assertFalse(ab.get());

        BooleanPOJO p;
        p = MAPPER_TO_EMPTY.readValue(DOC_WITH_0, BooleanPOJO.class);
        assertFalse(p.value);
        p = MAPPER_TO_EMPTY.readValue(DOC_WITH_1, BooleanPOJO.class);
        assertFalse(p.value);
    }
        
    public void testIntToTryCoercion() throws Exception
    {
        // And "TryCoerce" should do what would be typically expected

        assertEquals(Boolean.FALSE, MAPPER_TRY_CONVERT.readValue("0", Boolean.class));
        assertEquals(Boolean.TRUE, MAPPER_TRY_CONVERT.readValue("1", Boolean.class));

        assertEquals(Boolean.FALSE, MAPPER_TRY_CONVERT.readValue("0", Boolean.TYPE));
        assertEquals(Boolean.TRUE, MAPPER_TRY_CONVERT.readValue("1", Boolean.TYPE));

        AtomicBoolean ab;
        ab = MAPPER_TRY_CONVERT.readValue("0", AtomicBoolean.class);
        assertFalse(ab.get());
        ab = MAPPER_TRY_CONVERT.readValue("1", AtomicBoolean.class);
        assertTrue(ab.get());

        BooleanPOJO p;
        p = MAPPER_TRY_CONVERT.readValue(DOC_WITH_0, BooleanPOJO.class);
        assertFalse(p.value);
        p = MAPPER_TRY_CONVERT.readValue(DOC_WITH_1, BooleanPOJO.class);
        assertTrue(p.value);
    }

    /*
    /**********************************************************
    /* Unit tests: new CoercionConfig, failing
    /**********************************************************
     */

    public void testFailFromInteger() throws Exception
    {
        _verifyFailFromInteger(MAPPER_TO_FAIL, BooleanPOJO.class, DOC_WITH_0, Boolean.TYPE);
        _verifyFailFromInteger(MAPPER_TO_FAIL, BooleanPOJO.class, DOC_WITH_1, Boolean.TYPE);

        _verifyFailFromInteger(MAPPER_TO_FAIL, Boolean.class, "0");
        _verifyFailFromInteger(MAPPER_TO_FAIL, Boolean.class, "42");

        _verifyFailFromInteger(MAPPER_TO_FAIL, Boolean.TYPE, "0");
        _verifyFailFromInteger(MAPPER_TO_FAIL, Boolean.TYPE, "999");

        _verifyFailFromInteger(MAPPER_TO_FAIL, AtomicBoolean.class, "0");
        _verifyFailFromInteger(MAPPER_TO_FAIL, AtomicBoolean.class, "-123");
    }

    /*
    /**********************************************************
    /* Helper methods
    /**********************************************************
     */

    private void _verifyBooleanCoerceFail(String doc, boolean useBytes,
            JsonToken tokenType, String tokenValue, Class<?> targetType) throws IOException
    {
        // Test failure for root value: for both byte- and char-backed sources.

        // [databind#2635]: important, need to use `readValue()` that takes content and NOT
        // JsonParser, as this forces closing of underlying parser and exposes more issues.

        final ObjectReader r = LEGACY_NONCOERCING_MAPPER.readerFor(targetType);
        try {
            if (useBytes) {
                r.readValue(utf8Bytes(doc));
            } else {
                r.readValue(doc);
            }
            fail("Should not have allowed coercion");
        } catch (MismatchedInputException e) {
            _verifyBooleanCoerceFailReason(e, tokenType, tokenValue);
        }
    }

    @SuppressWarnings("resource")
    private void _verifyBooleanCoerceFailReason(MismatchedInputException e,
            JsonToken tokenType, String tokenValue) throws IOException
    {
        verifyException(e, "Cannot coerce ");
        verifyException(e, " to `");

        JsonParser p = (JsonParser) e.getProcessor();

        assertToken(tokenType, p.currentToken());

        final String text = p.getText();
        if (!tokenValue.equals(text)) {
            String textDesc = (text == null) ? "NULL" : quote(text);
            fail("Token text ("+textDesc+") via parser of type "+p.getClass().getName()
                    +" not as expected ("+quote(tokenValue)+")");
        }
    }

    private void _verifyFailFromInteger(ObjectMapper m, Class<?> targetType, String doc) throws Exception {
        _verifyFailFromInteger(m, targetType, doc, targetType);
    }

    private void _verifyFailFromInteger(ObjectMapper m, Class<?> targetType, String doc,
            Class<?> valueType) throws Exception
    {       
        try {
            m.readerFor(targetType).readValue(doc);
            fail("Should not accept Integer for "+targetType.getName()+" by default");
        } catch (MismatchedInputException e) {
            verifyException(e, "Cannot coerce Integer value");
            verifyException(e, "to `"+valueType.getName()+"`");
        }
    }
}