1 ;;;-*- Mode: Lisp; Syntax: ANSI-Common-Lisp -*-
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.
28 1. Read the documentation at
:
29 https
://github.com
/OdonataResearchLLC
/lisp-unit
/wiki
31 2. Make a file of DEFINE-TEST
's. See exercise-tests.lisp for many
32 examples. If you want
, start your test file with
(REMOVE-TESTS :ALL
)
33 to clear any previously defined tests.
37 4.
(use-package :lisp-unit
)
39 5. Load your code file and your file of tests.
41 6. Test your code with
(RUN-TESTS '(test-name1 test-name2 ...
)) or
42 simply
(RUN-TESTS :ALL
) to run all defined tests.
44 A summary of how many tests passed and failed will be printed.
46 NOTE
: Nothing is compiled until RUN-TESTS is expanded. Redefining
47 functions or even macros does not require reloading any tests.
55 (defpackage :lisp-unit
58 (:export
:*print-summary
*
61 ;; Forms for assertions
72 ;; Functions for managing tests
80 ;; Functions for managing tags
85 ;; Functions for reporting test results
93 ;; Functions for extensibility via signals
94 (:export
:signal-results
98 (:export
:logically-equal
:set-equal
))
100 (in-package :lisp-unit
)
104 (defparameter *pass
* 0
105 "The passed assertion results.")
107 (defparameter *fail
* ()
108 "The failed assertion results.")
110 (defun reset-counters ()
111 "Reset the counters to empty lists."
112 (setf *pass
* 0 *fail
* ()))
116 (defparameter *print-summary
* nil
117 "Print a summary of the pass, fail, and error count if non-nil.")
119 (defparameter *print-failures
* nil
120 "Print failure messages if non-NIL.")
122 (defparameter *print-errors
* nil
123 "Print error messages if non-NIL.")
125 (defparameter *use-debugger
* nil
126 "If not NIL, enter the debugger when an error is encountered in an
129 (defparameter *signal-results
* nil
130 "Signal the result if non NIL.")
132 (defun use-debugger-p (condition)
133 "Debug or ignore errors."
135 ((eq :ask
*use-debugger
*)
136 (y-or-n-p "~A -- debug?" condition
))
139 (defun use-debugger (&optional
(flag t
))
140 "Use the debugger when testing, or not."
141 (setq *use-debugger
* flag
))
143 (defun signal-results (&optional
(flag t
))
144 "Signal the results for extensibility."
145 (setq *signal-results
* flag
))
147 ;;; Global unit test database
149 (defparameter *test-db
* (make-hash-table :test
#'eq
)
150 "The unit test database is simply a hash table.")
152 (defun package-table (package &optional create
)
154 ((gethash (find-package package
) *test-db
*))
156 (setf (gethash package
*test-db
*) (make-hash-table)))
157 (t (warn "No tests defined for package: ~S" package
))))
159 ;;; Global tags database
161 (defparameter *tag-db
* (make-hash-table :test
#'eq
)
162 "The tag database is simply a hash table.")
164 (defun package-tags (package &optional create
)
165 "Return the tags DB for the package."
167 ((gethash (find-package package
) *tag-db
*))
169 (setf (gethash package
*tag-db
*) (make-hash-table)))
170 (t (warn "No tags defined for package: ~S" package
))))
172 ;;; Unit test definition
174 (defclass unit-test
()
183 (:default-initargs
:doc
"" :code
())
185 "Organize the unit test documentation and code."))
187 ;;; NOTE: Shamelessly taken from PG's analyze-body
188 (defun parse-body (body &optional doc tag
)
189 "Separate the components of the body."
190 (let ((item (first body
)))
192 ((and (listp item
) (eq :tag
(first item
)))
193 (parse-body (rest body
) doc
(nconc (rest item
) tag
)))
194 ((and (stringp item
) (not doc
) (rest body
))
196 (values doc tag
(rest body
))
197 (parse-body (rest body
) doc tag
)))
198 (t (values doc tag body
)))))
200 (defun test-name-error-report (test-name-error stream
)
201 "Write the test-name-error to the stream."
202 (format stream
"Test name ~S is not of type ~A."
203 (type-error-datum test-name-error
)
204 (type-error-expected-type test-name-error
)))
206 (define-condition test-name-error
(type-error)
208 (:default-initargs
:expected-type
'symbol
)
209 (:report test-name-error-report
)
211 "The test name error is a type error."))
213 (defun valid-test-name (name)
214 "Signal a type-error if the test name is not a symbol."
217 (error 'test-name-error
:datum name
)))
219 (defmacro define-test
(name &body body
)
220 "Store the test in the test database."
221 (let ((qname (gensym "NAME-")))
222 (multiple-value-bind (doc tag code
) (parse-body body
)
223 `(let* ((,qname
,(valid-test-name name
))
224 (doc (or ,doc
(string ,qname
))))
227 (gethash ,qname
(package-table *package
* t
))
228 (make-instance 'unit-test
:doc doc
:code
',code
))
230 (loop for tag in
',tag do
232 ,qname
(gethash tag
(package-tags *package
* t
))))
233 ;; Return the name of the test
238 (defun list-tests (&optional
(package *package
*))
239 "Return a list of the tests in package."
240 (let ((table (package-table package
)))
242 (loop for test-name being each hash-key in table
243 collect test-name
))))
245 (defun test-documentation (name &optional
(package *package
*))
246 "Return the documentation for the test."
247 (let ((unit-test (gethash name
(package-table package
))))
249 (warn "No code defined for test ~A in package ~S."
253 (defun test-code (name &optional
(package *package
*))
254 "Returns the code stored for the test name."
255 (let ((unit-test (gethash name
(package-table package
))))
257 (warn "No code defined for test ~A in package ~S."
261 (defun remove-tests (names &optional
(package *package
*))
262 "Remove individual tests or entire sets."
267 (remhash (find-package package
) *test-db
*)
268 (remhash (find-package package
) *tag-db
*)))
269 (let ((table (package-table package
)))
272 (loop for name in names
273 unless
(remhash name table
) do
274 (warn "No test ~A in package ~A to remove."
275 name
(package-name package
)))
276 ;; Remove tests from tags
277 (loop with tags
= (package-tags package
)
278 for tag being each hash-key in tags
279 using
(hash-value tagged-tests
)
283 (set-difference tagged-tests names
)))))))
287 (defun %tests-from-all-tags
(&optional
(package *package
*))
288 "Return all of the tests that have been tagged."
289 (loop for tests being each hash-value in
(package-tags package
)
290 nconc
(copy-list tests
) into all-tests
291 finally
(return (delete-duplicates all-tests
))))
293 (defun %tests-from-tags
(tags &optional
(package *package
*))
294 "Return the tests associated with the tags."
295 (loop with table
= (package-tags package
)
297 as tests
= (gethash tag table
)
298 if
(null tests
) do
(warn "No tests tagged with ~S." tag
)
299 else nconc
(copy-list tests
) into all-tests
300 finally
(return (delete-duplicates all-tests
))))
302 (defun list-tags (&optional
(package *package
*))
303 "Return a list of the tags in package."
304 (let ((tags (package-tags package
)))
306 (loop for tag being each hash-key in tags collect tag
))))
308 (defun tagged-tests (tags &optional
(package *package
*))
309 "Return a list of the tests associated with the tags."
311 (%tests-from-all-tags package
)
312 (%tests-from-tags tags package
)))
314 (defun remove-tags (tags &optional
(package *package
*))
315 "Remove individual tags or entire sets."
319 (remhash (find-package package
) *tag-db
*))
320 (let ((table (package-tags package
)))
322 (loop for tag in tags
323 unless
(remhash tag table
) do
324 (warn "No tag ~A in package ~A to remove."
325 tag
(package-name package
)))))))
329 (defmacro assert-eq
(expected form
&rest extras
)
330 "Assert whether expected and form are EQ."
331 `(expand-assert :equal
,form
,form
,expected
,extras
:test
#'eq
))
333 (defmacro assert-eql
(expected form
&rest extras
)
334 "Assert whether expected and form are EQL."
335 `(expand-assert :equal
,form
,form
,expected
,extras
:test
#'eql
))
337 (defmacro assert-equal
(expected form
&rest extras
)
338 "Assert whether expected and form are EQUAL."
339 `(expand-assert :equal
,form
,form
,expected
,extras
:test
#'equal
))
341 (defmacro assert-equalp
(expected form
&rest extras
)
342 "Assert whether expected and form are EQUALP."
343 `(expand-assert :equal
,form
,form
,expected
,extras
:test
#'equalp
))
345 (defmacro assert-error
(condition form
&rest extras
)
346 "Assert whether form signals condition."
347 `(expand-assert :error
,form
(expand-error-form ,form
)
350 (defmacro assert-expands
(expansion form
&rest extras
)
351 "Assert whether form expands to expansion."
352 `(expand-assert :macro
,form
353 (expand-macro-form ,form nil
)
354 ',expansion
,extras
))
356 (defmacro assert-false
(form &rest extras
)
357 "Assert whether the form is false."
358 `(expand-assert :result
,form
,form nil
,extras
))
360 (defmacro assert-equality
(test expected form
&rest extras
)
361 "Assert whether expected and form are equal according to test."
362 `(expand-assert :equal
,form
,form
,expected
,extras
:test
,test
))
364 (defmacro assert-prints
(output form
&rest extras
)
365 "Assert whether printing the form generates the output."
366 `(expand-assert :output
,form
(expand-output-form ,form
)
369 (defmacro assert-true
(form &rest extras
)
370 "Assert whether the form is true."
371 `(expand-assert :result
,form
,form t
,extras
))
373 (defmacro expand-assert
(type form body expected extras
&key
(test '#'eql
))
374 "Expand the assertion to the internal format."
375 `(internal-assert ,type
',form
377 (lambda () ,expected
)
378 (expand-extras ,extras
)
381 (defmacro expand-error-form
(form)
382 "Wrap the error assertion in HANDLER-CASE."
384 (condition (error) error
)))
386 (defmacro expand-output-form
(form)
387 "Capture the output of the form in a string."
388 (let ((out (gensym)))
389 `(let* ((,out
(make-string-output-stream))
391 (make-broadcast-stream *standard-output
* ,out
)))
393 (get-output-stream-string ,out
))))
395 (defmacro expand-macro-form
(form env
)
396 "Expand the macro form once."
397 `(let ((*gensym-counter
* 1))
398 (macroexpand-1 ',form
,env
)))
400 (defmacro expand-extras
(extras)
401 "Expand extra forms."
403 (list ,@(mapcan (lambda (form) (list `',form form
)) extras
))))
405 (defgeneric assert-result
(type test expected actual
)
407 "Return the result of the assertion."))
409 (defclass failure-result
()
430 "Failure details of the assertion."))
432 (defclass equal-result
(failure-result)
435 "Result of a failed equal assertion."))
437 (defmethod assert-result ((type (eql :equal
)) test expected actual
)
438 "Return the result of an equal assertion."
440 (<= (length expected
) (length actual
))
441 (every test expected actual
)))
443 (defclass error-result
(failure-result)
446 "Result of a failed error assertion."))
448 (defmethod assert-result ((type (eql :error
)) test expected actual
)
449 "Return the result of an error assertion."
450 (declare (ignore test
))
452 (eql (car actual
) (car expected
))
453 (typep (car actual
) (car expected
))))
455 (defclass macro-result
(failure-result)
458 "Result of a failed macro expansion assertion."))
460 (defun %expansion-equal
(form1 form2
)
461 "Descend into the forms checking for equality."
462 (let ((item1 (first form1
))
463 (item2 (first form2
)))
465 ((and (null item1
) (null item2
)))
466 ((and (listp item1
) (listp item2
))
468 (%expansion-equal item1 item2
)
469 (%expansion-equal
(rest form1
) (rest form2
))))
470 ((and (symbolp item1
) (symbolp item2
))
472 (string= (symbol-name item1
) (symbol-name item2
))
473 (%expansion-equal
(rest form1
) (rest form2
))))
476 (%expansion-equal
(rest form1
) (rest form2
)))))))
478 (defmethod assert-result ((type (eql :macro
)) test expected actual
)
479 "Return the result of a macro assertion."
480 (declare (ignore test
))
481 (%expansion-equal
(first expected
) (first actual
)))
483 (defclass boolean-result
(failure-result)
486 "Result of a failed boolean assertion."))
488 (defmethod assert-result ((type (eql :result
)) test expected actual
)
489 "Return the result of a result assertion."
490 (declare (ignore test
))
491 (logically-equal (car actual
) (car expected
)))
493 (defclass output-result
(failure-result)
496 "Result of a failed output assertion."))
498 (defmethod assert-result ((type (eql :output
)) test expected actual
)
499 "Return the result of an output assertion."
500 (declare (ignore test
))
502 (string-trim '(#\newline
#\return
#\space
) (car actual
))
505 (defun assert-class (type)
506 "Return the class for the assertion type."
508 (:equal
'equal-result
)
509 (:error
'error-result
)
510 (:macro
'macro-result
)
511 (:result
'boolean-result
)
512 (:output
'output-result
)))
514 (defun internal-assert
515 (type form code-thunk expected-thunk extras test
)
516 "Perform the assertion and record the results."
517 (let* ((actual (multiple-value-list (funcall code-thunk
)))
518 (expected (multiple-value-list (funcall expected-thunk
)))
519 (result (assert-result type test expected actual
)))
527 :extras
(when extras
(funcall extras
))
533 ;;; Unit test results
535 (defclass test-result
()
555 "Test run time measured in internal time units"))
556 (:default-initargs
:exerr nil
)
558 "Store the results of the unit test."))
560 (defun print-summary (test-result &optional
561 (stream *standard-output
*))
562 "Print a summary of the test result."
563 (format stream
"~&~A: ~S assertions passed, ~S failed"
566 (length (fail test-result
)))
567 (if (exerr test-result
)
568 (format stream
", and an execution error.")
569 (write-char #\. stream
))
573 (defun run-code (code)
574 "Run the code to test the assertions."
575 (funcall (coerce `(lambda () ,@code
) 'function
)))
577 (defun run-test-thunk (name code
)
580 (start (get-internal-run-time)))
584 (if (use-debugger-p condition
)
586 (return-from run-test-thunk
592 :run-time
(- (get-internal-run-time) start
)
593 :exerr condition
))))))
595 ;; Return the result count
601 :run-time
(- (get-internal-run-time) start
))))
603 ;;; Test results database
605 (defclass test-results-db
()
608 :initform
(make-hash-table :test
#'eq
)
625 :accessor failed-tests
)
629 :accessor error-tests
)
633 :accessor missing-tests
))
635 "Store the results of the tests for further evaluation."))
637 (defmethod print-object ((object test-results-db
) stream
)
638 "Print the summary counts with the object."
639 (let ((pass (pass object
))
641 (exerr (exerr object
)))
643 stream
"#<~A Total(~D) Passed(~D) Failed(~D) Errors(~D)>~%"
644 (class-name (class-of object
))
645 (+ pass fail
) pass fail exerr
)))
647 (defun test-names (test-results-db)
648 "Return a list of the test names in the database."
649 (loop for name being each hash-key in
(database test-results-db
)
652 (defun record-result (test-name code results
)
653 "Run the test code and record the result."
654 (let ((result (run-test-thunk test-name code
)))
656 (setf (gethash test-name
(database results
)) result
)
657 ;; Count passed tests
658 (when (plusp (pass result
))
659 (incf (pass results
) (pass result
)))
660 ;; Count failed tests and record the name
662 (incf (fail results
) (length (fail result
)))
663 (push test-name
(failed-tests results
)))
664 ;; Count errors and record the name
666 (incf (exerr results
))
667 (push test-name
(error-tests results
)))
669 (when *print-failures
* (print-failures result
))
670 (when *print-errors
* (print-errors result
))
671 (when (or *print-summary
* *print-failures
* *print-errors
*)
672 (print-summary result
))))
674 (defun summarize-results (results &optional
675 (stream *standard-output
*))
676 "Print a summary of all results to the stream."
677 (let ((pass (pass results
))
678 (fail (fail results
)))
679 (format stream
"~&Unit Test Summary~%")
680 (format stream
" | ~D assertions total~%" (+ pass fail
))
681 (format stream
" | ~D passed~%" pass
)
682 (format stream
" | ~D failed~%" fail
)
683 (format stream
" | ~D execution errors~%" (exerr results
))
684 (format stream
" | ~D missing tests~2%"
685 (length (missing-tests results
)))))
689 (define-condition test-run-complete
()
691 :type
'test-results-db
695 "Signaled when a test run is finished."))
697 (defun %run-all-thunks
(&optional
(package *package
*))
698 "Run all of the test thunks in the package."
700 with results
= (make-instance 'test-results-db
)
701 for test-name being each hash-key in
(package-table package
)
702 using
(hash-value unit-test
)
704 (record-result test-name
(code unit-test
) results
)
706 (push test-name
(missing-tests results
))
707 ;; Summarize and return the test results
709 (when *signal-results
*
710 (signal 'test-run-complete
:results results
))
711 (summarize-results results
)
714 (defun %run-thunks
(test-names &optional
(package *package
*))
715 "Run the list of test thunks in the package."
717 with table
= (package-table package
)
718 and results
= (make-instance 'test-results-db
)
719 for test-name in test-names
720 as unit-test
= (gethash test-name table
)
722 (record-result test-name
(code unit-test
) results
)
724 (push test-name
(missing-tests results
))
726 (when *signal-results
*
727 (signal 'test-run-complete
:results results
))
728 (summarize-results results
)
731 (defun run-tests (test-names &optional
(package *package
*))
732 "Run the specified tests in package."
734 (if (eq :all test-names
)
735 (%run-all-thunks package
)
736 (%run-thunks test-names package
)))
738 (defun run-tags (tags &optional
(package *package
*))
739 "Run the tests associated with the specified tags in package."
741 (%run-thunks
(tagged-tests tags package
) package
))
745 (defgeneric print-failures
(result &optional stream
)
747 "Report the results of the failed assertion."))
749 (defmethod print-failures :around
((result failure-result
) &optional
750 (stream *standard-output
*))
751 "Failure header and footer output."
752 (format stream
"~& | Failed Form: ~S" (form result
))
754 (when (extras result
)
755 (format stream
"~{~& | ~S => ~S~}~%" (extras result
)))
756 (format stream
"~& |~%"))
758 (defmethod print-failures ((result failure-result
) &optional
759 (stream *standard-output
*))
760 (format stream
"~& | Expected ~{~S~^; ~} " (expected result
))
761 (format stream
"~<~% | ~:;but saw ~{~S~^; ~}~>" (actual result
)))
763 (defmethod print-failures ((result error-result
) &optional
764 (stream *standard-output
*))
765 (format stream
"~& | ~@[Should have signalled ~{~S~^; ~} but saw~]"
767 (format stream
" ~{~S~^; ~}" (actual result
)))
769 (defmethod print-failures ((result macro-result
) &optional
770 (stream *standard-output
*))
771 (format stream
"~& | Should have expanded to ~{~S~^; ~} "
773 (format stream
"~<~%~:;but saw ~{~S~^; ~}~>" (actual result
)))
775 (defmethod print-failures ((result output-result
) &optional
776 (stream *standard-output
*))
777 (format stream
"~& | Should have printed ~{~S~^; ~} "
779 (format stream
"~<~%~:;but saw ~{~S~^; ~}~>"
782 (defmethod print-failures ((result test-result
) &optional
783 (stream *standard-output
*))
784 "Print the failed assertions in the unit test."
785 (loop for fail in
(fail result
) do
786 (print-failures fail stream
)))
788 (defmethod print-failures ((results test-results-db
) &optional
789 (stream *standard-output
*))
790 "Print all of the failure tests."
791 (loop with db
= (database results
)
792 for test in
(failed-tests results
)
793 as result
= (gethash test db
)
795 (print-failures result stream
)
796 (print-summary result stream
)))
800 (defgeneric print-errors
(result &optional stream
)
802 "Print the error condition."))
804 (defmethod print-errors ((result test-result
) &optional
805 (stream *standard-output
*))
806 "Print the error condition."
807 (let ((exerr (exerr result
))
808 (*print-escape
* nil
))
810 (format stream
"~& | Execution error:~% | ~W" exerr
)
811 (format stream
"~& |~%"))))
813 (defmethod print-errors ((results test-results-db
) &optional
814 (stream *standard-output
*))
815 "Print all of the error tests."
816 (loop with db
= (database results
)
817 for test in
(error-tests results
)
818 as result
= (gethash test db
)
820 (print-errors result stream
)
821 (print-summary result stream
)))
823 ;;; Useful equality predicates for tests
825 (defun logically-equal (x y
)
826 "Return true if x and y are both false or both true."
827 (eql (not x
) (not y
)))
829 (defun set-equal (list1 list2
&rest initargs
&key key
(test #'equal
))
830 "Return true if every element of list1 is an element of list2 and
832 (declare (ignore key test
))
836 (apply #'subsetp list1 list2 initargs
)
837 (apply #'subsetp list2 list1 initargs
)))
839 (pushnew :lisp-unit common-lisp
:*features
*)