Module B0_testing

Unit, random and snapshot testing for OCaml.

This example is a blueprint for a test executable. See also the b0 testing manual to integrate your tests in your B0.ml file and run them with b0 test.

This module is designed to be opened.

Warning. As it stands the module is not thread safe. It will be made thread safe in the future.

module Test : sig ... end

Testing structure and assertions.

module Snap : sig ... end

Snapshots.

val (!!) : ?loc:Test.loc -> 'a -> 'a Test.Snapshot.t

This doesn't work for now, but is what we would like to use in the future. Use Stdlib.__POS_OF__ for now see Snap.

Example

This is a typical test executable. Note that tests are let bound. This mans that you can load them in the toplevel to invoke them manually.

let test_string_get =
  Test.test "String.get" @@ fun () ->
  Test.char (String.get "a" 0) 'a' ~__POS__;
  Snap.char (String.get "ab" 1) @@ __POS_OF__ 'b';
  Snap.raise (fun () -> String.get "" 0) @@ __POS_OF__
    (Invalid_argument("index out of bounds"));
  ()

let test_list_map =
  Test.test "List.map" @@ fun () ->
  Test.(list T.int) (List.map succ [1; 2; 3]) [2; 3; 4] ~__POS__;
  Snap.(list T.int) (List.map succ [1; 2; 3]) @@ __POS_OF__
    [2; 3; 4];
  ()

let test_randomized =
  Test.test "Randomized" @@ fun () ->
  let rstate = Test.Rand.state () in
  let n = Random.State.int rstate 10 in
  let a = Array.init (n + 1) Fun.id in
  let asum = (n * (n + 1)) / 2 in
  Test.int (Array.fold_left ( + ) 0 a) asum ~__POS__;
  ()

let test_snapshots =
  Test.test "Snapshots" @@ fun () ->
  Snap.string (String.concat "," ["a";"b";"c"]) @@ __POS_OF__
    "a,b,c";
  ()

let main () = Test.main @@ fun () -> Test.autorun ()
let () = if !Sys.interactive then () else exit (main ())

Note that if you are in a testing hurry or migrating you can always simply use OCaml's assert in the test functions: you just won't get any rendering on assertion failures and tests stop at the first assertion failure.

TODO. Show how to use arguments.