OCaml Dune Projects and Testing
Real OCaml projects are built with dune and tested with a few standard tools. The playground can't run dune, so this lesson shows the files you would write and then a runnable, self-contained version of the same tests.
Project layout
dune init project wordstat
cd wordstatwordstat/
├── dune-project
├── bin/
│ ├── dune
│ └── main.ml
├── lib/
│ ├── dune
│ ├── wordstat.ml
│ └── wordstat.mli
└── test/
├── dune
└── test_wordstat.mlThe library in lib/ holds the logic, the executable in bin/ is a thin wrapper, and the tests in test/ use the library. Keeping logic in a library is what makes it testable.
dune files
; dune-project
(lang dune 3.17)
(name wordstat); lib/dune
(library
(name wordstat)); bin/dune
(executable
(public_name wordstat)
(name main)
(libraries wordstat)); test/dune
(test
(name test_wordstat)
(libraries wordstat alcotest))Dune files use S-expressions. (libraries ...) lists dependencies: other libraries in the project or opam packages.
Everyday commands
| Command | What it does |
|---|---|
dune build |
compile everything (output in _build/) |
dune build @fmt --auto-promote / dune fmt |
format the code with ocamlformat |
dune exec wordstat -- args |
build and run the executable |
dune test |
build and run all tests |
dune utop lib |
a toplevel with your library loaded |
dune build --watch |
rebuild on every file change |
dune clean |
remove _build/ |
In development builds, dune turns most warnings into errors (unused variables, non-exhaustive matches). This is strict but catches real bugs; release builds (--profile release) keep them as warnings.
The library under test
(* lib/wordstat.mli *)
val words : string -> string list
(** Lower-case words, splitting on anything that is not a letter. *)
val frequencies : string -> (string * int) list
(** Word counts, most frequent first, ties in alphabetical order. *)Testing styles
| Style | Tool | Idea |
|---|---|---|
| unit tests | Alcotest, OUnit | check int "count" 3 (f x) |
| expect tests | ppx_expect, dune cram tests | the test prints output; dune diffs it against the saved expectation (like this site's output blocks!) |
| property tests | QCheck | generate random inputs and check a law, such as rev (rev l) = l |
An Alcotest test file looks like this:
let test_words () =
Alcotest.(check (list string)) "split" [ "hello"; "world" ] (Wordstat.words "Hello, world!")
let () =
Alcotest.run "wordstat" [ ("words", [ Alcotest.test_case "basic" `Quick test_words ]) ]A runnable mini test framework
Here is the library together with a tiny homemade test runner, standard library only. It shows the same ideas: named checks, readable failure messages and a summary.
(* ---- library ---- *)
module Wordstat = struct
let words text =
let buf = Buffer.create 16 and acc = ref [] in
let flush () = if Buffer.length buf > 0 then (acc := Buffer.contents buf :: !acc; Buffer.clear buf) in
String.iter
(fun c -> match c with 'a' .. 'z' | 'A' .. 'Z' -> Buffer.add_char buf (Char.lowercase_ascii c) | _ -> flush ())
text;
flush ();
List.rev !acc
let frequencies text =
let tbl = Hashtbl.create 16 in
List.iter (fun w -> Hashtbl.replace tbl w (1 + Option.value (Hashtbl.find_opt tbl w) ~default:0)) (words text);
Hashtbl.fold (fun w n acc -> (w, n) :: acc) tbl []
|> List.sort (fun (w1, n1) (w2, n2) -> if n1 <> n2 then compare n2 n1 else compare w1 w2)
end
(* ---- test runner ---- *)
let passed = ref 0 and failed = ref 0
let check name ~expected ~actual ~show =
if expected = actual then incr passed
else begin
incr failed;
Printf.printf "FAIL %s\n expected: %s\n actual: %s\n" name (show expected) (show actual)
end
let show_words l = "[" ^ String.concat "; " l ^ "]"
let show_freq l = String.concat ", " (List.map (fun (w, n) -> Printf.sprintf "%s:%d" w n) l)
let () =
check "split on punctuation" ~expected:[ "hello"; "world" ] ~actual:(Wordstat.words "Hello, world!") ~show:show_words;
check "empty text" ~expected:[] ~actual:(Wordstat.words " ... ") ~show:show_words;
check "digits are separators" ~expected:[ "a"; "b" ] ~actual:(Wordstat.words "a1b") ~show:show_words;
check "frequencies order" ~expected:[ ("the", 2); ("cat", 1); ("hat", 1) ]
~actual:(Wordstat.frequencies "The cat, the hat.") ~show:show_freq;
(* a deliberately wrong expectation, to show a failure message *)
check "wrong on purpose" ~expected:[ ("cat", 2) ] ~actual:(Wordstat.frequencies "cat dog") ~show:show_freq;
Printf.printf "%d passed, %d failed\n" !passed !failedFAIL wrong on purpose
expected: cat:2
actual: cat:1, dog:1
4 passed, 1 failed
Notice that frequencies sorts its result, so the test does not depend on the unspecified Hashtbl order.
Property-based testing by hand
A property test checks a rule against many generated inputs. With a fixed random seed (here an explicit Random.State.t, so no global state is involved) the run is reproducible:
let rec is_sorted = function a :: (b :: _ as rest) -> a <= b && is_sorted rest | _ -> true
let () =
let seed = 2026 in
let rng = Random.State.make [| seed |] in
let random_list () = List.init (Random.State.int rng 20) (fun _ -> Random.State.int rng 100) in
let trials = 500 in
let ok = ref 0 in
for _ = 1 to trials do
let l = random_list () in
let sorted = List.sort compare l in
if List.rev (List.rev l) = l && List.length sorted = List.length l && is_sorted sorted then incr ok
done;
Printf.printf "%d/%d trials satisfied all properties\n" !ok trials500/500 trials satisfied all properties
QCheck automates this and, when a property fails, shrinks the input to a minimal counterexample.
Test yourself
Which command builds the project and runs all its tests?
dune builddune testopam testocamlopt -test
Why put the logic in lib/ instead of bin/main.ml?
- Executables cannot contain functions
- So tests and other programs can depend on it as a library
- dune requires it
- It compiles faster
What is an expect test?
- A test that expects an exception
- A test whose printed output is compared with a saved expectation
- A random test
- A benchmark