0f2ffd90ddb84ffcaa50cd4ee65f1619393904d3
[lisp-unit.git] / lisp-unit.lisp
blob0f2ffd90ddb84ffcaa50cd4ee65f1619393904d3
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 ;; Utility predicates
94 (:export :logically-equal :set-equal))
96 (in-package :lisp-unit)
98 ;;; Global counters
100 (defparameter *pass* ()
101 "The passed assertion results.")
103 (defparameter *fail* ()
104 "The failed assertion results.")
106 (defun reset-counters ()
107 "Reset the counters to empty lists."
108 (setf *pass* () *fail* ()))
110 ;;; Global options
112 (defparameter *print-summary* nil
113 "Print a summary of the pass, fail, and error count if non-nil.")
115 (defparameter *print-failures* nil
116 "Print failure messages if non-NIL.")
118 (defparameter *print-errors* nil
119 "Print error messages if non-NIL.")
121 (defparameter *use-debugger* nil
122 "If not NIL, enter the debugger when an error is encountered in an
123 assertion.")
125 (defun use-debugger-p (condition)
126 "Debug or ignore errors."
127 (cond
128 ((eq :ask *use-debugger*)
129 (y-or-n-p "~A -- debug?" condition))
130 (*use-debugger*)))
132 (defun use-debugger (&optional (flag t))
133 "Use the debugger when testing, or not."
134 (setq *use-debugger* flag))
136 ;;; Global unit test database
138 (defparameter *test-db* (make-hash-table :test #'eq)
139 "The unit test database is simply a hash table.")
141 (defun package-table (package &optional create)
142 (cond
143 ((gethash (find-package package) *test-db*))
144 (create
145 (setf (gethash package *test-db*) (make-hash-table)))
146 (t (warn "No tests defined for package: ~S" package))))
148 ;;; Global tags database
150 (defparameter *tag-db* (make-hash-table :test #'eq)
151 "The tag database is simply a hash table.")
153 (defun package-tags (package &optional create)
154 "Return the tags DB for the package."
155 (cond
156 ((gethash (find-package package) *tag-db*))
157 (create
158 (setf (gethash package *tag-db*) (make-hash-table)))
159 (t (warn "No tags defined for package: ~S" package))))
161 ;;; Unit test definition
163 (defclass unit-test ()
164 ((doc
165 :type string
166 :initarg :doc
167 :reader doc)
168 (code
169 :type list
170 :initarg :code
171 :reader code))
172 (:default-initargs :doc "" :code ())
173 (:documentation
174 "Organize the unit test documentation and code."))
176 ;;; NOTE: Shamelessly taken from PG's analyze-body
177 (defun parse-body (body &optional doc tag)
178 "Separate the components of the body."
179 (let ((item (first body)))
180 (cond
181 ((and (listp item) (eq :tag (first item)))
182 (parse-body (rest body) doc (nconc (rest item) tag)))
183 ((and (stringp item) (not doc) (rest body))
184 (if tag
185 (values doc tag (rest body))
186 (parse-body (rest body) doc tag)))
187 (t (values doc tag body)))))
189 (defmacro define-test (name &body body)
190 "Store the test in the test database."
191 (multiple-value-bind (doc tag code) (parse-body body)
192 `(let ((doc (or ,doc (string ',name))))
193 (setf
194 ;; Unit test
195 (gethash ',name (package-table *package* t))
196 (make-instance 'unit-test :doc doc :code ',code))
197 ;; Tags
198 (loop for tag in ',tag do
199 (pushnew
200 ',name (gethash tag (package-tags *package* t))))
201 ;; Return the name of the test
202 ',name)))
204 ;;; Manage tests
206 (defun list-tests (&optional (package *package*))
207 "Return a list of the tests in package."
208 (let ((table (package-table package)))
209 (when table
210 (loop for test-name being each hash-key in table
211 collect test-name))))
213 (defun test-documentation (name &optional (package *package*))
214 "Return the documentation for the test."
215 (let ((unit-test (gethash name (package-table package))))
216 (if (null unit-test)
217 (warn "No code defined for test ~A in package ~S."
218 name package)
219 (doc unit-test))))
221 (defun test-code (name &optional (package *package*))
222 "Returns the code stored for the test name."
223 (let ((unit-test (gethash name (package-table package))))
224 (if (null unit-test)
225 (warn "No code defined for test ~A in package ~S."
226 name package)
227 (code unit-test))))
229 (defun remove-tests (names &optional (package *package*))
230 "Remove individual tests or entire sets."
231 (if (eq :all names)
232 (if (null package)
233 (clrhash *test-db*)
234 (progn
235 (remhash (find-package package) *test-db*)
236 (remhash (find-package package) *tag-db*)))
237 (let ((table (package-table package)))
238 (unless (null table)
239 ;; Remove tests
240 (loop for name in names
241 always (remhash name table)
242 collect name into removed
243 finally (return removed))
244 ;; Remove tests from tags
245 (loop with tags = (package-tags package)
246 for tag being each hash-key in tags
247 using (hash-value tagged-tests)
249 (setf
250 (gethash tag tags)
251 (set-difference tagged-tests names)))))))
253 ;;; Manage tags
255 (defun %tests-from-all-tags (&optional (package *package*))
256 "Return all of the tests that have been tagged."
257 (loop for tests being each hash-value in (package-tags package)
258 nconc (copy-list tests) into all-tests
259 finally (return (delete-duplicates all-tests))))
261 (defun %tests-from-tags (tags &optional (package *package*))
262 "Return the tests associated with the tags."
263 (loop with table = (package-tags package)
264 for tag in tags
265 as tests = (gethash tag table)
266 nconc (copy-list tests) into all-tests
267 finally (return (delete-duplicates all-tests))))
269 (defun list-tags (&optional (package *package*))
270 "Return a list of the tags in package."
271 (let ((tags (package-tags package)))
272 (when tags
273 (loop for tag being each hash-key in tags collect tag))))
275 (defun tagged-tests (tags &optional (package *package*))
276 "Run the tests associated with the specified tags in package."
277 (if (eq :all tags)
278 (%tests-from-all-tags package)
279 (%tests-from-tags tags package)))
281 (defun remove-tags (tags &optional (package *package*))
282 "Remove individual tags or entire sets."
283 (if (eq :all tags)
284 (if (null package)
285 (clrhash *tag-db*)
286 (remhash (find-package package) *tag-db*))
287 (let ((table (package-tags package)))
288 (unless (null table)
289 (loop for tag in tags
290 always (remhash tag table)
291 collect tag into removed
292 finally (return removed))))))
294 ;;; Assert macros
296 (defmacro assert-eq (expected form &rest extras)
297 "Assert whether expected and form are EQ."
298 `(expand-assert :equal ,form ,form ,expected ,extras :test #'eq))
300 (defmacro assert-eql (expected form &rest extras)
301 "Assert whether expected and form are EQL."
302 `(expand-assert :equal ,form ,form ,expected ,extras :test #'eql))
304 (defmacro assert-equal (expected form &rest extras)
305 "Assert whether expected and form are EQUAL."
306 `(expand-assert :equal ,form ,form ,expected ,extras :test #'equal))
308 (defmacro assert-equalp (expected form &rest extras)
309 "Assert whether expected and form are EQUALP."
310 `(expand-assert :equal ,form ,form ,expected ,extras :test #'equalp))
312 (defmacro assert-error (condition form &rest extras)
313 "Assert whether form signals condition."
314 `(expand-assert :error ,form (expand-error-form ,form)
315 ,condition ,extras))
317 (defmacro assert-expands (expansion form &rest extras)
318 "Assert whether form expands to expansion."
319 `(expand-assert :macro ,form
320 (expand-macro-form ,form nil)
321 ,expansion ,extras))
323 (defmacro assert-false (form &rest extras)
324 "Assert whether the form is false."
325 `(expand-assert :result ,form ,form nil ,extras))
327 (defmacro assert-equality (test expected form &rest extras)
328 "Assert whether expected and form are equal according to test."
329 `(expand-assert :equal ,form ,form ,expected ,extras :test ,test))
331 (defmacro assert-prints (output form &rest extras)
332 "Assert whether printing the form generates the output."
333 `(expand-assert :output ,form (expand-output-form ,form)
334 ,output ,extras))
336 (defmacro assert-true (form &rest extras)
337 "Assert whether the form is true."
338 `(expand-assert :result ,form ,form t ,extras))
340 (defmacro expand-assert (type form body expected extras &key (test '#'eql))
341 "Expand the assertion to the internal format."
342 `(internal-assert ,type ',form
343 (lambda () ,body)
344 (lambda () ,expected)
345 (expand-extras ,extras)
346 ,test))
348 (defmacro expand-error-form (form)
349 "Wrap the error assertion in HANDLER-CASE."
350 `(handler-case ,form
351 (condition (error) error)))
353 (defmacro expand-output-form (form)
354 "Capture the output of the form in a string."
355 (let ((out (gensym)))
356 `(let* ((,out (make-string-output-stream))
357 (*standard-output*
358 (make-broadcast-stream *standard-output* ,out)))
359 ,form
360 (get-output-stream-string ,out))))
362 (defmacro expand-macro-form (form env)
363 "Expand the macro form once."
364 `(macroexpand-1 ',form ,env))
366 (defmacro expand-extras (extras)
367 "Expand extra forms."
368 `(lambda ()
369 (list ,@(mapcan (lambda (form) (list `',form form)) extras))))
371 (defclass assert-result ()
372 ((form
373 :initarg :form
374 :reader form)
375 (actual
376 :type list
377 :initarg :actual
378 :reader actual)
379 (expected
380 :type list
381 :initarg :expected
382 :reader expected)
383 (extras
384 :type list
385 :initarg :extras
386 :reader extras)
387 (test
388 :type function
389 :initarg :test
390 :reader test)
391 (passed
392 :type boolean
393 :reader passed))
394 (:documentation
395 "Result of the assertion."))
397 (defmethod initialize-instance :after ((self assert-result)
398 &rest initargs)
399 "Evaluate the actual and expected forms"
400 (with-slots (actual expected) self
401 (setf
402 actual (multiple-value-list (funcall actual))
403 expected (multiple-value-list (funcall expected))))
404 ;; Generate extras
405 (when (slot-boundp self 'extras)
406 (setf
407 (slot-value self 'extras)
408 (funcall (slot-value self 'extras)))))
410 (defclass equal-result (assert-result)
412 (:documentation
413 "Result of an equal assertion type."))
415 (defmethod initialize-instance :after ((self equal-result)
416 &rest initargs)
417 "Return the result of the equality assertion."
418 (with-slots (actual expected test passed) self
419 (setf
420 passed
421 (and
422 (<= (length expected) (length actual))
423 (every test expected actual)))))
425 (defclass error-result (assert-result)
427 (:documentation
428 "Result of an error assertion type."))
430 (defmethod initialize-instance :after ((self error-result)
431 &rest initargs)
432 "Evaluate the result."
433 (with-slots (actual expected passed) self
434 (setf
435 passed
437 (eql (car actual) (car expected))
438 (typep (car actual) (car expected))))))
440 (defclass macro-result (assert-result)
442 (:documentation
443 "Result of a macro assertion type."))
445 (defmethod initialize-instance :after ((self macro-result)
446 &rest initargs)
447 "Return the result of the macro expansion."
448 (with-slots (actual expected passed) self
449 (setf passed (equal (car actual) (car expected)))))
451 (defclass boolean-result (assert-result)
453 (:documentation
454 "Result of a result assertion type."))
456 (defmethod initialize-instance :after ((self boolean-result)
457 &rest initargs)
458 "Return the result of the assertion."
459 (with-slots (actual expected passed) self
460 (setf passed (logically-equal (car actual) (car expected)))))
462 (defclass output-result (assert-result)
464 (:documentation
465 "Result of an output assertion type."))
467 (defmethod initialize-instance :after ((self output-result)
468 &rest initargs)
469 "Return the result of the printed output."
470 (with-slots (actual expected passed) self
471 (setf
472 passed
473 (string=
474 (string-trim '(#\newline #\return #\space) (car actual))
475 (car expected)))))
477 (defun assert-class (type)
478 "Return the class name for the assertion type."
479 (ecase type
480 (:equal 'equal-result)
481 (:error 'error-result)
482 (:macro 'macro-result)
483 (:result 'boolean-result)
484 (:output 'output-result)))
486 (defun internal-assert
487 (type form code-thunk expected-thunk extras test)
488 "Perform the assertion and record the results."
489 (let ((result
490 (make-instance (assert-class type)
491 :form form
492 :actual code-thunk
493 :expected expected-thunk
494 :extras extras
495 :test test)))
496 (if (passed result)
497 (push result *pass*)
498 (push result *fail*))
499 ;; Return the result
500 (passed result)))
502 ;;; Unit test results
504 (defclass test-result ()
505 ((name
506 :type symbol
507 :initarg :name
508 :reader name)
509 (pass
510 :type list
511 :initarg :pass
512 :reader pass)
513 (fail
514 :type list
515 :initarg :fail
516 :reader fail)
517 (exerr
518 :type condition
519 :initarg :exerr
520 :reader exerr))
521 (:default-initargs :exerr nil)
522 (:documentation
523 "Store the results of the unit test."))
525 (defun print-summary (test-result)
526 "Print a summary of the test result."
527 (format t "~&~A: ~S assertions passed, ~S failed"
528 (name test-result)
529 (length (pass test-result))
530 (length (fail test-result)))
531 (if (exerr test-result)
532 (format t ", and an execution error.")
533 (write-char #\.))
534 (terpri)
535 (terpri))
537 (defun run-code (code)
538 "Run the code to test the assertions."
539 (funcall (coerce `(lambda () ,@code) 'function)))
541 (defun run-test-thunk (name code)
542 (let ((*pass* ())
543 (*fail* ()))
544 (handler-bind
545 ((error
546 (lambda (condition)
547 (if (use-debugger-p condition)
548 condition
549 (return-from run-test-thunk
550 (make-instance
551 'test-result
552 :name name
553 :pass *pass*
554 :fail *fail*
555 :exerr condition))))))
556 (run-code code))
557 ;; Return the result count
558 (make-instance 'test-result
559 :name name
560 :pass *pass*
561 :fail *fail*)))
563 ;;; Test results database
565 (defclass test-results-db ()
566 ((database
567 :type hash-table
568 :initform (make-hash-table :test #'eq)
569 :reader database)
570 (pass
571 :type fixnum
572 :initform 0
573 :accessor pass)
574 (fail
575 :type fixnum
576 :initform 0
577 :accessor fail)
578 (exerr
579 :type fixnum
580 :initform 0
581 :accessor exerr)
582 (failed-tests
583 :type list
584 :initform ()
585 :accessor failed-tests)
586 (error-tests
587 :type list
588 :initform ()
589 :accessor error-tests)
590 (missing-tests
591 :type list
592 :initform ()
593 :accessor missing-tests))
594 (:documentation
595 "Store the results of the tests for further evaluation."))
597 (defmethod print-object ((object test-results-db) stream)
598 "Print the summary counts with the object."
599 (let ((pass (pass object))
600 (fail (fail object))
601 (exerr (exerr object)))
602 (format
603 stream "#<~A Total(~D) Passed(~D) Failed(~D) Errors(~D)>~%"
604 (class-name (class-of object))
605 (+ pass fail) pass fail exerr)))
607 (defun test-names (test-results-db)
608 "Return a list of the test names in the database."
609 (loop for name being each hash-key in (database test-results-db)
610 collect name))
612 (defun record-result (test-name code results)
613 "Run the test code and record the result."
614 (let ((result (run-test-thunk test-name code)))
615 ;; Store the result
616 (setf (gethash test-name (database results)) result)
617 ;; Count passed tests
618 (when (pass result)
619 (incf (pass results) (length (pass result))))
620 ;; Count failed tests and record the name
621 (when (fail result)
622 (incf (fail results) (length (fail result)))
623 (push test-name (failed-tests results)))
624 ;; Count errors and record the name
625 (when (exerr result)
626 (incf (exerr results))
627 (push test-name (error-tests results)))
628 ;; Running output
629 (when *print-failures* (print-failures result))
630 (when *print-errors* (print-errors result))
631 (when (or *print-summary* *print-failures* *print-errors*)
632 (print-summary result))))
634 (defun summarize-results (results)
635 "Print a summary of all results."
636 (let ((pass (pass results))
637 (fail (fail results)))
638 (format t "~&Unit Test Summary~%")
639 (format t " | ~D assertions total~%" (+ pass fail))
640 (format t " | ~D passed~%" pass)
641 (format t " | ~D failed~%" fail)
642 (format t " | ~D execution errors~%" (exerr results))
643 (format t " | ~D missing tests~2%"
644 (length (missing-tests results)))))
646 ;;; Run the tests
648 (defun %run-all-thunks (&optional (package *package*))
649 "Run all of the test thunks in the package."
650 (loop
651 with results = (make-instance 'test-results-db)
652 for test-name being each hash-key in (package-table package)
653 using (hash-value unit-test)
654 if unit-test do
655 (record-result test-name (code unit-test) results)
656 else do
657 (push test-name (missing-tests results))
658 ;; Summarize and return the test results
659 finally
660 (summarize-results results)
661 (return results)))
663 (defun %run-thunks (test-names &optional (package *package*))
664 "Run the list of test thunks in the package."
665 (loop
666 with table = (package-table package)
667 and results = (make-instance 'test-results-db)
668 for test-name in test-names
669 as unit-test = (gethash test-name table)
670 if unit-test do
671 (record-result test-name (code unit-test) results)
672 else do
673 (push test-name (missing-tests results))
674 finally
675 (summarize-results results)
676 (return results)))
678 (defun run-tests (test-names &optional (package *package*))
679 "Run the specified tests in package."
680 (reset-counters)
681 (if (eq :all test-names)
682 (%run-all-thunks package)
683 (%run-thunks test-names package)))
685 (defun run-tags (tags &optional (package *package*))
686 "Run the tests associated with the specified tags in package."
687 (reset-counters)
688 (%run-thunks (tagged-tests tags package) package))
690 ;;; Print failures
692 (defgeneric print-failures (result)
693 (:documentation
694 "Report the results of the failed assertion."))
696 (defmethod print-failures :around ((result assert-result))
697 "Failure header and footer output."
698 (format t "~& | Failed Form: ~S" (form result))
699 (call-next-method)
700 (when (extras result)
701 (format t "~{~& | ~S => ~S~}~%" (extras result)))
702 (format t "~& |~%")
703 (class-name (class-of result)))
705 (defmethod print-failures ((result assert-result))
706 (format t "~& | Expected ~{~S~^; ~} " (expected result))
707 (format t "~<~% | ~:;but saw ~{~S~^; ~}~>" (actual result)))
709 (defmethod print-failures ((result error-result))
710 (format t "~& | ~@[Should have signalled ~{~S~^; ~} but saw~]"
711 (expected result))
712 (format t " ~{~S~^; ~}" (actual result)))
714 (defmethod print-failures ((result macro-result))
715 (format t "~& | Should have expanded to ~{~S~^; ~} "
716 (expected result))
717 (format t "~<~%~:;but saw ~{~S~^; ~}~>" (actual result)))
719 (defmethod print-failures ((result output-result))
720 (format t "~& | Should have printed ~{~S~^; ~} "
721 (expected result))
722 (format t "~<~%~:;but saw ~{~S~^; ~}~>"
723 (actual result)))
725 (defmethod print-failures ((result test-result))
726 "Print the failed assertions in the unit test."
727 (loop for fail in (fail result) do
728 (print-failures fail)))
730 (defmethod print-failures ((results test-results-db))
731 "Print all of the failure tests."
732 (loop with db = (database results)
733 for test in (failed-tests results)
734 as result = (gethash test db)
736 (print-failures result)
737 (print-summary result)))
739 ;;; Print errors
741 (defgeneric print-errors (result)
742 (:documentation
743 "Print the error condition."))
745 (defmethod print-errors ((result test-result))
746 "Print the error condition."
747 (let ((exerr (exerr result))
748 (*print-escape* nil))
749 (when exerr
750 (format t "~& | Execution error:~% | ~W" exerr)
751 (format t "~& |~%"))))
753 (defmethod print-errors ((results test-results-db))
754 "Print all of the error tests."
755 (loop with db = (database results)
756 for test in (error-tests results)
757 as result = (gethash test db)
759 (print-errors result)
760 (print-summary result)))
762 ;;; Useful equality predicates for tests
764 (defun logically-equal (x y)
765 "Return true if x and y are both false or both true."
766 (eql (not x) (not y)))
768 (defun set-equal (list1 list2 &rest initargs &key key (test #'equal))
769 "Return true if every element of list1 is an element of list2 and
770 vice versa."
771 (declare (ignore key test))
772 (and
773 (listp list1)
774 (listp list2)
775 (apply #'subsetp list1 list2 initargs)
776 (apply #'subsetp list2 list1 initargs)))
778 (pushnew :lisp-unit common-lisp:*features*)