• Stars
    star
    447
  • Rank 97,700 (Top 2 %)
  • Language
    OCaml
  • License
    ISC License
  • Created almost 11 years ago
  • Updated 4 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A lightweight and colourful test framework

A lightweight and colourful test framework.


Alcotest exposes a simple interface to perform unit tests. It exposes a simple TESTABLE module type, a check function to assert test predicates and a run function to perform a list of unit -> unit test callbacks.

Alcotest provides a quiet and colorful output where only faulty runs are fully displayed at the end of the run (with the full logs ready to inspect), with a simple (yet expressive) query language to select the tests to run. See the manpage for details.

The API documentation can be found here. For information on contributing to Alcotest, see CONTRIBUTING.md.

OCaml-CI Build Status Alcotest Documentation


Examples

A simple example (taken from examples/simple.ml):

Generated by the following test suite specification:

(* Build with `ocamlbuild -pkg alcotest simple.byte` *)

(* A module with functions to test *)
module To_test = struct
  let lowercase = String.lowercase_ascii
  let capitalize = String.capitalize_ascii
  let str_concat = String.concat ""
  let list_concat = List.append
end

(* The tests *)
let test_lowercase () =
  Alcotest.(check string) "same string" "hello!" (To_test.lowercase "hELLO!")

let test_capitalize () =
  Alcotest.(check string) "same string" "World." (To_test.capitalize "world.")

let test_str_concat () =
  Alcotest.(check string) "same string" "foobar" (To_test.str_concat ["foo"; "bar"])

let test_list_concat () =
  Alcotest.(check (list int)) "same lists" [1; 2; 3] (To_test.list_concat [1] [2; 3])

(* Run it *)
let () =
  let open Alcotest in
  run "Utils" [
      "string-case", [
          test_case "Lower case"     `Quick test_lowercase;
          test_case "Capitalization" `Quick test_capitalize;
        ];
      "string-concat", [ test_case "String mashing" `Quick test_str_concat  ];
      "list-concat",   [ test_case "List mashing"   `Slow  test_list_concat ];
    ]

The result is a self-contained binary which displays the test results. Use dune exec examples/simple.exe -- --help to see the runtime options.

Here's an example of a of failing test suite:

By default, only the first failing test log is printed to the console (and all test logs are captured on disk). Pass --show-errors to print all error messages.

Using Alcotest with opam and Dune

Add (alcotest :with-test) to the depends stanza of your dune-project file, or "alcotest" {with-test} to your opam file. Use the with-test package variable to declare your tests opam dependencies. Call opam to install them:

$ opam install --deps-only --with-test .

You can then declare your test and link with Alcotest: (test (libraries alcotest …) …), and run your tests:

$ dune runtest

Selecting tests to execute

You can filter which tests to run by supplying a regular expression matching the names of the tests to execute, or by passing a regular expression and a comma-separated list of test numbers (or ranges of test numbers, e.g. 2,4..9):

$ ./simple.native test '.*concat*'
Testing Utils.
[SKIP]     string-case            0   Lower case.
[SKIP]     string-case            1   Capitalization.
[OK]       string-concat          0   String mashing.
[OK]       list-concat            0   List mashing.
The full test results are available in `_build/_tests`.
Test Successful in 0.000s. 2 tests run.

$ ./simple.native test 'string-case' '1..3'
Testing Utils.
[SKIP]     string-case            0   Lower case.
[OK]       string-case            1   Capitalization.
[SKIP]     string-concat          0   String mashing.
[SKIP]     list-concat            0   List mashing.
The full test results are available in `_build/_tests`.
Test Successful in 0.000s. 1 test run.

Note that you cannot filter by test case name (i.e. Lower case or Capitalization), you must filter by test name & number instead.

See the examples directory for more examples.

Quick and Slow tests

In general you should use `Quick tests: tests that are ran on any invocations of the test suite. You should only use `Slow tests for stress tests that are ran only on occasion (typically before a release or after a major change). These slow tests can be suppressed by passing the -q flag on the command line, e.g.:

$ ./test.exe -q # run only the quick tests
$ ./test.exe    # run quick and slow tests

Passing custom options to the tests

In most cases, the base tests are unit -> unit functions. However, it is also possible to pass an extra option to all the test functions by using 'a -> unit, where 'a is the type of the extra parameter.

In order to do this, you need to specify how this extra parameter is read on the command-line, by providing a Cmdliner term for command-line arguments which explains how to parse and serialize values of type 'a (note: do not use positional arguments, only optional arguments are supported).

For instance:

let test_nice i = Alcotest.(check int) "Is it a nice integer?" i 42

let int =
  let doc = "What is your preferred number?" in
  Cmdliner.Arg.(required & opt (some int) None & info ["n"] ~doc ~docv:"NUM")

let () =
  Alcotest.run_with_args "foo" int [
    "all", ["nice", `Quick, test_nice]
  ]

Will generate test.exe such that:

$ test.exe test
test.exe: required option -n is missing

$ test.exe test -n 42
Testing foo.
[OK]                all          0   int.

Lwt

Alcotest provides an Alcotest_lwt module that you could use to wrap Lwt test cases. The basic idea is that instead of providing a test function in the form unit -> unit, you provide one with the type unit -> unit Lwt.t and alcotest-lwt calls Lwt_main.run for you.

However, there are a couple of extra features:

  • If an async exception occurs, it will cancel your test case for you and fail it (rather than exiting the process).

  • You get given a switch, which will be turned off when the test case finishes (or fails). You can use that to free up any resources.

For instance:

let free () = print_endline "freeing all resources"; Lwt.return ()

let test_lwt switch () =
  Lwt_switch.add_hook (Some switch) free;
  Lwt.async (fun () -> failwith "All is broken");
  Lwt_unix.sleep 10.

let () =
  Lwt_main.run @@ Alcotest_lwt.run "foo" [
    "all", [
      Alcotest_lwt.test_case "one" `Quick test_lwt
    ]
  ]

Will generate:

$ test.exe
Testing foo.
[ERROR]             all          0   one.
-- all.000 [one.] Failed --
in _build/_tests/all.000.output:
freeing all resources
[failure] All is broken

Comparison with other testing frameworks

The README is pretty clear about that:

Alcotest is a lightweight and colourful test framework.

Alcotest is the only testing framework using colors!

More seriously, Alcotest is similar to ounit but it fixes a few of the problems found in that library:

  • Alcotest has a nicer output, it is easier to see what failed and what succeeded and to read the log outputs of the failed tests;

  • Alcotest uses combinators to define pretty-printers and comparators between the things to test.

Other nice tools doing different kind of testing also exist:

  • qcheck does random generation and property testing (e.g. Quick Check);

  • crowbar and bun are similar to qcheck, but use compiler-directed randomness, i.e. they take advantage of the AFL support the OCaml compiler;

  • ppx_inline_tests allows to write tests in the same file as your source-code; they will be run only in a special mode of compilation.

More Repositories

1

mirage

MirageOS is a library operating system that constructs unikernels
OCaml
2,520
star
2

irmin

Irmin is a distributed database that follows the same design principles as Git
OCaml
1,742
star
3

ocaml-cohttp

An OCaml library for HTTP clients and servers using Lwt or Async
OCaml
644
star
4

ocaml-git

Pure OCaml Git format and protocol
OCaml
349
star
5

mirage-tcpip

TCP/IP networking stack in pure OCaml, using the Mirage platform libraries. Includes IPv4/6, ICMP, and UDP/TCP support.
OCaml
321
star
6

jitsu

A DNS server that automatically starts unikernels on demand
OCaml
307
star
7

mirage-skeleton

Examples of simple MirageOS apps
OCaml
224
star
8

qubes-mirage-firewall

A Mirage firewall VM for QubesOS
OCaml
207
star
9

mirage-www

Website infrastructure and content for mirage.io
HTML
162
star
10

decompress

Pure OCaml implementation of Zlib.
OCaml
116
star
11

ocaml-cow

Caml on the Web (COW) is a set of parsers and syntax extensions to let you manipulate HTML, CSS, XML, JSON and Markdown directly from OCaml code.
OCaml
105
star
12

awa-ssh

Purely functional SSH library in ocaml.
OCaml
104
star
13

ocaml-cstruct

Map OCaml arrays onto C-like structs
OCaml
103
star
14

ocaml-dns

OCaml implementation of the DNS protocol
OCaml
102
star
15

ocaml-solo5

Freestanding OCaml runtime
C
101
star
16

ocaml-github

GitHub APIv3 OCaml bindings
OCaml
100
star
17

capnp-rpc

Cap'n Proto RPC implementation
OCaml
97
star
18

ocaml-rpc

Light library to deal with RPCs in OCaml
OCaml
95
star
19

ocaml-uri

RFC3986 URI parsing library for OCaml
OCaml
93
star
20

digestif

Simple hash algorithms in OCaml
OCaml
88
star
21

ocaml-conduit

Dereference URIs into communication channels for Async or Lwt
OCaml
84
star
22

mirage-crypto

Cryptographic primitives for OCaml, in OCaml (also used in MirageOS)
C
77
star
23

mirage-platform

Archived, see https://github.com/mirage/mirage/issues/1159 for details. Old: Core platform libraries for Mirage (UNIX and Xen). This provides the `OS` library which handles timers, device setup and the main loop, as well as the runtime for the Xen unikernel.
C
77
star
24

xen

Unofficial mirror of xenbits.xen.org/xen.git
C
72
star
25

ocaml-crunch

Convert a filesystem into a static OCaml module
OCaml
70
star
26

ocaml-9p

An OCaml/Mirage-friendly implementation of the 9P protocol
OCaml
63
star
27

functoria

A DSL to invoke otherworldly functors
OCaml
63
star
28

mini-os

Mirror of the Xen MiniOS Git from git://xenbits.xen.org/mini-os.git
C
63
star
29

mirage-qubes

Mirage support for writing QubesOS AppVM unikernels
OCaml
62
star
30

xen-arm-builder

Archived - the Xen and ARM support in MirageOS has been superseeded by our PVH support - Build an SDcard image for Xen/ARM, for a Cubieboard
Shell
57
star
31

charrua

A DHCP library in OCaml
OCaml
55
star
32

orm

Object Relational Mapper extension
OCaml
54
star
33

ke

Fast implementation of queue in OCaml
HTML
52
star
34

eqaf

Constant time equal function to avoid timing attacks in OCaml
OCaml
51
star
35

conan

Like detective conan, find clue about the type of the file
OCaml
49
star
36

prometheus

OCaml library for reporting metrics to a Prometheus server
OCaml
49
star
37

ocaml-matrix

Implementation of a matrix server in OCaml for MirageOS
OCaml
49
star
38

ocaml-tar

Pure OCaml library to read and write tar files
OCaml
49
star
39

ocaml-vchan

Pure OCaml implementation of the "vchan" shared-memory communication protocol
OCaml
46
star
40

metrics

Infrastructure to collect metrics from OCaml applications.
OCaml
46
star
41

bechamel

Agnostic benchmark in OCaml (proof-of-concept)
OCaml
44
star
42

wodan

A Mirage filesystem library
OCaml
44
star
43

ocaml-base64

Base64 encoding and decoding in OCaml
OCaml
43
star
44

colombe

Implementation of SMTP protocols in OCaml
OCaml
42
star
45

ocaml-ipaddr

A library for manipulation of IP (and MAC) address representations
OCaml
40
star
46

mrmime

What do you mean?
OCaml
40
star
47

ezjsonm

An easy interface on top of the Jsonm library.
OCaml
40
star
48

index

A platform-agnostic multi-level index
OCaml
34
star
49

bloomf

Efficient Bloom filters for OCaml
OCaml
34
star
50

emile

& images
OCaml
31
star
51

mirage-nat

library for network address translation intended for use with mirage unikernels
OCaml
31
star
52

repr

OCaml
31
star
53

ocaml-hex

Hexadecimal converter
OCaml
29
star
54

ocaml-diet

A simple implementation of Discrete Interval Encoding Trees
OCaml
28
star
55

ptt

Postes, Télégraphes et Téléphones
OCaml
26
star
56

ocaml-fat

Read and write FAT format filesystems from OCaml
OCaml
26
star
57

encore

Synonym of angkor
OCaml
25
star
58

ocaml-magic-mime

Convert file extensions to MIME types
OCaml
24
star
59

irmin-server

A high-performance server for Irmin
OCaml
24
star
60

optint

Library to provide a fast integer (x64 arch) or allocated int32 (x84 arch)
OCaml
24
star
61

ocaml-lazy-trie

Lazy prefix trees in OCaml
OCaml
23
star
62

qubes-mirage-skeleton

An example Mirage unikernel that runs as a Qubes AppVM
OCaml
23
star
63

ocaml-pcap

OCaml code for generating and analysing pcap (packet capture) files
OCaml
22
star
64

duff

Pure OCaml implementation of libXdiff (Rabin's fingerprint)
OCaml
21
star
65

hacl

Archived. Curve25519 support has been integrated into mirage-crypto-ec (via fiat-crypto). Hacl bindings are available from the hacl-star opam package. OCaml bindings for HACL* elliptic curves
C
21
star
66

arp

Address resolution protocol (ARP) implementation in OCaml targeting MirageOS
OCaml
21
star
67

shared-memory-ring

Xen-style shared memory rings
OCaml
20
star
68

irmin-rpc

RPC client/server for Irmin
OCaml
20
star
69

typebeat

Parsing of the Content-Type header in pure OCaml
OCaml
20
star
70

mirage-solo5

Solo5 core platform libraries for MirageOS
OCaml
20
star
71

ocaml-tuntap

Bindings to UNIX tuntap facilities
OCaml
20
star
72

mirage-lambda

An eDSL for MirageOS apps
OCaml
19
star
73

merge-queues

Mergeable queues
OCaml
19
star
74

ocaml-qcow

Pure OCaml code for parsing, printing, modifying .qcow format data
OCaml
19
star
75

ocaml-vmnet

NATed networking on MacOS X using the vmnet framework
OCaml
18
star
76

mirage-xen

Xen core platform libraries for MirageOS
C
18
star
77

mirage-profile

Collect profiling information
OCaml
18
star
78

cactus

A Btree library in OCaml
OCaml
18
star
79

mirage-clock

Portable clock implementation for Unix and Xen
OCaml
18
star
80

ocaml-mbr

A simple library for manipulating Master Boot Records
OCaml
18
star
81

spamtacus

Ocaml modular spam filter
OCaml
16
star
82

mirage-dev

Development OPAM repository for work-in-progress packages
16
star
83

ocaml-fsevents

macOS bindings to the FSEvents API
OCaml
16
star
84

mirage-fs-unix

Unix Filesystem passthrough for MirageOS
OCaml
16
star
85

mirage-vnetif

Virtual network interface and software bridge for Mirage
OCaml
16
star
86

irmin-rs

Rust
15
star
87

ocaml-hvsock

Bindings for hypervisor sockets, for Linux, Windows and macOS (via Hyperkit)
OCaml
15
star
88

ca-certs

Detect root CA certificates from the operating system
OCaml
15
star
89

irmin-watcher

Portable implementation of the Irmin Watch API
OCaml
15
star
90

checkseum

C
15
star
91

mirage-handbook

WIP Handbook for MirageOS
14
star
92

retreat.mirage.io

Microsite for the MirageOS hack retreats
OCaml
14
star
93

mmap

File mapping
OCaml
13
star
94

mirage-decks

These are the MirageOS slide decks, written as a self-hosting unikernel
HTML
13
star
95

ezxmlm

Like the tax form, this is an easier interface for quick n dirty XMLM scripts
OCaml
13
star
96

mirage-unix

Unix core platform libraries for MirageOS
OCaml
13
star
97

ocaml-gpt

A simple library for manipulating GUID partition tables
OCaml
12
star
98

irmin.org

Irmin website
CSS
12
star
99

mirage-console

Portable console handling for Mirage applications
OCaml
12
star
100

mirage-net-xen

Xen Netfront and Netback ethernet device drivers for Mirage
OCaml
12
star