(* sqlite3's JSON text over nox-json's values. Every expected text is the answer of the reference sqlite3, 3.54.1 as Homebrew builds it: json() for what reading then writing gives, json_quote() for a written string, json_pretty() for an indented one and json_error_position() for where a malformed text fails. *) module J = Sql.Json let text = Json.Codec.Value.t (* json('[1.50,-0,0x1F,.5,Infinity,NaN,{a:''x''}]'): a number keeps the text sqlite3 writes for it, JSON5 is read *) let test_round_trip () = let v = J.of_string_exn text "[1.50,-0,0x1F,.5,Infinity,NaN,{a:'x'}]" in Alcotest.(check string) "json()" {|[1.50,-0,31,0.5,9e999,null,{"a":"x"}]|} (J.to_string text v); Alcotest.(check (list int)) "a typed codec" [ 1; 2; 3 ] (J.of_string_exn Json.Codec.(list int) " [1, 2, 3,] ") (* Strings may hold any byte, and write as json_quote() writes them: json_quote(char(97,1,8,127)) is "a\u0001\b" then DEL. *) let test_strings () = Alcotest.(check string) "invalid UTF-8 is read" "\xff" (J.of_string_exn Json.Codec.string "\"\xff\""); Alcotest.(check string) "a raw tab is read" "a\tb" (J.of_string_exn Json.Codec.string "'a\tb'"); Alcotest.(check string) "json_quote" "\"a\\u0001\\b\x7f\"" (J.to_string Json.Codec.string "a\001\b\x7f") (* json_pretty('[1,{"a":[2,3]}]', ' '): ~indent:2 is two spaces a level *) let test_indent () = Alcotest.(check string) "json_pretty" "[\n 1,\n {\n \"a\": [\n 2,\n 3\n ]\n }\n]" (J.to_string ~indent:2 text (J.of_string_exn text {|[1,{"a":[2,3]}]|})) (* json_error_position('[1,2,x]') is 6: the parser stops at byte 5. *) let test_malformed () = match J.of_string text "[1,2,x]" with | Ok _ -> Alcotest.fail "[1,2,x] read" | Error e -> Alcotest.(check int) "where" 5 (Loc.first_byte (Json.Meta.loc e.meta)); let msg = Json.Error.to_string e in let sub = "malformed JSON" in let n = String.length sub in let rec has i = i + n <= String.length msg && (String.sub msg i n = sub || has (i + 1)) in Alcotest.(check bool) ("the message: " ^ msg) true (has 0) let suite = ( "sqlite_json", [ Alcotest.test_case "round trip" `Quick test_round_trip; Alcotest.test_case "strings" `Quick test_strings; Alcotest.test_case "indent" `Quick test_indent; Alcotest.test_case "malformed" `Quick test_malformed; ] )