Clean up sumsq sump.
[lisp-unit.git] / lisp-unit.lisp
blob8aa831e92f3232c86fefe0fa6df6f75c58eda591
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 :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~^; ~} but saw~]"
148 expected)
149 (format t " ~{~S~^; ~}" actual))
151 (defmethod print-failure ((type (eql :macro))
152 form expected actual extras)
153 (format t "~& | Should have expanded to ~{~S~^; ~} " expected)
154 (format t "~<~%~:;but saw ~{~S~^; ~}~>" actual))
156 (defmethod print-failure ((type (eql :output))
157 form expected actual extras)
158 (format t "~& | Should have printed ~{~S~^; ~} " expected)
159 (format t "~<~%~:;but saw ~{~S~^; ~}~>" actual))
161 (defun print-error (condition)
162 "Print the error condition."
163 (let ((*print-escape* nil))
164 (format t "~& | Execution error:~% | ~W" condition)
165 (format t "~& |~%")))
167 (defun print-summary (name pass fail &optional exerr)
168 "Print a summary of the test results."
169 (format t "~&~A: ~S assertions passed, ~S failed"
170 name pass fail)
171 (format t "~@[, ~S execution errors~].~2%" exerr))
173 ;;; Global unit test database
175 (defparameter *test-db* (make-hash-table :test #'eq)
176 "The unit test database is simply a hash table.")
178 (defun package-table (package &optional create)
179 (cond
180 ((gethash (find-package package) *test-db*))
181 (create
182 (setf (gethash package *test-db*) (make-hash-table)))
183 (t (warn "No tests defined for package: ~S" package))))
185 ;;; Global tags database
187 (defparameter *tag-db* (make-hash-table :test #'eq)
188 "The tag database is simply a hash table.")
190 (defun package-tags (package &optional create)
191 "Return the tags DB for the package."
192 (cond
193 ((gethash (find-package package) *tag-db*))
194 (create
195 (setf (gethash package *tag-db*) (make-hash-table)))
196 (t (warn "No tags defined for package: ~S" package))))
198 (defclass unit-test ()
199 ((doc
200 :type string
201 :initarg :doc
202 :reader doc)
203 (code
204 :type list
205 :initarg :code
206 :reader code))
207 (:default-initargs :doc "" :code ())
208 (:documentation
209 "Organize the unit test documentation and code."))
211 ;;; NOTE: Shamelessly taken from PG's analyze-body
212 (defun parse-body (body &optional doc tag)
213 "Separate the components of the body."
214 (let ((item (first body)))
215 (cond
216 ((and (listp item) (eq :tag (first item)))
217 (parse-body (rest body) doc (nconc (rest item) tag)))
218 ((and (stringp item) (not doc) (rest body))
219 (if tag
220 (values doc tag (rest body))
221 (parse-body (rest body) doc tag)))
222 (t (values doc tag body)))))
224 (defmacro define-test (name &body body)
225 "Store the test in the test database."
226 (multiple-value-bind (doc tag code) (parse-body body)
227 `(let ((doc (or ,doc (string ',name))))
228 (setf
229 ;; Unit test
230 (gethash ',name (package-table *package* t))
231 (make-instance 'unit-test :doc doc :code ',code))
232 ;; Tags
233 (loop for tag in ',tag do
234 (pushnew
235 ',name (gethash tag (package-tags *package* t))))
236 ;; Return the name of the test
237 ',name)))
239 ;;; Manage tests
241 (defun list-tests (&optional (package *package*))
242 "Return a list of the tests in package."
243 (let ((table (package-table package)))
244 (when table
245 (loop for test-name being each hash-key in table
246 collect test-name))))
248 (defun test-documentation (name &optional (package *package*))
249 "Return the documentation for the test."
250 (let ((unit-test (gethash name (package-table package))))
251 (if (null unit-test)
252 (warn "No code defined for test ~A in package ~S."
253 name package)
254 (doc unit-test))))
256 (defun test-code (name &optional (package *package*))
257 "Returns the code stored for the test name."
258 (let ((unit-test (gethash name (package-table package))))
259 (if (null unit-test)
260 (warn "No code defined for test ~A in package ~S."
261 name package)
262 (code unit-test))))
264 (defun remove-tests (names &optional (package *package*))
265 "Remove individual tests or entire sets."
266 (if (eq :all names)
267 (if (null package)
268 (clrhash *test-db*)
269 (progn
270 (remhash (find-package package) *test-db*)
271 (remhash (find-package package) *tag-db*)))
272 (let ((table (package-table package)))
273 (unless (null table)
274 ;; Remove tests
275 (loop for name in names
276 always (remhash name table)
277 collect name into removed
278 finally (return removed))
279 ;; Remove tests from tags
280 (loop with tags = (package-tags package)
281 for tag being each hash-key in tags
282 using (hash-value tagged-tests)
284 (setf
285 (gethash tag tags)
286 (set-difference tagged-tests names)))))))
288 ;;; Manage tags
290 (defun %tests-from-all-tags (&optional (package *package*))
291 "Return all of the tests that have been tagged."
292 (loop for tests being each hash-value in (package-tags package)
293 nconc (copy-list tests) into all-tests
294 finally (return (delete-duplicates all-tests))))
296 (defun %tests-from-tags (tags &optional (package *package*))
297 "Return the tests associated with the tags."
298 (loop with table = (package-tags package)
299 for tag in tags
300 as tests = (gethash tag table)
301 nconc (copy-list tests) into all-tests
302 finally (return (delete-duplicates all-tests))))
304 (defun list-tags (&optional (package *package*))
305 "Return a list of the tags in package."
306 (let ((tags (package-tags package)))
307 (when tags
308 (loop for tag being each hash-key in tags collect tag))))
310 (defun tagged-tests (tags &optional (package *package*))
311 "Run the tests associated with the specified tags in package."
312 (if (eq :all tags)
313 (%tests-from-all-tags package)
314 (%tests-from-tags tags package)))
316 (defun remove-tags (tags &optional (package *package*))
317 "Remove individual tags or entire sets."
318 (if (eq :all tags)
319 (if (null package)
320 (clrhash *tag-db*)
321 (remhash (find-package package) *tag-db*))
322 (let ((table (package-tags package)))
323 (unless (null table)
324 (loop for tag in tags
325 always (remhash tag table)
326 collect tag into removed
327 finally (return removed))))))
329 ;;; Assert macros
331 (defmacro assert-eq (expected form &rest extras)
332 "Assert whether expected and form are EQ."
333 `(expand-assert :equal ,form ,form ,expected ,extras :test #'eq))
335 (defmacro assert-eql (expected form &rest extras)
336 "Assert whether expected and form are EQL."
337 `(expand-assert :equal ,form ,form ,expected ,extras :test #'eql))
339 (defmacro assert-equal (expected form &rest extras)
340 "Assert whether expected and form are EQUAL."
341 `(expand-assert :equal ,form ,form ,expected ,extras :test #'equal))
343 (defmacro assert-equalp (expected form &rest extras)
344 "Assert whether expected and form are EQUALP."
345 `(expand-assert :equal ,form ,form ,expected ,extras :test #'equalp))
347 (defmacro assert-error (condition form &rest extras)
348 "Assert whether form signals condition."
349 `(expand-assert :error ,form (expand-error-form ,form)
350 ,condition ,extras))
352 (defmacro assert-expands (expansion form &rest extras)
353 "Assert whether form expands to expansion."
354 `(expand-assert :macro ,form
355 (expand-macro-form ,form nil)
356 ,expansion ,extras))
358 (defmacro assert-false (form &rest extras)
359 "Assert whether the form is false."
360 `(expand-assert :result ,form ,form nil ,extras))
362 (defmacro assert-equality (test expected form &rest extras)
363 "Assert whether expected and form are equal according to test."
364 `(expand-assert :equal ,form ,form ,expected ,extras :test ,test))
366 (defmacro assert-prints (output form &rest extras)
367 "Assert whether printing the form generates the output."
368 `(expand-assert :output ,form (expand-output-form ,form)
369 ,output ,extras))
371 (defmacro assert-true (form &rest extras)
372 "Assert whether the form is true."
373 `(expand-assert :result ,form ,form t ,extras))
375 (defmacro expand-assert (type form body expected extras &key (test '#'eql))
376 "Expand the assertion to the internal format."
377 `(internal-assert ,type ',form
378 (lambda () ,body)
379 (lambda () ,expected)
380 (expand-extras ,extras)
381 ,test))
383 (defmacro expand-error-form (form)
384 "Wrap the error assertion in HANDLER-CASE."
385 `(handler-case ,form
386 (condition (error) error)))
388 (defmacro expand-output-form (form)
389 "Capture the output of the form in a string."
390 (let ((out (gensym)))
391 `(let* ((,out (make-string-output-stream))
392 (*standard-output*
393 (make-broadcast-stream *standard-output* ,out)))
394 ,form
395 (get-output-stream-string ,out))))
397 (defmacro expand-macro-form (form env)
398 "Expand the macro form once."
399 `(macroexpand-1 ',form ,env))
401 (defmacro expand-extras (extras)
402 "Expand extra forms."
403 `(lambda ()
404 (list ,@(mapcan (lambda (form) (list `',form form)) extras))))
406 (defun internal-assert
407 (type form code-thunk expected-thunk extras test)
408 "Perform the assertion and record the results."
409 (let* ((expected (multiple-value-list (funcall expected-thunk)))
410 (actual (multiple-value-list (funcall code-thunk)))
411 (passed (test-passed-p type expected actual test)))
412 ;; Count the assertion
413 (if passed
414 (incf *pass*)
415 (incf *fail*))
416 ;; Report the assertion
417 (when (and (not passed) *print-failures*)
418 (print-failure type form expected actual extras))
419 ;; Return the result
420 passed))
422 ;;; Test passed predicate.
424 (defgeneric test-passed-p (type expected actual test)
425 (:documentation
426 "Return the result of the test."))
428 (defmethod test-passed-p ((type (eql :error)) expected actual test)
429 "Return the result of the error assertion."
431 (eql (car actual) (car expected))
432 (typep (car actual) (car expected))))
434 (defmethod test-passed-p ((type (eql :equal)) expected actual test)
435 "Return the result of the equality assertion."
436 (and
437 (<= (length expected) (length actual))
438 (every test expected actual)))
440 (defmethod test-passed-p ((type (eql :macro)) expected actual test)
441 "Return the result of the macro expansion."
442 (equal (car actual) (car expected)))
444 (defmethod test-passed-p ((type (eql :output)) expected actual test)
445 "Return the result of the printed output."
446 (string=
447 (string-trim '(#\newline #\return #\space) (car actual))
448 (car expected)))
450 (defmethod test-passed-p ((type (eql :result)) expected actual test)
451 "Return the result of the assertion."
452 (logically-equal (car actual) (car expected)))
454 ;;; Results
456 (defclass test-results ()
457 ((test-names
458 :type list
459 :initarg :test-names
460 :accessor test-names)
461 (pass
462 :type fixnum
463 :initform 0
464 :accessor pass)
465 (fail
466 :type fixnum
467 :initform 0
468 :accessor fail)
469 (exerr
470 :type fixnum
471 :initform 0
472 :accessor exerr)
473 (failed-tests
474 :type list
475 :initform ()
476 :accessor failed-tests)
477 (error-tests
478 :type list
479 :initform ()
480 :accessor error-tests)
481 (missing-tests
482 :type list
483 :initform ()
484 :accessor missing-tests))
485 (:default-initargs :test-names ())
486 (:documentation
487 "Store the results of the tests for further evaluation."))
489 (defmethod print-object ((object test-results) stream)
490 "Print the summary counts with the object."
491 (format stream "#<~A Total(~D) Passed(~D) Failed(~D) Errors(~D)>~%"
492 (class-name (class-of object))
493 (+ (pass object) (fail object))
494 (pass object) (fail object) (exerr object)))
496 (defun record-result (test-name code results)
497 "Run the test code and record the result."
498 (multiple-value-bind (pass fail exerr)
499 (run-test-thunk code)
500 (push test-name (test-names results))
501 ;; Count passed tests
502 (when (plusp pass)
503 (incf (pass results) pass))
504 ;; Count failed tests and record name
505 (when (plusp fail)
506 (incf (fail results) fail)
507 (push test-name (failed-tests results)))
508 ;; Count errors and record name
509 (when (eq :error exerr)
510 (incf (exerr results))
511 (push test-name (error-tests results)))
512 ;; Print a summary of the results
513 (when (or *print-summary* *print-failures* *print-errors*)
514 (print-summary
515 test-name pass fail
516 (when (eq :error exerr) 1)))))
518 (defun summarize-results (results)
519 "Print a summary of all results."
520 (let ((pass (pass results))
521 (fail (fail results)))
522 (format t "~&Unit Test Summary~%")
523 (format t " | ~D assertions total~%" (+ pass fail))
524 (format t " | ~D passed~%" pass)
525 (format t " | ~D failed~%" fail)
526 (format t " | ~D execution errors~%" (exerr results))
527 (format t " | ~D missing tests~2%"
528 (length (missing-tests results)))))
530 ;;; Run the tests
532 (defun run-code (code)
533 "Run the code to test the assertions."
534 (funcall (coerce `(lambda () ,@code) 'function)))
536 (defun run-test-thunk (code)
537 (let ((*pass* 0)
538 (*fail* 0))
539 (handler-case (run-code code)
540 (error (condition)
541 (when *print-errors*
542 (print-error condition))
543 (if (use-debugger-p condition)
544 condition
545 (return-from run-test-thunk
546 (values *pass* *fail* :error)))))
547 ;; Return the result count
548 (values *pass* *fail* nil)))
550 (defun %run-all-thunks (&optional (package *package*))
551 "Run all of the test thunks in the package."
552 (loop
553 with results = (make-instance 'test-results)
554 for test-name being each hash-key in (package-table package)
555 using (hash-value unit-test)
556 if unit-test do
557 (record-result test-name (code unit-test) results)
558 else do
559 (push test-name (missing-tests results))
560 ;; Summarize and return the test results
561 finally
562 (summarize-results results)
563 (return results)))
565 (defun %run-thunks (test-names &optional (package *package*))
566 "Run the list of test thunks in the package."
567 (loop
568 with table = (package-table package)
569 and results = (make-instance 'test-results)
570 for test-name in test-names
571 as unit-test = (gethash test-name table)
572 if unit-test do
573 (record-result test-name (code unit-test) results)
574 else do
575 (push test-name (missing-tests results))
576 finally
577 (summarize-results results)
578 (return results)))
580 (defun run-tests (test-names &optional (package *package*))
581 "Run the specified tests in package."
582 (if (eq :all test-names)
583 (%run-all-thunks package)
584 (%run-thunks test-names package)))
586 (defun run-tags (tags &optional (package *package*))
587 "Run the tests associated with the specified tags in package."
588 (%run-thunks (get-tagged-tests tags package) package))
590 ;;; Useful equality predicates for tests
592 ;;; (LOGICALLY-EQUAL x y) => true or false
593 ;;; Return true if x and y both false or both true
594 (defun logically-equal (x y)
595 (eql (not x) (not y)))
597 ;;; (SET-EQUAL l1 l2 :test) => true or false
598 ;;; Return true if every element of l1 is an element of l2
599 ;;; and vice versa.
600 (defun set-equal (l1 l2 &key (test #'equal))
601 (and (listp l1)
602 (listp l2)
603 (subsetp l1 l2 :test test)
604 (subsetp l2 l1 :test test)))
606 (pushnew :lisp-unit common-lisp:*features*)