b63724c8f5cf23679777ea13690607d2004fa4e0
[lisp-unit.git] / lisp-unit.lisp
blobb63724c8f5cf23679777ea13690607d2004fa4e0
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.
25 How to use
26 ----------
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.
35 3. Load this file.
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.
51 ;;; Packages
53 (in-package :cl-user)
55 (defpackage :lisp-unit
56 (:use :common-lisp)
57 ;; Print parameters
58 (:export :*print-summary*
59 :*print-failures*
60 :*print-errors*)
61 ;; Forms for assertions
62 (:export :assert-eq
63 :assert-eql
64 :assert-equal
65 :assert-equalp
66 :assert-equality
67 :assert-prints
68 :assert-expands
69 :assert-true
70 :assert-false
71 :assert-error)
72 ;; Functions for managing tests
73 (:export :define-test
74 :list-tests
75 :test-code
76 :test-documentation
77 :remove-tests
78 :run-tests
79 :use-debugger)
80 ;; Functions for managing tags
81 (:export :list-tags
82 :tagged-tests
83 :remove-tags
84 :run-tags)
85 ;; Functions for reporting test results
86 (:export :test-names
87 :failed-tests
88 :error-tests
89 :missing-tests
90 :print-failures
91 :print-errors
92 :summarize-results)
93 ;; Functions for extensibility via signals
94 (:export :test-run-complete
95 :results)
96 ;; Utility predicates
97 (:export :logically-equal :set-equal))
99 (in-package :lisp-unit)
101 ;;; Global counters
103 (defparameter *pass* ()
104 "The passed assertion results.")
106 (defparameter *fail* ()
107 "The failed assertion results.")
109 (defun reset-counters ()
110 "Reset the counters to empty lists."
111 (setf *pass* () *fail* ()))
113 ;;; Global options
115 (defparameter *print-summary* nil
116 "Print a summary of the pass, fail, and error count if non-nil.")
118 (defparameter *print-failures* nil
119 "Print failure messages if non-NIL.")
121 (defparameter *print-errors* nil
122 "Print error messages if non-NIL.")
124 (defparameter *use-debugger* nil
125 "If not NIL, enter the debugger when an error is encountered in an
126 assertion.")
128 (defun use-debugger-p (condition)
129 "Debug or ignore errors."
130 (cond
131 ((eq :ask *use-debugger*)
132 (y-or-n-p "~A -- debug?" condition))
133 (*use-debugger*)))
135 (defun use-debugger (&optional (flag t))
136 "Use the debugger when testing, or not."
137 (setq *use-debugger* flag))
139 ;;; Global unit test database
141 (defparameter *test-db* (make-hash-table :test #'eq)
142 "The unit test database is simply a hash table.")
144 (defun package-table (package &optional create)
145 (cond
146 ((gethash (find-package package) *test-db*))
147 (create
148 (setf (gethash package *test-db*) (make-hash-table)))
149 (t (warn "No tests defined for package: ~S" package))))
151 ;;; Global tags database
153 (defparameter *tag-db* (make-hash-table :test #'eq)
154 "The tag database is simply a hash table.")
156 (defun package-tags (package &optional create)
157 "Return the tags DB for the package."
158 (cond
159 ((gethash (find-package package) *tag-db*))
160 (create
161 (setf (gethash package *tag-db*) (make-hash-table)))
162 (t (warn "No tags defined for package: ~S" package))))
164 ;;; Unit test definition
166 (defclass unit-test ()
167 ((doc
168 :type string
169 :initarg :doc
170 :reader doc)
171 (code
172 :type list
173 :initarg :code
174 :reader code))
175 (:default-initargs :doc "" :code ())
176 (:documentation
177 "Organize the unit test documentation and code."))
179 ;;; NOTE: Shamelessly taken from PG's analyze-body
180 (defun parse-body (body &optional doc tag)
181 "Separate the components of the body."
182 (let ((item (first body)))
183 (cond
184 ((and (listp item) (eq :tag (first item)))
185 (parse-body (rest body) doc (nconc (rest item) tag)))
186 ((and (stringp item) (not doc) (rest body))
187 (if tag
188 (values doc tag (rest body))
189 (parse-body (rest body) doc tag)))
190 (t (values doc tag body)))))
192 (defmacro define-test (name &body body)
193 "Store the test in the test database."
194 (let ((qname (gensym "NAME-")))
195 (multiple-value-bind (doc tag code) (parse-body body)
196 `(let* ((,qname ',name)
197 (doc (or ,doc (string ,qname))))
198 (setf
199 ;; Unit test
200 (gethash ,qname (package-table *package* t))
201 (make-instance 'unit-test :doc doc :code ',code))
202 ;; Tags
203 (loop for tag in ',tag do
204 (pushnew
205 ,qname (gethash tag (package-tags *package* t))))
206 ;; Return the name of the test
207 ,qname))))
209 ;;; Manage tests
211 (defun list-tests (&optional (package *package*))
212 "Return a list of the tests in package."
213 (let ((table (package-table package)))
214 (when table
215 (loop for test-name being each hash-key in table
216 collect test-name))))
218 (defun test-documentation (name &optional (package *package*))
219 "Return the documentation for the test."
220 (let ((unit-test (gethash name (package-table package))))
221 (if (null unit-test)
222 (warn "No code defined for test ~A in package ~S."
223 name package)
224 (doc unit-test))))
226 (defun test-code (name &optional (package *package*))
227 "Returns the code stored for the test name."
228 (let ((unit-test (gethash name (package-table package))))
229 (if (null unit-test)
230 (warn "No code defined for test ~A in package ~S."
231 name package)
232 (code unit-test))))
234 (defun remove-tests (names &optional (package *package*))
235 "Remove individual tests or entire sets."
236 (if (eq :all names)
237 (if (null package)
238 (clrhash *test-db*)
239 (progn
240 (remhash (find-package package) *test-db*)
241 (remhash (find-package package) *tag-db*)))
242 (let ((table (package-table package)))
243 (unless (null table)
244 ;; Remove tests
245 (loop for name in names
246 always (remhash name table)
247 collect name into removed
248 finally (return removed))
249 ;; Remove tests from tags
250 (loop with tags = (package-tags package)
251 for tag being each hash-key in tags
252 using (hash-value tagged-tests)
254 (setf
255 (gethash tag tags)
256 (set-difference tagged-tests names)))))))
258 ;;; Manage tags
260 (defun %tests-from-all-tags (&optional (package *package*))
261 "Return all of the tests that have been tagged."
262 (loop for tests being each hash-value in (package-tags package)
263 nconc (copy-list tests) into all-tests
264 finally (return (delete-duplicates all-tests))))
266 (defun %tests-from-tags (tags &optional (package *package*))
267 "Return the tests associated with the tags."
268 (loop with table = (package-tags package)
269 for tag in tags
270 as tests = (gethash tag table)
271 if (null tests) do (warn "No tests tagged with ~S." tag)
272 else nconc (copy-list tests) into all-tests
273 finally (return (delete-duplicates all-tests))))
275 (defun list-tags (&optional (package *package*))
276 "Return a list of the tags in package."
277 (let ((tags (package-tags package)))
278 (when tags
279 (loop for tag being each hash-key in tags collect tag))))
281 (defun tagged-tests (tags &optional (package *package*))
282 "Return a list of the tests associated with the tags."
283 (if (eq :all tags)
284 (%tests-from-all-tags package)
285 (%tests-from-tags tags package)))
287 (defun remove-tags (tags &optional (package *package*))
288 "Remove individual tags or entire sets."
289 (if (eq :all tags)
290 (if (null package)
291 (clrhash *tag-db*)
292 (remhash (find-package package) *tag-db*))
293 (let ((table (package-tags package)))
294 (unless (null table)
295 (loop for tag in tags
296 always (remhash tag table)
297 collect tag into removed
298 finally (return removed))))))
300 ;;; Assert macros
302 (defmacro assert-eq (expected form &rest extras)
303 "Assert whether expected and form are EQ."
304 `(expand-assert :equal ,form ,form ,expected ,extras :test #'eq))
306 (defmacro assert-eql (expected form &rest extras)
307 "Assert whether expected and form are EQL."
308 `(expand-assert :equal ,form ,form ,expected ,extras :test #'eql))
310 (defmacro assert-equal (expected form &rest extras)
311 "Assert whether expected and form are EQUAL."
312 `(expand-assert :equal ,form ,form ,expected ,extras :test #'equal))
314 (defmacro assert-equalp (expected form &rest extras)
315 "Assert whether expected and form are EQUALP."
316 `(expand-assert :equal ,form ,form ,expected ,extras :test #'equalp))
318 (defmacro assert-error (condition form &rest extras)
319 "Assert whether form signals condition."
320 `(expand-assert :error ,form (expand-error-form ,form)
321 ,condition ,extras))
323 (defmacro assert-expands (expansion form &rest extras)
324 "Assert whether form expands to expansion."
325 `(expand-assert :macro ,form
326 (expand-macro-form ,form nil)
327 ,expansion ,extras))
329 (defmacro assert-false (form &rest extras)
330 "Assert whether the form is false."
331 `(expand-assert :result ,form ,form nil ,extras))
333 (defmacro assert-equality (test expected form &rest extras)
334 "Assert whether expected and form are equal according to test."
335 `(expand-assert :equal ,form ,form ,expected ,extras :test ,test))
337 (defmacro assert-prints (output form &rest extras)
338 "Assert whether printing the form generates the output."
339 `(expand-assert :output ,form (expand-output-form ,form)
340 ,output ,extras))
342 (defmacro assert-true (form &rest extras)
343 "Assert whether the form is true."
344 `(expand-assert :result ,form ,form t ,extras))
346 (defmacro expand-assert (type form body expected extras &key (test '#'eql))
347 "Expand the assertion to the internal format."
348 `(internal-assert ,type ',form
349 (lambda () ,body)
350 (lambda () ,expected)
351 (expand-extras ,extras)
352 ,test))
354 (defmacro expand-error-form (form)
355 "Wrap the error assertion in HANDLER-CASE."
356 `(handler-case ,form
357 (condition (error) error)))
359 (defmacro expand-output-form (form)
360 "Capture the output of the form in a string."
361 (let ((out (gensym)))
362 `(let* ((,out (make-string-output-stream))
363 (*standard-output*
364 (make-broadcast-stream *standard-output* ,out)))
365 ,form
366 (get-output-stream-string ,out))))
368 (defmacro expand-macro-form (form env)
369 "Expand the macro form once."
370 `(macroexpand-1 ',form ,env))
372 (defmacro expand-extras (extras)
373 "Expand extra forms."
374 `(lambda ()
375 (list ,@(mapcan (lambda (form) (list `',form form)) extras))))
377 (defclass assert-result ()
378 ((form
379 :initarg :form
380 :reader form)
381 (actual
382 :type list
383 :initarg :actual
384 :reader actual)
385 (expected
386 :type list
387 :initarg :expected
388 :reader expected)
389 (extras
390 :type list
391 :initarg :extras
392 :reader extras)
393 (test
394 :type function
395 :initarg :test
396 :reader test)
397 (passed
398 :type boolean
399 :reader passed))
400 (:documentation
401 "Result of the assertion."))
403 (defclass equal-result (assert-result)
405 (:documentation
406 "Result of an equal assertion type."))
408 (defmethod initialize-instance :after ((self equal-result)
409 &rest initargs)
410 "Return the result of the equality assertion."
411 (with-slots (actual expected test passed) self
412 (setf passed
413 (and
414 (<= (length expected) (length actual))
415 (every test expected actual)))))
417 (defclass error-result (assert-result)
419 (:documentation
420 "Result of an error assertion type."))
422 (defmethod initialize-instance :after ((self error-result)
423 &rest initargs)
424 "Evaluate the result."
425 (with-slots (actual expected passed) self
426 (setf
427 passed
429 (eql (car actual) (car expected))
430 (typep (car actual) (car expected))))))
432 (defclass macro-result (assert-result)
434 (:documentation
435 "Result of a macro assertion type."))
437 (defmethod initialize-instance :after ((self macro-result)
438 &rest initargs)
439 "Return the result of the macro expansion."
440 (with-slots (actual expected passed) self
441 (setf passed (equal (car actual) (car expected)))))
443 (defclass boolean-result (assert-result)
445 (:documentation
446 "Result of a result assertion type."))
448 (defmethod initialize-instance :after ((self boolean-result)
449 &rest initargs)
450 "Return the result of the assertion."
451 (with-slots (actual expected passed) self
452 (setf passed (logically-equal (car actual) (car expected)))))
454 (defclass output-result (assert-result)
456 (:documentation
457 "Result of an output assertion type."))
459 (defmethod initialize-instance :after ((self output-result)
460 &rest initargs)
461 "Return the result of the printed output."
462 (with-slots (actual expected passed) self
463 (setf
464 passed
465 (string=
466 (string-trim '(#\newline #\return #\space) (car actual))
467 (car expected)))))
469 (defun assert-class (type)
470 "Return the class name for the assertion type."
471 (ecase type
472 (:equal 'equal-result)
473 (:error 'error-result)
474 (:macro 'macro-result)
475 (:result 'boolean-result)
476 (:output 'output-result)))
478 (defun internal-assert
479 (type form code-thunk expected-thunk extras test)
480 "Perform the assertion and record the results."
481 (let ((result
482 (make-instance
483 (assert-class type)
484 :form form
485 :actual (multiple-value-list (funcall code-thunk))
486 :expected (multiple-value-list (funcall expected-thunk))
487 :extras (when extras (funcall extras))
488 :test test)))
489 (if (passed result)
490 (push result *pass*)
491 (push result *fail*))
492 ;; Return the result
493 (passed result)))
495 ;;; Unit test results
497 (defclass test-result ()
498 ((name
499 :type symbol
500 :initarg :name
501 :reader name)
502 (pass
503 :type list
504 :initarg :pass
505 :reader pass)
506 (fail
507 :type list
508 :initarg :fail
509 :reader fail)
510 (exerr
511 :initarg :exerr
512 :reader exerr))
513 (:default-initargs :exerr nil)
514 (:documentation
515 "Store the results of the unit test."))
517 (defun print-summary (test-result)
518 "Print a summary of the test result."
519 (format t "~&~A: ~S assertions passed, ~S failed"
520 (name test-result)
521 (length (pass test-result))
522 (length (fail test-result)))
523 (if (exerr test-result)
524 (format t ", and an execution error.")
525 (write-char #\.))
526 (terpri)
527 (terpri))
529 (defun run-code (code)
530 "Run the code to test the assertions."
531 (funcall (coerce `(lambda () ,@code) 'function)))
533 (defun run-test-thunk (name code)
534 (let ((*pass* ())
535 (*fail* ()))
536 (handler-bind
537 ((error
538 (lambda (condition)
539 (if (use-debugger-p condition)
540 condition
541 (return-from run-test-thunk
542 (make-instance
543 'test-result
544 :name name
545 :pass *pass*
546 :fail *fail*
547 :exerr condition))))))
548 (run-code code))
549 ;; Return the result count
550 (make-instance 'test-result
551 :name name
552 :pass *pass*
553 :fail *fail*)))
555 ;;; Test results database
557 (defclass test-results-db ()
558 ((database
559 :type hash-table
560 :initform (make-hash-table :test #'eq)
561 :reader database)
562 (pass
563 :type fixnum
564 :initform 0
565 :accessor pass)
566 (fail
567 :type fixnum
568 :initform 0
569 :accessor fail)
570 (exerr
571 :type fixnum
572 :initform 0
573 :accessor exerr)
574 (failed-tests
575 :type list
576 :initform ()
577 :accessor failed-tests)
578 (error-tests
579 :type list
580 :initform ()
581 :accessor error-tests)
582 (missing-tests
583 :type list
584 :initform ()
585 :accessor missing-tests))
586 (:documentation
587 "Store the results of the tests for further evaluation."))
589 (defmethod print-object ((object test-results-db) stream)
590 "Print the summary counts with the object."
591 (let ((pass (pass object))
592 (fail (fail object))
593 (exerr (exerr object)))
594 (format
595 stream "#<~A Total(~D) Passed(~D) Failed(~D) Errors(~D)>~%"
596 (class-name (class-of object))
597 (+ pass fail) pass fail exerr)))
599 (defun test-names (test-results-db)
600 "Return a list of the test names in the database."
601 (loop for name being each hash-key in (database test-results-db)
602 collect name))
604 (defun record-result (test-name code results)
605 "Run the test code and record the result."
606 (let ((result (run-test-thunk test-name code)))
607 ;; Store the result
608 (setf (gethash test-name (database results)) result)
609 ;; Count passed tests
610 (when (pass result)
611 (incf (pass results) (length (pass result))))
612 ;; Count failed tests and record the name
613 (when (fail result)
614 (incf (fail results) (length (fail result)))
615 (push test-name (failed-tests results)))
616 ;; Count errors and record the name
617 (when (exerr result)
618 (incf (exerr results))
619 (push test-name (error-tests results)))
620 ;; Running output
621 (when *print-failures* (print-failures result))
622 (when *print-errors* (print-errors result))
623 (when (or *print-summary* *print-failures* *print-errors*)
624 (print-summary result))))
626 (defun summarize-results (results)
627 "Print a summary of all results."
628 (let ((pass (pass results))
629 (fail (fail results)))
630 (format t "~&Unit Test Summary~%")
631 (format t " | ~D assertions total~%" (+ pass fail))
632 (format t " | ~D passed~%" pass)
633 (format t " | ~D failed~%" fail)
634 (format t " | ~D execution errors~%" (exerr results))
635 (format t " | ~D missing tests~2%"
636 (length (missing-tests results)))))
638 ;;; Run the tests
639 (define-condition test-run-complete ()
640 ((results :initarg :results :reader results))
641 (:documentation "signaled when a test run is finished"))
643 (defun %run-all-thunks (&optional (package *package*))
644 "Run all of the test thunks in the package."
645 (loop
646 with results = (make-instance 'test-results-db)
647 for test-name being each hash-key in (package-table package)
648 using (hash-value unit-test)
649 if unit-test do
650 (record-result test-name (code unit-test) results)
651 else do
652 (push test-name (missing-tests results))
653 ;; Summarize and return the test results
654 finally
655 (summarize-results results)
656 (signal 'test-run-complete :results results)
657 (return results)))
659 (defun %run-thunks (test-names &optional (package *package*))
660 "Run the list of test thunks in the package."
661 (loop
662 with table = (package-table package)
663 and results = (make-instance 'test-results-db)
664 for test-name in test-names
665 as unit-test = (gethash test-name table)
666 if unit-test do
667 (record-result test-name (code unit-test) results)
668 else do
669 (push test-name (missing-tests results))
670 finally
671 (summarize-results results)
672 (signal 'test-run-complete :results results)
673 (return results)))
675 (defun run-tests (test-names &optional (package *package*))
676 "Run the specified tests in package."
677 (reset-counters)
678 (if (eq :all test-names)
679 (%run-all-thunks package)
680 (%run-thunks test-names package)))
682 (defun run-tags (tags &optional (package *package*))
683 "Run the tests associated with the specified tags in package."
684 (reset-counters)
685 (%run-thunks (tagged-tests tags package) package))
687 ;;; Print failures
689 (defgeneric print-failures (result)
690 (:documentation
691 "Report the results of the failed assertion."))
693 (defmethod print-failures :around ((result assert-result))
694 "Failure header and footer output."
695 (format t "~& | Failed Form: ~S" (form result))
696 (call-next-method)
697 (when (extras result)
698 (format t "~{~& | ~S => ~S~}~%" (extras result)))
699 (format t "~& |~%")
700 (class-name (class-of result)))
702 (defmethod print-failures ((result assert-result))
703 (format t "~& | Expected ~{~S~^; ~} " (expected result))
704 (format t "~<~% | ~:;but saw ~{~S~^; ~}~>" (actual result)))
706 (defmethod print-failures ((result error-result))
707 (format t "~& | ~@[Should have signalled ~{~S~^; ~} but saw~]"
708 (expected result))
709 (format t " ~{~S~^; ~}" (actual result)))
711 (defmethod print-failures ((result macro-result))
712 (format t "~& | Should have expanded to ~{~S~^; ~} "
713 (expected result))
714 (format t "~<~%~:;but saw ~{~S~^; ~}~>" (actual result)))
716 (defmethod print-failures ((result output-result))
717 (format t "~& | Should have printed ~{~S~^; ~} "
718 (expected result))
719 (format t "~<~%~:;but saw ~{~S~^; ~}~>"
720 (actual result)))
722 (defmethod print-failures ((result test-result))
723 "Print the failed assertions in the unit test."
724 (loop for fail in (fail result) do
725 (print-failures fail)))
727 (defmethod print-failures ((results test-results-db))
728 "Print all of the failure tests."
729 (loop with db = (database results)
730 for test in (failed-tests results)
731 as result = (gethash test db)
733 (print-failures result)
734 (print-summary result)))
736 ;;; Print errors
738 (defgeneric print-errors (result)
739 (:documentation
740 "Print the error condition."))
742 (defmethod print-errors ((result test-result))
743 "Print the error condition."
744 (let ((exerr (exerr result))
745 (*print-escape* nil))
746 (when exerr
747 (format t "~& | Execution error:~% | ~W" exerr)
748 (format t "~& |~%"))))
750 (defmethod print-errors ((results test-results-db))
751 "Print all of the error tests."
752 (loop with db = (database results)
753 for test in (error-tests results)
754 as result = (gethash test db)
756 (print-errors result)
757 (print-summary result)))
759 ;;; Useful equality predicates for tests
761 (defun logically-equal (x y)
762 "Return true if x and y are both false or both true."
763 (eql (not x) (not y)))
765 (defun set-equal (list1 list2 &rest initargs &key key (test #'equal))
766 "Return true if every element of list1 is an element of list2 and
767 vice versa."
768 (declare (ignore key test))
769 (and
770 (listp list1)
771 (listp list2)
772 (apply #'subsetp list1 list2 initargs)
773 (apply #'subsetp list2 list1 initargs)))
775 (pushnew :lisp-unit common-lisp:*features*)