Examples of using tags.
[lisp-unit.git] / lisp-unit.lisp
blobd440f534fff7d2a71d3725789c3f3b4bcc6f4407
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 if (null tests) do (warn "No tests tagged with ~S." tag)
267 else nconc (copy-list tests) into all-tests
268 finally (return (delete-duplicates all-tests))))
270 (defun list-tags (&optional (package *package*))
271 "Return a list of the tags in package."
272 (let ((tags (package-tags package)))
273 (when tags
274 (loop for tag being each hash-key in tags collect tag))))
276 (defun tagged-tests (tags &optional (package *package*))
277 "Return a list of the tests associated with the tags."
278 (if (eq :all tags)
279 (%tests-from-all-tags package)
280 (%tests-from-tags tags package)))
282 (defun remove-tags (tags &optional (package *package*))
283 "Remove individual tags or entire sets."
284 (if (eq :all tags)
285 (if (null package)
286 (clrhash *tag-db*)
287 (remhash (find-package package) *tag-db*))
288 (let ((table (package-tags package)))
289 (unless (null table)
290 (loop for tag in tags
291 always (remhash tag table)
292 collect tag into removed
293 finally (return removed))))))
295 ;;; Assert macros
297 (defmacro assert-eq (expected form &rest extras)
298 "Assert whether expected and form are EQ."
299 `(expand-assert :equal ,form ,form ,expected ,extras :test #'eq))
301 (defmacro assert-eql (expected form &rest extras)
302 "Assert whether expected and form are EQL."
303 `(expand-assert :equal ,form ,form ,expected ,extras :test #'eql))
305 (defmacro assert-equal (expected form &rest extras)
306 "Assert whether expected and form are EQUAL."
307 `(expand-assert :equal ,form ,form ,expected ,extras :test #'equal))
309 (defmacro assert-equalp (expected form &rest extras)
310 "Assert whether expected and form are EQUALP."
311 `(expand-assert :equal ,form ,form ,expected ,extras :test #'equalp))
313 (defmacro assert-error (condition form &rest extras)
314 "Assert whether form signals condition."
315 `(expand-assert :error ,form (expand-error-form ,form)
316 ,condition ,extras))
318 (defmacro assert-expands (expansion form &rest extras)
319 "Assert whether form expands to expansion."
320 `(expand-assert :macro ,form
321 (expand-macro-form ,form nil)
322 ,expansion ,extras))
324 (defmacro assert-false (form &rest extras)
325 "Assert whether the form is false."
326 `(expand-assert :result ,form ,form nil ,extras))
328 (defmacro assert-equality (test expected form &rest extras)
329 "Assert whether expected and form are equal according to test."
330 `(expand-assert :equal ,form ,form ,expected ,extras :test ,test))
332 (defmacro assert-prints (output form &rest extras)
333 "Assert whether printing the form generates the output."
334 `(expand-assert :output ,form (expand-output-form ,form)
335 ,output ,extras))
337 (defmacro assert-true (form &rest extras)
338 "Assert whether the form is true."
339 `(expand-assert :result ,form ,form t ,extras))
341 (defmacro expand-assert (type form body expected extras &key (test '#'eql))
342 "Expand the assertion to the internal format."
343 `(internal-assert ,type ',form
344 (lambda () ,body)
345 (lambda () ,expected)
346 (expand-extras ,extras)
347 ,test))
349 (defmacro expand-error-form (form)
350 "Wrap the error assertion in HANDLER-CASE."
351 `(handler-case ,form
352 (condition (error) error)))
354 (defmacro expand-output-form (form)
355 "Capture the output of the form in a string."
356 (let ((out (gensym)))
357 `(let* ((,out (make-string-output-stream))
358 (*standard-output*
359 (make-broadcast-stream *standard-output* ,out)))
360 ,form
361 (get-output-stream-string ,out))))
363 (defmacro expand-macro-form (form env)
364 "Expand the macro form once."
365 `(macroexpand-1 ',form ,env))
367 (defmacro expand-extras (extras)
368 "Expand extra forms."
369 `(lambda ()
370 (list ,@(mapcan (lambda (form) (list `',form form)) extras))))
372 (defclass assert-result ()
373 ((form
374 :initarg :form
375 :reader form)
376 (actual
377 :type list
378 :initarg :actual
379 :reader actual)
380 (expected
381 :type list
382 :initarg :expected
383 :reader expected)
384 (extras
385 :type list
386 :initarg :extras
387 :reader extras)
388 (test
389 :type function
390 :initarg :test
391 :reader test)
392 (passed
393 :type boolean
394 :reader passed))
395 (:documentation
396 "Result of the assertion."))
398 (defmethod initialize-instance :after ((self assert-result)
399 &rest initargs)
400 "Evaluate the actual and expected forms"
401 (with-slots (actual expected) self
402 (setf
403 actual (multiple-value-list (funcall actual))
404 expected (multiple-value-list (funcall expected))))
405 ;; Generate extras
406 (when (slot-boundp self 'extras)
407 (setf
408 (slot-value self 'extras)
409 (funcall (slot-value self 'extras)))))
411 (defclass equal-result (assert-result)
413 (:documentation
414 "Result of an equal assertion type."))
416 (defmethod initialize-instance :after ((self equal-result)
417 &rest initargs)
418 "Return the result of the equality assertion."
419 (with-slots (actual expected test passed) self
420 (setf
421 passed
422 (and
423 (<= (length expected) (length actual))
424 (every test expected actual)))))
426 (defclass error-result (assert-result)
428 (:documentation
429 "Result of an error assertion type."))
431 (defmethod initialize-instance :after ((self error-result)
432 &rest initargs)
433 "Evaluate the result."
434 (with-slots (actual expected passed) self
435 (setf
436 passed
438 (eql (car actual) (car expected))
439 (typep (car actual) (car expected))))))
441 (defclass macro-result (assert-result)
443 (:documentation
444 "Result of a macro assertion type."))
446 (defmethod initialize-instance :after ((self macro-result)
447 &rest initargs)
448 "Return the result of the macro expansion."
449 (with-slots (actual expected passed) self
450 (setf passed (equal (car actual) (car expected)))))
452 (defclass boolean-result (assert-result)
454 (:documentation
455 "Result of a result assertion type."))
457 (defmethod initialize-instance :after ((self boolean-result)
458 &rest initargs)
459 "Return the result of the assertion."
460 (with-slots (actual expected passed) self
461 (setf passed (logically-equal (car actual) (car expected)))))
463 (defclass output-result (assert-result)
465 (:documentation
466 "Result of an output assertion type."))
468 (defmethod initialize-instance :after ((self output-result)
469 &rest initargs)
470 "Return the result of the printed output."
471 (with-slots (actual expected passed) self
472 (setf
473 passed
474 (string=
475 (string-trim '(#\newline #\return #\space) (car actual))
476 (car expected)))))
478 (defun assert-class (type)
479 "Return the class name for the assertion type."
480 (ecase type
481 (:equal 'equal-result)
482 (:error 'error-result)
483 (:macro 'macro-result)
484 (:result 'boolean-result)
485 (:output 'output-result)))
487 (defun internal-assert
488 (type form code-thunk expected-thunk extras test)
489 "Perform the assertion and record the results."
490 (let ((result
491 (make-instance (assert-class type)
492 :form form
493 :actual code-thunk
494 :expected expected-thunk
495 :extras extras
496 :test test)))
497 (if (passed result)
498 (push result *pass*)
499 (push result *fail*))
500 ;; Return the result
501 (passed result)))
503 ;;; Unit test results
505 (defclass test-result ()
506 ((name
507 :type symbol
508 :initarg :name
509 :reader name)
510 (pass
511 :type list
512 :initarg :pass
513 :reader pass)
514 (fail
515 :type list
516 :initarg :fail
517 :reader fail)
518 (exerr
519 :type condition
520 :initarg :exerr
521 :reader exerr))
522 (:default-initargs :exerr nil)
523 (:documentation
524 "Store the results of the unit test."))
526 (defun print-summary (test-result)
527 "Print a summary of the test result."
528 (format t "~&~A: ~S assertions passed, ~S failed"
529 (name test-result)
530 (length (pass test-result))
531 (length (fail test-result)))
532 (if (exerr test-result)
533 (format t ", and an execution error.")
534 (write-char #\.))
535 (terpri)
536 (terpri))
538 (defun run-code (code)
539 "Run the code to test the assertions."
540 (funcall (coerce `(lambda () ,@code) 'function)))
542 (defun run-test-thunk (name code)
543 (let ((*pass* ())
544 (*fail* ()))
545 (handler-bind
546 ((error
547 (lambda (condition)
548 (if (use-debugger-p condition)
549 condition
550 (return-from run-test-thunk
551 (make-instance
552 'test-result
553 :name name
554 :pass *pass*
555 :fail *fail*
556 :exerr condition))))))
557 (run-code code))
558 ;; Return the result count
559 (make-instance 'test-result
560 :name name
561 :pass *pass*
562 :fail *fail*)))
564 ;;; Test results database
566 (defclass test-results-db ()
567 ((database
568 :type hash-table
569 :initform (make-hash-table :test #'eq)
570 :reader database)
571 (pass
572 :type fixnum
573 :initform 0
574 :accessor pass)
575 (fail
576 :type fixnum
577 :initform 0
578 :accessor fail)
579 (exerr
580 :type fixnum
581 :initform 0
582 :accessor exerr)
583 (failed-tests
584 :type list
585 :initform ()
586 :accessor failed-tests)
587 (error-tests
588 :type list
589 :initform ()
590 :accessor error-tests)
591 (missing-tests
592 :type list
593 :initform ()
594 :accessor missing-tests))
595 (:documentation
596 "Store the results of the tests for further evaluation."))
598 (defmethod print-object ((object test-results-db) stream)
599 "Print the summary counts with the object."
600 (let ((pass (pass object))
601 (fail (fail object))
602 (exerr (exerr object)))
603 (format
604 stream "#<~A Total(~D) Passed(~D) Failed(~D) Errors(~D)>~%"
605 (class-name (class-of object))
606 (+ pass fail) pass fail exerr)))
608 (defun test-names (test-results-db)
609 "Return a list of the test names in the database."
610 (loop for name being each hash-key in (database test-results-db)
611 collect name))
613 (defun record-result (test-name code results)
614 "Run the test code and record the result."
615 (let ((result (run-test-thunk test-name code)))
616 ;; Store the result
617 (setf (gethash test-name (database results)) result)
618 ;; Count passed tests
619 (when (pass result)
620 (incf (pass results) (length (pass result))))
621 ;; Count failed tests and record the name
622 (when (fail result)
623 (incf (fail results) (length (fail result)))
624 (push test-name (failed-tests results)))
625 ;; Count errors and record the name
626 (when (exerr result)
627 (incf (exerr results))
628 (push test-name (error-tests results)))
629 ;; Running output
630 (when *print-failures* (print-failures result))
631 (when *print-errors* (print-errors result))
632 (when (or *print-summary* *print-failures* *print-errors*)
633 (print-summary result))))
635 (defun summarize-results (results)
636 "Print a summary of all results."
637 (let ((pass (pass results))
638 (fail (fail results)))
639 (format t "~&Unit Test Summary~%")
640 (format t " | ~D assertions total~%" (+ pass fail))
641 (format t " | ~D passed~%" pass)
642 (format t " | ~D failed~%" fail)
643 (format t " | ~D execution errors~%" (exerr results))
644 (format t " | ~D missing tests~2%"
645 (length (missing-tests results)))))
647 ;;; Run the tests
649 (defun %run-all-thunks (&optional (package *package*))
650 "Run all of the test thunks in the package."
651 (loop
652 with results = (make-instance 'test-results-db)
653 for test-name being each hash-key in (package-table package)
654 using (hash-value unit-test)
655 if unit-test do
656 (record-result test-name (code unit-test) results)
657 else do
658 (push test-name (missing-tests results))
659 ;; Summarize and return the test results
660 finally
661 (summarize-results results)
662 (return results)))
664 (defun %run-thunks (test-names &optional (package *package*))
665 "Run the list of test thunks in the package."
666 (loop
667 with table = (package-table package)
668 and results = (make-instance 'test-results-db)
669 for test-name in test-names
670 as unit-test = (gethash test-name table)
671 if unit-test do
672 (record-result test-name (code unit-test) results)
673 else do
674 (push test-name (missing-tests results))
675 finally
676 (summarize-results results)
677 (return results)))
679 (defun run-tests (test-names &optional (package *package*))
680 "Run the specified tests in package."
681 (reset-counters)
682 (if (eq :all test-names)
683 (%run-all-thunks package)
684 (%run-thunks test-names package)))
686 (defun run-tags (tags &optional (package *package*))
687 "Run the tests associated with the specified tags in package."
688 (reset-counters)
689 (%run-thunks (tagged-tests tags package) package))
691 ;;; Print failures
693 (defgeneric print-failures (result)
694 (:documentation
695 "Report the results of the failed assertion."))
697 (defmethod print-failures :around ((result assert-result))
698 "Failure header and footer output."
699 (format t "~& | Failed Form: ~S" (form result))
700 (call-next-method)
701 (when (extras result)
702 (format t "~{~& | ~S => ~S~}~%" (extras result)))
703 (format t "~& |~%")
704 (class-name (class-of result)))
706 (defmethod print-failures ((result assert-result))
707 (format t "~& | Expected ~{~S~^; ~} " (expected result))
708 (format t "~<~% | ~:;but saw ~{~S~^; ~}~>" (actual result)))
710 (defmethod print-failures ((result error-result))
711 (format t "~& | ~@[Should have signalled ~{~S~^; ~} but saw~]"
712 (expected result))
713 (format t " ~{~S~^; ~}" (actual result)))
715 (defmethod print-failures ((result macro-result))
716 (format t "~& | Should have expanded to ~{~S~^; ~} "
717 (expected result))
718 (format t "~<~%~:;but saw ~{~S~^; ~}~>" (actual result)))
720 (defmethod print-failures ((result output-result))
721 (format t "~& | Should have printed ~{~S~^; ~} "
722 (expected result))
723 (format t "~<~%~:;but saw ~{~S~^; ~}~>"
724 (actual result)))
726 (defmethod print-failures ((result test-result))
727 "Print the failed assertions in the unit test."
728 (loop for fail in (fail result) do
729 (print-failures fail)))
731 (defmethod print-failures ((results test-results-db))
732 "Print all of the failure tests."
733 (loop with db = (database results)
734 for test in (failed-tests results)
735 as result = (gethash test db)
737 (print-failures result)
738 (print-summary result)))
740 ;;; Print errors
742 (defgeneric print-errors (result)
743 (:documentation
744 "Print the error condition."))
746 (defmethod print-errors ((result test-result))
747 "Print the error condition."
748 (let ((exerr (exerr result))
749 (*print-escape* nil))
750 (when exerr
751 (format t "~& | Execution error:~% | ~W" exerr)
752 (format t "~& |~%"))))
754 (defmethod print-errors ((results test-results-db))
755 "Print all of the error tests."
756 (loop with db = (database results)
757 for test in (error-tests results)
758 as result = (gethash test db)
760 (print-errors result)
761 (print-summary result)))
763 ;;; Useful equality predicates for tests
765 (defun logically-equal (x y)
766 "Return true if x and y are both false or both true."
767 (eql (not x) (not y)))
769 (defun set-equal (list1 list2 &rest initargs &key key (test #'equal))
770 "Return true if every element of list1 is an element of list2 and
771 vice versa."
772 (declare (ignore key test))
773 (and
774 (listp list1)
775 (listp list2)
776 (apply #'subsetp list1 list2 initargs)
777 (apply #'subsetp list2 list1 initargs)))
779 (pushnew :lisp-unit common-lisp:*features*)