|
| 1 | +package com.fasterxml.jackson.dataformat.yaml.deser; |
| 2 | + |
| 3 | +import java.io.*; |
| 4 | + |
| 5 | +import com.fasterxml.jackson.core.*; |
| 6 | +import com.fasterxml.jackson.databind.ObjectMapper; |
| 7 | +import com.fasterxml.jackson.dataformat.yaml.ModuleTestBase; |
| 8 | +import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; |
| 9 | + |
| 10 | +public class ParserDupHandlingTest extends ModuleTestBase |
| 11 | +{ |
| 12 | + private final static String YAML_WITH_DUPS = |
| 13 | +"name:\n" |
| 14 | ++" first: Bob\n" |
| 15 | ++" first: Dup\n"; |
| 16 | + |
| 17 | +public void testDupChecksDisabled() throws Exception |
| 18 | + { |
| 19 | +; |
| 20 | + YAMLFactory f = new YAMLFactory(); |
| 21 | + assertFalse(f.isEnabled(JsonParser.Feature.STRICT_DUPLICATE_DETECTION)); |
| 22 | + |
| 23 | + ObjectMapper mapper = new ObjectMapper(f); |
| 24 | + _verifyDupsOk(mapper, YAML_WITH_DUPS, false); |
| 25 | + _verifyDupsOk(mapper, YAML_WITH_DUPS, true); |
| 26 | + } |
| 27 | + |
| 28 | + public void testDupChecksEnabled() throws Exception |
| 29 | + { |
| 30 | + YAMLFactory f = new YAMLFactory(); |
| 31 | + f.enable(JsonParser.Feature.STRICT_DUPLICATE_DETECTION); |
| 32 | + ObjectMapper mapper = new ObjectMapper(f); |
| 33 | + _verifyDupsFail(mapper, YAML_WITH_DUPS, false); |
| 34 | + _verifyDupsFail(mapper, YAML_WITH_DUPS, true); |
| 35 | + } |
| 36 | + |
| 37 | + private void _verifyDupsOk(ObjectMapper mapper, String doc, boolean useBytes) throws Exception |
| 38 | + { |
| 39 | + JsonParser p = useBytes ? mapper.getFactory().createParser(new ByteArrayInputStream(doc.getBytes("UTF-8"))) |
| 40 | + : mapper.getFactory().createParser(new StringReader(doc)); |
| 41 | + _stream(p); |
| 42 | + p.close(); |
| 43 | + } |
| 44 | + |
| 45 | + private void _verifyDupsFail(ObjectMapper mapper, String doc, boolean useBytes) throws Exception |
| 46 | + { |
| 47 | + JsonParser p = useBytes ? mapper.getFactory().createParser(new ByteArrayInputStream(doc.getBytes("UTF-8"))) |
| 48 | + : mapper.getFactory().createParser(new StringReader(doc)); |
| 49 | + try { |
| 50 | + _stream(p); |
| 51 | + } catch (JsonProcessingException e) { |
| 52 | + verifyException(e, "Duplicate field 'first'"); |
| 53 | + } |
| 54 | + p.close(); |
| 55 | + } |
| 56 | + |
| 57 | + private void _stream(JsonParser p) throws Exception |
| 58 | + { |
| 59 | + while (p.nextToken() != null) { } |
| 60 | + } |
| 61 | +} |
0 commit comments