buttercup.el 65.5 KB
Newer Older
1
;;; buttercup.el --- Behavior-Driven Emacs Lisp Testing -*-lexical-binding:t-*-
Jorgen Schaefer's avatar
Jorgen Schaefer committed
2

Jorgen Schaefer's avatar
Jorgen Schaefer committed
3
;; Copyright (C) 2015-2017  Jorgen Schaefer <contact@jorgenschaefer.de>
Jorgen Schaefer's avatar
Jorgen Schaefer committed
4

5
;; Version: 1.12
Jorgen Schaefer's avatar
Jorgen Schaefer committed
6
;; Author: Jorgen Schaefer <contact@jorgenschaefer.de>
7 8
;; Package-Requires: ((emacs "24.3"))
;; URL: https://github.com/jorgenschaefer/emacs-buttercup
Jorgen Schaefer's avatar
Jorgen Schaefer committed
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24

;; This program is free software; you can redistribute it and/or
;; modify it under the terms of the GNU General Public License
;; as published by the Free Software Foundation; either version 3
;; of the License, or (at your option) any later version.

;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;; GNU General Public License for more details.

;; You should have received a copy of the GNU General Public License
;; along with this program. If not, see <http://www.gnu.org/licenses/>.

;;; Commentary:

25 26 27 28 29 30 31 32 33 34 35 36
;; Buttercup is a behavior-driven development framework for testing
;; Emacs Lisp code. It is heavily inspired by the Jasmine test
;; framework for JavaScript.

;; A test suite begins with a call to the Buttercup macro `describe` with
;; the first parameter describing the suite and the rest being the body
;; of code that implements the suite.

;; (describe "A suite"
;;   (it "contains a spec with an expectation"
;;     (expect t :to-be t)))

Jorgen Schaefer's avatar
Jorgen Schaefer committed
37 38 39 40 41 42 43
;; The ideas for project were shamelessly taken from Jasmine
;; <https://jasmine.github.io>.

;; All the good ideas are theirs. All the problems are mine.

;;; Code:

44
(require 'cl-lib)
45
(require 'buttercup-compat)
46 47 48 49
(require 'format-spec)
(require 'ert nil t)
(require 'warnings)

50 51
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; wrapper function manipulation
52

53
(defun buttercup--enclosed-expr (fun)
54
  "Given a zero-arg function FUN, return its unevaluated expression.
55

56
The function MUST have one of the following forms:
57

58
\(lambda () EXPR)
59
\(closure (ENVLIST) () EXPR)
60
\(lambda () (quote EXPR) EXPR)
61 62
\(closure (ENVLIST) () (quote EXPR) EXPR)

63 64 65 66
and the return value will be EXPR, unevaluated. The latter 2
forms are useful if EXPR is a macro call, in which case the
`quote' ensures access to the un-expanded form."
  (pcase fun
67
    (`(closure ,(pred listp) nil ,expr) expr)
68 69
    (`(closure ,(pred listp) nil (quote ,expr) . ,_rest) expr)
    (`(closure ,(pred listp) nil ,_expr . ,(pred identity))
70
     (error "Closure contains multiple expressions: %S" fun))
71
    (`(closure ,(pred listp) ,(pred identity) . ,(pred identity))
72
     (error "Closure has nonempty arglist: %S" fun))
73
    (`(lambda nil ,expr) expr)
74 75
    (`(lambda nil (quote ,expr) . ,_rest) expr)
    (`(lambda nil ,_expr . ,(pred identity))
76
     (error "Function contains multiple expressions: %S" fun))
77
    (`(lambda ,(pred identity) . ,(pred identity))
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
     (error "Function has nonempty arglist: %S" fun))
    (_ (error "Not a zero-arg one-expression closure: %S" fun))))

(defun buttercup--expr-and-value (fun)
  "Given a function, return its quoted expression and value.

FUN must be a zero-argument one-expression function, i.e.
something that satisfies `buttercup--wrapper-fun-p'. The return
value is `(cons EXPR VALUE)', where EXPR is the unevaluated
expression in the function, and VALUE is the result of calling
the function (thus evaluating EXPR in the proper lexical
environment)."
  (cons (buttercup--enclosed-expr fun)
        (funcall fun)))

(defun buttercup--wrapper-fun-p (fun)
94
  "Return non-nil if FUN is a zero-arg one-expression function."
95 96
  (condition-case nil
      (prog1 t
97
        (buttercup--enclosed-expr fun))
98
    (error nil)))
99

100 101 102 103 104 105 106 107 108 109 110
;;;;;;;;;;;;;;;;;;;;
;;; Helper functions

(defun buttercup-format-spec (format specification)
  "Return a string based on FORMAT and SPECIFICATION.

This is a wrapper around `format-spec', which see. This also adds
a call to `save-match-data', as `format-spec' modifies that."
  (save-match-data
    (format-spec format specification)))

Jorgen Schaefer's avatar
Jorgen Schaefer committed
111 112 113 114 115 116
;;;;;;;;;;
;;; expect

(define-error 'buttercup-failed
  "Buttercup test failed")

117 118 119
(define-error 'buttercup-pending
  "Buttercup test is pending")

120 121 122 123 124
(defmacro expect (arg &optional matcher &rest args)
  "Expect a condition to be true.

This macro knows three forms:

125
\(expect ARG :MATCHER ARGS...)
126 127 128
  Fail the current test iff the matcher does not match these arguments.
  See `buttercup-define-matcher' for more information on matchers.

129
\(expect (function ARG...))
130 131 132 133
  Fail the current test iff the function call does not return a true value.

\(expect ARG)
  Fail the current test iff ARG is not true."
134
  (let ((wrapped-args
135 136 137 138
         (mapcar (lambda (expr) `(lambda () (quote ,expr) ,expr)) args)))
    `(buttercup-expect
      (lambda () (quote ,arg) ,arg)
      ,(or matcher :to-be-truthy)
139
      ,@wrapped-args)))
140 141

(defun buttercup-expect (arg &optional matcher &rest args)
142 143 144 145
  "The function for the `expect' macro.

See the macro documentation for details and the definition of
ARG, MATCHER and ARGS."
146
  (cl-assert (cl-every #'buttercup--wrapper-fun-p (cons arg args)) t)
Jorgen Schaefer's avatar
Jorgen Schaefer committed
147
  (if (not matcher)
148 149 150 151 152
      (progn
        (cl-assert (not args) t)
        (when (not (funcall arg))
          (buttercup-fail "Expected %S to be non-nil"
                          (buttercup--enclosed-expr arg))))
Jorgen Schaefer's avatar
Jorgen Schaefer committed
153 154 155
    (let ((result (buttercup--apply-matcher matcher (cons arg args))))
      (if (consp result)
          (when (not (car result))
156
            (buttercup-fail "%s" (cdr result)))
Jorgen Schaefer's avatar
Jorgen Schaefer committed
157
        (when (not result)
158 159
          (buttercup-fail "Expected %S %S %s"
                          (buttercup--enclosed-expr arg)
Jorgen Schaefer's avatar
Jorgen Schaefer committed
160 161
                          matcher
                          (mapconcat (lambda (obj)
162
                                       (format "%S" (funcall obj)))
Jorgen Schaefer's avatar
Jorgen Schaefer committed
163
                                     args
164
                                     " ")))))))
Jorgen Schaefer's avatar
Jorgen Schaefer committed
165

166 167 168 169
(defun buttercup-fail (format &rest args)
  "Fail the current test with the given description.

This is the mechanism underlying `expect'. You can use it
170 171 172
directly if you want to write your own testing functionality.

FORMAT and ARGS are passed to `format'."
173
  (signal 'buttercup-failed (apply #'format format args)))
Jorgen Schaefer's avatar
Jorgen Schaefer committed
174

175
(defun buttercup-skip (format &rest args)
176 177 178
  "Skip the current test with the given description.

FORMAT and ARGS are passed to `format'."
179 180 181 182 183 184
  (signal 'buttercup-pending (apply #'format format args)))

(defmacro assume (condition &optional message)
  "Assume CONDITIION for the current test.

Assume that CONDITION evaluates to non-nil in the current test.
185
If it evaluates to nil cancel the current test with MESSAGE. If
186 187 188 189 190
MESSAGE is omitted or nil show the condition form instead."
  (let ((message (or message (format "%S => nil" condition))))
    `(unless ,condition
       (buttercup-skip "!! CANCELLED !! %s" ,message))))

Jorgen Schaefer's avatar
Jorgen Schaefer committed
191
(defmacro buttercup-define-matcher (matcher args &rest body)
192 193 194
  "Define a matcher named MATCHER to be used in `expect'.

ARGS is a list of the elements to match together.
Jorgen Schaefer's avatar
Jorgen Schaefer committed
195

196 197 198 199 200 201
The BODY will receive ARGS as functions that can be called (using
`funcall') to get their values. BODY should return either a
simple boolean, or a cons cell of the form (RESULT . MESSAGE). If
RESULT is nil, MESSAGE should describe why the matcher failed. If
RESULT is non-nil, MESSAGE should describe why a negated matcher
failed."
Jorgen Schaefer's avatar
Jorgen Schaefer committed
202 203 204 205 206
  (declare (indent defun))
  `(put ,matcher 'buttercup-matcher
        (lambda ,args
          ,@body)))

207 208 209 210 211 212 213 214 215 216 217 218 219 220
(defun buttercup--function-as-matcher (fun)
  (cl-assert (functionp fun) t)
  (lambda (&rest args)
    (apply fun (mapcar #'funcall args))))

(defun buttercup--find-matcher-function (matcher)
  (let ((matcher-prop
         (when (symbolp matcher)
           (get matcher 'buttercup-matcher))))
    (cond
     ;; Use `buttercup-matcher' property if it's a function
     ((functionp matcher-prop)
      matcher-prop)
     (matcher-prop
221
      (error "%S %S has a `buttercup-matcher' property that is not a function. Buttercup has been misconfigured"
222 223
             (if (keywordp matcher) "Keyword" "Symbol") matcher))
     ;; Otherwise just use `matcher' as a function, wrapping it in
224
     ;; code to unpack function-wrapped arguments.
225 226 227 228 229 230 231 232
     ((functionp matcher)
      (buttercup--function-as-matcher matcher))
     (matcher (error "Not a test: `%S'" matcher))
     ;; If `matcher' is nil, then we just want a basic truth test
     ((null matcher)
      (buttercup--find-matcher-function :to-be-truthy))
     (t (error "This line should never run")))))

Jorgen Schaefer's avatar
Jorgen Schaefer committed
233
(defun buttercup--apply-matcher (matcher args)
234
  "Apply MATCHER to ARGS.
235

236
ARGS is a list of functions that must be `funcall'ed to get their
237 238
values.

239
MATCHER is either a matcher keyword defined with
240
`buttercup-define-matcher', or a function."
241
  (cl-assert (cl-every #'buttercup--wrapper-fun-p args) t)
242 243
  (let ((function
         (buttercup--find-matcher-function matcher)))
Jorgen Schaefer's avatar
Jorgen Schaefer committed
244 245
    (apply function args)))

246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334
(cl-defmacro buttercup--test-expectation
    (expr &key expect-match-phrase expect-mismatch-phrase)
  "Wrapper for the common matcher case of two possible messages.

The logic for the return values of buttercup matchers can be
unintuitive, since the return value is a cons cell whose first
element is t for a mismatch and nil for a match. In the simple
case where there are only two possible messages (one for a match
and one for a mismatch), this macro allows you to simply specify
those two phrases and the expression to test."
  (declare (indent 1))
  (cl-assert expect-match-phrase)
  (cl-assert expect-mismatch-phrase)
  `(let ((value ,expr))
     (if value
         (cons t ,expect-mismatch-phrase)
       (cons nil ,expect-match-phrase))))

(cl-defmacro buttercup-define-matcher-for-unary-function
    (matcher function &key
             expect-match-phrase expect-mismatch-phrase function-name)
  "Shortcut to define a macther for a 1-argument function.

When the matcher is used, keyword arguments EXPECT-MATCH-PHRASE
and EXPECT-MISMATCH-PHRASE are used to construct the return
message. It may contain `%f', `%A', and `%a', which will be
replaced with the function name, the expression of the argument
the matcher was called on, and the value of that argument,
respectively. If not provided, the default EXPECT-MATCH-PHRASE
is:

    Expected `%A' to match `%f', but instead it was `%a'.

Similarly, the default EXPECT-MISMATCH-PHRASE is:

    Expected `%A' not to match `%f', but it was `%a'.

To include a literal `%' in either message, use `%%'.

If FUNCTION is passed as a lambda expression or other non-symbol, then
you must provide a keyword argument FUNCTION-NAME to be used in
the match/mismatch messages. Otherwise, FUNCTION-NAME will be
used instead of FUNCTION if both are non-nil SYMBOLS.

If FUNCTION (or FUNCTION-NAME) has an `ert-explainer' property,
this will be used to generate the default EXPECT-MATCH-PHRASE.

See also `buttercup-define-matcher'."
  (declare (indent 2))
  ;; Use the ERT explainer for FUNCTION if available to generate the
  ;; default expect-match phrase.
  (let ((explainer (or (when function-name
                         (get function-name 'ert-explainer))
                       (when (symbolp function)
                         (get function 'ert-explainer)))))
    (cl-assert (symbolp function-name) t)
    (cl-assert (functionp function) t)
    (unless expect-match-phrase
      (setq expect-match-phrase
            (if explainer
                ;; %x is the undocumented substitution for the
                ;; explainer's output
                "Expected `%A' to match `%f', but instead it was `%a' which did not match because: %x."
              "Expected `%A' to match `%f', but instead it was `%a'.")))
    (unless expect-mismatch-phrase
      (setq expect-mismatch-phrase
            "Expected `%A' not to match `%f', but it was `%a'."))
    (when (and (null function-name)
               ;; Only need a function name if either phrase contains
               ;; an unescaped `%f'.
               (string-match-p
                "%f"
                (replace-regexp-in-string
                 "%%" ""
                 (concat expect-match-phrase " "
                         expect-mismatch-phrase))))
      (if (symbolp function)
          (setq function-name function)
        (error "The `:function-name' keyword is required if FUNCTION is not a symbol")))
    `(buttercup-define-matcher ,matcher (arg)
       (let* ((expr (buttercup--enclosed-expr arg))
              (value (funcall arg))
              (explanation (and ',explainer (funcall ',explainer arg)))
              (spec (format-spec-make
                     ?f ',function-name
                     ?A (format "%S" expr)
                     ?a (format "%S" value)
                     ?x (format "%S" explanation))))
         (buttercup--test-expectation (funcall ',function value)
335 336
           :expect-match-phrase (buttercup-format-spec ,expect-match-phrase spec)
           :expect-mismatch-phrase (buttercup-format-spec ,expect-mismatch-phrase spec))))))
337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403

(cl-defmacro buttercup-define-matcher-for-binary-function
    (matcher function &key
             expect-match-phrase expect-mismatch-phrase function-name)
  "Shortcut to define a macther for a 2-argument function.

When the matcher is used, keyword arguments EXPECT-MATCH-PHRASE
and EXPECT-MISMATCH-PHRASE are used to construct the return
message. It may contain `%f', `%A', `%a', `%B', and `%b'. The
token `%f' will be replaced with the function name. `%A' and `%B'
will be replaced with the unevaluted expressions of the two
arguments passed to the function, while `%a' and `%b' will be
replaced with their values. not provided, the default
EXPECT-MATCH-PHRASE is:

    Expected `%A' to be `%f' to `%b', but instead it was `%a'.

Similarly, the default EXPECT-MISMATCH-PHRASE is:

    Expected `%A' not to be `%f' to `%b', but it was.

To include a literal `%' in either message, use `%%'.

If FUNCTION is passed as a lambda expression or other non-symbol, then
you must provide a keyword argument FUNCTION-NAME to be used in
the match/mismatch messages (unless neither one contains `%f').
If both are non-nil symbols, FUNCTION-NAME will be used instead
of FUNCTION in messages.

If FUNCTION (or FUNCTION-NAME) has an `ert-explainer' property,
this will be used to generate the default EXPECT-MATCH-PHRASE.

See also `buttercup-define-matcher'."
  (declare (indent 2))
  ;; Use the ERT explainer for FUNCTION if available to generate the
  ;; default expect-match phrase.
  (let ((explainer (or (when function-name
                         (get function-name 'ert-explainer))
                       (when (symbolp function)
                         (get function 'ert-explainer)))))
    (cl-assert (symbolp function-name) t)
    (cl-assert (functionp function) t)
    (unless expect-match-phrase
      (setq expect-match-phrase
            (if explainer
                ;; %x is the undocumented substitution for the
                ;; explainer's output
                "Expected `%A' to be `%f' to `%b', but instead it was `%a' which does not match because: %x."
              "Expected `%A' to be `%f' to `%b', but instead it was `%a'.")))
    (unless expect-mismatch-phrase
      (setq expect-mismatch-phrase
            "Expected `%A' not to be `%f' to `%b', but it was."))
    (when (and (null function-name)
               ;; Only need a function name if either phrase contains
               ;; an unescaped `%f'.
               (string-match-p
                "%f"
                (replace-regexp-in-string
                 "%%" ""
                 (concat expect-match-phrase " "
                         expect-mismatch-phrase))))
      (if (symbolp function)
          (setq function-name function)
        (error "The `:function-name' keyword is required if FUNCTION is not a symbol")))
    `(buttercup-define-matcher ,matcher (a b)
       (cl-destructuring-bind
           ((a-expr . a) (b-expr . b))
404
           (mapcar #'buttercup--expr-and-value (list a b))
405 406 407 408 409 410 411 412 413
         (let* ((explanation (and ',explainer (funcall ',explainer a b)))
                (spec (format-spec-make
                       ?f ',function-name
                       ?A (format "%S" a-expr)
                       ?a (format "%S" a)
                       ?B (format "%S" b-expr)
                       ?b (format "%S" b)
                       ?x (format "%S" explanation))))
           (buttercup--test-expectation (funcall #',function a b)
414 415
             :expect-match-phrase (buttercup-format-spec ,expect-match-phrase spec)
             :expect-mismatch-phrase (buttercup-format-spec ,expect-mismatch-phrase spec)))))))
416

417 418 419
;;;;;;;;;;;;;;;;;;;;;
;;; Built-in matchers

420 421 422 423 424 425 426
(buttercup-define-matcher-for-unary-function :to-be-truthy identity
  :expect-match-phrase "Expected `%A' to be non-nil, but instead it was nil."
  :expect-mismatch-phrase "Expected `%A' to be nil, but instead it was `%a'.")

(buttercup-define-matcher-for-binary-function :to-be eq)
(buttercup-define-matcher-for-binary-function :to-equal equal)

Jorgen Schaefer's avatar
Jorgen Schaefer committed
427
(buttercup-define-matcher :not (obj matcher &rest args)
428 429
  (let* ((matcher (funcall matcher))
         (result (buttercup--apply-matcher matcher (cons obj args))))
Jorgen Schaefer's avatar
Jorgen Schaefer committed
430 431 432 433 434
    (if (consp result)
        (cons (not (car result))
              (cdr result))
      (not result))))

435
(buttercup-define-matcher :to-have-same-items-as (a b)
436 437
  (cl-destructuring-bind
      ((a-expr . a) (b-expr . b))
438
      (mapcar #'buttercup--expr-and-value (list a b))
439 440 441 442 443 444 445 446 447 448 449
    (let* ((a-uniques (cl-set-difference a b :test #'equal))
           (b-uniques (cl-set-difference b a :test #'equal))
           (spec (format-spec-make
                  ?A (format "%S" a-expr)
                  ?a (format "%S" a)
                  ?B (format "%S" b-expr)
                  ?b (format "%S" b)
                  ?m (format "%S" b-uniques)
                  ?p (format "%S" a-uniques))))
      (cond
       ((and a-uniques b-uniques)
450
        (cons nil (buttercup-format-spec
451 452
                   "Expected `%A' to contain the same items as `%b', but `%m' are missing and `%p' are present unexpectedly."
                   spec)))
453
       (a-uniques
454
        (cons nil (buttercup-format-spec
Wieland Hoffmann's avatar
Wieland Hoffmann committed
455
                   "Expected `%A' to contain the same items as `%b', but `%p' are present unexpectedly."
456
                   spec)))
457
       (b-uniques
458
        (cons nil (buttercup-format-spec
459 460
                   "Expected `%A' to contain the same items as `%b', but `%m' are missing."
                   spec)))
461
       (t
462
        (cons t (buttercup-format-spec
463 464
                 "Expected `%A' not to have same items as `%b'"
                 spec)))))))
465

Jorgen Schaefer's avatar
Jorgen Schaefer committed
466
(buttercup-define-matcher :to-match (text regexp)
467 468
  (cl-destructuring-bind
      ((text-expr . text) (regexp-expr . regexp))
469
      (mapcar #'buttercup--expr-and-value (list text regexp))
470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504
    (save-match-data
      (let* (;; For string literals, juse use them normally, but for
             ;; expressions, show both the expr and its string value
             (text-is-literal (equal text-expr text))
             (regexp-is-literal (equal regexp-expr regexp))
             (text-desc
              (if text-is-literal
                  text-expr
                (format "`%S' with value %S"
                        text-expr text)))
             (regexp-desc
              (if regexp-is-literal
                  regexp-expr
                (format "`%S' with value %S"
                        regexp-expr regexp)))
             (match-p (string-match regexp text))
             ;; Get some more details about the match
             (start
              (when match-p
                (match-beginning 0)))
             (end
              (when match-p
                (match-end 0)))
             (matched-substring
              (when match-p
                (substring text start end)))
             (spec (format-spec-make
                    ?T text-desc
                    ?t (format "%S" text)
                    ?R regexp-desc
                    ?r (format "%S" regexp)
                    ?m (format "%S" matched-substring)
                    ?a start
                    ?z end)))
        (buttercup--test-expectation match-p
505 506 507 508 509 510
          :expect-match-phrase
          (buttercup-format-spec "Expected %T to match the regexp %r, but instead it was %t."
                                 spec)
          :expect-mismatch-phrase
          (buttercup-format-spec "Expected %T not to match the regexp %r, but it matched the substring %m from position %a to %z."
                                 spec))))))
511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538

(buttercup-define-matcher-for-binary-function
    :to-be-in member
  :expect-match-phrase "Expected `%A' to be an element of `%b', but it was `%a'."
  :expect-mismatch-phrase "Expected `%A' not to be an element of `%b', but it was `%a'.")

(buttercup-define-matcher-for-binary-function
    ;; Reverse the args
    :to-contain (lambda (a b) (member b a))
  :expect-match-phrase "Expected `%A' to be a list containing `%b', but instead it was `%a'."
  :expect-mismatch-phrase "Expected `%A' to be a list not containing `%b', but instead it was `%a'.")

(buttercup-define-matcher-for-binary-function
    :to-be-less-than <
  :expect-match-phrase "Expected `%A' < %b, but `%A' was %a."
  :expect-mismatch-phrase "Expected `%A' >= %b, but `%A' was %a.")
(buttercup-define-matcher-for-binary-function
    :to-be-greater-than >
  :expect-match-phrase "Expected `%A' > %b, but `%A' was %a."
  :expect-mismatch-phrase "Expected `%A' <= %b, but `%A' was %a.")
(buttercup-define-matcher-for-binary-function
    :to-be-weakly-less-than <=
  :expect-match-phrase "Expected `%A' <= %b, but `%A' was %a."
  :expect-mismatch-phrase "Expected `%A' > %b, but `%A' was %a.")
(buttercup-define-matcher-for-binary-function
    :to-be-weakly-greater-than >=
  :expect-match-phrase "Expected `%A' >= %b, but `%A' was %a."
  :expect-mismatch-phrase "Expected `%A' < %b, but `%A' was %a.")
Jorgen Schaefer's avatar
Jorgen Schaefer committed
539 540

(buttercup-define-matcher :to-be-close-to (a b precision)
541
  (cl-destructuring-bind
542
      (precision (a-expr . a) (_b-expr . b))
543
      (cons (funcall precision)
544
            (mapcar #'buttercup--expr-and-value (list a b)))
545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602
    (let ((tolerance (expt 10.0 (- precision))))
      (buttercup--test-expectation
          (< (abs (- a b)) tolerance)
        :expect-match-phrase
        (format "Expected `%S' to be within %s of %s, but instead it was %s, with a difference of %s"
                a-expr tolerance b a (abs (- a b)))
        :expect-mismatch-phrase
        (format "Expected `%S' to differ from %s by more than %s, but instead it was %s, with a difference of %s"
                a-expr b tolerance a (abs (- a b)))))))

(buttercup-define-matcher :to-throw (expr &optional signal signal-args)
  (let ((expected-signal-symbol (or (and signal (funcall signal)) 'error))
        (expected-signal-args (and signal-args (funcall signal-args)))
        (unevaluated-expr (buttercup--enclosed-expr expr))
        expr-value
        thrown-signal
        thrown-signal-symbol
        thrown-signal-args)
    (when (and (functionp unevaluated-expr)
               (member (car unevaluated-expr) '(lambda closure)))
      (display-warning
       'buttercup
       (buttercup-colorize
        (format "Probable incorrect use of `:to-throw' matcher: pass an expression instead of a function: `%S'"
                unevaluated-expr)
        'yellow)))
    ;; If no signal specificaiton, use `error' as the signal symbol
    (when (and (null expected-signal-symbol)
               (null expected-signal-args))
      (setq expected-signal-symbol 'error))
    ;; Set the above 4 variables
    (condition-case err
        (setq expr-value
              (funcall expr))
      (error
       (setq thrown-signal err
             thrown-signal-symbol (car err)
             thrown-signal-args (cdr err))
       nil))
    (let*
        ((matched
          (and thrown-signal
               (or (null expected-signal-symbol)
                   (memq expected-signal-symbol (get thrown-signal-symbol 'error-conditions)))
               (or (null expected-signal-args)
                   (equal thrown-signal-args expected-signal-args))))
         (spec (format-spec-make
                ?E (format "%S" unevaluated-expr)
                ?e (format "%S" expr-value)
                ?t (format "%S" thrown-signal)
                ?s (if expected-signal-symbol
                       (format "a child signal of `%S'" expected-signal-symbol)
                     "a signal")
                ?a (if expected-signal-args
                       (format " with args `%S'" expected-signal-args)
                     "")))
         (result-text
          (if thrown-signal
603 604
              (buttercup-format-spec "it threw %t" spec)
            (buttercup-format-spec "it evaluated successfully, returning value `%e'" spec)))
605 606

         (expect-match-text
607
          (concat (buttercup-format-spec "Expected `%E' to throw %s%a" spec)
608 609 610
                  ", but instead "
                  result-text))
         (expect-mismatch-text
611
          (concat (buttercup-format-spec "Expected `%E' not to throw %s%a" spec)
612 613 614
                  ", but "
                  result-text)))
      (buttercup--test-expectation matched
615 616
        :expect-match-phrase expect-match-text
        :expect-mismatch-phrase expect-mismatch-text))))
617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659

(buttercup-define-matcher :to-have-been-called (spy)
  (setq spy (funcall spy))
  (cl-assert (symbolp spy))
  (if (spy-calls-all (funcall spy))
      t
    nil))

(buttercup-define-matcher :to-have-been-called-with (spy &rest args)
  (setq spy (funcall spy))
  (cl-assert (symbolp spy))
  (setq args (mapcar #'funcall args))
  (let* ((calls (mapcar 'spy-context-args (spy-calls-all spy))))
    (cond
     ((not calls)
      (cons nil
            (format "Expected `%s' to have been called with %s, but it was not called at all" spy args)))
     ((not (member args calls))
      (cons nil
            (format "Expected `%s' to have been called with %s, but it was called with %s"
                    spy
                    args
                    (mapconcat (lambda (args)
                                 (format "%S" args))
                               calls
                               ", "))))
     (t
      t))))

(buttercup-define-matcher :to-have-been-called-times (spy number)
  (setq spy (funcall spy)
        number (funcall number))
  (cl-assert (symbolp spy))
  (let* ((call-count (length (spy-calls-all spy))))
    (cond
     ((= number call-count)
      t)
     (t
      (cons nil
            (format "Expected `%s' to have been called %s %s, but it was called %s %s"
                    spy
                    number (if (= number 1) "time" "times")
                    call-count (if (= call-count 1) "time" "times")))))))
Jorgen Schaefer's avatar
Jorgen Schaefer committed
660

661 662
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Suite and spec data structures
Jorgen Schaefer's avatar
Jorgen Schaefer committed
663

664
(cl-defstruct buttercup-suite-or-spec
665
  ;; The name of this specific suite
Jorgen Schaefer's avatar
Jorgen Schaefer committed
666
  description
667
  ;; The parent of this suite, another suite
668
  parent
669 670 671 672 673 674 675 676 677
  ;; One of: passed failed pending
  (status 'passed)
  failure-description
  failure-stack
  )

(cl-defstruct (buttercup-suite (:include buttercup-suite-or-spec))
  ;; Any children of this suite, both suites and specs
  children
678 679
  ;; Closure to run before and after each spec in this suite and its
  ;; children
680 681
  before-each
  after-each
682
  ;; Likewise, but before and after all specs.
683
  before-all
684
  after-all)
Jorgen Schaefer's avatar
Jorgen Schaefer committed
685

686
(cl-defstruct (buttercup-spec (:include buttercup-suite-or-spec))
687
  ;; The closure to run for this spec
688
  function)
689

690 691 692 693
(defun buttercup-suite-add-child (parent child)
  "Add a CHILD suite to a PARENT suite."
  (setf (buttercup-suite-children parent)
        (append (buttercup-suite-children parent)
694
                (list child)))
695
  (setf (buttercup-suite-or-spec-parent child) parent))
696

697 698 699 700 701 702
(defun buttercup-suite-or-spec-parents (suite-or-spec)
  "Return a list of parents of SUITE-OR-SPEC."
  (when (buttercup-suite-or-spec-parent suite-or-spec)
    (cons (buttercup-suite-or-spec-parent suite-or-spec)
          (buttercup-suite-or-spec-parents (buttercup-suite-or-spec-parent suite-or-spec)))))

703 704
(define-obsolete-function-alias 'buttercup-suite-parents 'buttercup-suite-or-spec-parents "emacs-buttercup 1.12")
(define-obsolete-function-alias 'buttercup-spec-parents 'buttercup-suite-or-spec-parents "emacs-buttercup 1.12")
Jorgen Schaefer's avatar
Jorgen Schaefer committed
705

706 707
(defun buttercup-suites-total-specs-defined (suite-list)
  "Return the number of specs defined in all suites in SUITE-LIST."
708
  (length (buttercup--specs suite-list)))
709

710 711
(defun buttercup-suites-total-specs-status (suite-list status)
  "Return the number of specs in SUITE-LIST marked with STATUS."
712
  (cl-count status (buttercup--specs suite-list) :key #'buttercup-spec-status))
713 714 715 716

(defun buttercup-suites-total-specs-pending (suite-list)
  "Return the number of specs marked as pending in all suites in SUITE-LIST."
  (buttercup-suites-total-specs-status suite-list 'pending))
717

718 719
(defun buttercup-suites-total-specs-failed (suite-list)
  "Return the number of failed specs in all suites in SUITE-LIST."
720
  (buttercup-suites-total-specs-status suite-list 'failed))
721

722 723 724 725 726 727 728 729 730
(defun buttercup--specs (spec-or-suite-list)
  "Return a flat list of all specs in SPEC-OR-SUITE-LIST."
  (let (specs)
    (dolist (spec-or-suite spec-or-suite-list specs)
      (if (buttercup-spec-p spec-or-suite)
          (setq specs (append specs (list spec-or-suite)))
        (setq specs (append specs (buttercup--specs
                                   (buttercup-suite-children spec-or-suite))))))))

731
(defun buttercup--specs-and-suites (spec-or-suite-list)
732
  "Return a flat list of all specs and suites in SPEC-OR-SUITE-LIST."
733
  (let ((specs-and-suites nil))
734
    (dolist (spec-or-suite spec-or-suite-list specs-and-suites)
735 736 737 738 739 740
      (setq specs-and-suites (append specs-and-suites
                                     (list spec-or-suite)))
      (when (buttercup-suite-p spec-or-suite)
        (setq specs-and-suites
              (append specs-and-suites
                      (buttercup--specs-and-suites
741
                       (buttercup-suite-children spec-or-suite))))))))
742

743 744
(defun buttercup-suite-full-name (suite)
  "Return the full name of SUITE, which includes the names of the parents."
745 746 747
  (mapconcat #'buttercup-suite-description
             (nreverse (cons suite (buttercup-suite-parents suite)))
             " "))
748

749 750 751 752 753 754 755 756 757
(defun buttercup-spec-full-name (spec)
  "Return the full name of SPEC, which includes the full name of its suite."
  (let ((parent (buttercup-spec-parent spec)))
    (if parent
        (concat (buttercup-suite-full-name parent)
                " "
                (buttercup-spec-description spec))
      (buttercup-spec-description spec))))

758 759 760
(defun buttercup--full-spec-names (spec-or-suite-list)
  "Return full names of all specs in SPEC-OR-SUITE-LIST."
  (cl-loop
761
   for x in (buttercup--specs spec-or-suite-list)
762 763 764 765 766 767 768 769 770 771 772 773
   collect (buttercup-spec-full-name x)))

(defun buttercup--find-duplicate-spec-names (spec-or-suite-list)
  "Return duplicate full spec names among SPEC-OR-SUITE-LIST."
  (let ((seen '())
        (duplicates '()))
    (dolist (name (buttercup--full-spec-names spec-or-suite-list)
                  (nreverse duplicates))
      (if (member name seen)
          (push name duplicates)
        (push name seen)))))

774 775 776
;;;;;;;;;;;;;;;;;;;;
;;; Suites: describe

Jorgen Schaefer's avatar
Jorgen Schaefer committed
777 778 779 780 781 782 783 784 785 786
(defvar buttercup-suites nil
  "The list of all currently defined Buttercup suites.")

(defvar buttercup--current-suite nil
  "The suite currently being defined.

Do not set this globally. It is let-bound by the `describe'
form.")

(defmacro describe (description &rest body)
787 788 789 790
  "Describe a test suite.

DESCRIPTION is a string. BODY is a sequence of instructions,
mainly calls to `describe', `it' and `before-each'."
myeffort's avatar
myeffort committed
791
  (declare (indent 1) (debug (&define sexp def-body)))
792 793 794 795 796
  (let ((new-body (if (eq (elt body 0) :var)
                      `((let ,(elt body 1)
                          ,@(cddr body)))
                    body)))
    `(buttercup-describe ,description (lambda () ,@new-body))))
Jorgen Schaefer's avatar
Jorgen Schaefer committed
797

798
(defun buttercup-describe (description body-function)
799 800 801 802 803
  "Function to handle a `describe' form.

DESCRIPTION has the same meaning as in `describe'. BODY-FUNCTION
is a function containing the body instructions passed to
`describe'."
Jorgen Schaefer's avatar
Jorgen Schaefer committed
804 805 806
  (let* ((enclosing-suite buttercup--current-suite)
         (buttercup--current-suite (make-buttercup-suite
                                    :description description)))
807
    (condition-case nil
808 809 810 811
        (funcall body-function)
      (buttercup-pending
       (setf (buttercup-suite-status buttercup--current-suite)
             'pending)))
Jorgen Schaefer's avatar
Jorgen Schaefer committed
812
    (if enclosing-suite
813 814
        (buttercup-suite-add-child enclosing-suite
                                   buttercup--current-suite)
815 816 817 818
      ;; At top level, warn about duplicate spec names
      (let ((dups (buttercup--find-duplicate-spec-names
                   (list buttercup--current-suite))))
        (when dups
819 820 821 822 823
          ;; TODO: Use `buttercup--warn'
          (display-warning
           'buttercup
           (format "Found duplicate spec names in suite: %S"
                   (delete-dups dups)))))
Jorgen Schaefer's avatar
Jorgen Schaefer committed
824 825 826
      (setq buttercup-suites (append buttercup-suites
                                     (list buttercup--current-suite))))))

Jorgen Schaefer's avatar
Jorgen Schaefer committed
827 828 829
;;;;;;;;;;;;;
;;; Specs: it

Jorgen Schaefer's avatar
Jorgen Schaefer committed
830
(defmacro it (description &rest body)
831 832 833 834
  "Define a spec.

DESCRIPTION is a string. BODY is a sequence of instructions,
most probably including one or more calls to `expect'."
myeffort's avatar
myeffort committed
835
  (declare (indent 1) (debug (&define sexp def-body)))
836
  (if body
837 838 839 840
      `(buttercup-it ,description
         (lambda ()
           (buttercup-with-converted-ert-signals
             ,@body)))
841
    `(buttercup-xit ,description)))
Jorgen Schaefer's avatar
Jorgen Schaefer committed
842

843
(defun buttercup-it (description body-function)
844 845 846 847
  "Function to handle an `it' form.

DESCRIPTION has the same meaning as in `it'. BODY-FUNCTION is a
function containing the body instructions passed to `it'."
848
  (declare (indent 1))
849
  (when (not buttercup--current-suite)
850
    (error "`it' has to be called from within a `describe' form"))
851 852 853 854
  (buttercup-suite-add-child buttercup--current-suite
                             (make-buttercup-spec
                              :description description
                              :function body-function)))
Jorgen Schaefer's avatar
Jorgen Schaefer committed
855

856 857 858 859
;;;;;;;;;;;;;;;;;;;;;;
;;; Setup and Teardown

(defmacro before-each (&rest body)
860
  "Run BODY before each spec in the current suite."
myeffort's avatar
myeffort committed
861
  (declare (indent 0) (debug (&define def-body)))
862 863 864
  `(buttercup-before-each (lambda () ,@body)))

(defun buttercup-before-each (function)
865 866 867 868
  "The function to handle a `before-each' form.

FUNCTION is a function containing the body instructions passed to
`before-each'."
869 870 871 872 873
  (setf (buttercup-suite-before-each buttercup--current-suite)
        (append (buttercup-suite-before-each buttercup--current-suite)
                (list function))))

(defmacro after-each (&rest body)
874
  "Run BODY after each spec in the current suite."
myeffort's avatar
myeffort committed
875
  (declare (indent 0) (debug (&define def-body)))
876 877 878
  `(buttercup-after-each (lambda () ,@body)))

(defun buttercup-after-each (function)
879 880 881 882
  "The function to handle an `after-each' form.

FUNCTION is a function containing the body instructions passed to
`after-each'."
883 884 885 886 887
  (setf (buttercup-suite-after-each buttercup--current-suite)
        (append (buttercup-suite-after-each buttercup--current-suite)
                (list function))))

(defmacro before-all (&rest body)
888
  "Run BODY before every spec in the current suite."
myeffort's avatar
myeffort committed
889
  (declare (indent 0) (debug (&define def-body)))
890 891 892
  `(buttercup-before-all (lambda () ,@body)))

(defun buttercup-before-all (function)
893 894 895 896
  "The function to handle a `before-all' form.

FUNCTION is a function containing the body instructions passed to
`before-all'."
897 898 899 900 901
  (setf (buttercup-suite-before-all buttercup--current-suite)
        (append (buttercup-suite-before-all buttercup--current-suite)
                (list function))))

(defmacro after-all (&rest body)
902
  "Run BODY after every spec in the current suite."
myeffort's avatar
myeffort committed
903
  (declare (indent 0) (debug (&define def-body)))
904 905 906
  `(buttercup-after-all (lambda () ,@body)))

(defun buttercup-after-all (function)
907 908 909 910
  "The function to handle an `after-all' form.

FUNCTION is a function containing the body instructions passed to
`after-all'."
911 912 913 914
  (setf (buttercup-suite-after-all buttercup--current-suite)
        (append (buttercup-suite-after-all buttercup--current-suite)
                (list function))))

915 916 917 918 919 920
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Disabled Suites: xdescribe

(defmacro xdescribe (description &rest body)
  "Like `describe', but mark the suite as disabled.

921 922 923 924
A disabled suite is not run.

DESCRIPTION is a string. BODY is a sequence of instructions,
mainly calls to `describe', `it' and `before-each'."
925 926 927 928 929 930
  (declare (indent 1))
  `(buttercup-xdescribe ,description (lambda () ,@body)))

(defun buttercup-xdescribe (description function)
  "Like `buttercup-describe', but mark the suite as disabled.

931 932 933 934 935 936
A disabled suite is not run.

DESCRIPTION has the same meaning as in `xdescribe'. FUNCTION
is ignored.
`describe'."
  (ignore function)
937
  (buttercup-describe description (lambda ()
938
                                    (signal 'buttercup-pending "PENDING"))))
939 940 941 942 943 944 945

;;;;;;;;;;;;;;;;;;;;;;
;;; Pending Specs: xit

(defmacro xit (description &rest body)
  "Like `it', but mark the spec as disabled.

946 947 948
A disabled spec is not run.

DESCRIPTION is a string. BODY is ignored."
949
  (declare (indent 1))
950
  (ignore body)
951
  `(buttercup-xit ,description))
952

953
(defun buttercup-xit (description &optional function)
954
  "Like `buttercup-it', but mark the spec as disabled.
955
A disabled spec is not run.
956

957
DESCRIPTION has the same meaning as in `xit'. FUNCTION is ignored."
958
  (declare (indent 1))
959
  (ignore function)
960
  (buttercup-it description (lambda ()
961 962 963 964
                              (signal 'buttercup-pending "PENDING")))
  (let ((spec (car (last (buttercup-suite-children
                          buttercup--current-suite)))))
    (setf (buttercup-spec-status spec)
965 966 967
          'pending
          (buttercup-spec-failure-description spec)
          "")))
968

Jorgen Schaefer's avatar
Jorgen Schaefer committed
969 970 971
;;;;;;;;;
;;; Spies

972 973
(defvar buttercup--spy-contexts (make-hash-table :test 'eq
                                                 :weakness 'key)
974
  "A mapping of currently-defined spies to their contexts.")
Jorgen Schaefer's avatar
Jorgen Schaefer committed
975

976 977 978 979 980
(cl-defstruct spy-context
  args
  return-value
  current-buffer)

981
(defun spy-on (symbol &optional keyword arg)
982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998
  "Create a spy (mock) for the function SYMBOL.

KEYWORD can have one of the following values:

  :and-call-through -- Track calls, but call the original
      function.

  :and-return-value -- Track calls, but return ARG instead of
      calling the original function.

  :and-call-fake -- Track calls, but call ARG instead of the
      original function.

  :and-throw-error -- Signal ARG as an error instead of calling
      the original function.

  nil -- Track calls, but simply return nil instead of calling
999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022
      the original function.

If the original function was a command, the generated spy will
also be a command with the same interactive form, unless
`:and-call-fake' is used, in which case it is the caller's
responsibility to ensure ARG is a command."
  ;; We need to load an autoloaded function before spying on it
  (when (autoloadp (symbol-function symbol))
    (autoload-do-load (symbol-function symbol) symbol))
  (cl-assert (not (autoloadp (symbol-function symbol))))
  (let* ((orig (symbol-function symbol))
         (orig-intform (interactive-form orig))
         (replacement
          (pcase
              keyword
            (:and-call-through
             (when arg
               (error "`spy-on' with `:and-call-through' does not take an ARG"))
             `(lambda (&rest args)
                ,orig-intform
                (apply ',orig args)))
            (:and-return-value
             `(lambda (&rest args)
                ,orig-intform
1023
                ',arg))
1024 1025 1026 1027
            (:and-call-fake
             (let ((replacement-intform (interactive-form arg)))
               (when (and replacement-intform
                          (not (equal orig-intform replacement-intform)))
1028 1029 1030 1031
                 (display-warning
                  'buttercup
                  (format "While spying on `%S': replacement does not have the same interactive form"
                          symbol)))
1032 1033 1034 1035 1036 1037 1038 1039 1040 1041
               `(lambda (&rest args)
                  ,(or replacement-intform orig-intform)
                  (apply (function ,arg) args))))
            (:and-throw-error
             `(lambda (&rest args)
                ,orig-intform
                (signal ',(or arg 'error) "Stubbed error")))
            ;; No keyword: just spy
            (`nil
             (when arg
1042
               (error "`spy-on' with no KEYWORD does not take an ARG"))
1043 1044 1045 1046 1047 1048
             `(lambda (&rest args)
                ,orig-intform
                nil))
            (_
             (error "Invalid `spy-on' keyword: `%S'" keyword)))))
    (buttercup--spy-on-and-call-fake symbol replacement)))
1049 1050

(defun buttercup--spy-on-and-call-fake (spy fake-function)
1051
  "Replace the function in symbol SPY with a spy calling FAKE-FUNCTION."
1052 1053 1054 1055 1056 1057
  (let ((orig-function (symbol-function spy)))
    (fset spy (buttercup--make-spy fake-function))
    (buttercup--add-cleanup (lambda ()
                              (fset spy orig-function)))))

(defun buttercup--make-spy (fake-function)
1058
  "Create a new spy function wrapping FAKE-FUNCTION and tracking calls to itself."
1059 1060 1061 1062
  (let (this-spy-function)
    (setq this-spy-function
          (lambda (&rest args)
            (let ((return-value (apply fake-function args)))
1063
              (buttercup--spy-calls-add
1064 1065 1066 1067 1068
               this-spy-function
               (make-spy-context :args args
                                 :return-value return-value
                                 :current-buffer (current-buffer)))
              return-value)))
1069 1070 1071 1072 1073 1074
    ;; Add the interactive form from `fake-function', if any
    (when (interactive-form fake-function)
      (setq this-spy-function
            `(lambda (&rest args)
               ,(interactive-form fake-function)
               (apply ',this-spy-function args))))
1075
    this-spy-function))
Jorgen Schaefer's avatar
Jorgen Schaefer committed
1076

1077 1078
(defvar buttercup--cleanup-functions nil)

1079
(defmacro buttercup-with-cleanup (&rest body)
1080
  "Execute BODY, cleaning spys and the rest afterwards."
1081 1082 1083 1084 1085 1086
  `(let ((buttercup--cleanup-functions nil))
     (unwind-protect (progn ,@body)
       (dolist (fun buttercup--cleanup-functions)
         (ignore-errors
           (funcall fun))))))

Jorgen Schaefer's avatar
Jorgen Schaefer committed
1087
(defun buttercup--add-cleanup (function)
1088
  "Register FUNCTION for cleanup in `buttercup-with-cleanup'."
1089 1090
  (setq buttercup--cleanup-functions
        (cons function buttercup--cleanup-functions)))
Jorgen Schaefer's avatar
Jorgen Schaefer committed
1091

1092 1093 1094 1095 1096 1097
(defun spy-calls-all (spy)
  "Return the contexts of calls to SPY."
  (gethash (symbol-function spy)
           buttercup--spy-contexts))

(defun buttercup--spy-calls-add (spy-function context)
1098
  "Add CONTEXT to the recorded calls to SPY."
1099 1100 1101
  (puthash spy-function
           (append (gethash spy-function
                            buttercup--spy-contexts)
1102
                   (list context))
1103
           buttercup--spy-contexts))
Jorgen Schaefer's avatar
Jorgen Schaefer committed
1104

1105 1106 1107 1108 1109
(defun spy-calls-reset (spy)
  "Reset SPY, removing all recorded calls."
  (puthash (symbol-function spy)
           nil
           buttercup--spy-contexts))
Jorgen Schaefer's avatar
Jorgen Schaefer committed
1110 1111

(buttercup-define-matcher :to-have-been-called (spy)
1112
  (if (spy-calls-all (funcall spy))
1113 1114
      t
    nil))
Jorgen Schaefer's avatar
Jorgen Schaefer committed
1115

1116
(defun spy-calls-any (spy)
1117
  "Return t iff SPY has been called at all, nil otherwise."
1118
  (if (spy-calls-all spy)
1119 1120 1121 1122
      t
    nil))

(defun spy-calls-count (spy)
1123
  "Return the number of times SPY has been called so far."
1124
  (length (spy-calls-all spy)))
1125 1126

(defun spy-calls-args-for (spy index)
1127
  "Return the context of the INDEXth call to SPY."
1128
  (let ((context (elt (spy-calls-all spy)
1129 1130 1131 1132 1133 1134
                      index)))
    (if context
        (spy-context-args context)
      nil)))

(defun spy-calls-all-args (spy)
1135
  "Return the arguments to all calls to SPY."
1136
  (mapcar 'spy-context-args (spy-calls-all spy)))
1137 1138

(defun spy-calls-most-recent (spy)
1139
  "Return the context of the most recent call to SPY."
1140
  (car (last (spy-calls-all spy))))
1141 1142

(defun spy-calls-first (spy)
1143
  "Return the context of the first call to SPY."
1144
  (car (spy-calls-all spy)))
1145

Jorgen Schaefer's avatar
Jorgen Schaefer committed
1146 1147 1148
;;;;;;;;;;;;;;;;
;;; Test Runners

1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195
;; These variables are generally used in the test runners, but set
;; elsewhere. They must be defined here before their first use.
(defvar buttercup-reporter #'buttercup-reporter-adaptive
  "The reporter function for buttercup test runs.

During a run of buttercup, the value of this variable is called
as a function with two arguments. The first argument is a symbol
describing the event, the second depends on the event.

The following events are known:

buttercup-started -- The test run is starting. The argument is a
  list of suites this run will execute.

suite-started -- A suite is starting. The argument is the suite.
  See `make-buttercup-suite' for details on this structure.

spec-started -- A spec in is starting. The argument is the spec.
  See `make-buttercup-spec' for details on this structure.

spec-done -- A spec has finished executing. The argument is the
  spec.

suite-done -- A suite has finished. The argument is the spec.

buttercup-done -- All suites have run, the test run is over.")

(defvar buttercup-stack-frame-style (car '(crop full pretty))
  "Style to use when printing stack traces of tests.

`full' is roughly the same style as normal Emacs stack traces:
print each stack frame in full with no line breaks. `crop' is
like full, but truncates each line to 80 characters. `pretty'
uses `pp' to generate a multi-line indented representation of
each frame, and prefixes each stack frame with lambda or M to
indicate whether it represents a normal evaluated function call
or a macro/special form.")

(defvar buttercup-color t
  "Whether to use colors in output.")

(defconst buttercup-warning-buffer-name " *Buttercup-Warnings*"
  "Buffer name used to collect warnings issued while running a spec.

A buffer with this name should only exist while running a test
spec, and should be killed after running the spec.")

1196
;;;###autoload
1197 1198 1199 1200 1201
(defun buttercup-run-at-point ()
  "Run the buttercup suite at point."
  (interactive)
  (let ((buttercup-suites nil)
        (lexical-binding t))
1202 1203 1204
    (save-selected-window
      (eval-defun nil)
      (buttercup-run))
1205 1206
    (message "Suite executed successfully")))

1207 1208 1209
(defvar buttercup-color t
  "Whether to use colors in output.")

1210
;;;###autoload
1211 1212 1213 1214 1215
(defun buttercup-run-discover ()
  "Discover and load test files, then run all defined suites.

Takes directories as command line arguments, defaulting to the
current directory."
1216 1217 1218 1219 1220
  (let ((dirs nil)
        (patterns nil)
        (args command-line-args-left))
    (while args
      (cond
1221 1222 1223 1224 1225 1226 1227 1228
       ((member (car args) '("--traceback"))
        (when (not (cdr args))
          (error "Option requires argument: %s" (car args)))
        ;; Make sure it's a valid style by trying to format a dummy
        ;; frame with it
        (buttercup--format-stack-frame '(t myfun 1 2) (intern (cadr args)))
        (setq buttercup-stack-frame-style (intern (cadr args)))
        (setq args (cddr args)))
1229 1230
       ((member (car args) '("-p" "--pattern"))
        (when (not (cdr args))
1231
          (error "Option requires argument: %s" (car args)))
1232 1233
        (push (cadr args) patterns)
        (setq args (cddr args)))
Thomas Fini Hansen's avatar
Thomas Fini Hansen committed
1234 1235 1236
       ((member (car args) '("-c" "--no-color"))
        (setq buttercup-color nil)
        (setq args (cdr args)))
1237 1238 1239 1240 1241 1242
       (t
        (push (car args) dirs)
        (setq args (cdr args)))))
    (setq command-line-args-left nil)
    (dolist (dir (or dirs '(".")))
      (dolist (file (directory-files-recursively
1243
                     dir "\\`test-.*\\.el\\'\\|-tests?\\.el\\'"))
1244
        (when (not (string-match "\\(^\\|/\\)\\." (file-relative-name file)))
1245
          (load file nil t))))
1246
    (when patterns
1247 1248 1249 1250 1251 1252 1253
      (dolist (spec (buttercup--specs buttercup-suites))
        (let ((spec-full-name (buttercup-spec-full-name spec)))
          (unless (cl-dolist (p patterns)
                    (when (string-match p spec-full-name)
                      (cl-return t)))
            (setf (buttercup-spec-function spec)
                  (lambda () (signal 'buttercup-pending "SKIPPED")))))))
1254
    (buttercup-run)))
1255

1256
;;;###autoload
1257
(defun buttercup-run-markdown ()
1258 1259
  "Run all test suites defined in Markdown files passed as arguments.
A suite must be defined within a Markdown \"lisp\" code block."
1260 1261 1262 1263
  (let ((lisp-buffer (generate-new-buffer "elisp")))
    (dolist (file command-line-args-left)
      (with-current-buffer (find-file-noselect file)
        (goto-char (point-min))
1264 1265
        (let ((case-fold-search t))
          (while (re-search-forward
1266
                  "```\\(?:emacs-\\|e\\)?lisp\n\\(\\(?:.\\|\n\\)*?\\)```"
1267 1268 1269 1270
                  nil t)
            (let ((code (match-string 1)))
              (with-current-buffer lisp-buffer
                (insert code)))))))
1271 1272 1273 1274 1275 1276
    (with-current-buffer lisp-buffer
      (setq lexical-binding t)
      (eval-region (point-min)
                   (point-max)))
    (buttercup-run)))

1277 1278 1279 1280
(eval-when-compile
  ;; Defined below in a dedicated section
  (defvar buttercup-reporter))

Jorgen Schaefer's avatar
Jorgen Schaefer committed
1281
(defun buttercup-run ()
1282
  "Run all described suites."
Jorgen Schaefer's avatar
Jorgen Schaefer committed
1283
  (if buttercup-suites
1284
      (progn
1285 1286 1287
        (funcall buttercup-reporter 'buttercup-started buttercup-suites)
        (mapc #'buttercup--run-suite buttercup-suites)
        (funcall buttercup-reporter 'buttercup-done buttercup-suites))
Jorgen Schaefer's avatar
Jorgen Schaefer committed
1288 1289
    (error "No suites defined")))

1290 1291 1292 1293 1294 1295 1296 1297 1298 1299
(defvar buttercup--before-each nil
  "A list of functions to call before each spec.

Do not change the global value.")

(defvar buttercup--after-each nil
  "A list of functions to call after each spec.

Do not change the global value.")

1300
(defun buttercup--run-suite (suite)
1301
  "Run SUITE. A suite is a sequence of suites and specs."
1302
  (let* ((buttercup--before-each (append buttercup--before-each
1303 1304
                                         (buttercup-suite-before-each suite)))
         (buttercup--after-each (append (buttercup-suite-after-each suite)
1305
                                        buttercup--after-each)))
1306
    (funcall buttercup-reporter 'suite-started suite)
1307
    (dolist (f (buttercup-suite-before-all suite))
1308
      (buttercup--update-with-funcall suite f))
1309 1310 1311 1312 1313 1314
    (dolist (sub (buttercup-suite-children suite))
      (cond
       ((buttercup-suite-p sub)
        (buttercup--run-suite sub))
       ((buttercup-spec-p sub)
        (buttercup--run-spec sub))))
1315
    (dolist (f (buttercup-suite-after-all suite))
1316
      (buttercup--update-with-funcall suite f))
1317
    (funcall buttercup-reporter 'suite-done suite)))
Jorgen Schaefer's avatar
Jorgen Schaefer committed
1318

1319
(defun buttercup--run-spec (spec)
1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344
  (unwind-protect
      (progn
        ;; Kill any previous warning buffer, just in case
        (when (get-buffer buttercup-warning-buffer-name)
          (kill-buffer buttercup-warning-buffer-name))
        (get-buffer-create buttercup-warning-buffer-name)

        (funcall buttercup-reporter 'spec-started spec)
        (buttercup-with-cleanup
         (dolist (f buttercup--before-each)
           (buttercup--update-with-funcall spec f))
         (buttercup--update-with-funcall spec (buttercup-spec-function spec))
         (dolist (f buttercup--after-each)
           (buttercup--update-with-funcall spec f)))
        (funcall buttercup-reporter 'spec-done spec)
        ;; Display warnings that were issued while running the the
        ;; spec, if any
        (with-current-buffer buttercup-warning-buffer-name
          (when (string-match-p "[^[:space:]\n\r]" (buffer-string))
            (buttercup--print
             (buttercup-colorize
              (buffer-string)
              'yellow)))))
    (when (get-buffer buttercup-warning-buffer-name)
      (kill-buffer buttercup-warning-buffer-name))))
1345

1346 1347 1348 1349 1350 1351 1352 1353 1354
(defun buttercup--update-with-funcall (suite-or-spec function &rest args)
  (let* ((result (apply 'buttercup--funcall function args))
         (status (elt result 0))
         (description (elt result 1))
         (stack (elt result 2)))
    (when (eq status 'failed)
      (pcase description
        (`(error (buttercup-failed . ,failure-description))
         (setq description failure-description))
1355
        (`(error (buttercup-pending . ,pending-description))
1356
         (setq status 'pending
1357
               description pending-description))))
1358 1359 1360 1361 1362
    (when (eq (buttercup-suite-or-spec-status suite-or-spec)
              'passed)
      (setf (buttercup-suite-or-spec-status suite-or-spec) status
            (buttercup-suite-or-spec-failure-description suite-or-spec) description
            (buttercup-suite-or-spec-failure-stack suite-or-spec) stack))))
1363

1364 1365 1366
;;;;;;;;;;;;;
;;; Reporters

1367 1368 1369 1370
(defun buttercup-reporter-adaptive (event arg)
  "A reporter that handles both interactive and noninteractive sessions.

Calls either `buttercup-reporter-batch' or
1371 1372 1373
`buttercup-reporter-interactive', depending.

EVENT and ARG are described in `buttercup-reporter'."
1374
  (if noninteractive
Thomas Fini Hansen's avatar
Thomas Fini Hansen committed
1375 1376 1377
      (if buttercup-color
          (buttercup-reporter-batch-color event arg)
        (buttercup-reporter-batch event arg))
1378 1379
    (buttercup-reporter-interactive event arg)))

1380 1381 1382 1383 1384 1385
(defvar buttercup-reporter-batch--start-time nil
  "The time the last batch report started.")

(defvar buttercup-reporter-batch--failures nil
  "List of failed specs of the current batch report.")

1386
(defun buttercup-reporter-batch (event arg)
1387 1388 1389
  "A reporter that handles batch sessions.

EVENT and ARG are described in `buttercup-reporter'."
1390 1391 1392 1393
  (let ((print-escape-newlines t)
        (print-escape-nonascii t))
    (pcase event
      (`buttercup-started
1394 1395
       (setq buttercup-reporter-batch--start-time (float-time)
             buttercup-reporter-batch--failures nil)
1396 1397 1398 1399 1400 1401 1402
       (let ((defined (buttercup-suites-total-specs-defined arg))
             (pending (buttercup-suites-total-specs-pending arg)))
         (if (> pending 0)
             (buttercup--print "Running %s out of %s specs.\n\n"
                               (- defined pending)
                               defined)
           (buttercup--print "Running %s specs.\n\n" defined))))
1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424

      (`suite-started
       (let ((level (length (buttercup-suite-parents arg))))
         (buttercup--print "%s%s\n"
                           (make-string (* 2 level) ?\s)
                           (buttercup-suite-description arg))))

      (`spec-started
       (let ((level (length (buttercup-spec-parents arg))))
         (buttercup--print "%s%s"
                           (make-string (* 2 level) ?\s)
                           (buttercup-spec-description arg))))

      (`spec-done
       (cond
        ((eq (buttercup-spec-status arg) 'passed)
         (buttercup--print "\n"))
        ((eq (buttercup-spec-status arg) 'failed)
         (buttercup--print "  FAILED\n")
         (setq buttercup-reporter-batch--failures
               (append buttercup-reporter-batch--failures
                       (list arg))))
1425
        ((eq (buttercup-spec-status arg) 'pending)
1426
         (buttercup--print "  %s\n" (buttercup-spec-failure-description arg)))
1427
        (t
1428 1429 1430 1431
         (error "Unknown spec status %s" (buttercup-spec-status arg)))))

      (`suite-done
       (when (= 0 (length (buttercup-suite-parents arg)))
1432
         (buttercup--print "\n")))
1433 1434 1435 1436 1437 1438 1439 1440 1441 1442

      (`buttercup-done
       (dolist (failed buttercup-reporter-batch--failures)
         (let ((description (buttercup-spec-failure-description failed))
               (stack (buttercup-spec-failure-stack failed)))
           (buttercup--print "%s\n" (make-string 40 ?=))
           (buttercup--print "%s\n" (buttercup-spec-full-name failed))
           (when stack
             (buttercup--print "\nTraceback (most recent call last):\n")
             (dolist (frame stack)
1443 1444
               (let ((frame-text (buttercup--format-stack-frame frame)))
                 (buttercup--print "%s\n" frame-text))))
1445 1446 1447 1448 1449 1450 1451 1452 1453 1454
           (cond
            ((stringp description)
             (buttercup--print "FAILED: %s\n" description))
            ((eq (car description) 'error)
             (buttercup--print "%S: %S\n\n"
                               (car description)
                               (cadr description)))
            (t
             (buttercup--print "FAILED: %S\n" description)))
           (buttercup--print "\n")))
1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472
       (let ((defined (buttercup-suites-total-specs-defined arg))
             (pending (buttercup-suites-total-specs-pending arg))
             (failed (buttercup-suites-total-specs-failed arg))
             (duration (- (float-time)
                          buttercup-reporter-batch--start-time)))
         (if (> pending 0)
             (buttercup--print
              "Ran %s out of %s specs, %s failed, in %.1f seconds.\n"
              (- defined pending)
              defined
              failed
              duration)
           (buttercup--print "Ran %s specs, %s failed, in %.1f seconds.\n"
                             defined
                             failed
                             duration))
         (when (> failed 0)
           (error ""))))
1473

1474
      (_
1475
       (error "Unknown event %s" event)))))
Jorgen Schaefer's avatar
Jorgen Schaefer committed
1476

Thomas Fini Hansen's avatar
Thomas Fini Hansen committed
1477
(defun buttercup-reporter-batch-color (event arg)
1478 1479 1480 1481 1482 1483
  "A reporter that handles batch sessions.

Compared to `buttercup-reporter-batch', this reporter uses
colors.

EVENT and ARG are described in `buttercup-reporter'."
Thomas Fini Hansen's avatar
Thomas Fini Hansen committed
1484 1485 1486 1487 1488 1489 1490 1491
  (pcase event
    (`spec-done
     (let ((level (length (buttercup-spec-parents arg))))
       (cond
        ((eq (buttercup-spec-status arg) 'passed)
         (buttercup--print (buttercup-colorize "\r%s%s\n" 'green)
                           (make-string (* 2 level) ?\s)
                           (buttercup-spec-description arg)))
1492 1493
        ((eq (buttercup-spec-status arg) 'failed)
         (buttercup--print (buttercup-colorize "\r%s%s  FAILED\n" 'red)
Thomas Fini Hansen's avatar
Thomas Fini Hansen committed
1494
                           (make-string (* 2 level) ?\s)
1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505
                           (buttercup-spec-description arg))
         (setq buttercup-reporter-batch--failures
               (append buttercup-reporter-batch--failures
                       (list arg))))
        ((eq (buttercup-spec-status arg) 'pending)
         (if (equal (buttercup-spec-failure-description arg) "SKIPPED")
             (buttercup--print "  %s\n" (buttercup-spec-failure-description arg))
           (buttercup--print (buttercup-colorize "\r%s%s  %s\n" 'yellow)
                             (make-string (* 2 level) ?\s)
                             (buttercup-spec-description arg)
                             (buttercup-spec-failure-description arg))))
1506
        (t
1507
         (error "Unknown spec status %s" (buttercup-spec-status arg))))))
Thomas Fini Hansen's avatar
Thomas Fini Hansen committed
1508 1509 1510 1511 1512 1513 1514 1515 1516 1517

    (`buttercup-done
     (dolist (failed buttercup-reporter-batch--failures)
       (let ((description (buttercup-spec-failure-description failed))
             (stack (buttercup-spec-failure-stack failed)))
         (buttercup--print "%s\n" (make-string 40 ?=))
         (buttercup--print (buttercup-colorize "%s\n" 'red) (buttercup-spec-full-name failed))
         (when stack
           (buttercup--print "\nTraceback (most recent call last):\n")
           (dolist (frame stack)
1518 1519
             (let ((frame-text (buttercup--format-stack-frame frame)))
               (buttercup--print "%s\n" frame-text))))
Thomas Fini Hansen's avatar
Thomas Fini Hansen committed
1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561
         (cond
          ((stringp description)
           (buttercup--print (concat (buttercup-colorize "FAILED" 'red ) ": %s\n")
                             description))
          ((eq (car description) 'error)
           (buttercup--print "%S: %S\n\n"
                             (car description)
                             (cadr description)))
          (t
           (buttercup--print "FAILED: %S\n" description)))
         (buttercup--print "\n")))
     (let ((defined (buttercup-suites-total-specs-defined arg))
           (pending (buttercup-suites-total-specs-pending arg))
           (failed (buttercup-suites-total-specs-failed arg))
           (duration (- (float-time)
                        buttercup-reporter-batch--start-time)))
       (if (> pending 0)
           (buttercup--print
            (concat
             "Ran %s out of %s specs,"
             (buttercup-colorize " %s failed" (if (eq 0 failed) 'green 'red))
             ", in %.1f seconds.\n")
            (- defined pending)
            defined
            failed
            duration)
         (buttercup--print
          (concat
           "Ran %s specs,"
           (buttercup-colorize " %s failed" (if (eq 0 failed) 'green 'red))
           ", in %.1f seconds.\n")
          defined
          failed
          duration))
       (when (> failed 0)
         (error ""))))

    (_
     ;; Fall through to buttercup-reporter-batch implementation.
     (buttercup-reporter-batch event arg)))
  )

1562
(defun buttercup--print (fmt &rest args)
1563 1564 1565
  "Format a string and send it to terminal without alteration.

FMT and ARGS are passed to `format'."
1566
  (send-string-to-terminal (apply #'format fmt args)))
1567

Ryan C. Thompson's avatar