|
| 1 | +package tools.jackson.dataformat.yaml.tofix; |
| 2 | + |
| 3 | +import org.junit.jupiter.api.Test; |
| 4 | + |
| 5 | +import com.fasterxml.jackson.annotation.JsonCreator; |
| 6 | +import com.fasterxml.jackson.annotation.JsonIdentityInfo; |
| 7 | +import com.fasterxml.jackson.annotation.ObjectIdGenerators; |
| 8 | +import tools.jackson.databind.ObjectMapper; |
| 9 | +import tools.jackson.dataformat.yaml.ModuleTestBase; |
| 10 | +import tools.jackson.dataformat.yaml.testutil.failure.JacksonTestFailureExpected; |
| 11 | + |
| 12 | +import static org.junit.jupiter.api.Assertions.assertEquals; |
| 13 | +import static org.junit.jupiter.api.Assertions.assertNotNull; |
| 14 | +import static org.junit.jupiter.api.Assertions.assertSame; |
| 15 | + |
| 16 | +// [dataformats-text#296]: YAML Anchor and alias fails with ObjectIdGenerators.None |
| 17 | +public class ObjectIdNone296Test extends ModuleTestBase |
| 18 | +{ |
| 19 | + private final ObjectMapper MAPPER = newObjectMapper(); |
| 20 | + |
| 21 | + @JacksonTestFailureExpected |
| 22 | + @Test |
| 23 | + public void testObjectIdUsingNativeAnchorsWithNoneGenerator() throws Exception |
| 24 | + { |
| 25 | + // YAML content with anchor (&foo1) and alias (*foo1) |
| 26 | + final String YAML_CONTENT = |
| 27 | + "foo: &foo1\n" + |
| 28 | + " value: bar\n" + |
| 29 | + "boo: *foo1\n"; |
| 30 | + |
| 31 | + // This should work: YAML anchors/aliases should be recognized natively |
| 32 | + // when using ObjectIdGenerators.None, but currently fails with: |
| 33 | + // "Cannot construct instance of StringHolder... no String-argument |
| 34 | + // constructor/factory method to deserialize from String value ('foo1')" |
| 35 | + ScratchModel result = MAPPER.readValue(YAML_CONTENT, ScratchModel.class); |
| 36 | + |
| 37 | + assertNotNull(result); |
| 38 | + assertNotNull(result.foo); |
| 39 | + assertEquals("bar", result.foo.value); |
| 40 | + assertNotNull(result.boo); |
| 41 | + assertEquals("bar", result.boo.value); |
| 42 | + // The key assertion: both fields should point to the same object instance |
| 43 | + assertSame(result.foo, result.boo); |
| 44 | + } |
| 45 | + |
| 46 | + static class ScratchModel { |
| 47 | + public StringHolder foo; |
| 48 | + public StringHolder boo; |
| 49 | + } |
| 50 | + |
| 51 | + // Using ObjectIdGenerators.None should allow YAML's native anchor/alias to work |
| 52 | + @JsonIdentityInfo(generator = ObjectIdGenerators.None.class) |
| 53 | + static class StringHolder { |
| 54 | + public String value; |
| 55 | + |
| 56 | + protected StringHolder() { } |
| 57 | + |
| 58 | + @JsonCreator(mode = JsonCreator.Mode.DELEGATING) |
| 59 | + public StringHolder(String v) { value = v; } |
| 60 | + |
| 61 | + @Override |
| 62 | + public String toString() { |
| 63 | + return "StringHolder{" + value +" }"; |
| 64 | + } |
| 65 | + } |
| 66 | +} |
0 commit comments