How can I create asserts with error messages?

Hello,

I want to be able to write one-liners for my asserts like this:

assert a = b, "the LHS was supposed to be equal to the RHS"

or even formatted:

assert a = b, "the LHS %d was supposed to be equal to the RHS %d", a, b

is there a way to do this with the stdlib or janestreet’s base?

It depends of what you mean by assert. You can define a debugf function with the Format module:

let debugf s test fmt =
  if test then Format.ifprintf Format.err_formatter fmt
  else begin
    Format.eprintf "@[<v 2> %s:@," s;
    Format.kfprintf 
       (fun ppf -> Format.fprintf ppf "@]@."; exit 2)
       Format.err_formatter
     fmt
end

which can be used with the __LOC__ variable to keep the location of the debug test in the message

debugf __LOC__ (Int.max_int + 1 > 1) "Test that %d + %d > %d" Int.max_int 1 1
2 Likes

Thanks! I guess this means the stdlib doesn’t have that already?

No there is no such functions by default in the standard library; and there are many moving parts (where to print and how to exit in particular) in the function above that often make it better to customize for the use case at hand.

You might be interested in ppx_assert, which is intended for testing but can certainly also be used for assertions in regular code as well:

4 Likes