|
| 1 | +package com.fasterxml.jackson.databind.ser.dos; |
| 2 | + |
| 3 | +import com.fasterxml.jackson.core.StreamWriteConstraints; |
| 4 | +import com.fasterxml.jackson.databind.BaseMapTest; |
| 5 | +import com.fasterxml.jackson.databind.JsonMappingException; |
| 6 | +import com.fasterxml.jackson.databind.ObjectMapper; |
| 7 | +import com.fasterxml.jackson.databind.exc.InvalidDefinitionException; |
| 8 | +import com.fasterxml.jackson.databind.ser.CyclicTypeSerTest; |
| 9 | + |
| 10 | +import java.util.ArrayList; |
| 11 | +import java.util.List; |
| 12 | + |
| 13 | +/** |
| 14 | + * Simple unit tests to verify that we fail gracefully if you attempt to serialize |
| 15 | + * data that is cyclic (eg a list that contains itself). |
| 16 | + */ |
| 17 | +public class CyclicDataSerTest |
| 18 | + extends BaseMapTest |
| 19 | +{ |
| 20 | + private final ObjectMapper MAPPER = newJsonMapper(); |
| 21 | + |
| 22 | + public void testLinkedAndCyclic() throws Exception { |
| 23 | + CyclicTypeSerTest.Bean bean = new CyclicTypeSerTest.Bean(null, "last"); |
| 24 | + bean.assignNext(bean); |
| 25 | + try { |
| 26 | + writeAndMap(MAPPER, bean); |
| 27 | + fail("expected InvalidDefinitionException"); |
| 28 | + } catch (InvalidDefinitionException idex) { |
| 29 | + assertTrue("InvalidDefinitionException message is as expected?", |
| 30 | + idex.getMessage().startsWith("Direct self-reference leading to cycle")); |
| 31 | + } |
| 32 | + } |
| 33 | + |
| 34 | + public void testListWithSelfReference() throws Exception { |
| 35 | + List<Object> list = new ArrayList<>(); |
| 36 | + list.add(list); |
| 37 | + try { |
| 38 | + writeAndMap(MAPPER, list); |
| 39 | + fail("expected JsonMappingException"); |
| 40 | + } catch (JsonMappingException jmex) { |
| 41 | + String exceptionPrefix = String.format("Document nesting depth (%d) exceeds the maximum allowed", |
| 42 | + StreamWriteConstraints.DEFAULT_MAX_DEPTH + 1); |
| 43 | + assertTrue("JsonMappingException message is as expected?", |
| 44 | + jmex.getMessage().startsWith(exceptionPrefix)); |
| 45 | + } |
| 46 | + } |
| 47 | +} |
0 commit comments