From 1a17a0716dd8b83cc65fd14209ef63d99b00f9e1 Mon Sep 17 00:00:00 2001 From: Hitalo Souza Date: Mon, 29 Jul 2024 21:36:37 -0300 Subject: [PATCH] json: increase test cases before enabling sumtype decode in all json libraries (#21958) --- vlib/json/json_sumtype_test.v | 50 +++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) diff --git a/vlib/json/json_sumtype_test.v b/vlib/json/json_sumtype_test.v index 979abf059b..5ead3605d0 100644 --- a/vlib/json/json_sumtype_test.v +++ b/vlib/json/json_sumtype_test.v @@ -14,6 +14,16 @@ struct Price { net f64 } +type Animal = Cat | Dog + +struct Cat { + cat_name string +} + +struct Dog { + dog_name string +} + fn test_main() { data := '{"attributes": {"price": [{"net": 1, "_type": "Price"}, {"net": 2, "_type": "Price"}]}}' entity := json.decode(ShopResponseData, data) or { panic(err) } @@ -55,3 +65,43 @@ fn test_main() { } } } + +fn test_sum_types() { + data1 := json.encode(Animal(Dog{ + dog_name: 'Caramelo' + })) + assert data1 == '{"dog_name":"Caramelo","_type":"Dog"}' + + s := '{"_type":"Cat","cat_name":"Whiskers"}' + animal := json.decode(Animal, s) or { + println(err) + assert false + return + } + + assert animal is Cat + if animal is Cat { + assert animal.cat_name == 'Whiskers' + } else { + assert false, 'Wrong sumtype decode. In this case animal is a Cat' + } + + s2 := '[{"_type":"Cat","cat_name":"Whiskers"}, {"_type":"Dog","dog_name":"Goofie"}]' + + animals := json.decode([]Animal, s2) or { + println(err) + assert false + return + } + + assert animals.len == 2 + assert animals[0] is Cat + assert animals[1] is Dog + cat := animals[0] as Cat + dog := animals[1] as Dog + assert cat.cat_name == 'Whiskers' + assert dog.dog_name == 'Goofie' + + j := json.encode(animals[0]) + assert j == '{"cat_name":"Whiskers","_type":"Cat"}' +}