For some reason, Read World OCaml does not cover testing for exceptions.
https://dev.realworldocaml.org/testing.html
Not possible? I could reg exp the stack trace, I guess, but seems like a roundabout kinda way.
Seems like OUnit supports it? So inline test is inferior? tdd - Using ocaml OUnit2 assert_raise - Stack Overflow
One way to do it:
try
Infer.run ast
with
ex -> [%test_eq exn] ex Type_error
But:
146 | ex → [%test_eq exn] ex Type_error
Error: PTyp expected
And there’s a test_eq_exn
in this file: learn-ocaml/src/grader/test_lib.ml at master · ocaml-sf/learn-ocaml · GitHub
My current solution:
Use let%test ...
And then
try
ignore (Infer.run ast);
false
with
| Infer.Type_error s -> true
| _ -> false
Sad thing is, I won’t get any debug output at false, here, only
File “lib/test.ml”, line 134, characters 0-393: trivial concat type error is false.
You could shorten this a bit more with:
match Infer.run ast with
| exception Infer.Type_error s -> true
| exception _ | _ -> false
1 Like
bcc32
August 22, 2022, 4:06am
4
If you want to just test whether an expression raises, you can use:
let%test _ = Exn.does_raise (fun () -> Infer.run ast)
I would actually recommend using an “expect test” instead. You can use something like:
open Expect_test_helpers_base
let%expect_test _ =
require_does_raise [%here] (fun () -> Infer.run ast);
[%expect {||}]
;;
And the expect test will be filled in with the contents of the exception, or an error message if no exception was raised. This is better if you want to check which exception was raised.
3 Likes
Great advice, guys, will test.
Hm, how to install this? opam search gives nothing.
Trying opam install expect_test_helpers_kernel
but:
===== ∗ 28 ↘ 21 =====
Yikes.
Hm, works better now but still getting
771 | require_does_raise [%here] (fun () ->
Error: Uninterpreted extension 'here'.
bcc32
September 24, 2022, 7:23pm
7
[%here]
is provided by ppx_here
, one of the Jane Street suite of ppx rewriters. You can specify it individually in the dune
file, or I usually use ppx_jane
(which basically packages all of the JS ppx rewriters together):
(library
(name ...)
(preprocess (pps ppx_jane)))
1 Like