Compile-time tests
(require examples) | package: examples |
This library allows writing compile-time unit tests, so that tests provide programmers with instant and prominent feedback similar to a type system. IDEs and editors such as DrRacket, Emacs, or VS Code should highlight test failures the same way they highlight other syntax errors.
1 Defining a test suite
syntax
(with-examples (name:id ...) body ...)
(with-examples (name:id ...) #:timeout timeout:number body ...)
The (body ...) can run arbitrary code. Runtime errors and timeout within the body will be handled as syntax errors. The default timeout applied for each entire suite is one second, and can be customized with timeout as a positive real number.
#lang racket/base (require examples) (define (factorial n) (if (< n 2) 1 (* n (- n 1)))) (with-examples (factorial) (check-equal? (factorial 0) (*)) (check-equal? (factorial 1) (* 1)) (check-equal? (factorial 2) (* 1 2)) (check-equal? (factorial 3) (* 1 2 3)) (check-equal? (factorial 4) (* 1 2 3 4)))
Note that while test suites can appear to "modify state", they are merely modifying their own instantiations "in a separate timeline". In the following example, each test suite observes its own version of the state, which is also distinct from the state initialized at runtime.
#lang racket/base (require examples) (define state (box 0)) (with-examples (state) (check-equal? (unbox state) 0) (set-box! state 1) (check-equal? (unbox state) 1)) (with-examples (state) (check-equal? (unbox state) 0) (set-box! state 2) (check-equal? (unbox state) 2)) (module+ main (printf "Init state: ~a~n" (unbox state)))
2 Checks mirroring RackUnit
Compared to their counterparts from RackUnit, the checks are all macros instead of procedures. They have been reimplemented instead of a wrapping RackUnit’s utils, in order to provide fine-grained syntax error locations.
syntax
(check-eq? expr1 expr2)
syntax
(check-not-eq? expr1 expr2)
syntax
(check-eqv? expr1 expr2)
syntax
(check-not-eqv? expr1 expr2)
syntax
(check-equal? expr1 expr2)
syntax
(check-not-equal? expr1 expr2)
syntax
(check-= expr1 expr2 epsilon)
syntax
(check-pred pred v)
syntax
(check-true v)
syntax
(check-false v)
syntax
(check-not-false v)
syntax
(check-not-exn thunk)
syntax
(check-regexp-match regexp string)
syntax
(check-match expr pattern)
(check-match expr pattern guard)