usage/JSON_SafeTest.bend
qasim-bend-kit@0.1.0.2 · 43 lines · 7 definitions
1import Base
2import qasim-bend-kit@0.1.0.2/libs/JSON.bend as Json
3
4def check(ok: Bool, label: String) -> IO(Unit):
5 match ok:
6 case True{}:
7 IO.pure(Unit, Unit{})
8 case False{}:
9 IO.die(Unit, 1, "JSON test failed: " ++ label)
10
11def valid_reparse(result: Result<&1, &1, Json.Error, Json.Value>, value: Json.Value) -> Bool:
12 match result:
13 case Fail{_}:
14 False{}
15 case Done{again}:
16 String.eq(Json.stringify(again), Json.stringify(value))
17
18
19def valid_parse(result: Result<&1, &1, Json.Error, Json.Value>) -> Bool:
20 match result:
21 case Fail{_}:
22 False{}
23 case Done{+value}:
24 valid_reparse(Json.parse(Json.stringify(value)), value)
25
26def valid_roundtrip(text: String) -> Bool:
27 valid_parse(Json.parse(text))
28
29def rejects_parse(result: Result<&1, &1, Json.Error, Json.Value>) -> Bool:
30 match result:
31 case Fail{_}: True{}
32 case Done{_}: False{}
33
34def rejects(text: String) -> Bool:
35 rejects_parse(Json.parse(text))
36
37def main() -> IO(Unit):
38 do IO<Unit>:
39 sample_ok : Bool = valid_roundtrip("{\"shop\":\"Bend & Thread\",\"active\":true,\"currency\":\"USD\",\"items\":[{\"listing_id\":84512037,\"title\":\"Handwoven linen table runner\",\"price\":42.5,\"tags\":[\"linen\",\"table decor\",\"handmade\"],\"personalization_enabled\":false},{\"listing_id\":84512038,\"title\":\"Indigo napkins\",\"price\":18.0,\"tags\":[],\"personalization_enabled\":true}],\"notes\":null}")
40 check(sample_ok, "assets/sample.json round trip")
41 check(valid_roundtrip("[null,true,false,0,-3,1.2e+4,\"ok\"]"), "nested values and numbers")
42 check(rejects("01") && rejects("1.") && rejects("[1,]") && rejects("{\"x\":}"), "malformed JSON")
43 IO.print("JSON parser tests passed")