(** Alcotest tests for the Wire_diff library. *) module D = Wire_diff.Diff let pad wire_size buf = if String.length buf >= wire_size then String.sub buf 0 wire_size else let b = Bytes.make wire_size '\000' in Bytes.blit_string buf 0 b 0 (String.length buf); Bytes.to_string b let check_result name = function | D.Match | D.Both_failed -> () | D.Value_mismatch msg -> Alcotest.failf "%s: value mismatch: %s" name msg | D.Only_c_ok msg -> Alcotest.failf "%s: only C succeeded: %s" name msg | D.Only_ocaml_ok msg -> Alcotest.failf "%s: only OCaml succeeded: %s" name msg (* Roundtrip a simple struct through the OCaml codec *) let test_roundtrip_struct () = let s = Wire.struct_ "Simple" [ Wire.field "a" Wire.uint8; Wire.field "b" Wire.uint16 ] in let buf = "\x01\x02\x03" in match D.roundtrip_struct s buf with | Ok out -> Alcotest.(check string) "roundtrip" buf out | Error e -> Alcotest.failf "roundtrip failed: %a" Wire.pp_parse_error e (* Schema with no C implementation — Both_failed is acceptable *) let test_schema_read_no_c () = let wire_size = 3 in let buf = pad wire_size "\xff\xff\xff" in let s = Wire.Codec.( record "NoCTest" (fun a b -> (a, b)) |+ field "a" Wire.uint8 fst |+ field "b" Wire.uint16 snd |> seal) in let schema = D.schema ~name:"NoCTest" ~codec:s ~c_read:(fun _ -> None) ~c_write:(fun _ -> None) ~equal:(fun (a1, b1) (a2, b2) -> a1 = a2 && b1 = b2) in check_result "no_c read" (D.read schema buf) let suite = ( "diff", [ Alcotest.test_case "roundtrip_struct" `Quick test_roundtrip_struct; Alcotest.test_case "schema read (no C)" `Quick test_schema_read_no_c; ] )