96d48fa40f4cd436d9b316417bfa9842c7824679
[fiveam.git] / src / check.lisp
1 ;;;; -*- Mode: Lisp; indent-tabs-mode: nil -*-
2
3 (in-package :it.bese.fiveam)
4
5 ;;;; * Checks
6
7 ;;;; At the lowest level testing the system requires that certain
8 ;;;; forms be evaluated and that certain post conditions are met: the
9 ;;;; value returned must satisfy a certain predicate, the form must
10 ;;;; (or must not) signal a certain condition, etc. In FiveAM these
11 ;;;; low level operations are called 'checks' and are defined using
12 ;;;; the various checking macros.
13
14 ;;;; Checks are the basic operators for collecting results. Tests and
15 ;;;; test suites on the other hand allow grouping multiple checks into
16 ;;;; logic collections.
17
18 (defvar *test-dribble* t)
19
20 (defmacro with-*test-dribble* (stream &body body)
21   `(let ((*test-dribble* ,stream))
22      (declare (special *test-dribble*))
23      ,@body))
24
25 (eval-when (:compile-toplevel :load-toplevel :execute)
26   (def-special-environment run-state ()
27     result-list
28     current-test))
29
30 ;;;; ** Types of test results
31
32 ;;;; Every check produces a result object.
33
34 (defclass test-result ()
35   ((reason :accessor reason :initarg :reason :initform "no reason given")
36    (test-case :accessor test-case :initarg :test-case)
37    (test-expr :accessor test-expr :initarg :test-expr))
38   (:documentation "All checking macros will generate an object of
39 type TEST-RESULT."))
40
41 (defclass test-passed (test-result)
42   ()
43   (:documentation "Class for successful checks."))
44
45 (defgeneric test-passed-p (object)
46   (:method ((o t)) nil)
47   (:method ((o test-passed)) t))
48
49 (define-condition check-failure (error)
50   ((reason :accessor reason :initarg :reason :initform "no reason given")
51    (test-case :accessor test-case :initarg :test-case)
52    (test-expr :accessor test-expr :initarg :test-expr))
53   (:documentation "Signaled when a check fails.")
54   (:report  (lambda (c stream)
55               (format stream "The following check failed: ~S~%~A."
56                       (test-expr c)
57                       (reason c)))))
58
59 (defmacro process-failure (&rest args)
60   `(progn
61      (with-simple-restart (ignore-failure "Continue the test run.")
62        (error 'check-failure ,@args))
63      (add-result 'test-failure ,@args)))
64
65 (defclass test-failure (test-result)
66   ()
67   (:documentation "Class for unsuccessful checks."))
68
69 (defgeneric test-failure-p (object)
70   (:method ((o t)) nil)
71   (:method ((o test-failure)) t))
72
73 (defclass unexpected-test-failure (test-failure)
74   ((actual-condition :accessor actual-condition :initarg :condition))
75   (:documentation "Represents the result of a test which neither
76 passed nor failed, but signaled an error we couldn't deal
77 with.
78
79 Note: This is very different than a SIGNALS check which instead
80 creates a TEST-PASSED or TEST-FAILURE object."))
81
82 (defclass test-skipped (test-result)
83   ()
84   (:documentation "A test which was not run. Usually this is due
85 to unsatisfied dependencies, but users can decide to skip test
86 when appropiate."))
87
88 (defgeneric test-skipped-p (object)
89   (:method ((o t)) nil)
90   (:method ((o test-skipped)) t))
91
92 (defun add-result (result-type &rest make-instance-args)
93   "Create a TEST-RESULT object of type RESULT-TYPE passing it the
94 initialize args MAKE-INSTANCE-ARGS and adds the resulting object to
95 the list of test results."
96   (with-run-state (result-list current-test)
97     (let ((result (apply #'make-instance result-type
98                          (append make-instance-args (list :test-case current-test)))))
99       (etypecase result
100         (test-passed  (format *test-dribble* "."))
101         (unexpected-test-failure (format *test-dribble* "X"))
102         (test-failure (format *test-dribble* "f"))
103         (test-skipped (format *test-dribble* "s")))
104       (push result result-list))))
105
106 ;;;; ** The check operators
107
108 ;;;; *** The IS check
109
110 (defmacro is (test &rest reason-args)
111   "The DWIM checking operator.
112
113 If TEST returns a true value a test-passed result is generated,
114 otherwise a test-failure result is generated. The reason, unless
115 REASON-ARGS is provided, is generated based on the form of TEST:
116
117 `(predicate expected actual)`::
118
119 Means that we want to check whether, according to PREDICATE, the
120 ACTUAL value is in fact what we EXPECTED. `expected` can also be a
121 values form, `(cl:values &rest values)`. In this case the values
122 returned by `actual` will be converted to a list and that list will be
123 compared, via `predicate` to the list `values`.
124
125 `(predicate value)`::
126
127 Means that we want to ensure that VALUE satisfies PREDICATE.
128
129 Wrapping the TEST form in a NOT simply produces a negated reason
130 string."
131   (assert (listp test)
132           (test)
133           "Argument to IS must be a list, not ~S" test)
134   (let (bindings effective-test default-reason-args)
135     (with-gensyms (e a v)
136       (flet ((process-entry (predicate expected actual &optional negatedp)
137                ;; make sure EXPECTED is holding the entry that starts with 'values
138                (when (and (consp actual)
139                           (eq (car actual) 'values))
140                  (assert (not (and (consp expected)
141                                    (eq (car expected) 'values))) ()
142                                    "Both the expected and actual part is a values expression.")
143                  (rotatef expected actual))
144                (let ((setf-forms))
145                  (if (and (consp expected)
146                           (eq (car expected) 'values))
147                      (progn
148                        (setf expected (copy-list expected))
149                        (setf setf-forms (loop for cell = (rest expected) then (cdr cell)
150                                               for i from 0
151                                               while cell
152                                               when (eq (car cell) '*)
153                                               collect `(setf (elt ,a ,i) nil)
154                                               and do (setf (car cell) nil)))
155                        (setf bindings (list (list e `(list ,@(rest expected)))
156                                             (list a `(multiple-value-list ,actual)))))
157                      (setf bindings (list (list e expected)
158                                           (list a actual))))
159                  (setf effective-test `(progn
160                                          ,@setf-forms
161                                          ,(if negatedp
162                                               `(not (,predicate ,e ,a))
163                                               `(,predicate ,e ,a)))))))
164         (list-match-case test
165           ((not (?predicate ?expected ?actual))
166            (process-entry ?predicate ?expected ?actual t)
167            (setf default-reason-args
168                  (list "~2&~S~2% evaluated to ~2&~S~2% which is ~2&~S~2%to ~2&~S~2% (it should not be)"
169                        `',?actual a `',?predicate e)))
170           ((not (?satisfies ?value))
171            (setf bindings (list (list v ?value))
172                  effective-test `(not (,?satisfies ,v))
173                  default-reason-args
174                  (list "~2&~S~2% evaluated to ~2&~S~2% which satisfies ~2&~S~2% (it should not)"
175                        `',?value v `',?satisfies)))
176           ((?predicate ?expected ?actual)
177            (process-entry ?predicate ?expected ?actual)
178            (setf default-reason-args
179                  (list "~2&~S~2% evaluated to ~2&~S~2% which is not ~2&~S~2% to ~2&~S~2%."
180                        `',?actual a `',?predicate e)))
181           ((?satisfies ?value)
182            (setf bindings (list (list v ?value))
183                  effective-test `(,?satisfies ,v)
184                  default-reason-args
185                  (list "~2&~S~2% evaluated to ~2&~S~2% which does not satisfy ~2&~S~2%"
186                        `',?value v `',?satisfies)))
187           (?_
188            (setf bindings '()
189                  effective-test test
190                  default-reason-args (list "~2&~S~2% was NIL." `',test)))))
191       `(let ,bindings
192          (if ,effective-test
193              (add-result 'test-passed :test-expr ',test)
194              (process-failure :reason (format nil ,@(or reason-args default-reason-args))
195                               :test-expr ',test))))))
196
197 ;;;; *** Other checks
198
199 (defmacro is-every (predicate &body clauses)
200   "Tests that all the elements of CLAUSES are equal, according to PREDICATE.
201
202 If every element of CLAUSES is a cons we assume the `first` of each
203 element is the expected value, and the `second` of each element is the
204 actual value and generate a call to `IS` accordingly.
205
206 If not every element of CLAUSES is a cons then we assume that each
207 element is a value to pass to predicate (the 1 argument form of `IS`)"
208   `(progn
209      ,@(if (every #'consp clauses)
210            (loop for (expected actual . reason) in clauses
211                  collect `(is (,predicate ,expected ,actual) ,@reason))
212            (progn
213              (assert (evenp (list-length clauses)))
214              (loop for (expr value) on clauses by #'cddr
215                    collect `(is (,predicate ,expr ,value)))))))
216
217 (defmacro is-true (condition &rest reason-args)
218   "Like IS this check generates a pass if CONDITION returns true
219   and a failure if CONDITION returns false. Unlike IS this check
220   does not inspect CONDITION to determine how to report the
221   failure."
222   `(if ,condition
223        (add-result 'test-passed :test-expr ',condition)
224        (process-failure
225         :reason ,(if reason-args
226                      `(format nil ,@reason-args)
227                      `(format nil "~S did not return a true value" ',condition))
228         :test-expr ',condition)))
229
230 (defmacro is-false (condition &rest reason-args)
231   "Generates a pass if CONDITION returns false, generates a
232   failure otherwise. Like IS-TRUE, and unlike IS, IS-FALSE does
233   not inspect CONDITION to determine what reason to give it case
234   of test failure"
235
236   (with-gensyms (value)
237     `(let ((,value ,condition))
238        (if ,value
239            (process-failure
240             :reason ,(if reason-args
241                          `(format nil ,@reason-args)
242                          `(format nil "~S returned the value ~S, which is true" ',condition ,value ))
243             :test-expr ',condition)
244            (add-result 'test-passed :test-expr ',condition)))))
245
246 (defmacro signals (condition-spec
247                    &body body)
248   "Generates a pass if `BODY` signals a condition of type
249 `CONDITION`. `BODY` is evaluated in a block named `NIL`, `CONDITION`
250 is not evaluated."
251   (let ((block-name (gensym)))
252     (destructuring-bind (condition &optional reason-control reason-args)
253         (ensure-list condition-spec)
254       `(block ,block-name
255          (handler-bind ((,condition (lambda (c)
256                                       (declare (ignore c))
257                                       ;; ok, body threw condition
258                                       (add-result 'test-passed
259                                                   :test-expr ',condition)
260                                       (return-from ,block-name t))))
261            (block nil
262              ,@body))
263          (process-failure
264           :reason ,(if reason-control
265                        `(format nil ,reason-control ,@reason-args)
266                        `(format nil "Failed to signal a ~S" ',condition))
267           :test-expr ',condition)
268          (return-from ,block-name nil)))))
269
270 (defmacro finishes (&body body)
271   "Generates a pass if BODY executes to normal completion. 
272
273 In other words if body signals a condition (which is then handled),
274 return-froms or throws this test fails."
275   `(let ((ok nil))
276      (unwind-protect
277           (progn
278             ,@body
279             (setf ok t))
280        (if ok
281            (add-result 'test-passed :test-expr ',body)
282            (process-failure
283             :reason (format nil "Test didn't finish")
284             :test-expr ',body)))))
285
286 (defmacro pass (&rest message-args)
287   "Generate a PASS."
288   `(add-result 'test-passed
289                :test-expr ',message-args
290                ,@(when message-args
291                        `(:reason (format nil ,@message-args)))))
292
293 (defmacro fail (&rest message-args)
294   "Generate a FAIL."
295   `(process-failure
296     :test-expr ',message-args
297     ,@(when message-args
298             `(:reason (format nil ,@message-args)))))
299
300 (defmacro skip (&rest message-args)
301   "Generates a SKIP result."
302   `(progn
303      (format *test-dribble* "s")
304      (add-result 'test-skipped :reason (format nil ,@message-args))))
305
306 ;; Copyright (c) 2002-2003, Edward Marco Baringer
307 ;; All rights reserved.
308 ;;
309 ;; Redistribution and use in source and binary forms, with or without
310 ;; modification, are permitted provided that the following conditions are
311 ;; met:
312 ;;
313 ;;  - Redistributions of source code must retain the above copyright
314 ;;    notice, this list of conditions and the following disclaimer.
315 ;;
316 ;;  - Redistributions in binary form must reproduce the above copyright
317 ;;    notice, this list of conditions and the following disclaimer in the
318 ;;    documentation and/or other materials provided with the distribution.
319 ;;
320 ;;  - Neither the name of Edward Marco Baringer, nor BESE, nor the names
321 ;;    of its contributors may be used to endorse or promote products
322 ;;    derived from this software without specific prior written permission.
323 ;;
324 ;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
325 ;; "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
326 ;; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
327 ;; A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT
328 ;; OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
329 ;; SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
330 ;; LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
331 ;; DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
332 ;; THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
333 ;; (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
334 ;; OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE