json: increase test cases before enabling sumtype decode in all json libraries (#21958)

This commit is contained in:
Hitalo Souza 2024-07-29 21:36:37 -03:00 committed by GitHub
parent c9c38d5c11
commit 1a17a0716d
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -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"}'
}