Update get-tests and get-test-code for managing tests.
[lisp-unit.git] / lisp-unit.lisp
bloba143bd27937c2077cb81ce7c38bdf49e5e9cac66
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 2. Load this file.
37 2. (use-package :lisp-unit)
39 3. Load your code file and your file of tests.
41 4. 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 :remove-tests
77 :run-tests
78 :use-debugger)
79 ;; Functions for reporting test results
80 (:export :test-names
81 :failed-tests
82 :error-tests
83 :missing-tests
84 :summarize-results)
85 ;; Utility predicates
86 (:export :logically-equal :set-equal))
88 (in-package :lisp-unit)
90 ;;; Global counters
92 (defparameter *pass* 0
93 "The number of passed assertions.")
95 (defparameter *fail* 0
96 "The number of failed assertions.")
98 ;;; Global options
100 (defparameter *print-summary* nil
101 "Print a summary of the pass, fail, and error count if non-nil.")
103 (defparameter *print-failures* nil
104 "Print failure messages if non-NIL.")
106 (defparameter *print-errors* nil
107 "Print error messages if non-NIL.")
109 (defparameter *use-debugger* nil
110 "If not NIL, enter the debugger when an error is encountered in an
111 assertion.")
113 (defun use-debugger-p (condition)
114 "Debug or ignore errors."
115 (cond
116 ((eq :ask *use-debugger*)
117 (y-or-n-p "~A -- debug?" condition))
118 (*use-debugger*)))
120 ;;; Failure control strings
122 (defgeneric failure-control-string (type)
123 (:method (type)
124 "~& | Expected ~{~S~^; ~} ~<~% | ~:;but saw ~{~S~^; ~}~>")
125 (:documentation
126 "Return the FORMAT control string for the failure type."))
128 (defmethod failure-control-string ((type (eql :error)))
129 "~& | ~@[Should have signalled ~{~S~^; ~} but saw~] ~{~S~^; ~}")
131 (defmethod failure-control-string ((type (eql :macro)))
132 "~& | Should have expanded to ~{~S~^; ~} ~<~%~:;but saw ~{~S~^; ~}~>")
134 (defmethod failure-control-string ((type (eql :output)))
135 "~& | Should have printed ~{~S~^; ~} ~<~%~:;but saw ~{~S~^; ~}~>")
137 (defun print-failure (type form expected actual extras)
138 "Report the details of the failure assertion."
139 (format t " | Failed Form: ~S" form)
140 (format t (failure-control-string type) expected actual)
141 (when extras
142 (format t "~{~& | ~S => ~S~}~%" (funcall extras)))
143 (format t "~& |~%")
144 type)
146 (defun print-error (condition)
147 "Print the error condition."
148 (let ((*print-escape* nil))
149 (format t "~& | Execution error:~% | ~W" condition)
150 (format t "~& |~%")))
152 (defun print-summary (name pass fail &optional exerr)
153 "Print a summary of the test results."
154 (format t "~&~A: ~S assertions passed, ~S failed"
155 name pass fail)
156 (format t "~@[, ~S execution errors~].~2%" exerr))
158 ;;; Global unit test database
160 (defparameter *test-db* (make-hash-table :test #'eq)
161 "The unit test database is simply a hash table.")
163 (defun package-table (package &optional create)
164 (cond
165 ((gethash (find-package package) *test-db*))
166 (create
167 (setf (gethash package *test-db*) (make-hash-table)))
168 (t (warn "No tests defined for package: ~S" package))))
170 (defmacro define-test (name &body body)
171 "Store the test in the test database."
172 `(progn
173 (setf
174 (gethash ',name (package-table *package* t))
175 ',body)
176 ;; Return the name of the test
177 ',name))
179 ;;; Manage tests
181 (defun get-tests (&optional (package *package*))
182 "Return a list of the tests in package."
183 (let ((table (package-table package)))
184 (when table
185 (loop for test-name being each hash-key in table
186 collect test-name))))
188 (defun get-test-code (name &optional (package *package*))
189 "Returns the code stored for the test name."
190 (let ((code (gethash name (package-table package))))
191 (if (null code)
192 (warn "No code defined for test ~A in package ~S."
193 name package)
194 code)))
196 (defun remove-tests (names &optional (package *package*))
197 "Remove individual tests or entire sets."
198 (if (eq :all names)
199 (if (null package)
200 (clrhash *test-db*)
201 (remhash (find-package package) *test-db*))
202 (let ((table (package-table package)))
203 (unless (null table)
204 (loop for name in names
205 always (remhash name table)
206 collect name into removed
207 finally (return removed))))))
209 ;;; Assert macros
211 (defmacro assert-eq (expected form &rest extras)
212 "Assert whether expected and form are EQ."
213 `(expand-assert :equal ,form ,form ,expected ,extras :test #'eq))
215 (defmacro assert-eql (expected form &rest extras)
216 "Assert whether expected and form are EQL."
217 `(expand-assert :equal ,form ,form ,expected ,extras :test #'eql))
219 (defmacro assert-equal (expected form &rest extras)
220 "Assert whether expected and form are EQUAL."
221 `(expand-assert :equal ,form ,form ,expected ,extras :test #'equal))
223 (defmacro assert-equalp (expected form &rest extras)
224 "Assert whether expected and form are EQUALP."
225 `(expand-assert :equal ,form ,form ,expected ,extras :test #'equalp))
227 (defmacro assert-error (condition form &rest extras)
228 "Assert whether form signals condition."
229 `(expand-assert :error ,form (expand-error-form ,form)
230 ,condition ,extras))
232 (defmacro assert-expands (expansion form &rest extras)
233 "Assert whether form expands to expansion."
234 `(expand-assert :macro ,form
235 (expand-macro-form ,form nil)
236 ,expansion ,extras))
238 (defmacro assert-false (form &rest extras)
239 "Assert whether the form is false."
240 `(expand-assert :result ,form ,form nil ,extras))
242 (defmacro assert-equality (test expected form &rest extras)
243 "Assert whether expected and form are equal according to test."
244 `(expand-assert :equal ,form ,form ,expected ,extras :test ,test))
246 (defmacro assert-prints (output form &rest extras)
247 "Assert whether printing the form generates the output."
248 `(expand-assert :output ,form (expand-output-form ,form)
249 ,output ,extras))
251 (defmacro assert-true (form &rest extras)
252 "Assert whether the form is true."
253 `(expand-assert :result ,form ,form t ,extras))
255 (defmacro expand-assert (type form body expected extras &key (test '#'eql))
256 "Expand the assertion to the internal format."
257 `(internal-assert ,type ',form
258 (lambda () ,body)
259 (lambda () ,expected)
260 (expand-extras ,extras)
261 ,test))
263 (defmacro expand-error-form (form)
264 "Wrap the error assertion in HANDLER-CASE."
265 `(handler-case ,form
266 (condition (error) error)))
268 (defmacro expand-output-form (form)
269 "Capture the output of the form in a string."
270 (let ((out (gensym)))
271 `(let* ((,out (make-string-output-stream))
272 (*standard-output*
273 (make-broadcast-stream *standard-output* ,out)))
274 ,form
275 (get-output-stream-string ,out))))
277 (defmacro expand-macro-form (form env)
278 "Expand the macro form once."
279 `(macroexpand-1 ',form ,env))
281 (defmacro expand-extras (extras)
282 "Expand extra forms."
283 `(lambda ()
284 (list ,@(mapcan (lambda (form) (list `',form form)) extras))))
286 (defun internal-assert
287 (type form code-thunk expected-thunk extras test)
288 "Perform the assertion and record the results."
289 (let ((expected (multiple-value-list (funcall expected-thunk)))
290 (actual (multiple-value-list (funcall code-thunk)))
291 (passed nil))
292 ;; Count the assertion
293 (if (setq passed (test-passed-p type expected actual test))
294 (incf *pass*)
295 (incf *fail*))
296 ;; Report the assertion
297 (when (and (not passed) *print-failures*)
298 (print-failure type form expected actual extras))
299 ;; Return the result
300 passed))
302 ;;; Test passed predicate.
304 (defgeneric test-passed-p (type expected actual test)
305 (:documentation
306 "Return the result of the test."))
308 (defmethod test-passed-p ((type (eql :error)) expected actual test)
309 "Return the result of the error assertion."
311 (eql (car actual) (car expected))
312 (typep (car actual) (car expected))))
314 (defmethod test-passed-p ((type (eql :equal)) expected actual test)
315 "Return the result of the equality assertion."
316 (and
317 (<= (length expected) (length actual))
318 (every test expected actual)))
320 (defmethod test-passed-p ((type (eql :macro)) expected actual test)
321 "Return the result of the macro expansion."
322 (equal (car actual) (car expected)))
324 (defmethod test-passed-p ((type (eql :output)) expected actual test)
325 "Return the result of the printed output."
326 (string=
327 (string-trim '(#\newline #\return #\space) (car actual))
328 (car expected)))
330 (defmethod test-passed-p ((type (eql :result)) expected actual test)
331 "Return the result of the assertion."
332 (logically-equal (car actual) (car expected)))
334 ;;; Results
336 (defclass test-results ()
337 ((test-names
338 :type list
339 :initarg :test-names
340 :accessor test-names)
341 (pass
342 :type fixnum
343 :initform 0
344 :accessor pass)
345 (fail
346 :type fixnum
347 :initform 0
348 :accessor fail)
349 (exerr
350 :type fixnum
351 :initform 0
352 :accessor exerr)
353 (failed-tests
354 :type list
355 :initform ()
356 :accessor failed-tests)
357 (error-tests
358 :type list
359 :initform ()
360 :accessor error-tests)
361 (missing-tests
362 :type list
363 :initform ()
364 :accessor missing-tests))
365 (:default-initargs :test-names ())
366 (:documentation
367 "Store the results of the tests for further evaluation."))
369 (defmethod print-object ((object test-results) stream)
370 "Print the summary counts with the object."
371 (format stream "#<~A Total(~D) Passed(~D) Failed(~D) Errors(~D)>~%"
372 (class-name (class-of object))
373 (+ (pass object) (fail object))
374 (pass object) (fail object) (exerr object)))
376 (defun record-result (test-name code results)
377 "Run the test code and record the result."
378 (multiple-value-bind (pass fail exerr)
379 (run-test-thunk code)
380 (push test-name (test-names results))
381 ;; Count passed tests
382 (when (plusp pass)
383 (incf (pass results) pass))
384 ;; Count failed tests and record name
385 (when (plusp fail)
386 (incf (fail results) fail)
387 (push test-name (failed-tests results)))
388 ;; Count errors and record name
389 (when (eq :error exerr)
390 (incf (exerr results))
391 (push test-name (error-tests results)))
392 ;; Print a summary of the results
393 (when (or *print-summary* *print-failures* *print-errors*)
394 (print-summary
395 test-name pass fail
396 (when (eq :error exerr) 1)))))
398 (defun summarize-results (results)
399 "Print a summary of all results."
400 (let ((pass (pass results))
401 (fail (fail results)))
402 (format t "~&Unit Test Summary~%")
403 (format t " | ~D assertions total~%" (+ pass fail))
404 (format t " | ~D passed~%" pass)
405 (format t " | ~D failed~%" fail)
406 (format t " | ~D execution errors~%" (exerr results))
407 (format t " | ~D missing tests~2%"
408 (length (missing-tests results)))))
410 ;;; Run the tests
412 (defun run-code (code)
413 "Run the code to test the assertions."
414 (funcall (coerce `(lambda () ,@code) 'function)))
416 (defun run-test-thunk (code)
417 (let ((*pass* 0)
418 (*fail* 0))
419 (handler-case (run-code code)
420 (error (condition)
421 (when *print-errors*
422 (print-error condition))
423 (if (use-debugger-p condition)
424 condition
425 (return-from run-test-thunk
426 (values *pass* *fail* :error)))))
427 ;; Return the result count
428 (values *pass* *fail* nil)))
430 (defun %run-all-thunks (&optional (package *package*))
431 "Run all of the test thunks in the package."
432 (loop
433 with results = (make-instance 'test-results)
434 for test-name being each hash-key in (package-table package)
435 using (hash-value code)
436 if code do
437 (record-result test-name code results)
438 else do
439 (push test-name (missing-tests results))
440 ;; Summarize and return the test results
441 finally
442 (summarize-results results)
443 (return results)))
445 (defun %run-thunks (test-names &optional (package *package*))
446 "Run the list of test thunks in the package."
447 (loop
448 with table = (package-table package)
449 and results = (make-instance 'test-results)
450 for test-name in test-names
451 as code = (gethash test-name table)
452 if code do
453 (record-result test-name code results)
454 else do
455 (push test-name (missing-tests results))
456 finally
457 (summarize-results results)
458 (return results)))
460 (defun run-tests (test-names &optional (package *package*))
461 "Run the specified tests in package."
462 (if (eq :all test-names)
463 (%run-all-thunks package)
464 (%run-thunks test-names package)))
466 ;;; Useful equality predicates for tests
468 ;;; (LOGICALLY-EQUAL x y) => true or false
469 ;;; Return true if x and y both false or both true
470 (defun logically-equal (x y)
471 (eql (not x) (not y)))
473 ;;; (SET-EQUAL l1 l2 :test) => true or false
474 ;;; Return true if every element of l1 is an element of l2
475 ;;; and vice versa.
476 (defun set-equal (l1 l2 &key (test #'equal))
477 (and (listp l1)
478 (listp l2)
479 (subsetp l1 l2 :test test)
480 (subsetp l2 l1 :test test)))
482 (pushnew :lisp-unit common-lisp:*features*)