summaryrefslogtreecommitdiff
path: root/gson
diff options
context:
space:
mode:
authorLinnea Gräf <nea@nea.moe>2024-11-14 21:10:13 +0100
committerLinnea Gräf <nea@nea.moe>2024-11-14 21:10:13 +0100
commit742a354000241d25406ffbe9a38f9eb2e6d0e128 (patch)
tree55009350bddd9c4f315ba12f19eb15b627cb1114 /gson
parent4289518c93cf8bf04f88125ef3deea3af8978607 (diff)
downloadprofunctor-codecs-java-742a354000241d25406ffbe9a38f9eb2e6d0e128.tar.gz
profunctor-codecs-java-742a354000241d25406ffbe9a38f9eb2e6d0e128.tar.bz2
profunctor-codecs-java-742a354000241d25406ffbe9a38f9eb2e6d0e128.zip
Add dispatch codecs
Diffstat (limited to 'gson')
-rw-r--r--gson/src/test/java/moe/nea/jcp/gson/test/TestBasic.java38
1 files changed, 35 insertions, 3 deletions
diff --git a/gson/src/test/java/moe/nea/jcp/gson/test/TestBasic.java b/gson/src/test/java/moe/nea/jcp/gson/test/TestBasic.java
index 70c4345..628518c 100644
--- a/gson/src/test/java/moe/nea/jcp/gson/test/TestBasic.java
+++ b/gson/src/test/java/moe/nea/jcp/gson/test/TestBasic.java
@@ -91,10 +91,17 @@ public class TestBasic {
new UnexpectedJsonElement("number", mkPrim("1")));
}
+ sealed interface Parent permits OtherTestObject, TestObject {
+ }
+
+ record OtherTestObject(
+ String test
+ ) implements Parent {}
+
record TestObject(
String foo,
int bar
- ) {}
+ ) implements Parent {}
@Test
@@ -109,7 +116,7 @@ public class TestBasic {
codecs.STRING.fieldOf("foo").withGetter(TestObject::foo),
codecs.INTEGER.fieldOf("bar").withGetter(TestObject::bar),
TestObject::new
- );
+ ).codec();
assertSuccess(decode(codec, mkJsonObject("foo", "fooValue", "bar", -10)),
new TestObject("fooValue", -10));
assertFail(decode(codec, mkJsonObject("foo", "fooValue")),
@@ -124,7 +131,7 @@ public class TestBasic {
codecs.STRING.fieldOf("foo").withGetter(TestObject::foo),
codecs.INTEGER.fieldOf("foo").withGetter(TestObject::bar),
TestObject::new
- );
+ ).codec();
// TODO: add test for decoding with duplicate keys warning (esp. optional fields)
assertFail(codec.encode(new TestObject("", 0), GsonOperations.INSTANCE),
new DuplicateJsonKey("foo"));
@@ -138,5 +145,30 @@ public class TestBasic {
assertFail(decode(codec, mkJsonArray("foo", mkJsonObject("hello", "bar"))),
new AtIndex(0, new UnexpectedJsonElement("object", mkPrim("foo"))));
}
+
+ @Test
+ void testDispatched() {
+ var testObjectCodec = RecordJoiners.join(
+ codecs.STRING.fieldOf("foo").withGetter(TestObject::foo),
+ codecs.INTEGER.fieldOf("bar").withGetter(TestObject::bar),
+ TestObject::new
+ );
+ var otherObjectCodec = RecordJoiners.join(
+ codecs.STRING.fieldOf("test").withGetter(OtherTestObject::test),
+ OtherTestObject::new
+ );
+ codecs.STRING.fieldOf("type")
+ .<Parent>dispatch(
+ obj -> switch (obj) {
+ case OtherTestObject ignored -> "other";
+ case TestObject ignored -> "normal";
+ },
+ key -> switch (key) {
+ case "other" -> otherObjectCodec;
+ case "normal" -> testObjectCodec;
+ default -> throw new AssertionError("Unknown thing");
+ }
+ );
+ }
}