OCaml wire format DSL with EverParse 3D output for verified parsers
at main 52 lines 1.7 kB view raw
1(** Alcotest tests for the Wire_diff library. *) 2 3module D = Wire_diff.Diff 4 5let pad wire_size buf = 6 if String.length buf >= wire_size then String.sub buf 0 wire_size 7 else 8 let b = Bytes.make wire_size '\000' in 9 Bytes.blit_string buf 0 b 0 (String.length buf); 10 Bytes.to_string b 11 12let check_result name = function 13 | D.Match | D.Both_failed -> () 14 | D.Value_mismatch msg -> Alcotest.failf "%s: value mismatch: %s" name msg 15 | D.Only_c_ok msg -> Alcotest.failf "%s: only C succeeded: %s" name msg 16 | D.Only_ocaml_ok msg -> 17 Alcotest.failf "%s: only OCaml succeeded: %s" name msg 18 19(* Roundtrip a simple struct through the OCaml codec *) 20let test_roundtrip_struct () = 21 let s = 22 Wire.struct_ "Simple" 23 [ Wire.field "a" Wire.uint8; Wire.field "b" Wire.uint16 ] 24 in 25 let buf = "\x01\x02\x03" in 26 match D.roundtrip_struct s buf with 27 | Ok out -> Alcotest.(check string) "roundtrip" buf out 28 | Error e -> Alcotest.failf "roundtrip failed: %a" Wire.pp_parse_error e 29 30(* Schema with no C implementation — Both_failed is acceptable *) 31let test_schema_read_no_c () = 32 let wire_size = 3 in 33 let buf = pad wire_size "\xff\xff\xff" in 34 let s = 35 Wire.Codec.( 36 record "NoCTest" (fun a b -> (a, b)) 37 |+ field "a" Wire.uint8 fst |+ field "b" Wire.uint16 snd |> seal) 38 in 39 let schema = 40 D.schema ~name:"NoCTest" ~codec:s 41 ~c_read:(fun _ -> None) 42 ~c_write:(fun _ -> None) 43 ~equal:(fun (a1, b1) (a2, b2) -> a1 = a2 && b1 = b2) 44 in 45 check_result "no_c read" (D.read schema buf) 46 47let suite = 48 ( "diff", 49 [ 50 Alcotest.test_case "roundtrip_struct" `Quick test_roundtrip_struct; 51 Alcotest.test_case "schema read (no C)" `Quick test_schema_read_no_c; 52 ] )