Merge failure-control-string with print-failure.
[lisp-unit.git] / lisp-unit.lisp
blob78ee58e76a916cb9e5bd3e7ac13585c211a2d558
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 :get-tests
75 :get-test-code
76 :get-test-documentation
77 :remove-tests
78 :run-tests
79 :use-debugger)
80 ;; Functions for managing tags
81 (:export :get-tags
82 :get-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 :summarize-results)
91 ;; Utility predicates
92 (:export :logically-equal :set-equal))
94 (in-package :lisp-unit)
96 ;;; Global counters
98 (defparameter *pass* 0
99 "The number of passed assertions.")
101 (defparameter *fail* 0
102 "The number of failed assertions.")
104 ;;; Global options
106 (defparameter *print-summary* nil
107 "Print a summary of the pass, fail, and error count if non-nil.")
109 (defparameter *print-failures* nil
110 "Print failure messages if non-NIL.")
112 (defparameter *print-errors* nil
113 "Print error messages if non-NIL.")
115 (defparameter *use-debugger* nil
116 "If not NIL, enter the debugger when an error is encountered in an
117 assertion.")
119 (defun use-debugger-p (condition)
120 "Debug or ignore errors."
121 (cond
122 ((eq :ask *use-debugger*)
123 (y-or-n-p "~A -- debug?" condition))
124 (*use-debugger*)))
126 ;;; Failure control strings
128 (defgeneric print-failure (type form expected actual extras)
129 (:documentation
130 "Report the details of the failure assertion."))
132 (defmethod print-failure :around (type form expected actual extras)
133 "Failure header and footer output."
134 (format t " | Failed Form: ~S" form)
135 (call-next-method)
136 (when extras
137 (format t "~{~& | ~S => ~S~}~%" (funcall extras)))
138 (format t "~& |~%")
139 type)
141 (defmethod print-failure (type form expected actual extras)
142 (format t "~& | Expected ~{~S~^; ~} " expected)
143 (format t "~<~% | ~:;but saw ~{~S~^; ~}~>" actual))
145 (defmethod print-failure ((type (eql :error))
146 form expected actual extras)
147 (format t "~& | ~@[Should have signalled ~{~S~^; ~}" expected)
148 (format t " but saw~] ~{~S~^; ~}" actual))
150 (defmethod print-failure ((type (eql :macro))
151 form expected actual extras)
152 (format t "~& | Should have expanded to ~{~S~^; ~} " expected)
153 (format t "~<~%~:;but saw ~{~S~^; ~}~>" actual))
155 (defmethod print-failure ((type (eql :output))
156 form expected actual extras)
157 (format t "~& | Should have printed ~{~S~^; ~} " expected)
158 (format t "~<~%~:;but saw ~{~S~^; ~}~>" actual))
160 (defun print-error (condition)
161 "Print the error condition."
162 (let ((*print-escape* nil))
163 (format t "~& | Execution error:~% | ~W" condition)
164 (format t "~& |~%")))
166 (defun print-summary (name pass fail &optional exerr)
167 "Print a summary of the test results."
168 (format t "~&~A: ~S assertions passed, ~S failed"
169 name pass fail)
170 (format t "~@[, ~S execution errors~].~2%" exerr))
172 ;;; Global unit test database
174 (defparameter *test-db* (make-hash-table :test #'eq)
175 "The unit test database is simply a hash table.")
177 (defun package-table (package &optional create)
178 (cond
179 ((gethash (find-package package) *test-db*))
180 (create
181 (setf (gethash package *test-db*) (make-hash-table)))
182 (t (warn "No tests defined for package: ~S" package))))
184 ;;; Global tags database
186 (defparameter *tag-db* (make-hash-table :test #'eq)
187 "The tag database is simply a hash table.")
189 (defun package-tags (package &optional create)
190 "Return the tags DB for the package."
191 (cond
192 ((gethash (find-package package) *tag-db*))
193 (create
194 (setf (gethash package *tag-db*) (make-hash-table)))
195 (t (warn "No tags defined for package: ~S" package))))
197 (defclass unit-test ()
198 ((doc
199 :type string
200 :initarg :doc
201 :reader doc)
202 (code
203 :type list
204 :initarg :code
205 :reader code))
206 (:default-initargs :doc "" :code ())
207 (:documentation
208 "Organize the unit test documentation and code."))
210 ;;; NOTE: Shamelessly taken from PG's analyze-body
211 (defun parse-body (body &optional doc tag)
212 "Separate the components of the body."
213 (let ((item (first body)))
214 (cond
215 ((and (listp item) (eq :tag (first item)))
216 (parse-body (rest body) doc (nconc (rest item) tag)))
217 ((and (stringp item) (not doc) (rest body))
218 (if tag
219 (values doc tag (rest body))
220 (parse-body (rest body) doc tag)))
221 (t (values doc tag body)))))
223 (defmacro define-test (name &body body)
224 "Store the test in the test database."
225 (multiple-value-bind (doc tag code) (parse-body body)
226 `(progn
227 (setf
228 ;; Unit test
229 (gethash ',name (package-table *package* t))
230 (make-instance 'unit-test :doc ,doc :code ',code))
231 ;; Tags
232 (loop for tag in ',tag do
233 (pushnew
234 ',name (gethash tag (package-tags *package* t))))
235 ;; Return the name of the test
236 ',name)))
238 ;;; Manage tests
240 (defun get-tests (&optional (package *package*))
241 "Return a list of the tests in package."
242 (let ((table (package-table package)))
243 (when table
244 (loop for test-name being each hash-key in table
245 collect test-name))))
247 (defun get-test-documentation (name &optional (package *package*))
248 "Return the documentation for the test."
249 (let ((unit-test (gethash name (package-table package))))
250 (if (null unit-test)
251 (warn "No code defined for test ~A in package ~S."
252 name package)
253 (doc unit-test))))
255 (defun get-test-code (name &optional (package *package*))
256 "Returns the code stored for the test name."
257 (let ((unit-test (gethash name (package-table package))))
258 (if (null unit-test)
259 (warn "No code defined for test ~A in package ~S."
260 name package)
261 (code unit-test))))
263 (defun remove-tests (names &optional (package *package*))
264 "Remove individual tests or entire sets."
265 (if (eq :all names)
266 (if (null package)
267 (clrhash *test-db*)
268 (remhash (find-package package) *test-db*))
269 (let ((table (package-table package)))
270 (unless (null table)
271 (loop for name in names
272 always (remhash name table)
273 collect name into removed
274 finally (return removed))))))
276 ;;; Manage tags
278 (defun %tests-from-all-tags (&optional (package *package*))
279 "Return all of the tests that have been tagged."
280 (loop for tests being each hash-value in (package-tags package)
281 nconc (copy-list tests) into all-tests
282 finally (return (delete-duplicates all-tests))))
284 (defun %tests-from-tags (tags &optional (package *package*))
285 "Return the tests associated with the tags."
286 (loop with table = (package-tags package)
287 for tag in tags
288 as tests = (gethash tag table)
289 nconc (copy-list tests) into all-tests
290 finally (return (delete-duplicates all-tests))))
292 (defun get-tags (&optional (package *package*))
293 "Return a list of the tags in package."
294 (let ((tags (package-tags package)))
295 (when tags
296 (loop for tag being each hash-key in tags
297 collect tag))))
299 (defun get-tagged-tests (tags &optional (package *package*))
300 "Run the tests associated with the specified tags in package."
301 (if (eq :all tags)
302 (%tests-from-all-tags package)
303 (%tests-from-tags tags package)))
305 (defun remove-tags (tags &optional (package *package*))
306 "Remove individual tags or entire sets."
307 (if (eq :all tags)
308 (if (null package)
309 (clrhash *tag-db*)
310 (remhash (find-package package) *tag-db*))
311 (let ((table (package-tags package)))
312 (unless (null table)
313 (loop for tag in tags
314 always (remhash tag table)
315 collect tag into removed
316 finally (return removed))))))
318 ;;; Assert macros
320 (defmacro assert-eq (expected form &rest extras)
321 "Assert whether expected and form are EQ."
322 `(expand-assert :equal ,form ,form ,expected ,extras :test #'eq))
324 (defmacro assert-eql (expected form &rest extras)
325 "Assert whether expected and form are EQL."
326 `(expand-assert :equal ,form ,form ,expected ,extras :test #'eql))
328 (defmacro assert-equal (expected form &rest extras)
329 "Assert whether expected and form are EQUAL."
330 `(expand-assert :equal ,form ,form ,expected ,extras :test #'equal))
332 (defmacro assert-equalp (expected form &rest extras)
333 "Assert whether expected and form are EQUALP."
334 `(expand-assert :equal ,form ,form ,expected ,extras :test #'equalp))
336 (defmacro assert-error (condition form &rest extras)
337 "Assert whether form signals condition."
338 `(expand-assert :error ,form (expand-error-form ,form)
339 ,condition ,extras))
341 (defmacro assert-expands (expansion form &rest extras)
342 "Assert whether form expands to expansion."
343 `(expand-assert :macro ,form
344 (expand-macro-form ,form nil)
345 ,expansion ,extras))
347 (defmacro assert-false (form &rest extras)
348 "Assert whether the form is false."
349 `(expand-assert :result ,form ,form nil ,extras))
351 (defmacro assert-equality (test expected form &rest extras)
352 "Assert whether expected and form are equal according to test."
353 `(expand-assert :equal ,form ,form ,expected ,extras :test ,test))
355 (defmacro assert-prints (output form &rest extras)
356 "Assert whether printing the form generates the output."
357 `(expand-assert :output ,form (expand-output-form ,form)
358 ,output ,extras))
360 (defmacro assert-true (form &rest extras)
361 "Assert whether the form is true."
362 `(expand-assert :result ,form ,form t ,extras))
364 (defmacro expand-assert (type form body expected extras &key (test '#'eql))
365 "Expand the assertion to the internal format."
366 `(internal-assert ,type ',form
367 (lambda () ,body)
368 (lambda () ,expected)
369 (expand-extras ,extras)
370 ,test))
372 (defmacro expand-error-form (form)
373 "Wrap the error assertion in HANDLER-CASE."
374 `(handler-case ,form
375 (condition (error) error)))
377 (defmacro expand-output-form (form)
378 "Capture the output of the form in a string."
379 (let ((out (gensym)))
380 `(let* ((,out (make-string-output-stream))
381 (*standard-output*
382 (make-broadcast-stream *standard-output* ,out)))
383 ,form
384 (get-output-stream-string ,out))))
386 (defmacro expand-macro-form (form env)
387 "Expand the macro form once."
388 `(macroexpand-1 ',form ,env))
390 (defmacro expand-extras (extras)
391 "Expand extra forms."
392 `(lambda ()
393 (list ,@(mapcan (lambda (form) (list `',form form)) extras))))
395 (defun internal-assert
396 (type form code-thunk expected-thunk extras test)
397 "Perform the assertion and record the results."
398 (let ((expected (multiple-value-list (funcall expected-thunk)))
399 (actual (multiple-value-list (funcall code-thunk)))
400 (passed nil))
401 ;; Count the assertion
402 (if (setq passed (test-passed-p type expected actual test))
403 (incf *pass*)
404 (incf *fail*))
405 ;; Report the assertion
406 (when (and (not passed) *print-failures*)
407 (print-failure type form expected actual extras))
408 ;; Return the result
409 passed))
411 ;;; Test passed predicate.
413 (defgeneric test-passed-p (type expected actual test)
414 (:documentation
415 "Return the result of the test."))
417 (defmethod test-passed-p ((type (eql :error)) expected actual test)
418 "Return the result of the error assertion."
420 (eql (car actual) (car expected))
421 (typep (car actual) (car expected))))
423 (defmethod test-passed-p ((type (eql :equal)) expected actual test)
424 "Return the result of the equality assertion."
425 (and
426 (<= (length expected) (length actual))
427 (every test expected actual)))
429 (defmethod test-passed-p ((type (eql :macro)) expected actual test)
430 "Return the result of the macro expansion."
431 (equal (car actual) (car expected)))
433 (defmethod test-passed-p ((type (eql :output)) expected actual test)
434 "Return the result of the printed output."
435 (string=
436 (string-trim '(#\newline #\return #\space) (car actual))
437 (car expected)))
439 (defmethod test-passed-p ((type (eql :result)) expected actual test)
440 "Return the result of the assertion."
441 (logically-equal (car actual) (car expected)))
443 ;;; Results
445 (defclass test-results ()
446 ((test-names
447 :type list
448 :initarg :test-names
449 :accessor test-names)
450 (pass
451 :type fixnum
452 :initform 0
453 :accessor pass)
454 (fail
455 :type fixnum
456 :initform 0
457 :accessor fail)
458 (exerr
459 :type fixnum
460 :initform 0
461 :accessor exerr)
462 (failed-tests
463 :type list
464 :initform ()
465 :accessor failed-tests)
466 (error-tests
467 :type list
468 :initform ()
469 :accessor error-tests)
470 (missing-tests
471 :type list
472 :initform ()
473 :accessor missing-tests))
474 (:default-initargs :test-names ())
475 (:documentation
476 "Store the results of the tests for further evaluation."))
478 (defmethod print-object ((object test-results) stream)
479 "Print the summary counts with the object."
480 (format stream "#<~A Total(~D) Passed(~D) Failed(~D) Errors(~D)>~%"
481 (class-name (class-of object))
482 (+ (pass object) (fail object))
483 (pass object) (fail object) (exerr object)))
485 (defun record-result (test-name code results)
486 "Run the test code and record the result."
487 (multiple-value-bind (pass fail exerr)
488 (run-test-thunk code)
489 (push test-name (test-names results))
490 ;; Count passed tests
491 (when (plusp pass)
492 (incf (pass results) pass))
493 ;; Count failed tests and record name
494 (when (plusp fail)
495 (incf (fail results) fail)
496 (push test-name (failed-tests results)))
497 ;; Count errors and record name
498 (when (eq :error exerr)
499 (incf (exerr results))
500 (push test-name (error-tests results)))
501 ;; Print a summary of the results
502 (when (or *print-summary* *print-failures* *print-errors*)
503 (print-summary
504 test-name pass fail
505 (when (eq :error exerr) 1)))))
507 (defun summarize-results (results)
508 "Print a summary of all results."
509 (let ((pass (pass results))
510 (fail (fail results)))
511 (format t "~&Unit Test Summary~%")
512 (format t " | ~D assertions total~%" (+ pass fail))
513 (format t " | ~D passed~%" pass)
514 (format t " | ~D failed~%" fail)
515 (format t " | ~D execution errors~%" (exerr results))
516 (format t " | ~D missing tests~2%"
517 (length (missing-tests results)))))
519 ;;; Run the tests
521 (defun run-code (code)
522 "Run the code to test the assertions."
523 (funcall (coerce `(lambda () ,@code) 'function)))
525 (defun run-test-thunk (code)
526 (let ((*pass* 0)
527 (*fail* 0))
528 (handler-case (run-code code)
529 (error (condition)
530 (when *print-errors*
531 (print-error condition))
532 (if (use-debugger-p condition)
533 condition
534 (return-from run-test-thunk
535 (values *pass* *fail* :error)))))
536 ;; Return the result count
537 (values *pass* *fail* nil)))
539 (defun %run-all-thunks (&optional (package *package*))
540 "Run all of the test thunks in the package."
541 (loop
542 with results = (make-instance 'test-results)
543 for test-name being each hash-key in (package-table package)
544 using (hash-value unit-test)
545 if unit-test do
546 (record-result test-name (code unit-test) results)
547 else do
548 (push test-name (missing-tests results))
549 ;; Summarize and return the test results
550 finally
551 (summarize-results results)
552 (return results)))
554 (defun %run-thunks (test-names &optional (package *package*))
555 "Run the list of test thunks in the package."
556 (loop
557 with table = (package-table package)
558 and results = (make-instance 'test-results)
559 for test-name in test-names
560 as unit-test = (gethash test-name table)
561 if unit-test do
562 (record-result test-name (code unit-test) results)
563 else do
564 (push test-name (missing-tests results))
565 finally
566 (summarize-results results)
567 (return results)))
569 (defun run-tests (test-names &optional (package *package*))
570 "Run the specified tests in package."
571 (if (eq :all test-names)
572 (%run-all-thunks package)
573 (%run-thunks test-names package)))
575 (defun run-tags (tags &optional (package *package*))
576 "Run the tests associated with the specified tags in package."
577 (%run-thunks (get-tagged-tests tags package) package))
579 ;;; Useful equality predicates for tests
581 ;;; (LOGICALLY-EQUAL x y) => true or false
582 ;;; Return true if x and y both false or both true
583 (defun logically-equal (x y)
584 (eql (not x) (not y)))
586 ;;; (SET-EQUAL l1 l2 :test) => true or false
587 ;;; Return true if every element of l1 is an element of l2
588 ;;; and vice versa.
589 (defun set-equal (l1 l2 &key (test #'equal))
590 (and (listp l1)
591 (listp l2)
592 (subsetp l1 l2 :test test)
593 (subsetp l2 l1 :test test)))
595 (pushnew :lisp-unit common-lisp:*features*)