Hello,
I’m reading the book “Ocaml from the very beginning”, and using inline tests to validate my implementations + to explore different ways of structuring the code.
Overall, I very much enjoy the ability to declare inline tests, as such:
let rec insert a lst =
match lst with
| [] -> [ a ]
| x :: xs -> if a <= x
then a :: x :: xs
else x :: insert a xs
[@@ocamlformat "disable"]
let%test _ = insert 1 [ 1; 2 ] = [ 1; 1; 2 ]
let%test _ = insert 2 [ 1; 2 ] = [ 1; 2; 2 ]
let%test _ = insert 3 [ 1; 2 ] = [ 1; 2; 99 ]
I thing that’s bugging me though, is that the failure message doesn’t really tell me what went wrong. I introduced an obvious typo here to illustrate.
$ dune runtest
File "lib/chapter05.ml", line 11, characters 0-45: <<(insert 3 [1; 2]) = [1; 2; 99]>> is false.
FAILED 1 / 107 tests
I’d like to get something resembling the kind of output below, here’s an example of a similar feature in Elixir:
defmodule Example do
@doc """
## Examples
iex> Example.insert(1, [])
[1]
iex> Example.insert(1, [1])
[1, 1]
iex> Example.insert(2, [1, 2])
[1, 2, 2]
iex> Example.insert(3, [1, 2])
[1, 2, 99]
"""
def insert(h, []), do: [h]
def insert(h1, t1) do
[h2 | t2] = t1
if h1 <= h2 do
[h1 | insert(h2, t2)]
else
[h2 | insert(h1, t2)]
end
end
end
Can I get close to something like this with ppx_inline_test
or any other tool?
I’m not looking at creating a “proper” test file, I’d like to keep my “test examples” close to the implementation.
Prior to finding ppx_inline_test
, I played with the qtest library but found it didn’t work too well with dune
out of the box, I would often need to clear dune’s cache to ensure a proper test run.
Thanks