Declarative JSON data manipulation for OCaml
1(** Tests for JSON decode/encode roundtrips through the bytesrw streaming I/O
2 surface. *)
3
4let test_decode_primitive () =
5 match Json.of_string Json.Codec.int "42" with
6 | Error e -> Alcotest.failf "decode failed: %a" Json.Error.pp e
7 | Ok n -> Alcotest.(check int) "42 round-trip" 42 n
8
9let test_encode_primitive () =
10 let s = Json.to_string Json.Codec.int 7 in
11 Alcotest.(check string) "7 encoded" "7" s
12
13let test_roundtrip_object () =
14 let pair_codec =
15 let open Json.Codec.Object in
16 map ~kind:"pair" (fun a b -> (a, b))
17 |> member "a" Json.Codec.int ~enc:fst
18 |> member "b" Json.Codec.string ~enc:snd
19 |> seal
20 in
21 let input = {|{"a": 7, "b": "hi"}|} in
22 match Json.of_string pair_codec input with
23 | Error e -> Alcotest.failf "decode failed: %a" Json.Error.pp e
24 | Ok (a, b) ->
25 Alcotest.(check int) "a" 7 a;
26 Alcotest.(check string) "b" "hi" b
27
28let test_decode_error () =
29 match Json.of_string Json.Codec.int "not json" with
30 | Ok _ -> Alcotest.fail "expected decode error"
31 | Error _ -> ()
32
33let suite =
34 ( "json_bytesrw",
35 [
36 Alcotest.test_case "decode int" `Quick test_decode_primitive;
37 Alcotest.test_case "encode int" `Quick test_encode_primitive;
38 Alcotest.test_case "roundtrip object" `Quick test_roundtrip_object;
39 Alcotest.test_case "decode error" `Quick test_decode_error;
40 ] )