8325bdef538448ef719fd869841ce8f5d58ec54b
[fiveam.git] / src / check.lisp
1 ;; -*- lisp -*-
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
95   object to 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) - Means that we want to check
118  whether, according to PREDICATE, the ACTUAL value is
119  in fact what we EXPECTED.
120
121  (predicate value) - Means that we want to ensure that VALUE
122  satisfies PREDICATE.
123
124  Wrapping the TEST form in a NOT simply preducse a negated reason
125  string."
126   (assert (listp test)
127           (test)
128           "Argument to IS must be a list, not ~S" test)
129   (let (bindings effective-test default-reason-args)
130     (with-unique-names (e a v)
131       (flet ((process-entry (predicate expected actual &optional negatedp)
132                ;; make sure EXPECTED is holding the entry that starts with 'values
133                (when (and (consp actual)
134                           (eq (car actual) 'values))
135                  (assert (not (and (consp expected)
136                                    (eq (car expected) 'values))) ()
137                                    "Both the expected and actual part is a values expression.")
138                  (let ((tmp expected))
139                    (setf expected actual
140                          actual tmp)))
141                (let ((setf-forms))
142                  (if (and (consp expected)
143                           (eq (car expected) 'values))
144                      (progn
145                        (setf expected (copy-list expected))
146                        (setf setf-forms (loop for cell = (rest expected) then (cdr cell)
147                                               for i from 0
148                                               while cell
149                                               when (eq (car cell) '*)
150                                               collect `(setf (elt ,a ,i) nil)
151                                               and do (setf (car cell) nil)))
152                        (setf bindings (list (list e `(list ,@(rest expected)))
153                                             (list a `(multiple-value-list ,actual)))))
154                      (setf bindings (list (list e expected)
155                                           (list a actual))))
156                  (setf effective-test `(progn
157                                          ,@setf-forms
158                                          ,(if negatedp
159                                               `(not (,predicate ,e ,a))
160                                               `(,predicate ,e ,a)))))))
161         (list-match-case test
162           ((not (?predicate ?expected ?actual))
163            (process-entry ?predicate ?expected ?actual t)
164            (setf default-reason-args
165                  (list "~S evaluated to ~S, which is ~S to ~S (it should not be)"
166                        `',?actual a `',?predicate e)))
167           ((not (?satisfies ?value))
168            (setf bindings (list (list v ?value))
169                  effective-test `(not (,?satisfies ,v))
170                  default-reason-args
171                  (list "~S evaluated to ~S, which satisfies ~S (it should not)"
172                        `',?value v `',?satisfies)))
173           ((?predicate ?expected ?actual)
174            (process-entry ?predicate ?expected ?actual)
175            (setf default-reason-args
176                  (list "~S evaluated to ~S, which is not ~S to ~S."
177                        `',?actual a `',?predicate e)))
178           ((?satisfies ?value)
179            (setf bindings (list (list v ?value))
180                  effective-test `(,?satisfies ,v)
181                  default-reason-args
182                  (list "~S evaluated to ~S, which does not satisfy ~S"
183                        `',?value v `',?satisfies)))
184           (?_
185            (setf bindings '()
186                  effective-test test
187                  default-reason-args (list "~S was NIL." `',test)))))
188       `(let ,bindings
189          (if ,effective-test
190              (add-result 'test-passed :test-expr ',test)
191              (process-failure :reason (format nil ,@(or reason-args default-reason-args))
192                               :test-expr ',test))))))
193
194 ;;;; *** Other checks
195
196 (defmacro skip (&rest reason)
197   "Generates a TEST-SKIPPED result."
198   `(progn
199      (format *test-dribble* "s")
200      (add-result 'test-skipped :reason (format nil ,@reason))))
201
202 (defmacro is-every (predicate &body clauses)
203   "The input is either a list of lists, or a list of pairs. Generates (is (,predicate ,expr ,value))
204    for each pair of elements or (is (,predicate ,expr ,value) ,@reason) for each list."
205   `(progn
206      ,@(if (every #'consp clauses)
207            (loop for (expected actual . reason) in clauses
208                  collect `(is (,predicate ,expected ,actual) ,@reason))
209            (progn
210              (assert (evenp (list-length clauses)))
211              (loop for (expr value) on clauses by #'cddr
212                    collect `(is (,predicate ,expr ,value)))))))
213
214 (defmacro is-true (condition &rest reason-args)
215   "Like IS this check generates a pass if CONDITION returns true
216   and a failure if CONDITION returns false. Unlike IS this check
217   does not inspect CONDITION to determine how to report the
218   failure."
219   `(if ,condition
220        (add-result 'test-passed :test-expr ',condition)
221        (process-failure
222         :reason ,(if reason-args
223                      `(format nil ,@reason-args)
224                      `(format nil "~S did not return a true value" ',condition))
225         :test-expr ',condition)))
226
227 (defmacro is-false (condition &rest reason-args)
228   "Generates a pass if CONDITION returns false, generates a
229   failure otherwise. Like IS-TRUE, and unlike IS, IS-FALSE does
230   not inspect CONDITION to determine what reason to give it case
231   of test failure"
232   
233   (with-unique-names (value)
234     `(let ((,value ,condition))
235        (if ,value
236            (process-failure
237             :reason ,(if reason-args
238                          `(format nil ,@reason-args)
239                          `(format nil "~S returned the value ~S, which is true" ',condition ,value ))
240             :test-expr ',condition)
241            (add-result 'test-passed :test-expr ',condition)))))
242
243 (defmacro signals (condition-spec
244                    &body body)
245   "Generates a pass if BODY signals a condition of type
246 CONDITION. BODY is evaluated in a block named NIL, CONDITION is
247 not evaluated."
248   (let ((block-name (gensym)))
249     (destructuring-bind (condition &optional reason-control reason-args)
250         (ensure-list condition-spec)
251       `(block ,block-name
252          (handler-bind ((,condition (lambda (c)
253                                       (declare (ignore c))
254                                       ;; ok, body threw condition
255                                       (add-result 'test-passed
256                                                   :test-expr ',condition)
257                                       (return-from ,block-name t))))
258            (block nil
259              ,@body))
260          (process-failure
261           :reason ,(if reason-control
262                        `(format nil ,reason-control ,@reason-args)
263                        `(format nil "Failed to signal a ~S" ',condition))
264           :test-expr ',condition)
265          (return-from ,block-name nil)))))
266
267 (defmacro finishes (&body body)
268   "Generates a pass if BODY executes to normal completion. In
269 other words if body does signal, return-from or throw this test
270 fails."
271   `(let ((ok nil))
272      (unwind-protect
273           (progn
274             ,@body
275             (setf ok t))
276        (if ok
277            (add-result 'test-passed :test-expr ',body)
278            (process-failure
279             :reason (format nil "Test didn't finish")
280             :test-expr ',body)))))
281
282 (defmacro pass (&rest message-args)
283   "Simply generate a PASS."
284   `(add-result 'test-passed
285                :test-expr ',message-args
286                ,@(when message-args
287                        `(:reason (format nil ,@message-args)))))
288
289 (defmacro fail (&rest message-args)
290   "Simply generate a FAIL."
291   `(process-failure
292     :test-expr ',message-args
293     ,@(when message-args
294             `(:reason (format nil ,@message-args)))))
295
296 ;; Copyright (c) 2002-2003, Edward Marco Baringer
297 ;; All rights reserved.
298 ;;
299 ;; Redistribution and use in source and binary forms, with or without
300 ;; modification, are permitted provided that the following conditions are
301 ;; met:
302 ;;
303 ;;  - Redistributions of source code must retain the above copyright
304 ;;    notice, this list of conditions and the following disclaimer.
305 ;;
306 ;;  - Redistributions in binary form must reproduce the above copyright
307 ;;    notice, this list of conditions and the following disclaimer in the
308 ;;    documentation and/or other materials provided with the distribution.
309 ;;
310 ;;  - Neither the name of Edward Marco Baringer, nor BESE, nor the names
311 ;;    of its contributors may be used to endorse or promote products
312 ;;    derived from this software without specific prior written permission.
313 ;;
314 ;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
315 ;; "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
316 ;; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
317 ;; A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT
318 ;; OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
319 ;; SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
320 ;; LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
321 ;; DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
322 ;; THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
323 ;; (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
324 ;; OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE