[project @ Corrected NORMALIZE-FLOAT for significands equal to 10.]
[lisp-unit.git] / lisp-unit.lisp
blobb4c596f9b19495dbecb4577b56af6b1332625518
1 ;;;-*- Mode: Lisp; Syntax: ANSI-Common-Lisp -*-
3 #|
4 Copyright (c) 2004-2005 Christopher K. Riesbeck
6 Permission is hereby granted, free of charge, to any person obtaining
7 a copy of this software and associated documentation files (the "Software"),
8 to deal in the Software without restriction, including without limitation
9 the rights to use, copy, modify, merge, publish, distribute, sublicense,
10 and/or sell copies of the Software, and to permit persons to whom the
11 Software is furnished to do so, subject to the following conditions:
13 The above copyright notice and this permission notice shall be included
14 in all copies or substantial portions of the Software.
16 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
17 OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
20 OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
21 ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
22 OTHER DEALINGS IN THE SOFTWARE.
26 ;;; A test suite package, modelled after JUnit.
27 ;;; Author: Chris Riesbeck
28 ;;;
29 ;;; Update history:
30 ;;;
31 ;;; 04/07/06 added ~<...~> to remaining error output forms [CKR]
32 ;;; 04/06/06 added ~<...~> to compact error output better [CKR]
33 ;;; 04/06/06 fixed RUN-TESTS to get tests dynamically (bug reported
34 ;;; by Daniel Edward Burke) [CKR]
35 ;;; 02/08/06 added newlines to error output [CKR]
36 ;;; 12/30/05 renamed ASSERT-PREDICATE to ASSERT-EQUALITY [CKR]
37 ;;; 12/29/05 added ASSERT-EQ, ASSERT-EQL, ASSERT-EQUALP [CKR]
38 ;;; 12/22/05 recoded use-debugger to use handler-bind, added option to prompt for debugger,
39 ;;; 11/07/05 added *use-debugger* and assert-predicate [DFB]
40 ;;; 09/18/05 replaced Academic Free License with MIT Licence [CKR]
41 ;;; 08/30/05 added license notice [CKR]
42 ;;; 06/28/05 changed RUN-TESTS to compile code at run time, not expand time [CKR]
43 ;;; 02/21/05 removed length check from SET-EQUAL [CKR]
44 ;;; 02/17/05 added RUN-ALL-TESTS [CKR]
45 ;;; 01/18/05 added ASSERT-EQUAL back in [CKR]
46 ;;; 01/17/05 much clean up, added WITH-TEST-LISTENER [CKR]
47 ;;; 01/15/05 replaced ASSERT-EQUAL etc. with ASSERT-TRUE and ASSERT-FALSE [CKR]
48 ;;; 01/04/05 changed COLLECT-RESULTS to echo output on *STANDARD-OUTPuT* [CKR]
49 ;;; 01/04/05 added optional package argument to REMOVE-ALL-TESTS [CKR]
50 ;;; 01/04/05 changed OUTPUT-OK-P to trim spaces and returns [CKR]
51 ;;; 01/04/05 changed OUTPUT-OK-P to not check output except when asked to [CKR]
52 ;;; 12/03/04 merged REMOVE-TEST into REMOVE-TESTS [CKR]
53 ;;; 12/03/04 removed ability to pass forms to RUN-TESTS [CKR]
54 ;;; 12/03/04 refactored RUN-TESTS expansion into RUN-TEST-THUNKS [CKR]
55 ;;; 12/02/04 changed to group tests under packages [CKR]
56 ;;; 11/30/04 changed assertions to put expected value first, like JUnit [CKR]
57 ;;; 11/30/04 improved error handling and summarization [CKR]
58 ;;; 11/30/04 generalized RUN-TESTS, removed RUN-TEST [CKR]
59 ;;; 02/27/04 fixed ASSERT-PRINTS not ignoring value [CKR]
60 ;;; 02/07/04 fixed ASSERT-EXPANDS failure message [CKR]
61 ;;; 02/07/04 added ASSERT-NULL, ASSERT-NOT-NULL [CKR]
62 ;;; 01/31/04 added error handling and totalling to RUN-TESTS [CKR]
63 ;;; 01/31/04 made RUN-TEST/RUN-TESTS macros [CKR]
64 ;;; 01/29/04 fixed ASSERT-EXPANDS quote bug [CKR]
65 ;;; 01/28/04 major changes from BUG-FINDER to be more like JUnit [CKR]
69 How to use
70 ----------
72 1. Read the documentation in lisp-unit.html.
74 2. Make a file of DEFINE-TEST's. See exercise-tests.lisp for many
75 examples. If you want, start your test file with (REMOVE-TESTS) to
76 clear any previously defined tests.
78 2. Load this file.
80 2. (use-package :lisp-unit)
82 3. Load your code file and your file of tests.
84 4. Test your code with (RUN-TESTS test-name1 test-name2 ...) -- no quotes! --
85 or simply (RUN-TESTS) to run all defined tests.
87 A summary of how many tests passed and failed will be printed,
88 with details on the failures.
90 Note: Nothing is compiled until RUN-TESTS is expanded. Redefining
91 functions or even macros does not require reloading any tests.
93 For more information, see lisp-unit.html.
97 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
98 ;;; Packages
99 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
101 (cl:defpackage #:lisp-unit
102 (:use #:common-lisp)
103 (:export #:define-test #:run-all-tests #:run-tests
104 #:assert-eq #:assert-eql #:assert-equal #:assert-equalp
105 #:assert-error #:assert-expands #:assert-false
106 #:assert-equality #:assert-prints #:assert-true
107 #:get-test-code #:get-tests
108 #:remove-all-tests #:remove-tests
109 #:logically-equal #:set-equal
110 #:float-equal #:complex-equal #:number-equal
111 #:array-equal
112 #:significant-figures-equal
113 #:use-debugger
114 #:with-test-listener)
117 (in-package #:lisp-unit)
119 (pushnew :lisp-unit *features*)
121 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
122 ;;; Globals
123 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
125 (defparameter *test-listener* nil)
127 (defparameter *tests* (make-hash-table))
129 ;;; Used by RUN-TESTS to collect summary statistics
130 (defvar *test-count* 0)
131 (defvar *pass-count* 0)
133 ;;; Set by RUN-TESTS for use by SHOW-FAILURE
134 (defvar *test-name* nil)
136 ;;; If nil, errors in tests are caught and counted.
137 ;;; If :ask, user is given option of entering debugger or not.
138 ;;; If true and not :ask, debugger is entered.
139 (defparameter *use-debugger* nil)
141 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
142 ;;; Macros
143 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
145 ;;; DEFINE-TEST
147 (defmacro define-test (name &body body)
148 `(progn
149 (store-test-code ',name ',body)
150 ',name))
152 ;;; ASSERT macros
154 (defmacro assert-eq (expected form &rest extras)
155 (expand-assert :equal form form expected extras :test #'eq))
157 (defmacro assert-eql (expected form &rest extras)
158 (expand-assert :equal form form expected extras :test #'eql))
160 (defmacro assert-equal (expected form &rest extras)
161 (expand-assert :equal form form expected extras :test #'equal))
163 (defmacro assert-equalp (expected form &rest extras)
164 (expand-assert :equal form form expected extras :test #'equalp))
166 (defmacro assert-error (condition form &rest extras)
167 (expand-assert :error form (expand-error-form form)
168 condition extras))
170 (defmacro assert-expands (&environment env expansion form &rest extras)
171 (expand-assert :macro form
172 (expand-macro-form form #+lispworks nil #-lispworks env)
173 expansion extras))
175 (defmacro assert-false (form &rest extras)
176 (expand-assert :result form form nil extras))
178 (defmacro assert-equality (test expected form &rest extras)
179 (expand-assert :equal form form expected extras :test test))
181 (defmacro assert-prints (output form &rest extras)
182 (expand-assert :output form (expand-output-form form)
183 output extras))
185 (defmacro assert-true (form &rest extras)
186 (expand-assert :result form form t extras))
189 (defun expand-assert (type form body expected extras &key (test #'eql))
190 `(internal-assert
191 ,type ',form #'(lambda () ,body) #'(lambda () ,expected) ,(expand-extras extras), test))
193 (defun expand-error-form (form)
194 `(handler-case ,form
195 (condition (error) error)))
197 (defun expand-output-form (form)
198 (let ((out (gensym)))
199 `(let* ((,out (make-string-output-stream))
200 (*standard-output* (make-broadcast-stream *standard-output* ,out)))
201 ,form
202 (get-output-stream-string ,out))))
204 (defun expand-macro-form (form env)
205 `(macroexpand-1 ',form ,env))
207 (defun expand-extras (extras)
208 `#'(lambda ()
209 (list ,@(mapcan #'(lambda (form) (list `',form form)) extras))))
212 ;;; RUN-TESTS
214 (defmacro run-all-tests (package &rest tests)
215 `(let ((*package* (find-package ',package)))
216 (run-tests
217 ,@(mapcar #'(lambda (test) (find-symbol (symbol-name test) package))
218 tests))))
220 (defmacro run-tests (&rest names)
221 `(run-test-thunks (get-test-thunks ,(if (null names) '(get-tests *package*) `',names))))
223 (defun get-test-thunks (names &optional (package *package*))
224 (mapcar #'(lambda (name) (get-test-thunk name package))
225 names))
227 (defun get-test-thunk (name package)
228 (assert (get-test-code name package) (name package)
229 "No test defined for ~S in package ~S" name package)
230 (list name (coerce `(lambda () ,@(get-test-code name)) 'function)))
232 (defun use-debugger (&optional (flag t))
233 (setq *use-debugger* flag))
235 ;;; WITH-TEST-LISTENER
236 (defmacro with-test-listener (listener &body body)
237 `(let ((*test-listener* #',listener)) ,@body))
239 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
240 ;;; Public functions
241 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
243 (defun get-test-code (name &optional (package *package*))
244 (let ((table (get-package-table package)))
245 (unless (null table)
246 (gethash name table))))
248 (defun get-tests (&optional (package *package*))
249 (let ((l nil)
250 (table (get-package-table package)))
251 (cond ((null table) nil)
253 (maphash #'(lambda (key val)
254 (declare (ignore val))
255 (push key l))
256 table)
257 (sort l #'string< :key #'string)))))
260 (defun remove-tests (names &optional (package *package*))
261 (let ((table (get-package-table package)))
262 (unless (null table)
263 (if (null names)
264 (clrhash table)
265 (dolist (name names)
266 (remhash name table))))))
268 (defun remove-all-tests (&optional (package *package*))
269 (if (null package)
270 (clrhash *tests*)
271 (remhash (find-package package) *tests*)))
274 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
275 ;;; Private functions
276 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
279 ;;; DEFINE-TEST support
281 (defun get-package-table (package &key create)
282 (let ((table (gethash (find-package package) *tests*)))
283 (or table
284 (and create
285 (setf (gethash package *tests*)
286 (make-hash-table))))))
288 (defun get-test-name (form)
289 (if (atom form) form (cadr form)))
291 (defun store-test-code (name code &optional (package *package*))
292 (setf (gethash name
293 (get-package-table package :create t))
294 code))
297 ;;; ASSERTION support
299 (defun internal-assert (type form code-thunk expected-thunk extras test)
300 (let* ((expected (multiple-value-list (funcall expected-thunk)))
301 (actual (multiple-value-list (funcall code-thunk)))
302 (passed (test-passed-p type expected actual test)))
304 (incf *test-count*)
305 (when passed
306 (incf *pass-count*))
308 (record-result passed type form expected actual extras)
310 passed))
312 (defun record-result (passed type form expected actual extras)
313 (funcall (or *test-listener* 'default-listener)
314 passed type *test-name* form expected actual
315 (and extras (funcall extras))
316 *test-count* *pass-count*))
318 (defun default-listener
319 (passed type name form expected actual extras test-count pass-count)
320 (declare (ignore test-count pass-count))
321 (unless passed
322 (show-failure type (get-failure-message type)
323 name form expected actual extras)))
325 (defun test-passed-p (type expected actual test)
326 (ecase type
327 (:error
328 (or (eql (car actual) (car expected))
329 (typep (car actual) (car expected))))
330 (:equal
331 (and (<= (length expected) (length actual))
332 (every test expected actual)))
333 (:macro
334 (equal (car actual) (car expected)))
335 (:output
336 (string= (string-trim '(#\newline #\return #\space)
337 (car actual))
338 (car expected)))
339 (:result
340 (logically-equal (car actual) (car expected)))
344 ;;; RUN-TESTS support
346 (defun run-test-thunks (test-thunks)
347 (unless (null test-thunks)
348 (let ((total-test-count 0)
349 (total-pass-count 0)
350 (total-error-count 0))
351 (dolist (test-thunk test-thunks)
352 (multiple-value-bind (test-count pass-count error-count)
353 (run-test-thunk (car test-thunk) (cadr test-thunk))
354 (incf total-test-count test-count)
355 (incf total-pass-count pass-count)
356 (incf total-error-count error-count)))
357 (unless (null (cdr test-thunks))
358 (show-summary 'total total-test-count total-pass-count total-error-count))
359 (values))))
361 (defun run-test-thunk (*test-name* thunk)
362 (if (null thunk)
363 (format t "~& Test ~S not found" *test-name*)
364 (prog ((*test-count* 0)
365 (*pass-count* 0)
366 (error-count 0))
367 (handler-bind
368 ((error #'(lambda (e)
369 (let ((*print-escape* nil))
370 (setq error-count 1)
371 (format t "~& ~S: ~W" *test-name* e))
372 (if (use-debugger-p e) e (go exit)))))
373 (funcall thunk)
374 (show-summary *test-name* *test-count* *pass-count*))
375 exit
376 (return (values *test-count* *pass-count* error-count)))))
378 (defun use-debugger-p (e)
379 (and *use-debugger*
380 (or (not (eql *use-debugger* :ask))
381 (y-or-n-p "~A -- debug?" e))))
383 ;;; OUTPUT support
385 (defun get-failure-message (type)
386 (case type
387 (:error "~&~@[Should have signalled ~{~S~^; ~} but saw~] ~{~S~^; ~}")
388 (:macro "~&Should have expanded to ~{~S~^; ~} ~<~%~:;but saw ~{~S~^; ~}~>")
389 (:output "~&Should have printed ~{~S~^; ~} ~<~%~:;but saw ~{~S~^; ~}~>")
390 (t "~&Expected ~{~S~^; ~} ~<~%~:;but saw ~{~S~^; ~}~>")
393 (defun show-failure (type msg name form expected actual extras)
394 (format t "~&~@[~S: ~]~S failed: " name form)
395 (format t msg expected actual)
396 (format t "~{~& ~S => ~S~}~%" extras)
397 type)
399 (defun show-summary (name test-count pass-count &optional error-count)
400 (format t "~&~A: ~S assertions passed, ~S failed~@[, ~S execution errors~]."
401 name pass-count (- test-count pass-count) error-count))
403 (defun collect-form-values (form values)
404 (mapcan #'(lambda (form-arg value)
405 (if (constantp form-arg)
407 (list form-arg value)))
408 (cdr form)
409 values))
412 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
413 ;;; Useful equality predicates for tests
414 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
416 ;;; (LOGICALLY-EQUAL x y) => true or false
417 ;;; Return true if x and y both false or both true
419 (defun logically-equal (x y)
420 (eql (not x) (not y)))
422 ;;; (SET-EQUAL l1 l2 :test) => true or false
423 ;;; Return true if every element of l1 is an element of l2
424 ;;; and vice versa.
426 (defun set-equal (l1 l2 &key (test #'equal))
427 (and (listp l1)
428 (listp l2)
429 (subsetp l1 l2 :test test)
430 (subsetp l2 l1 :test test)))
432 ;;; (ROUNDOFF-ERROR x y) => number
433 ;;; Return the error delta between the exact and approximate floating
434 ;;; point value.
435 ;;; Equation 1.1 in NumLinAlg
436 (defun roundoff-error (exact approximate)
437 "Returned the error delta between the exact and approximate floating
438 point value."
439 (abs (if (or (= 0.0 exact) (= 0.0 approximate))
440 (+ exact approximate)
441 (- (/ approximate exact) 1.0))))
443 ;;; (FLOAT-EQUAL float1 float2 &optional epsilon) => true or false
444 ;;; Return true if the absolute difference between float1 and float2
445 ;;; is less than epsilon. If an epsilon is not specified and either
446 ;;; float1 or float2 is single precision, the single-float-epsilon is
447 ;;; used.
448 (defun float-equal (float1 float2 &optional epsilon)
449 "Return true if the absolute difference between float1 and float2 is
450 less than some epsilon."
451 (and
452 (floatp float1)
453 (floatp float2)
454 (cond
455 ((and (zerop float1) (zerop float2)))
456 (epsilon
457 (> epsilon (roundoff-error float1 float2)))
458 ((and (typep float1 'double-float) (typep float2 'double-float))
459 (> (* 2.0 double-float-epsilon) (roundoff-error float1 float2)))
460 ((or (typep float1 'single-float) (typep float2 'single-float))
461 (> (* 2.0 single-float-epsilon) (roundoff-error float1 float2)))
462 (t nil))))
464 ;;; (COMPLEX-EQUAL complex1 complex2 &optional epsilon) => true or false
465 ;;; Return true if the absolute difference of the real components and
466 ;;; the absolute difference of the imaginary components is less then
467 ;;; epsilon. If an epsilon is not specified and either complex1 or
468 ;;; complex2 is (complex single-float), the single-float-epsilon is
469 ;;; used.
470 (defun complex-equal (complex1 complex2 &optional epsilon)
471 "Return true if the absolute difference between Re(complex1),
472 Re(complex2) and the absolute difference between Im(complex1),
473 Im(complex2) is less than epsilon."
474 (and
475 (typep complex1 '(complex float))
476 (typep complex2 '(complex float))
477 (float-equal (realpart complex1) (realpart complex2) epsilon)
478 (float-equal (imagpart complex1) (imagpart complex2) epsilon)))
480 ;;; (NUMBER-EQUAL number1 number2) => true or false
481 ;;; Return true if the numbers are equal using the appropriate
482 ;;; comparison.
483 (defun number-equal (number1 number2 &optional epsilon)
484 "Return true if the numbers are equal using the appropriate
485 comparison."
486 (cond
487 ((and (floatp number1) (floatp number2))
488 (float-equal number1 number2 epsilon))
489 ((and (typep number1 '(complex float)) (typep number2 '(complex float)))
490 (complex-equal number1 number2 epsilon))
491 ((and (numberp number1) (numberp number2))
492 (= number1 number2))
493 (t (error "~A and ~A are not numbers." number1 number2))))
495 ;;; (ELEMENT-EQUAL array1 array2 indice dimensions) => true or false
496 ;;; A utility function for ARRAY-EQUAL.
497 (defun element-equal (array1 array2 indices dimensions &optional epsilon)
498 "Return true if the index of array1 equals array2."
499 (let* ((rank (first dimensions))
500 (remaining (rest dimensions))
501 (update-result
502 (if remaining
503 (lambda (index)
504 (element-equal array1 array2
505 (cons index indices) remaining epsilon))
506 (lambda (index)
507 (number-equal (apply #'aref array1 index (reverse indices))
508 (apply #'aref array2 index (reverse indices))
509 epsilon)))))
510 (do ((index 0 (1+ index))
511 (result t (funcall update-result index)))
512 ((or (not result) (>= index rank)) result))))
514 ;;; (DIMENSIONS-EQUAL array1 array2) => true or false
515 ;;; A utility function for ARRAY-EQUAL
516 (defun dimensions-equal (array1 array2)
517 "Return trun if ARRAY1 and ARRAY2 are equal dimensions."
518 (and
519 (= (array-rank array1) (array-rank array2))
520 (equal (array-dimensions array1) (array-dimensions array2))))
522 ;;; (ARRAY-EQUAL array1 array2) => true or false
523 ;;; Return true of the elements of the array are equal.
524 (defun array-equal (array1 array2 &optional epsilon)
525 "Return true if the elements of the array are equal."
526 (when (dimensions-equal array1 array2)
527 (element-equal array1 array2 nil (array-dimensions array1) epsilon)))
529 ;;; (NORMALIZE-FLOAT significand &optional exponent) => significand,exponent
530 (defun normalize-float (significand &optional (exponent 0))
531 "Return the normalized floating point number and exponent."
532 (cond
533 ((>= (abs significand) 10)
534 (normalize-float (* significand 0.10) (1+ exponent)))
535 ((< (abs significand) 1)
536 (normalize-float (* significand 10.0) (1- exponent)))
537 (t (values significand exponent))))
539 ;;; (SIGNIFICANT-FIGURES-EQUAL float1 float2 significant-figures) => true or false
540 (defun significant-figures-equal (float1 float2 significant-figures)
541 "Return true if the floating point numbers have equal significant
542 figures."
543 (multiple-value-bind (sig1 exp1) (normalize-float float1)
544 (multiple-value-bind (sig2 exp2) (normalize-float float2)
545 (and (= exp1 exp2)
546 (< (abs (- sig1 sig2))
547 (* (float 5 float1) (expt (float 10 float2) (- significant-figures))))))))
549 ;;;; References
550 ;;;; [NumLinAlg] James W. Demmel "Applied Numerical Linear Algebra",
551 ;;;; Society for Industrial and Applied Mathematics, 1997
552 ;;;; ISBN: 0-89871-389-7
554 (provide "lisp-unit")