// Expected values come from RFC 8259 and from the cases of // JSONTestSuite (github.com/nst/JSONTestSuite): `y_` must parse, `n_` // must be refused. They are written here by hand, not produced by this // package. import gen import gen/check import json. { type ToJson , type Value , Array , Bool , Float , Int , Malformed , Null , Object , String } import std/bytes import std/list import std/random.{type random} import std/result import std/string import std/test.{assert, assert_equal} // ---- parsing ------------------------------------------------------------------- @test fn the_rfc_8259_object_example :: { let text = "\{\"Image\": \{\"Width\": 800, \"Height\": 600, \"Title\": \"View from 15th Floor\", \"Thumbnail\": \{\"Url\": \"http://www.example.com/image/481989943\", \"Height\": 125, \"Width\": 100\}, \"Animated\" : false, \"IDs\": [116, 943, 234, 38793]\}\}" let thumbnail = Object( [ ("Url", String("http://www.example.com/image/481989943")) , ("Height", Int(125)) , ("Width", Int(100)) ] ) let expected = Object( [ ( "Image" , Object( [ ("Width", Int(800)) , ("Height", Int(600)) , ("Title", String("View from 15th Floor")) , ("Thumbnail", thumbnail) , ("Animated", Bool(False)) , ("IDs", Array([Int(116), Int(943), Int(234), Int(38793)])) ] ) ) ] ) assert_equal (json.parse text) Ok(expected) } @test fn the_rfc_8259_array_example :: { let text = "[\{\"precision\": \"zip\", \"Latitude\": 37.7668, \"Longitude\": -122.3959, \"Address\": \"\", \"Zip\": \"94107\"\}]" let expected = Array( [ Object( [ ("precision", String("zip")) , ("Latitude", Float(37.7668)) , ("Longitude", Float(-122.3959)) , ("Address", String("")) , ("Zip", String("94107")) ] ) ] ) assert_equal (json.parse text) Ok(expected) } @test fn scalars_alone_are_json_texts :: { assert_equal (json.parse "null") Ok(Null) assert_equal (json.parse " true ") Ok(Bool(True)) assert_equal (json.parse "\"hi\"") Ok(String("hi")) assert_equal (json.parse "\n42\t") Ok(Int(42)) } @test fn numbers :: { assert_equal (json.parse "0") Ok(Int(0)) assert_equal (json.parse "-0") Ok(Int(0)) assert_equal (json.parse "-12") Ok(Int(-12)) assert_equal (json.parse "1.5") Ok(Float(1.5)) assert_equal (json.parse "1e3") Ok(Float(1000.0)) assert_equal (json.parse "1E+2") Ok(Float(100.0)) assert_equal (json.parse "-2.5e-3") Ok(Float(-0.0025)) assert_equal (json.parse "0.0") Ok(Float(0.0)) } @test fn an_integer_of_any_size_stays_exact :: { let big = "123456789012345678901234567890" assert_equal (json.parse big |> result.map json.write) Ok(big) } @test fn escapes :: { assert_equal (json.parse "\"a\\\"b\\\\c\\/d\\be\\ff\\ng\\rh\\ti\"") Ok(String("a\"b\\c/d\u{8}e\u{c}f\ng\rh\ti")) assert_equal (json.parse "\"\\u0041\\u00e9\\u20ac\"") Ok(String("Aé€")) assert_equal (json.parse "\"\\uD83D\\uDE80\"") Ok(String("🚀")) assert_equal (json.parse "\"\\u00E9\"") Ok(String("é")) } @test fn text_that_is_not_ascii_passes_through :: { assert_equal (json.parse "\"Café 🚀 日本\"") Ok(String("Café 🚀 日本")) } /// JSONTestSuite's `y_` cases (a selection): each must parse. @test fn texts_that_must_parse :: { let accepted = [ "[]" , "\{\}" , "[[] ]" , "[\"\"]" , "[1,null,null,null,2]" , "[-0]" , "[1E22]" , "[0e+1]" , "[0e1]" , "[-123]" , "[123e-10000000]" , "\{\"a\":\"b\",\"c\":\"d\"\}" , "\{\"\":0\}" , "[\"\\u0000\"]" , "[\"\\uFFFF\"]" , "[\"\\u005C\"]" , " [] " , "[\"\u{7f}\"]" ] let refused = list.filter accepted fn t { result.is_error (json.parse t) } assert_equal refused [] } /// JSONTestSuite's `n_` cases (a selection): each must be refused. @test fn texts_that_must_not_parse :: { let refused = [ "" , " " , "[" , "[1,]" , "[,1]" , "[1 2]" , "\{\"a\":1,\}" , "\{\"a\" 1\}" , "\{1:1\}" , "\{'a':1\}" , "['single']" , "[01]" , "[-01]" , "[1.]" , "[.5]" , "[+1]" , "[1e]" , "[1e+]" , "[-]" , "[Infinity]" , "[NaN]" , "[1e999]" , "[tru]" , "[nul]" , "[True]" , "[\"\\x41\"]" , "[\"\\u12\"]" , "[\"\\uD800\"]" , "[\"\\uDC00\"]" , "[\"\\uD800\\u0041\"]" , "[\"a\nb\"]" , "[\"a\tb\"]" , "[\"unterminated]" , "[] []" , "[]x" , "\{\"a\":1,\"a\":2\}" ] let accepted = list.filter refused fn t { result.is_ok (json.parse t) } assert_equal accepted [] } @test fn an_error_says_where :: { assert_equal (json.parse "[1, 2,, 3]") Error(Malformed(6, "expected a value")) assert_equal (json.parse "[1] x") Error(Malformed(4, "text after the value")) assert_equal (json.parse "\{\"a\":1,\"a\":2\}") Error(Malformed(7, "the key \"a\" appears twice")) } @test fn nesting_is_bounded :: { let deep = fn n { string.repeat "[" n <> string.repeat "]" n } assert (result.is_ok (json.parse (deep (json.max_depth ())))) "at the bound" assert ( json.parse (deep (json.max_depth () + 1)) == Error(Malformed(json.max_depth (), "nesting deeper than 512 levels")) ) "past the bound" } @test fn a_body_must_be_utf8 :: { assert_equal (json.parse_bytes (bytes.from_string "[1]")) Ok(Array([Int(1)])) assert (result.is_error (json.parse_bytes (bytes.from_list [91, 255, 93]))) "refused" } // ---- writing ------------------------------------------------------------------- @test fn writing_is_compact :: { let v = Object( [ ("name", String("Orion")) , ("fuel", Int(80)) , ("speed", Float(2.5)) , ("cargo", Array([])) , ("docked", Bool(True)) , ("captain", Null) ] ) assert_equal (json.write v) "\{\"name\":\"Orion\",\"fuel\":80,\"speed\":2.5,\"cargo\":[],\"docked\":true,\"captain\":null\}" } @test fn writing_escapes_what_json_needs :: { assert_equal (json.write (String("say \"hi\"\\\n\t\u{1}/é"))) "\"say \\\"hi\\\"\\\\\\n\\t\\u0001/é\"" } @test fn floats_are_written_as_json_numbers :: { assert_equal (json.write (Float(1.0))) "1.0" assert_equal (json.write (Float(1.0e300))) "1e300" assert_equal (json.write (Float(-1.5e-7))) "-1.5e-7" } @should_panic "is not a JSON number" @test fn an_infinity_is_not_written :: { let _ = json.write (Float(1.0 / 0.0)) } @test fn pretty_indents_by_two :: { let v = Object( [ ("a", Array([Int(1), Int(2)])) , ("b", Object([])) , ("c", Array([])) ] ) assert_equal (json.pretty v) "\{\n \"a\": [\n 1,\n 2\n ],\n \"b\": \{\},\n \"c\": []\n\}" } @test fn show_is_write :: { assert_equal "{Array([Int(1), Null])}" "[1,null]" } @test fn get_reads_a_field :: { let v = Object([("a", Int(1))]) assert_equal (json.get v "a") Some(Int(1)) assert_equal (json.get v "b") None assert_equal (json.get (Int(1)) "a") None } // ---- deriving ------------------------------------------------------------------ @derive Eq Debug ToJson type Status { Docked, InOrbit, InTransit(String, Int) } @derive Eq Debug ToJson type Ship { Ship(symbol: String, fuel: Int, status: Status, crew: Option) } @test fn a_derived_record_is_an_object :: { assert_equal (json.encode (Ship("ORION-1", 80, Docked, None))) "\{\"symbol\":\"ORION-1\",\"fuel\":80,\"status\":\"Docked\",\"crew\":null\}" assert_equal (json.encode [InTransit("SOL-A2", 30), InOrbit]) "[\{\"InTransit\":[\"SOL-A2\",30]\},\"InOrbit\"]" } // ---- properties ---------------------------------------------------------------- fn any_value :: depth: Int -> Value / { let leaves = [ (1, fn { Null }) , (1, fn { Bool(gen.bool ()) }) , (3, fn { Int(gen.int ~low: (-1000000000000) ~high: 1000000000000) }) , (2, fn { Float(float_of (gen.int ~low: (-1000000) ~high: 1000000)) }) , (3, fn { String(any_text ()) }) ] let branches = [ (2, fn { Array(gen.list ~min: 0 ~max: 4 fn { any_value (depth - 1) }) }) , ( 2 , fn { Object( distinct ( gen.list ~min: 0 ~max: 4 fn { (any_text (), any_value (depth - 1)) } ) ) } ) ] let pick = gen.weighted (if depth <= 0 { leaves } else { list.append leaves branches }) pick () } fn float_of :: n: Int -> Float { json.parse "{n}.25" |> result.map fn v { match v { Float(x) -> x, _ -> 0.0 } } |> result.unwrap_or 0.0 } fn any_text :: -> String / { gen.string ~alphabet: "ab\"\\/\n\t\u{1}\u{1f} é€🚀" ~min: 0 ~max: 6 } fn distinct :: entries: List<(String, Value)> -> List<(String, Value)> { list.fold entries [] fn kept entry { if list.any kept fn k: (String, Value) { k.0 == entry.0 } { kept } else { list.append kept [entry] } } } @test fn parsing_undoes_writing :: -> () / { check.property ~runs: 300 fn { any_value 3 } fn v { json.parse (json.write v) == Ok(v) } } @test fn parsing_undoes_pretty_writing :: -> () / { check.property ~runs: 200 fn { any_value 3 } fn v { json.parse (json.pretty v) == Ok(v) } } @test fn every_string_round_trips :: -> () / { check.property ~runs: 300 fn { gen.string ~alphabet: (gen.printable ()) ~min: 0 ~max: 40 } fn s { json.parse (json.write (String(s))) == Ok(String(s)) } }