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