buttercup.el 68.8 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.14
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
  ;; One of: passed failed pending
  (status 'passed)
  failure-description
  failure-stack
673 674
  time-started
  time-ended)
675 676 677 678

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

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

691 692 693 694
(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)
695
                (list child)))
696
  (setf (buttercup-suite-or-spec-parent child) parent))
697

698 699 700 701 702 703
(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)))))

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

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

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

(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))
718

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

723 724 725 726 727 728 729 730 731
(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))))))))

732
(defun buttercup--specs-and-suites (spec-or-suite-list)
733
  "Return a flat list of all specs and suites in SPEC-OR-SUITE-LIST."
734
  (let ((specs-and-suites nil))
735
    (dolist (spec-or-suite spec-or-suite-list specs-and-suites)
736 737 738 739 740 741
      (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
742
                       (buttercup-suite-children spec-or-suite))))))))
743

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

750 751 752 753 754 755 756 757 758
(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))))

759 760 761
(defun buttercup--full-spec-names (spec-or-suite-list)
  "Return full names of all specs in SPEC-OR-SUITE-LIST."
  (cl-loop
762
   for x in (buttercup--specs spec-or-suite-list)
763 764 765 766 767 768 769 770 771 772 773 774
   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)))))

775 776 777 778 779 780 781 782 783 784 785 786 787 788 789
(defun buttercup--set-start-time (suite-or-spec)
  "Set time-started of SUITE-OR-SPEC to `current-time'."
  (setf (buttercup-suite-or-spec-time-started suite-or-spec) (current-time)))

(defun buttercup--set-end-time (suite-or-spec)
  "Set time-ended of SUITE-OR-SPEC to `current-time'."
  (setf (buttercup-suite-or-spec-time-ended suite-or-spec) (current-time)))

(defun buttercup-elapsed-time (suite-or-spec)
  "Get elapsed time of SUITE-OR-SPEC."
  ;; time-subtract does not handle nil arguments until Emacs 25.1
  (time-subtract
   (or (buttercup-suite-or-spec-time-ended suite-or-spec) (current-time))
   (or (buttercup-suite-or-spec-time-started suite-or-spec) (current-time))))

790 791 792
;;;;;;;;;;;;;;;;;;;;
;;; Suites: describe

Jorgen Schaefer's avatar
Jorgen Schaefer committed
793 794 795 796 797 798 799 800 801 802
(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)
803 804 805 806
  "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
807
  (declare (indent 1) (debug (&define sexp def-body)))
808 809 810 811 812
  (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
813

814
(defun buttercup-describe (description body-function)
815 816 817 818 819
  "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
820 821 822
  (let* ((enclosing-suite buttercup--current-suite)
         (buttercup--current-suite (make-buttercup-suite
                                    :description description)))
823
    (condition-case nil
824 825 826 827
        (funcall body-function)
      (buttercup-pending
       (setf (buttercup-suite-status buttercup--current-suite)
             'pending)))
Jorgen Schaefer's avatar
Jorgen Schaefer committed
828
    (if enclosing-suite
829 830
        (buttercup-suite-add-child enclosing-suite
                                   buttercup--current-suite)
831 832 833 834
      ;; At top level, warn about duplicate spec names
      (let ((dups (buttercup--find-duplicate-spec-names
                   (list buttercup--current-suite))))
        (when dups
835 836 837 838 839
          ;; 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
840 841 842
      (setq buttercup-suites (append buttercup-suites
                                     (list buttercup--current-suite))))))

Jorgen Schaefer's avatar
Jorgen Schaefer committed
843 844 845
;;;;;;;;;;;;;
;;; Specs: it

Jorgen Schaefer's avatar
Jorgen Schaefer committed
846
(defmacro it (description &rest body)
847 848 849 850
  "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
851
  (declare (indent 1) (debug (&define sexp def-body)))
852
  (if body
853 854 855 856
      `(buttercup-it ,description
         (lambda ()
           (buttercup-with-converted-ert-signals
             ,@body)))
857
    `(buttercup-xit ,description)))
Jorgen Schaefer's avatar
Jorgen Schaefer committed
858

859
(defun buttercup-it (description body-function)
860 861 862 863
  "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'."
864
  (declare (indent 1))
865
  (when (not buttercup--current-suite)
866
    (error "`it' has to be called from within a `describe' form"))
867 868 869 870
  (buttercup-suite-add-child buttercup--current-suite
                             (make-buttercup-spec
                              :description description
                              :function body-function)))
Jorgen Schaefer's avatar
Jorgen Schaefer committed
871

872 873 874 875
;;;;;;;;;;;;;;;;;;;;;;
;;; Setup and Teardown

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

(defun buttercup-before-each (function)
881 882 883 884
  "The function to handle a `before-each' form.

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

(defmacro after-each (&rest body)
890
  "Run BODY after each spec in the current suite."
myeffort's avatar
myeffort committed
891
  (declare (indent 0) (debug (&define def-body)))
892 893 894
  `(buttercup-after-each (lambda () ,@body)))

(defun buttercup-after-each (function)
895 896 897 898
  "The function to handle an `after-each' form.

FUNCTION is a function containing the body instructions passed to
`after-each'."
899 900 901 902 903
  (setf (buttercup-suite-after-each buttercup--current-suite)
        (append (buttercup-suite-after-each buttercup--current-suite)
                (list function))))

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

(defun buttercup-before-all (function)
909 910 911 912
  "The function to handle a `before-all' form.

FUNCTION is a function containing the body instructions passed to
`before-all'."
913 914 915 916 917
  (setf (buttercup-suite-before-all buttercup--current-suite)
        (append (buttercup-suite-before-all buttercup--current-suite)
                (list function))))

(defmacro after-all (&rest body)
918
  "Run BODY after every spec in the current suite."
myeffort's avatar
myeffort committed
919
  (declare (indent 0) (debug (&define def-body)))
920 921 922
  `(buttercup-after-all (lambda () ,@body)))

(defun buttercup-after-all (function)
923 924 925 926
  "The function to handle an `after-all' form.

FUNCTION is a function containing the body instructions passed to
`after-all'."
927 928 929 930
  (setf (buttercup-suite-after-all buttercup--current-suite)
        (append (buttercup-suite-after-all buttercup--current-suite)
                (list function))))

931 932 933
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Disabled Suites: xdescribe

934 935 936 937
(defun buttercup--disable-specs (forms)
  "Process FORMS to make any suites or specs pending."
  (when (eq (car forms) :var)
    (setq forms (cddr forms)))
938
  (let (retained)
939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971
    (dolist (form forms (nreverse retained))
      (pcase form
        ;; Make it pending by just keeping the description
        (`(it ,description . ,_)
         (push (list 'it description) retained))
        (`(xit ,description . ,_)
         (push (list 'it description) retained))
        ;; Just make nested describes into xdescribes and handle them
        ;; in another macro invocation
        (`(describe . ,tail)
         (push (cons 'xdescribe tail) retained))
        (`(xdescribe . ,tail)
         (push (cons 'xdescribe tail) retained))
        ;; Special case to ignore before-* and after-* forms
        (`(before-each . ,_)) ; nop
        (`(after-each . ,_)) ; nop
        (`(before-all . ,_)) ; nop
        (`(after-all . ,_)) ; nop
        ;; Any list starting with a list, like a let varlist.
        ((and (pred consp)
              ls
              (guard (consp (car ls))))
         (dolist (elt (buttercup--disable-specs ls))
           (push elt retained)))
        ;; Any function call list
        (`(,_ . ,tail)
         (dolist (elt (buttercup--disable-specs tail))
           (push elt retained)))
        ;; non-cons items
        ((and elt (guard (not (consp elt))))) ; nop
        (_
         (error "Unrecognized form in `xdescribe': `%s'" (pp-to-string form)))
        ))))
972

973 974
(defmacro xdescribe (description &rest body)
  "Like `describe', but mark any specs as disabled.
975 976 977

DESCRIPTION is a string. BODY is a sequence of instructions,
mainly calls to `describe', `it' and `before-each'."
978
  (declare (indent 1))
979 980 981 982
  `(describe ,description
     ,@(buttercup--disable-specs body)
     ;; make sure the suite is marked as pending
     (signal 'buttercup-pending "PENDING")))
983 984 985 986 987 988 989

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

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

990 991 992
A disabled spec is not run.

DESCRIPTION is a string. BODY is ignored."
993
  (declare (indent 1))
994
  (ignore body)
995
  `(buttercup-xit ,description))
996

997
(defun buttercup-xit (description &optional function)
998
  "Like `buttercup-it', but mark the spec as disabled.
999
A disabled spec is not run.
1000

1001
DESCRIPTION has the same meaning as in `xit'. FUNCTION is ignored."
1002
  (declare (indent 1))
1003
  (ignore function)
1004
  (buttercup-it description (lambda ()
1005 1006 1007 1008
                              (signal 'buttercup-pending "PENDING")))
  (let ((spec (car (last (buttercup-suite-children
                          buttercup--current-suite)))))
    (setf (buttercup-spec-status spec)
1009 1010 1011
          'pending
          (buttercup-spec-failure-description spec)
          "")))
1012

Jorgen Schaefer's avatar
Jorgen Schaefer committed
1013 1014 1015
;;;;;;;;;
;;; Spies

1016 1017
(defvar buttercup--spy-contexts (make-hash-table :test 'eq
                                                 :weakness 'key)
1018
  "A mapping of currently-defined spies to their contexts.")
Jorgen Schaefer's avatar
Jorgen Schaefer committed
1019

1020 1021 1022 1023 1024
(cl-defstruct spy-context
  args
  return-value
  current-buffer)

1025
(defun spy-on (symbol &optional keyword arg)
1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042
  "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
1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066
      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
1067
                ',arg))
1068 1069 1070 1071
            (:and-call-fake
             (let ((replacement-intform (interactive-form arg)))
               (when (and replacement-intform
                          (not (equal orig-intform replacement-intform)))
1072 1073 1074 1075
                 (display-warning
                  'buttercup
                  (format "While spying on `%S': replacement does not have the same interactive form"
                          symbol)))
1076 1077 1078 1079 1080 1081 1082 1083 1084 1085
               `(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
1086
               (error "`spy-on' with no KEYWORD does not take an ARG"))
1087 1088 1089 1090 1091 1092
             `(lambda (&rest args)
                ,orig-intform
                nil))
            (_
             (error "Invalid `spy-on' keyword: `%S'" keyword)))))
    (buttercup--spy-on-and-call-fake symbol replacement)))
1093 1094

(defun buttercup--spy-on-and-call-fake (spy fake-function)
1095
  "Replace the function in symbol SPY with a spy calling FAKE-FUNCTION."
1096 1097 1098 1099 1100 1101
  (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)
1102
  "Create a new spy function wrapping FAKE-FUNCTION and tracking calls to itself."
1103 1104 1105 1106
  (let (this-spy-function)
    (setq this-spy-function
          (lambda (&rest args)
            (let ((return-value (apply fake-function args)))
1107
              (buttercup--spy-calls-add
1108 1109 1110 1111 1112
               this-spy-function
               (make-spy-context :args args
                                 :return-value return-value
                                 :current-buffer (current-buffer)))
              return-value)))
1113 1114 1115 1116 1117 1118
    ;; 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))))
1119
    this-spy-function))
Jorgen Schaefer's avatar
Jorgen Schaefer committed
1120

1121 1122
(defvar buttercup--cleanup-functions nil)

1123
(defmacro buttercup-with-cleanup (&rest body)
1124
  "Execute BODY, cleaning spys and the rest afterwards."
1125 1126 1127 1128 1129 1130
  `(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
1131
(defun buttercup--add-cleanup (function)
1132
  "Register FUNCTION for cleanup in `buttercup-with-cleanup'."
1133 1134
  (setq buttercup--cleanup-functions
        (cons function buttercup--cleanup-functions)))
Jorgen Schaefer's avatar
Jorgen Schaefer committed
1135

1136 1137 1138 1139 1140 1141
(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)
1142
  "Add CONTEXT to the recorded calls to SPY."
1143 1144 1145
  (puthash spy-function
           (append (gethash spy-function
                            buttercup--spy-contexts)
1146
                   (list context))
1147
           buttercup--spy-contexts))
Jorgen Schaefer's avatar
Jorgen Schaefer committed
1148

1149 1150 1151 1152 1153
(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
1154 1155

(buttercup-define-matcher :to-have-been-called (spy)
1156
  (if (spy-calls-all (funcall spy))
1157 1158
      t
    nil))
Jorgen Schaefer's avatar
Jorgen Schaefer committed
1159

1160
(defun spy-calls-any (spy)
1161
  "Return t iff SPY has been called at all, nil otherwise."
1162
  (if (spy-calls-all spy)
1163 1164 1165 1166
      t
    nil))

(defun spy-calls-count (spy)
1167
  "Return the number of times SPY has been called so far."
1168
  (length (spy-calls-all spy)))
1169 1170

(defun spy-calls-args-for (spy index)
1171
  "Return the context of the INDEXth call to SPY."
1172
  (let ((context (elt (spy-calls-all spy)
1173 1174 1175 1176 1177 1178
                      index)))
    (if context
        (spy-context-args context)
      nil)))

(defun spy-calls-all-args (spy)
1179
  "Return the arguments to all calls to SPY."
1180
  (mapcar 'spy-context-args (spy-calls-all spy)))
1181 1182

(defun spy-calls-most-recent (spy)
1183
  "Return the context of the most recent call to SPY."
1184
  (car (last (spy-calls-all spy))))
1185 1186

(defun spy-calls-first (spy)
1187
  "Return the context of the first call to SPY."
1188
  (car (spy-calls-all spy)))
1189

Jorgen Schaefer's avatar
Jorgen Schaefer committed
1190 1191 1192
;;;;;;;;;;;;;;;;
;;; Test Runners

1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239
;; 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.")

1240
;;;###autoload
1241 1242 1243 1244 1245
(defun buttercup-run-at-point ()
  "Run the buttercup suite at point."
  (interactive)
  (let ((buttercup-suites nil)
        (lexical-binding t))
1246 1247 1248
    (save-selected-window
      (eval-defun nil)
      (buttercup-run))
1249 1250
    (message "Suite executed successfully")))

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

1254
;;;###autoload
1255 1256 1257 1258 1259
(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."
1260 1261 1262 1263 1264
  (let ((dirs nil)
        (patterns nil)
        (args command-line-args-left))
    (while args
      (cond
1265 1266 1267 1268 1269 1270 1271 1272
       ((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)))
1273 1274
       ((member (car args) '("-p" "--pattern"))
        (when (not (cdr args))
1275
          (error "Option requires argument: %s" (car args)))
1276 1277
        (push (cadr args) patterns)
        (setq args (cddr args)))
Thomas Fini Hansen's avatar
Thomas Fini Hansen committed
1278 1279 1280
       ((member (car args) '("-c" "--no-color"))
        (setq buttercup-color nil)
        (setq args (cdr args)))
1281 1282 1283 1284 1285 1286
       (t
        (push (car args) dirs)
        (setq args (cdr args)))))
    (setq command-line-args-left nil)
    (dolist (dir (or dirs '(".")))
      (dolist (file (directory-files-recursively
1287
                     dir "\\`test-.*\\.el\\'\\|-tests?\\.el\\'"))
1288
        (when (not (string-match "\\(^\\|/\\)\\." (file-relative-name file)))
1289
          (load file nil t))))
1290
    (when patterns
1291 1292 1293 1294 1295 1296 1297
      (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")))))))
1298
    (buttercup-run)))
1299

1300
;;;###autoload
1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320
(defun buttercup-run-markdown-buffer (&rest markdown-buffers)
  "Run all test suites defined in MARKDOWN-BUFFERS.
A suite must be defined within a Markdown \"lisp\" code block.
If MARKDOWN-BUFFERS is empty (nil), use the current buffer."
  (interactive)
  (unless markdown-buffers
    (setq markdown-buffers (list (current-buffer))))
  (let ((lisp-buffer (generate-new-buffer "elisp"))
        (case-fold-search t)
        code
        buttercup-suites)
    (dolist (markdown-buffer markdown-buffers)
      (with-current-buffer markdown-buffer
        (save-excursion
          (save-match-data
            (goto-char (point-min))
            (while (re-search-forward
                    "```\\(?:emacs-\\|e\\)?lisp\n\\(\\(?:.\\|\n\\)*?\\)```"
                    nil t)
              (setq code (match-string 1))
1321 1322
              (with-current-buffer lisp-buffer
                (insert code)))))))
1323 1324 1325 1326 1327 1328
    (with-current-buffer lisp-buffer
      (setq lexical-binding t)
      (eval-region (point-min)
                   (point-max)))
    (buttercup-run)))

1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342
;;;###autoload
(defun buttercup-run-markdown ()
  "Run all test suites defined in Markdown files passed as arguments.
A suite must be defined within a Markdown \"lisp\" code block."
  (apply #'buttercup-run-markdown-buffer (mapcar #'find-file-noselect
                                                 command-line-args-left)))

;;;###autoload
(defun buttercup-run-markdown-file (file)
  "Run all test suites defined in Markdown FILE.
A suite must be defined within a Markdown \"lisp\" code block."
  (interactive "fMarkdown file: ")
  (buttercup-run-markdown-buffer (find-file-noselect file)))

1343 1344 1345 1346
(eval-when-compile
  ;; Defined below in a dedicated section
  (defvar buttercup-reporter))

Jorgen Schaefer's avatar
Jorgen Schaefer committed
1347
(defun buttercup-run ()
1348
  "Run all described suites."
Jorgen Schaefer's avatar
Jorgen Schaefer committed
1349
  (if buttercup-suites
1350
      (progn
1351 1352 1353
        (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
1354 1355
    (error "No suites defined")))

1356 1357 1358 1359 1360 1361 1362 1363 1364 1365
(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.")

1366
(defun buttercup--run-suite (suite)
1367
  "Run SUITE. A suite is a sequence of suites and specs."
1368
  (buttercup--set-start-time suite)
1369
  (let* ((buttercup--before-each (append buttercup--before-each
1370 1371
                                         (buttercup-suite-before-each suite)))
         (buttercup--after-each (append (buttercup-suite-after-each suite)
1372
                                        buttercup--after-each)))
1373
    (funcall buttercup-reporter 'suite-started suite)
1374
    (dolist (f (buttercup-suite-before-all suite))
1375
      (buttercup--update-with-funcall suite f))
1376 1377 1378 1379 1380 1381
    (dolist (sub (buttercup-suite-children suite))
      (cond
       ((buttercup-suite-p sub)
        (buttercup--run-suite sub))
       ((buttercup-spec-p sub)
        (buttercup--run-spec sub))))
1382
    (dolist (f (buttercup-suite-after-all suite))
1383
      (buttercup--update-with-funcall suite f))
1384
    (buttercup--set-end-time suite)
1385
    (funcall buttercup-reporter 'suite-done suite)))
Jorgen Schaefer's avatar
Jorgen Schaefer committed
1386

1387
(defun buttercup--run-spec (spec)
1388
  (buttercup--set-start-time spec)
1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412
  (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)
1413 1414
      (kill-buffer buttercup-warning-buffer-name))
    (buttercup--set-end-time spec)))
1415

1416
(defun buttercup--update-with-funcall (suite-or-spec function &rest args)
1417 1418 1419
  "Update SUITE-OR-SPEC with the result of calling FUNCTION with ARGS.
Sets the `status', `failure-description', and `failure-stack' for
failed and pending specs."
1420 1421 1422 1423 1424 1425 1426 1427
  (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))
1428
        (`(error (buttercup-pending . ,pending-description))
1429
         (setq status 'pending
1430
               description pending-description))))
1431 1432
    (when (memq (buttercup-suite-or-spec-status suite-or-spec)
                '(passed pending))
1433 1434 1435
      (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))))
1436

1437 1438 1439
;;;;;;;;;;;;;
;;; Reporters

1440 1441 1442 1443
(defun buttercup-reporter-adaptive (event arg)
  "A reporter that handles both interactive and noninteractive sessions.

Calls either `buttercup-reporter-batch' or
1444 1445 1446
`buttercup-reporter-interactive', depending.

EVENT and ARG are described in `buttercup-reporter'."
1447
  (if noninteractive
Thomas Fini Hansen's avatar
Thomas Fini Hansen committed
1448 1449 1450
      (if buttercup-color
          (buttercup-reporter-batch-color event arg)
        (buttercup-reporter-batch event arg))
1451 1452
    (buttercup-reporter-interactive event arg)))

1453 1454 1455 1456 1457 1458
(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.")

1459
(defun buttercup-reporter-batch (event arg)
1460 1461 1462
  "A reporter that handles batch sessions.

EVENT and ARG are described in `buttercup-reporter'."
1463 1464 1465 1466
  (let ((print-escape-newlines t)
        (print-escape-nonascii t))
    (pcase event
      (`buttercup-started
1467 1468
       (setq buttercup-reporter-batch--start-time (float-time)
             buttercup-reporter-batch--failures nil)
1469 1470 1471 1472 1473 1474 1475
       (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))))
1476 1477

      (`suite-started
1478
       (let ((level (length (buttercup-suite-or-spec-parents arg))))
1479 1480 1481 1482 1483
         (buttercup--print "%s%s\n"
                           (make-string (* 2 level) ?\s)
                           (buttercup-suite-description arg))))

      (`spec-started
1484
       (let ((level (length (buttercup-suite-or-spec-parents arg))))
1485 1486 1487 1488 1489 1490
         (buttercup--print "%s%s"
                           (make-string (* 2 level) ?\s)
                           (buttercup-spec-description arg))))

      (`spec-done
       (cond
1491
        ((eq (buttercup-spec-status arg) 'passed)) ; do nothing
1492
        ((eq (buttercup-spec-status arg) 'failed)
1493
         (buttercup--print "  FAILED")
1494 1495 1496
         (setq buttercup-reporter-batch--failures
               (append buttercup-reporter-batch--failures
                       (list arg))))
1497
        ((eq (buttercup-spec-status arg) 'pending)
1498
         (buttercup--print "  %s" (buttercup-spec-failure-description arg)))
1499
        (t
1500 1501 1502 1503
         (error "Unknown spec status %s" (buttercup-spec-status arg))))
       (buttercup--print " (%s)\n"
                         (seconds-to-string
                          (float-time (buttercup-elapsed-time arg)))))
1504 1505

      (`suite-done
1506
       (when (= 0 (length (buttercup-suite-or-spec-parents arg)))
1507
         (buttercup--print "\n")))
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 "%s\n" (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))))
1520 1521 1522 1523 1524 1525 1526 1527 1528 1529
           (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")))
1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547
       (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 ""))))
1548

1549
      (_
1550
       (error "Unknown event %s" event)))))
Jorgen Schaefer's avatar
Jorgen Schaefer committed
1551