forked from FasterXML/jackson-databind
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSimpleModuleTest.java
More file actions
566 lines (488 loc) · 19.7 KB
/
SimpleModuleTest.java
File metadata and controls
566 lines (488 loc) · 19.7 KB
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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
package tools.jackson.databind.module;
import java.util.*;
import org.junit.jupiter.api.Test;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import tools.jackson.core.*;
import tools.jackson.core.exc.StreamReadException;
import tools.jackson.databind.*;
import tools.jackson.databind.cfg.MapperBuilder;
import tools.jackson.databind.exc.UnrecognizedPropertyException;
import tools.jackson.databind.json.JsonMapper;
import tools.jackson.databind.ser.std.StdScalarSerializer;
import tools.jackson.databind.ser.std.StdSerializer;
import tools.jackson.databind.testutil.DatabindTestUtil;
import static org.junit.jupiter.api.Assertions.*;
@SuppressWarnings("serial")
public class SimpleModuleTest extends DatabindTestUtil
{
/**
* Trivial bean that requires custom serializer and deserializer
*/
final static class CustomBean
{
protected String str;
protected int num;
public CustomBean(String s, int i) {
str = s;
num = i;
}
}
static enum SimpleEnum { A, B; }
// Extend SerializerBase to get access to declared handledType
static class CustomBeanSerializer extends StdSerializer<CustomBean>
{
public CustomBeanSerializer() { super(CustomBean.class); }
@Override
public void serialize(CustomBean value, JsonGenerator g, SerializerProvider provider)
{
// We will write it as a String, with '|' as delimiter
g.writeString(value.str + "|" + value.num);
}
}
static class CustomBeanDeserializer extends ValueDeserializer<CustomBean>
{
@Override
public CustomBean deserialize(JsonParser p, DeserializationContext ctxt)
{
String text = p.getText();
int ix = text.indexOf('|');
if (ix < 0) {
throw new StreamReadException(p, "Failed to parse String value of \""+text+"\"");
}
String str = text.substring(0, ix);
int num = Integer.parseInt(text.substring(ix+1));
return new CustomBean(str, num);
}
}
static class SimpleEnumSerializer extends StdSerializer<SimpleEnum>
{
public SimpleEnumSerializer() { super(SimpleEnum.class); }
@Override
public void serialize(SimpleEnum value, JsonGenerator g, SerializerProvider provider)
{
g.writeString(value.name().toLowerCase());
}
}
static class SimpleEnumDeserializer extends ValueDeserializer<SimpleEnum>
{
@Override
public SimpleEnum deserialize(JsonParser p, DeserializationContext ctxt)
{
return SimpleEnum.valueOf(p.getText().toUpperCase());
}
}
interface Base {
public String getText();
}
static class Impl1 implements Base {
@Override
public String getText() { return "1"; }
}
static class Impl2 extends Impl1 {
@Override
public String getText() { return "2"; }
}
static class BaseSerializer extends StdScalarSerializer<Base>
{
public BaseSerializer() { super(Base.class); }
@Override
public void serialize(Base value, JsonGenerator g, SerializerProvider provider) {
g.writeString("Base:"+value.getText());
}
}
static class MixableBean {
public int a = 1;
public int b = 2;
public int c = 3;
}
@JsonPropertyOrder({"c", "a", "b"})
static class MixInForOrder { }
protected static class MySimpleSerializers extends SimpleSerializers { }
protected static class MySimpleDeserializers extends SimpleDeserializers { }
/**
* Test module which uses custom 'serializers' and 'deserializers' container; used
* to trigger type problems.
*/
protected static class MySimpleModule extends SimpleModule
{
public MySimpleModule(String name, Version version) {
super(name, version);
_deserializers = new MySimpleDeserializers();
_serializers = new MySimpleSerializers();
}
}
/**
* Test module that is different from MySimpleModule. Used to test registration
* of multiple modules.
*/
protected static class AnotherSimpleModule extends SimpleModule
{
public AnotherSimpleModule(String name, Version version) {
super(name, version);
}
}
static class TestModule626 extends SimpleModule {
final Class<?> mixin, target;
public TestModule626(Class<?> t, Class<?> m) {
super("Test");
target = t;
mixin = m;
}
@Override
public void setupModule(SetupContext context) {
context.setMixIn(target, mixin);
}
}
// [databind#3787]
static class Test3787Bean {
public String value;
}
static class Deserializer3787A extends ValueDeserializer<Test3787Bean> {
@Override
public Test3787Bean deserialize(JsonParser p, DeserializationContext ctxt) {
Test3787Bean simpleTestBean = new Test3787Bean();
simpleTestBean.value = "I am A";
return simpleTestBean;
}
}
static class Deserializer3787B extends ValueDeserializer<Test3787Bean> {
@Override
public Test3787Bean deserialize(JsonParser p, DeserializationContext ctxt) {
Test3787Bean simpleTestBean = new Test3787Bean();
simpleTestBean.value = "I am B";
return simpleTestBean;
}
}
static class Serializer3787A extends ValueSerializer<Test3787Bean> {
@Override
public void serialize(Test3787Bean value, JsonGenerator gen, SerializerProvider serializers) {
gen.writeRaw("a-result");
}
}
static class Serializer3787B extends ValueSerializer<Test3787Bean> {
@Override
public void serialize(Test3787Bean value, JsonGenerator gen, SerializerProvider serializers) {
gen.writeRaw("b-result");
}
}
/*
/**********************************************************************
/* Unit tests; first, verifying need for custom handlers
/**********************************************************************
*/
/**
* Basic test to ensure we do not have functioning default
* serializers for custom types used in tests.
*/
@Test
public void testWithoutModule()
{
ObjectMapper mapper = jsonMapperBuilder().enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES).build();
// first: serialization failure:
try {
mapper.writeValueAsString(new CustomBean("foo", 3));
fail("Should have caused an exception");
} catch (JacksonException e) {
verifyException(e, "No serializer found");
}
// then deserialization
try {
mapper.readValue("{\"str\":\"ab\",\"num\":2}", CustomBean.class);
fail("Should have caused an exception");
} catch (UnrecognizedPropertyException e) {
// 20-Sep-2017, tatu: Jackson 2.x had different exception; 3.x finds implicits too
verifyException(e, "Unrecognized property \"str\"");
/*
verifyException(e, "Cannot construct");
verifyException(e, "no creators");
*/
}
}
/*
/**********************************************************************
/* Unit tests; simple serializers
/**********************************************************************
*/
@Test
public void testSimpleBeanSerializer() throws Exception
{
SimpleModule mod = new SimpleModule("test", Version.unknownVersion());
mod.addSerializer(new CustomBeanSerializer());
ObjectMapper mapper = JsonMapper.builder()
.addModule(mod)
.build();
assertEquals(q("abcde|5"), mapper.writeValueAsString(new CustomBean("abcde", 5)));
}
@Test
public void testSimpleEnumSerializer() throws Exception
{
SimpleModule mod = new SimpleModule("test", Version.unknownVersion());
mod.addSerializer(new SimpleEnumSerializer());
// for fun, call "multi-module" registration
ObjectMapper mapper = JsonMapper.builder()
.addModules(mod)
.build();
assertEquals(q("b"), mapper.writeValueAsString(SimpleEnum.B));
}
@Test
public void testSimpleInterfaceSerializer() throws Exception
{
SimpleModule mod = new SimpleModule("test", Version.unknownVersion());
mod.addSerializer(new BaseSerializer());
// and another variant here too
List<SimpleModule> mods = Arrays.asList(mod);
ObjectMapper mapper = JsonMapper.builder()
.addModules(mods)
.build();
assertEquals(q("Base:1"), mapper.writeValueAsString(new Impl1()));
assertEquals(q("Base:2"), mapper.writeValueAsString(new Impl2()));
}
/*
/**********************************************************************
/* Unit tests; simple deserializers
/**********************************************************************
*/
@Test
public void testSimpleBeanDeserializer() throws Exception
{
SimpleModule mod = new SimpleModule("test", Version.unknownVersion());
mod.addDeserializer(CustomBean.class, new CustomBeanDeserializer());
ObjectMapper mapper = jsonMapperBuilder()
.addModule(mod)
.build();
CustomBean bean = mapper.readValue(q("xyz|3"), CustomBean.class);
assertEquals("xyz", bean.str);
assertEquals(3, bean.num);
}
@Test
public void testSimpleEnumDeserializer() throws Exception
{
SimpleModule mod = new SimpleModule("test", Version.unknownVersion());
mod.addDeserializer(SimpleEnum.class, new SimpleEnumDeserializer());
ObjectMapper mapper = jsonMapperBuilder()
.addModule(mod)
.build();
SimpleEnum result = mapper.readValue(q("a"), SimpleEnum.class);
assertSame(SimpleEnum.A, result);
}
@Test
public void testMultipleModules() throws Exception
{
MySimpleModule mod1 = new MySimpleModule("test1", Version.unknownVersion());
SimpleModule mod2 = new SimpleModule("test2", Version.unknownVersion());
mod1.addSerializer(SimpleEnum.class, new SimpleEnumSerializer());
mod1.addDeserializer(CustomBean.class, new CustomBeanDeserializer());
Map<Class<?>,ValueDeserializer<?>> desers = new HashMap<>();
desers.put(SimpleEnum.class, new SimpleEnumDeserializer());
mod2.setDeserializers(new SimpleDeserializers(desers));
mod2.addSerializer(CustomBean.class, new CustomBeanSerializer());
ObjectMapper mapper = jsonMapperBuilder()
.addModule(mod1)
.addModule(mod2)
.build();
assertEquals(q("b"), mapper.writeValueAsString(SimpleEnum.B));
SimpleEnum result = mapper.readValue(q("a"), SimpleEnum.class);
assertSame(SimpleEnum.A, result);
// also let's try it with different order of registration, just in case
mapper = jsonMapperBuilder()
.addModule(mod2)
.addModule(mod1)
.build();
assertEquals(q("b"), mapper.writeValueAsString(SimpleEnum.B));
result = mapper.readValue(q("a"), SimpleEnum.class);
assertSame(SimpleEnum.A, result);
}
@Test
public void testGetRegisteredModules()
{
MySimpleModule mod1 = new MySimpleModule("test1", Version.unknownVersion());
AnotherSimpleModule mod2 = new AnotherSimpleModule("test2", Version.unknownVersion());
ObjectMapper mapper = jsonMapperBuilder()
.addModule(mod1)
.addModule(mod2)
.build();
List<JacksonModule> mods = new ArrayList<>(mapper.getRegisteredModules());
assertEquals(2, mods.size());
// Should retain ordering even if not mandated
assertEquals("test1", mods.get(0).getModuleName());
assertEquals("test2", mods.get(1).getModuleName());
// 01-Jul-2019, [databind#2374]: verify empty list is fine
mapper = newJsonMapper();
assertEquals(0, mapper.getRegisteredModules().size());
// 07-Jun-2021, tatu [databind#3110] Casual SimpleModules ARE returned
// too!
mapper = JsonMapper.builder()
.addModule(new SimpleModule())
.build();
assertEquals(1, mapper.getRegisteredModules().size());
Object id = mapper.getRegisteredModules().iterator().next().getRegistrationId();
// Id type won't be String but...
if (!id.toString().startsWith("SimpleModule-")) {
fail("SimpleModule registration id should start with 'SimpleModule-', does not: ["
+id+"]");
}
// And named ones retain their name
final JacksonModule vsm = new SimpleModule("VerySpecialModule");
mapper = JsonMapper.builder()
.addModule(vsm)
.build();
Collection<JacksonModule> reg = mapper.getRegisteredModules();
assertEquals(1, reg.size());
assertSame(vsm, reg.iterator().next());
}
// More [databind#3110] testing
@Test
public void testMultipleSimpleModules()
{
final SimpleModule mod1 = new SimpleModule();
final SimpleModule mod2 = new SimpleModule();
ObjectMapper mapper = JsonMapper.builder()
.addModule(mod1)
.addModule(mod2)
.build();
assertEquals(2, mapper.getRegisteredModules().size());
// Still avoid actual duplicates
mapper = JsonMapper.builder()
.addModule(mod1)
.addModule(mod1)
.build();
assertEquals(1, mapper.getRegisteredModules().size());
// Same for (anonymous) sub-classes
final SimpleModule subMod1 = new SimpleModule() { };
final SimpleModule subMod2 = new SimpleModule() { };
mapper = JsonMapper.builder()
.addModule(subMod1)
.addModule(subMod2)
.build();
assertEquals(2, mapper.getRegisteredModules().size());
mapper = JsonMapper.builder()
.addModule(subMod1)
.addModule(subMod1)
.build();
assertEquals(1, mapper.getRegisteredModules().size());
}
/*
/**********************************************************************
/* Unit tests; other
/**********************************************************************
*/
@Test
public void testMixIns() throws Exception
{
SimpleModule module = new SimpleModule("test", Version.unknownVersion());
module.setMixInAnnotation(MixableBean.class, MixInForOrder.class);
ObjectMapper mapper = jsonMapperBuilder()
.addModule(module)
.build();
Map<String,Object> props = writeAndMap(mapper, new MixableBean());
assertEquals(3, props.size());
assertEquals(Integer.valueOf(3), props.get("c"));
assertEquals(Integer.valueOf(1), props.get("a"));
assertEquals(Integer.valueOf(2), props.get("b"));
}
@Test
public void testAccessToMapper() throws Exception
{
final JacksonModule module = new JacksonModule()
{
@Override
public String getModuleName() { return "x"; }
@Override
public Version version() { return Version.unknownVersion(); }
@Override
public void setupModule(SetupContext context)
{
Object c = context.getOwner();
if (!(c instanceof MapperBuilder<?,?>)) {
throw new RuntimeException("Owner should be a `MapperBuilder` but is not; is: "+c);
}
}
};
ObjectMapper mapper = jsonMapperBuilder()
.addModule(module)
.build();
assertNotNull(mapper);
}
@Test
public void testAutoDiscovery() throws Exception
{
List<?> mods = MapperBuilder.findModules();
assertEquals(0, mods.size());
}
@Test
public void testAddSerializerTwiceThenOnlyLatestIsKept() throws Exception {
SimpleModule module = new SimpleModule()
.addSerializer(Test3787Bean.class, new Serializer3787A())
.addSerializer(Test3787Bean.class, new Serializer3787B());
ObjectMapper objectMapper = JsonMapper.builder()
.addModule(module)
.build();
assertEquals("b-result", objectMapper.writeValueAsString(new Test3787Bean()));
}
@Test
public void testAddModuleWithSerializerTwiceThenOnlyLatestIsKept() throws Exception {
SimpleModule firstModule = new SimpleModule()
.addSerializer(Test3787Bean.class, new Serializer3787A());
SimpleModule secondModule = new SimpleModule()
.addSerializer(Test3787Bean.class, new Serializer3787B());
ObjectMapper objectMapper = JsonMapper.builder()
.addModule(firstModule)
.addModule(secondModule)
.build();
Test3787Bean obj = new Test3787Bean();
String result = objectMapper.writeValueAsString(obj);
assertEquals("b-result", result);
}
@Test
public void testAddModuleWithSerializerTwiceThenOnlyLatestIsKept_reverseOrder() throws Exception {
SimpleModule firstModule = new SimpleModule()
.addSerializer(Test3787Bean.class, new Serializer3787A());
SimpleModule secondModule = new SimpleModule()
.addSerializer(Test3787Bean.class, new Serializer3787B());
ObjectMapper objectMapper = JsonMapper.builder()
.addModule(secondModule)
.addModule(firstModule)
.build();
assertEquals("a-result", objectMapper.writeValueAsString(new Test3787Bean()));
}
@Test
public void testAddDeserializerTwiceThenOnlyLatestIsKept() throws Exception {
SimpleModule module = new SimpleModule();
module.addDeserializer(Test3787Bean.class, new Deserializer3787A())
.addDeserializer(Test3787Bean.class, new Deserializer3787B());
ObjectMapper objectMapper = JsonMapper.builder()
.addModule(module)
.build();
Test3787Bean result = objectMapper.readValue(
"{\"value\" : \"I am C\"}", Test3787Bean.class);
assertEquals("I am B", result.value);
}
@Test
public void testAddModuleWithDeserializerTwiceThenOnlyLatestIsKept() throws Exception {
SimpleModule firstModule = new SimpleModule()
.addDeserializer(Test3787Bean.class, new Deserializer3787A());
SimpleModule secondModule = new SimpleModule()
.addDeserializer(Test3787Bean.class, new Deserializer3787B());
ObjectMapper objectMapper = JsonMapper.builder()
.addModule(firstModule)
.addModule(secondModule)
.build();
Test3787Bean result = objectMapper.readValue(
"{\"value\" : \"I am C\"}", Test3787Bean.class);
assertEquals("I am B", result.value);
}
@Test
public void testAddModuleWithDeserializerTwiceThenOnlyLatestIsKept_reverseOrder() throws Exception {
SimpleModule firstModule = new SimpleModule()
.addDeserializer(Test3787Bean.class, new Deserializer3787A());
SimpleModule secondModule = new SimpleModule()
.addDeserializer(Test3787Bean.class, new Deserializer3787B());
ObjectMapper objectMapper = JsonMapper.builder()
.addModule(secondModule)
.addModule(firstModule)
.build();
Test3787Bean result = objectMapper.readValue(
"{\"value\" : \"I am C\"}", Test3787Bean.class);
assertEquals("I am A", result.value);
}
}