d2a88db9ca55f80b6461ed67882c1a6a611642b8
[lisp-unit.git] / lisp-unit.lisp
blobd2a88db9ca55f80b6461ed67882c1a6a611642b8
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 (let ((qname (gensym "NAME-")))
192 (multiple-value-bind (doc tag code) (parse-body body)
193 `(let* ((,qname ',name)
194 (doc (or ,doc (string ,qname))))
195 (setf
196 ;; Unit test
197 (gethash ,qname (package-table *package* t))
198 (make-instance 'unit-test :doc doc :code ',code))
199 ;; Tags
200 (loop for tag in ',tag do
201 (pushnew
202 ,qname (gethash tag (package-tags *package* t))))
203 ;; Return the name of the test
204 ,qname))))
206 ;;; Manage tests
208 (defun list-tests (&optional (package *package*))
209 "Return a list of the tests in package."
210 (let ((table (package-table package)))
211 (when table
212 (loop for test-name being each hash-key in table
213 collect test-name))))
215 (defun test-documentation (name &optional (package *package*))
216 "Return the documentation for the test."
217 (let ((unit-test (gethash name (package-table package))))
218 (if (null unit-test)
219 (warn "No code defined for test ~A in package ~S."
220 name package)
221 (doc unit-test))))
223 (defun test-code (name &optional (package *package*))
224 "Returns the code stored for the test name."
225 (let ((unit-test (gethash name (package-table package))))
226 (if (null unit-test)
227 (warn "No code defined for test ~A in package ~S."
228 name package)
229 (code unit-test))))
231 (defun remove-tests (names &optional (package *package*))
232 "Remove individual tests or entire sets."
233 (if (eq :all names)
234 (if (null package)
235 (clrhash *test-db*)
236 (progn
237 (remhash (find-package package) *test-db*)
238 (remhash (find-package package) *tag-db*)))
239 (let ((table (package-table package)))
240 (unless (null table)
241 ;; Remove tests
242 (loop for name in names
243 always (remhash name table)
244 collect name into removed
245 finally (return removed))
246 ;; Remove tests from tags
247 (loop with tags = (package-tags package)
248 for tag being each hash-key in tags
249 using (hash-value tagged-tests)
251 (setf
252 (gethash tag tags)
253 (set-difference tagged-tests names)))))))
255 ;;; Manage tags
257 (defun %tests-from-all-tags (&optional (package *package*))
258 "Return all of the tests that have been tagged."
259 (loop for tests being each hash-value in (package-tags package)
260 nconc (copy-list tests) into all-tests
261 finally (return (delete-duplicates all-tests))))
263 (defun %tests-from-tags (tags &optional (package *package*))
264 "Return the tests associated with the tags."
265 (loop with table = (package-tags package)
266 for tag in tags
267 as tests = (gethash tag table)
268 if (null tests) do (warn "No tests tagged with ~S." tag)
269 else nconc (copy-list tests) into all-tests
270 finally (return (delete-duplicates all-tests))))
272 (defun list-tags (&optional (package *package*))
273 "Return a list of the tags in package."
274 (let ((tags (package-tags package)))
275 (when tags
276 (loop for tag being each hash-key in tags collect tag))))
278 (defun tagged-tests (tags &optional (package *package*))
279 "Return a list of the tests associated with the tags."
280 (if (eq :all tags)
281 (%tests-from-all-tags package)
282 (%tests-from-tags tags package)))
284 (defun remove-tags (tags &optional (package *package*))
285 "Remove individual tags or entire sets."
286 (if (eq :all tags)
287 (if (null package)
288 (clrhash *tag-db*)
289 (remhash (find-package package) *tag-db*))
290 (let ((table (package-tags package)))
291 (unless (null table)
292 (loop for tag in tags
293 always (remhash tag table)
294 collect tag into removed
295 finally (return removed))))))
297 ;;; Assert macros
299 (defmacro assert-eq (expected form &rest extras)
300 "Assert whether expected and form are EQ."
301 `(expand-assert :equal ,form ,form ,expected ,extras :test #'eq))
303 (defmacro assert-eql (expected form &rest extras)
304 "Assert whether expected and form are EQL."
305 `(expand-assert :equal ,form ,form ,expected ,extras :test #'eql))
307 (defmacro assert-equal (expected form &rest extras)
308 "Assert whether expected and form are EQUAL."
309 `(expand-assert :equal ,form ,form ,expected ,extras :test #'equal))
311 (defmacro assert-equalp (expected form &rest extras)
312 "Assert whether expected and form are EQUALP."
313 `(expand-assert :equal ,form ,form ,expected ,extras :test #'equalp))
315 (defmacro assert-error (condition form &rest extras)
316 "Assert whether form signals condition."
317 `(expand-assert :error ,form (expand-error-form ,form)
318 ,condition ,extras))
320 (defmacro assert-expands (expansion form &rest extras)
321 "Assert whether form expands to expansion."
322 `(expand-assert :macro ,form
323 (expand-macro-form ,form nil)
324 ,expansion ,extras))
326 (defmacro assert-false (form &rest extras)
327 "Assert whether the form is false."
328 `(expand-assert :result ,form ,form nil ,extras))
330 (defmacro assert-equality (test expected form &rest extras)
331 "Assert whether expected and form are equal according to test."
332 `(expand-assert :equal ,form ,form ,expected ,extras :test ,test))
334 (defmacro assert-prints (output form &rest extras)
335 "Assert whether printing the form generates the output."
336 `(expand-assert :output ,form (expand-output-form ,form)
337 ,output ,extras))
339 (defmacro assert-true (form &rest extras)
340 "Assert whether the form is true."
341 `(expand-assert :result ,form ,form t ,extras))
343 (defmacro expand-assert (type form body expected extras &key (test '#'eql))
344 "Expand the assertion to the internal format."
345 `(internal-assert ,type ',form
346 (lambda () ,body)
347 (lambda () ,expected)
348 (expand-extras ,extras)
349 ,test))
351 (defmacro expand-error-form (form)
352 "Wrap the error assertion in HANDLER-CASE."
353 `(handler-case ,form
354 (condition (error) error)))
356 (defmacro expand-output-form (form)
357 "Capture the output of the form in a string."
358 (let ((out (gensym)))
359 `(let* ((,out (make-string-output-stream))
360 (*standard-output*
361 (make-broadcast-stream *standard-output* ,out)))
362 ,form
363 (get-output-stream-string ,out))))
365 (defmacro expand-macro-form (form env)
366 "Expand the macro form once."
367 `(macroexpand-1 ',form ,env))
369 (defmacro expand-extras (extras)
370 "Expand extra forms."
371 `(lambda ()
372 (list ,@(mapcan (lambda (form) (list `',form form)) extras))))
374 (defclass assert-result ()
375 ((form
376 :initarg :form
377 :reader form)
378 (actual
379 :type list
380 :initarg :actual
381 :reader actual)
382 (expected
383 :type list
384 :initarg :expected
385 :reader expected)
386 (extras
387 :type list
388 :initarg :extras
389 :reader extras)
390 (test
391 :type function
392 :initarg :test
393 :reader test)
394 (passed
395 :type boolean
396 :reader passed))
397 (:documentation
398 "Result of the assertion."))
400 (defclass equal-result (assert-result)
402 (:documentation
403 "Result of an equal assertion type."))
405 (defmethod initialize-instance :after ((self equal-result)
406 &rest initargs)
407 "Return the result of the equality assertion."
408 (with-slots (actual expected test passed) self
409 (setf passed
410 (and
411 (<= (length expected) (length actual))
412 (every test expected actual)))))
414 (defclass error-result (assert-result)
416 (:documentation
417 "Result of an error assertion type."))
419 (defmethod initialize-instance :after ((self error-result)
420 &rest initargs)
421 "Evaluate the result."
422 (with-slots (actual expected passed) self
423 (setf
424 passed
426 (eql (car actual) (car expected))
427 (typep (car actual) (car expected))))))
429 (defclass macro-result (assert-result)
431 (:documentation
432 "Result of a macro assertion type."))
434 (defmethod initialize-instance :after ((self macro-result)
435 &rest initargs)
436 "Return the result of the macro expansion."
437 (with-slots (actual expected passed) self
438 (setf passed (equal (car actual) (car expected)))))
440 (defclass boolean-result (assert-result)
442 (:documentation
443 "Result of a result assertion type."))
445 (defmethod initialize-instance :after ((self boolean-result)
446 &rest initargs)
447 "Return the result of the assertion."
448 (with-slots (actual expected passed) self
449 (setf passed (logically-equal (car actual) (car expected)))))
451 (defclass output-result (assert-result)
453 (:documentation
454 "Result of an output assertion type."))
456 (defmethod initialize-instance :after ((self output-result)
457 &rest initargs)
458 "Return the result of the printed output."
459 (with-slots (actual expected passed) self
460 (setf
461 passed
462 (string=
463 (string-trim '(#\newline #\return #\space) (car actual))
464 (car expected)))))
466 (defun assert-class (type)
467 "Return the class name for the assertion type."
468 (ecase type
469 (:equal 'equal-result)
470 (:error 'error-result)
471 (:macro 'macro-result)
472 (:result 'boolean-result)
473 (:output 'output-result)))
475 (defun internal-assert
476 (type form code-thunk expected-thunk extras test)
477 "Perform the assertion and record the results."
478 (let ((result
479 (make-instance
480 (assert-class type)
481 :form form
482 :actual (multiple-value-list (funcall code-thunk))
483 :expected (multiple-value-list (funcall expected-thunk))
484 :extras (when extras (funcall extras))
485 :test test)))
486 (if (passed result)
487 (push result *pass*)
488 (push result *fail*))
489 ;; Return the result
490 (passed result)))
492 ;;; Unit test results
494 (defclass test-result ()
495 ((name
496 :type symbol
497 :initarg :name
498 :reader name)
499 (pass
500 :type list
501 :initarg :pass
502 :reader pass)
503 (fail
504 :type list
505 :initarg :fail
506 :reader fail)
507 (exerr
508 :initarg :exerr
509 :reader exerr))
510 (:default-initargs :exerr nil)
511 (:documentation
512 "Store the results of the unit test."))
514 (defun print-summary (test-result)
515 "Print a summary of the test result."
516 (format t "~&~A: ~S assertions passed, ~S failed"
517 (name test-result)
518 (length (pass test-result))
519 (length (fail test-result)))
520 (if (exerr test-result)
521 (format t ", and an execution error.")
522 (write-char #\.))
523 (terpri)
524 (terpri))
526 (defun run-code (code)
527 "Run the code to test the assertions."
528 (funcall (coerce `(lambda () ,@code) 'function)))
530 (defun run-test-thunk (name code)
531 (let ((*pass* ())
532 (*fail* ()))
533 (handler-bind
534 ((error
535 (lambda (condition)
536 (if (use-debugger-p condition)
537 condition
538 (return-from run-test-thunk
539 (make-instance
540 'test-result
541 :name name
542 :pass *pass*
543 :fail *fail*
544 :exerr condition))))))
545 (run-code code))
546 ;; Return the result count
547 (make-instance 'test-result
548 :name name
549 :pass *pass*
550 :fail *fail*)))
552 ;;; Test results database
554 (defclass test-results-db ()
555 ((database
556 :type hash-table
557 :initform (make-hash-table :test #'eq)
558 :reader database)
559 (pass
560 :type fixnum
561 :initform 0
562 :accessor pass)
563 (fail
564 :type fixnum
565 :initform 0
566 :accessor fail)
567 (exerr
568 :type fixnum
569 :initform 0
570 :accessor exerr)
571 (failed-tests
572 :type list
573 :initform ()
574 :accessor failed-tests)
575 (error-tests
576 :type list
577 :initform ()
578 :accessor error-tests)
579 (missing-tests
580 :type list
581 :initform ()
582 :accessor missing-tests))
583 (:documentation
584 "Store the results of the tests for further evaluation."))
586 (defmethod print-object ((object test-results-db) stream)
587 "Print the summary counts with the object."
588 (let ((pass (pass object))
589 (fail (fail object))
590 (exerr (exerr object)))
591 (format
592 stream "#<~A Total(~D) Passed(~D) Failed(~D) Errors(~D)>~%"
593 (class-name (class-of object))
594 (+ pass fail) pass fail exerr)))
596 (defun test-names (test-results-db)
597 "Return a list of the test names in the database."
598 (loop for name being each hash-key in (database test-results-db)
599 collect name))
601 (defun record-result (test-name code results)
602 "Run the test code and record the result."
603 (let ((result (run-test-thunk test-name code)))
604 ;; Store the result
605 (setf (gethash test-name (database results)) result)
606 ;; Count passed tests
607 (when (pass result)
608 (incf (pass results) (length (pass result))))
609 ;; Count failed tests and record the name
610 (when (fail result)
611 (incf (fail results) (length (fail result)))
612 (push test-name (failed-tests results)))
613 ;; Count errors and record the name
614 (when (exerr result)
615 (incf (exerr results))
616 (push test-name (error-tests results)))
617 ;; Running output
618 (when *print-failures* (print-failures result))
619 (when *print-errors* (print-errors result))
620 (when (or *print-summary* *print-failures* *print-errors*)
621 (print-summary result))))
623 (defun summarize-results (results)
624 "Print a summary of all results."
625 (let ((pass (pass results))
626 (fail (fail results)))
627 (format t "~&Unit Test Summary~%")
628 (format t " | ~D assertions total~%" (+ pass fail))
629 (format t " | ~D passed~%" pass)
630 (format t " | ~D failed~%" fail)
631 (format t " | ~D execution errors~%" (exerr results))
632 (format t " | ~D missing tests~2%"
633 (length (missing-tests results)))))
635 ;;; Run the tests
637 (defun %run-all-thunks (&optional (package *package*))
638 "Run all of the test thunks in the package."
639 (loop
640 with results = (make-instance 'test-results-db)
641 for test-name being each hash-key in (package-table package)
642 using (hash-value unit-test)
643 if unit-test do
644 (record-result test-name (code unit-test) results)
645 else do
646 (push test-name (missing-tests results))
647 ;; Summarize and return the test results
648 finally
649 (summarize-results results)
650 (return results)))
652 (defun %run-thunks (test-names &optional (package *package*))
653 "Run the list of test thunks in the package."
654 (loop
655 with table = (package-table package)
656 and results = (make-instance 'test-results-db)
657 for test-name in test-names
658 as unit-test = (gethash test-name table)
659 if unit-test do
660 (record-result test-name (code unit-test) results)
661 else do
662 (push test-name (missing-tests results))
663 finally
664 (summarize-results results)
665 (return results)))
667 (defun run-tests (test-names &optional (package *package*))
668 "Run the specified tests in package."
669 (reset-counters)
670 (if (eq :all test-names)
671 (%run-all-thunks package)
672 (%run-thunks test-names package)))
674 (defun run-tags (tags &optional (package *package*))
675 "Run the tests associated with the specified tags in package."
676 (reset-counters)
677 (%run-thunks (tagged-tests tags package) package))
679 ;;; Print failures
681 (defgeneric print-failures (result)
682 (:documentation
683 "Report the results of the failed assertion."))
685 (defmethod print-failures :around ((result assert-result))
686 "Failure header and footer output."
687 (format t "~& | Failed Form: ~S" (form result))
688 (call-next-method)
689 (when (extras result)
690 (format t "~{~& | ~S => ~S~}~%" (extras result)))
691 (format t "~& |~%")
692 (class-name (class-of result)))
694 (defmethod print-failures ((result assert-result))
695 (format t "~& | Expected ~{~S~^; ~} " (expected result))
696 (format t "~<~% | ~:;but saw ~{~S~^; ~}~>" (actual result)))
698 (defmethod print-failures ((result error-result))
699 (format t "~& | ~@[Should have signalled ~{~S~^; ~} but saw~]"
700 (expected result))
701 (format t " ~{~S~^; ~}" (actual result)))
703 (defmethod print-failures ((result macro-result))
704 (format t "~& | Should have expanded to ~{~S~^; ~} "
705 (expected result))
706 (format t "~<~%~:;but saw ~{~S~^; ~}~>" (actual result)))
708 (defmethod print-failures ((result output-result))
709 (format t "~& | Should have printed ~{~S~^; ~} "
710 (expected result))
711 (format t "~<~%~:;but saw ~{~S~^; ~}~>"
712 (actual result)))
714 (defmethod print-failures ((result test-result))
715 "Print the failed assertions in the unit test."
716 (loop for fail in (fail result) do
717 (print-failures fail)))
719 (defmethod print-failures ((results test-results-db))
720 "Print all of the failure tests."
721 (loop with db = (database results)
722 for test in (failed-tests results)
723 as result = (gethash test db)
725 (print-failures result)
726 (print-summary result)))
728 ;;; Print errors
730 (defgeneric print-errors (result)
731 (:documentation
732 "Print the error condition."))
734 (defmethod print-errors ((result test-result))
735 "Print the error condition."
736 (let ((exerr (exerr result))
737 (*print-escape* nil))
738 (when exerr
739 (format t "~& | Execution error:~% | ~W" exerr)
740 (format t "~& |~%"))))
742 (defmethod print-errors ((results test-results-db))
743 "Print all of the error tests."
744 (loop with db = (database results)
745 for test in (error-tests results)
746 as result = (gethash test db)
748 (print-errors result)
749 (print-summary result)))
751 ;;; Useful equality predicates for tests
753 (defun logically-equal (x y)
754 "Return true if x and y are both false or both true."
755 (eql (not x) (not y)))
757 (defun set-equal (list1 list2 &rest initargs &key key (test #'equal))
758 "Return true if every element of list1 is an element of list2 and
759 vice versa."
760 (declare (ignore key test))
761 (and
762 (listp list1)
763 (listp list2)
764 (apply #'subsetp list1 list2 initargs)
765 (apply #'subsetp list2 list1 initargs)))
767 (pushnew :lisp-unit common-lisp:*features*)