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