Skip to content

Commit

Permalink
add QCheck.assume; explain preconditions a bit (close #9)
Browse files Browse the repository at this point in the history
  • Loading branch information
c-cube committed Jan 5, 2017
1 parent 6c813aa commit 09106d1
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 0 deletions.
20 changes: 20 additions & 0 deletions README.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,26 @@ QCheck_runner.run_tests [test_mirror];;
----

=== Preconditions

The functions `QCheck.assume` and `QCheck.(==>)` can be used for
tests with preconditions.
For instance, `List.hd l :: List.tl l = l` only holds for non-empty lists.
Without the precondition, the property is false and will even rais
an exception in some cases.

[source,OCaml]
----
let test_hd_tl =
QCheck.(Test.make
(list int) (fun l ->
assume (l <> []);
l = List.hd l :: List.tl l));;
QCheck_runner.run_tests [test_hd_tl];;
----


=== Runners

The module `QCheck_runner` defines several functions to run tests, including
Expand Down
2 changes: 2 additions & 0 deletions src/QCheck.ml
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,8 @@ let sum_int = List.fold_left (+) 0
exception FailedPrecondition
(* raised if precondition is false *)

let assume b = if not b then raise FailedPrecondition

let (==>) b1 b2 = if b1 then b2 else raise FailedPrecondition

module Gen = struct
Expand Down
24 changes: 24 additions & 0 deletions src/QCheck.mli
Original file line number Diff line number Diff line change
Expand Up @@ -95,8 +95,32 @@ val (==>) : bool -> bool -> bool
ie [not b1 || b2] (except that it is strict and will interact
better with {!Test.check_exn} and the likes, because they will know
the precondition was not satisfied.).
{b WARNING}: this function should only be used in a property
(see {!Test.make}), because it raises a special exception in case of
failure of the first argument, to distinguish between failed test
and failed precondition. Because of OCaml's evaluation order,
both [b1] and [b2] are always evaluated; if [b2] should only be
evaluated when [b1] holds, see {!assume}.
*)

val assume : bool -> unit
(** [assume cond] checks the precondition [cond], and does nothing
if [cond=true]. If [cond=false], it interrupts the current test.
{b WARNING} This function, like {!(==>)}, should only be used in
a test. not outside.
Example:
{[
Test.make (list int) (fun l ->
assume (l <> []);
List.hd l :: List.tl l = l)
]}
@since NEXT_RELEASE
*)


(** {2 Generate Random Values} *)
module Gen : sig
type 'a t = Random.State.t -> 'a
Expand Down

0 comments on commit 09106d1

Please sign in to comment.