package hedgehog

  1. Overview
  2. Docs
Property-based testing with integrated shrinking for OCaml

Install

dune-project
 Dependency

Authors

Maintainers

Sources

hedgehog-0.1.tbz
sha256=336e7547dd1e41b3e4839a11aaec56d4e2fe14b7dc82a9caa560dbd24f2614f7
sha512=5f040fc5e41b4571b75c460622becd98c54a1d5cb36574a9d2ed6d06e71a5b31673b8ea69d9bb5972af9c71dff58fba2b9d33932a6bffc04c6dcd757583895cb

doc/getting-started.html

Getting Started

This guide walks you through installing Hedgehog and writing your first property test.

Installation

Install via opam:

opam install hedgehog

Project setup

Add Hedgehog to your dune-project:

(lang dune 3.0)

(package
 (name my-project)
 (depends
  (hedgehog (>= 0.1))))

And to your test executable's dune file:

(test
 (name my_tests)
 (libraries hedgehog))

Your first property

Create test/my_tests.ml:

open Hedgehog

let prop_reverse_reverse =
  Property.(property Gen.(
    let* xs = list (Range.linear 0 100) (int (Range.linear 0 1000)) in
    return (fun () ->
      assert_ (List.rev (List.rev xs) = xs))))

let () =
  let passed =
    Property.check_group
      { name = "my first tests"
      ; properties =
          [ "reverse reverse", prop_reverse_reverse
          ]
      }
  in
  if not passed then exit 1

Running tests

dune runtest

You should see output like:

━━━ my first tests ━━━
  ✓ reverse reverse passed 100 tests.

  ✓ 1 succeeded.

A failing property

Let's write a property that will fail, to see how Hedgehog reports counterexamples with shrinking:

open Hedgehog

let prop_bad_sort =
  Property.(property Gen.(
    let* xs = list (Range.linear 0 100) (int (Range.linear 0 1000)) in
    return (fun () ->
      let sorted = List.sort Int.compare xs in
      assert_ (sorted = xs))))

let () =
  Property.check prop_bad_sort |> ignore

Hedgehog will find a minimal counterexample, typically a two-element list like [1; 0], demonstrating that not all lists are already sorted. The integrated shrinking automatically reduces the counterexample without any extra work from you.

Next steps

  • tutorial — Full guide to generators, ranges, assertions, and coverage
  • motivation — Why Hedgehog's approach to shrinking matters