d9b8c5f5ac18183e900109458d7ff0350e381235
[fiveam.git] / src / run.lisp
1 ;;;; -*- Mode: Lisp; indent-tabs-mode: nil -*-
2
3 (in-package :it.bese.fiveam)
4
5 ;;;; * Running Tests
6
7 ;;;; Once the programmer has defined what the tests are these need to
8 ;;;; be run and the expected effects should be compared with the
9 ;;;; actual effects. FiveAM provides the function RUN for this
10 ;;;; purpose, RUN executes a number of tests and collects the results
11 ;;;; of each individual check into a list which is then
12 ;;;; returned. There are three types of test results: passed, failed
13 ;;;; and skipped, these are represented by TEST-RESULT objects.
14
15 ;;;; Generally running a test will return normally, but there are two
16 ;;;; exceptional situations which can occur:
17
18 ;;;; - An exception is signaled while running the test. If the
19 ;;;;   variable *debug-on-error* is T than FiveAM will enter the
20 ;;;;   debugger, otherwise a test failure (of type
21 ;;;;   unexpected-test-failure) is returned. When entering the
22 ;;;;   debugger two restarts are made available, one simply reruns the
23 ;;;;   current test and another signals a test-failure and continues
24 ;;;;   with the remaining tests.
25
26 ;;;; - A circular dependency is detected. An error is signaled and a
27 ;;;;   restart is made available which signals a test-skipped and
28 ;;;;   continues with the remaining tests. This restart also sets the
29 ;;;;   dependency status of the test to nil, so any tests which depend
30 ;;;;   on this one (even if the dependency is not circular) will be
31 ;;;;   skipped.
32
33 ;;;; The functions RUN!, !, !! and !!! are convenient wrappers around
34 ;;;; RUN and EXPLAIN.
35
36 (defparameter *debug-on-error* nil
37   "T if we should drop into a debugger on error, NIL otherwise.")
38
39 (defparameter *debug-on-failure* nil
40   "T if we should drop into a debugger on a failing check, NIL otherwise.")
41
42 (defparameter *print-names* t
43   "T if we should print test running progress, NIL otherwise.")
44
45 (defun import-testing-symbols (package-designator)
46   (import '(5am::is 5am::is-true 5am::is-false 5am::signals 5am::finishes)
47           package-designator))
48
49 (defparameter *run-queue* '()
50   "List of test waiting to be run.")
51
52 (define-condition circular-dependency (error)
53   ((test-case :initarg :test-case))
54   (:report (lambda (cd stream)
55              (format stream "A circular dependency wes detected in ~S." (slot-value cd 'test-case))))
56   (:documentation "Condition signaled when a circular dependency
57 between test-cases has been detected."))
58
59 (defgeneric run-resolving-dependencies (test)
60   (:documentation "Given a dependency spec determine if the spec
61 is satisfied or not, this will generally involve running other
62 tests. If the dependency spec can be satisfied the test is also
63 run."))
64
65 (defmethod run-resolving-dependencies ((test test-case))
66   "Return true if this test, and its dependencies, are satisfied,
67   NIL otherwise."
68   (case (status test)
69     (:unknown
70      (setf (status test) :resolving)
71      (if (or (not (depends-on test))
72              (eql t (resolve-dependencies (depends-on test))))
73          (progn
74            (run-test-lambda test)
75            (status test))
76          (with-run-state (result-list)
77            (unless (eql :circular (status test))
78              (push (make-instance 'test-skipped
79                                   :test-case test
80                                   :reason "Dependencies not satisfied")
81                    result-list)
82              (setf (status test) :depends-not-satisfied)))))
83     (:resolving
84      (restart-case
85          (error 'circular-dependency :test-case test)
86        (skip ()
87          :report (lambda (s)
88                    (format s "Skip the test ~S and all its dependencies." (name test)))
89          (with-run-state (result-list)
90            (push (make-instance 'test-skipped :reason "Circular dependencies" :test-case test)
91                  result-list))
92          (setf (status test) :circular))))
93     (t (status test))))
94
95 (defgeneric resolve-dependencies (depends-on))
96
97 (defmethod resolve-dependencies ((depends-on symbol))
98   "A test which depends on a symbol is interpreted as `(AND
99   ,DEPENDS-ON)."
100   (run-resolving-dependencies (get-test depends-on)))
101
102 (defmethod resolve-dependencies ((depends-on list))
103   "Return true if the dependency spec DEPENDS-ON is satisfied,
104   nil otherwise."
105   (if (null depends-on)
106       t
107       (flet ((satisfies-depends-p (test)
108                (funcall test (lambda (dep)
109                                (eql t (resolve-dependencies dep)))
110                         (cdr depends-on))))
111         (ecase (car depends-on)
112           (and (satisfies-depends-p #'every))
113           (or  (satisfies-depends-p #'some))
114           (not (satisfies-depends-p #'notany))
115           (:before (every #'(lambda (dep)
116                               (let ((status (status (get-test dep))))
117                                 (eql :unknown status)))
118                           (cdr depends-on)))))))
119
120 (defun results-status (result-list)
121   "Given a list of test results (generated while running a test)
122   return true if all of the results are of type TEST-PASSED,
123   fail otherwise.
124   Returns a second value, which is the set of failed tests."
125   (let ((failed-tests
126           (remove-if #'test-passed-p result-list)))
127     (values (null failed-tests)
128             failed-tests)))
129
130 (defun return-result-list (test-lambda)
131   "Run the test function TEST-LAMBDA and return a list of all
132   test results generated, does not modify the special environment
133   variable RESULT-LIST."
134   (bind-run-state ((result-list '()))
135     (funcall test-lambda)
136     result-list))
137
138 (defgeneric run-test-lambda (test))
139
140 (defmethod run-test-lambda ((test test-case))
141   (with-run-state (result-list)
142     (bind-run-state ((current-test test))
143       (labels ((abort-test (e)
144                  (add-result 'unexpected-test-failure
145                              :test-expr nil
146                              :test-case test
147                              :reason (format nil "Unexpected Error: ~S~%~A." e e)
148                              :condition e))
149                (run-it ()
150                  (let ((result-list '()))
151                    (declare (special result-list))
152                    (handler-bind ((check-failure (lambda (e)
153                                                    (declare (ignore e))
154                                                    (unless *debug-on-failure*
155                                                      (invoke-restart
156                                                       (find-restart 'ignore-failure)))))
157                                   (error (lambda (e)
158                                            (unless (or *debug-on-error*
159                                                        (typep e 'check-failure))
160                                              (abort-test e)
161                                              (return-from run-it result-list)))))
162                      (restart-case
163                          (let ((*readtable* (copy-readtable))
164                                (*package* (runtime-package test)))
165                            (if (collect-profiling-info test)
166                                ;; Timing info doesn't get collected ATM, we need a portable library
167                                ;; (setf (profiling-info test) (collect-timing (test-lambda test)))
168                                (funcall (test-lambda test))
169                                (funcall (test-lambda test))))
170                        (retest ()
171                          :report (lambda (stream)
172                                    (format stream "~@<Rerun the test ~S~@:>" test))
173                          (return-from run-it (run-it)))
174                        (ignore ()
175                          :report (lambda (stream)
176                                    (format stream "~@<Signal an exceptional test failure and abort the test ~S.~@:>" test))
177                          (abort-test (make-instance 'test-failure :test-case test
178                                                     :reason "Failure restart."))))
179                      result-list))))
180         (let ((results (run-it)))
181           (setf (status test) (results-status results)
182                 result-list (nconc result-list results)))))))
183
184 (defgeneric %run (test-spec)
185   (:documentation "Internal method for running a test. Does not
186   update the status of the tests nor the special variables !,
187   !!, !!!"))
188
189 (defmethod %run ((test test-case))
190   (when *print-names*
191     (format *test-dribble* "~% Running test ~A " (name test)))
192   (run-resolving-dependencies test))
193
194 (defmethod %run ((tests list))
195   (mapc #'%run tests))
196
197 (defmethod %run ((suite test-suite))
198   (when *print-names*
199     (format *test-dribble* "~%Running test suite ~A~%" (name suite)))
200   (let ((suite-results '()))
201     (flet ((run-tests ()
202              (loop
203                 for test being the hash-values of (tests suite)
204                 do (%run test))))
205       (unwind-protect
206            (bind-run-state ((result-list '()))
207              (unwind-protect
208                   (if (collect-profiling-info suite)
209                       ;; Timing info doesn't get collected ATM, we need a portable library
210                       ;; (setf (profiling-info suite) (collect-timing #'run-tests))
211                       (run-tests)
212                       (run-tests)))
213              (setf suite-results result-list
214                    (status suite) (every #'test-passed-p suite-results)))
215         (with-run-state (result-list)
216           (setf result-list (nconc result-list suite-results)))))))
217
218 (defmethod %run ((test-name symbol))
219   (when-let (test (get-test test-name))
220     (%run test)))
221
222 (defvar *initial-!* (lambda () (format t "Haven't run that many tests yet.~%")))
223
224 (defvar *!* *initial-!*)
225 (defvar *!!* *initial-!*)
226 (defvar *!!!* *initial-!*)
227
228 ;;;; ** Public entry points
229
230 (defun run! (&optional (test-spec *suite*)
231              &key ((:print-names *print-names*) *print-names*))
232   "Equivalent to (explain! (run TEST-SPEC))."
233   (explain! (run test-spec)))
234
235 (defun explain! (result-list)
236   "Explain the results of RESULT-LIST using a
237 detailed-text-explainer with output going to *test-dribble*"
238   (explain (make-instance 'detailed-text-explainer) result-list *test-dribble*))
239
240 (defun debug! (&optional (test-spec *suite*))
241   "Calls (run! test-spec) but enters the debugger if any kind of error happens."
242   (let ((*debug-on-error* t)
243         (*debug-on-failure* t))
244     (run! test-spec)))
245
246 (defun run (test-spec &key ((:print-names *print-names*) *print-names*))
247   "Run the test specified by TEST-SPEC.
248
249 TEST-SPEC can be either a symbol naming a test or test suite, or
250 a testable-object object. This function changes the operations
251 performed by the !, !! and !!! functions."
252   (psetf *!* (lambda ()
253                (loop :for test :being :the :hash-keys :of *test*
254                      :do (setf (status (get-test test)) :unknown))
255                (bind-run-state ((result-list '()))
256                  (with-simple-restart (explain "Ignore the rest of the tests and explain current results")
257                    (%run test-spec))
258                  result-list))
259          *!!* *!*
260          *!!!* *!!*)
261   (funcall *!*))
262
263 (defun ! ()
264   "Rerun the most recently run test and explain the results."
265   (explain! (funcall *!*)))
266
267 (defun !! ()
268   "Rerun the second most recently run test and explain the results."
269   (explain! (funcall *!!*)))
270
271 (defun !!! ()
272   "Rerun the third most recently run test and explain the results."
273   (explain! (funcall *!!!*)))
274
275 ;; Copyright (c) 2002-2003, Edward Marco Baringer
276 ;; All rights reserved.
277 ;;
278 ;; Redistribution and use in source and binary forms, with or without
279 ;; modification, are permitted provided that the following conditions are
280 ;; met:
281 ;;
282 ;;  - Redistributions of source code must retain the above copyright
283 ;;    notice, this list of conditions and the following disclaimer.
284 ;;
285 ;;  - Redistributions in binary form must reproduce the above copyright
286 ;;    notice, this list of conditions and the following disclaimer in the
287 ;;    documentation and/or other materials provided with the distribution.
288 ;;
289 ;;  - Neither the name of Edward Marco Baringer, nor BESE, nor the names
290 ;;    of its contributors may be used to endorse or promote products
291 ;;    derived from this software without specific prior written permission.
292 ;;
293 ;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
294 ;; "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
295 ;; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
296 ;; A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT
297 ;; OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
298 ;; SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
299 ;; LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
300 ;; DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
301 ;; THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
302 ;; (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
303 ;; OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.