Advertisement
DanFloyd

Assert module for Ocaml

Aug 9th, 2015
231
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
OCaml 1.57 KB | None | 0 0
  1. (* Assert module for Ocaml *)
  2.  
  3. (* You do not need to modify this file. *)
  4.  
  5. open Printf
  6. open List
  7.  
  8.  
  9. (* When set to true, stop immediately on a failing test *)
  10. let stop_on_failure_flag = ref false
  11.  
  12. let stop_on_failure () = stop_on_failure_flag := true
  13.  
  14. let error_mesg (s: string) =
  15.   print_endline s;
  16.   if !stop_on_failure_flag then exit 1 else ()
  17.  
  18. type result = Succ | Fail | Err of string
  19.  
  20. let assert_eqf (msg: string) actual_fcn expected : unit =
  21.   let _ = print_string ("Running: "^msg^" ... ") in
  22.   let _ = flush_all () in
  23.   let outcome = try if expected = (actual_fcn ()) then Succ else Fail
  24.                 with Failure s -> Err s
  25.                    | e         -> Err (Printexc.to_string e) in
  26.  
  27.   begin match outcome with
  28.              | Succ -> print_endline ("Test passed!")
  29.              | Fail ->
  30.                 print_newline ();
  31.                 error_mesg ("Test failed: "^msg^"\n")
  32.              | Err s ->
  33.                 print_newline ();
  34.                 error_mesg ("Test error: `"^msg^"` reported `" ^ s ^ "`\n")
  35.             end
  36.  
  37.  
  38. let assert_eq (msg:string) actual expected : unit =
  39.   assert_eqf msg (fun () -> actual) expected
  40.  
  41. let run_test msg f = assert_eqf msg f true
  42.  
  43. let run_failing_test msg f =
  44.   let _ = print_string ("Running: "^msg^" ... ") in
  45.   let _ = flush_all () in
  46.   let result = (try (ignore (f ()) ; Fail) with
  47.   | _ -> Succ) in
  48.   match result with
  49.   | Succ -> print_endline ("Test passed!")
  50.   | Fail -> error_mesg ("Test error: should have failed.")
  51.   | Err s -> error_mesg ("run_failing_test BUG: shouldn't get here.")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement