-
Notifications
You must be signed in to change notification settings - Fork 32
/
test.clj
640 lines (518 loc) · 22.8 KB
/
test.clj
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
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
335
336
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
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
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
505
506
507
508
509
510
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
539
540
541
542
543
544
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
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
(ns
^{:author "Stuart Sierra, with contributions and suggestions by
Chas Emerick, Allen Rohner, and Stuart Halloway",
:doc "A unit testing framework.
NOTE: This documentation is copied verbatim from clojure.test,
and describes behaviour that does not apply to this ClojureScript port.
Proper documentation to follow. :-P
ASSERTIONS
The core of the library is the \"is\" macro, which lets you make
assertions of any arbitrary expression:
(is (= 4 (+ 2 2)))
(is (instance? Integer 256))
(is (.startsWith \"abcde\" \"ab\"))
You can type an \"is\" expression directly at the REPL, which will
print a message if it fails.
user> (is (= 5 (+ 2 2)))
FAIL in (:1)
expected: (= 5 (+ 2 2))
actual: (not (= 5 4))
false
The \"expected:\" line shows you the original expression, and the
\"actual:\" shows you what actually happened. In this case, it
shows that (+ 2 2) returned 4, which is not = to 5. Finally, the
\"false\" on the last line is the value returned from the
expression. The \"is\" macro always returns the result of the
inner expression.
There are two special assertions for testing exceptions. The
\"(is (thrown? c ...))\" form tests if an exception of class c is
thrown:
(is (thrown? ArithmeticException (/ 1 0)))
\"(is (thrown-with-msg? c re ...))\" does the same thing and also
tests that the message on the exception matches the regular
expression re:
(is (thrown-with-msg? ArithmeticException #\"Divide by zero\"
(/ 1 0)))
DOCUMENTING TESTS
\"is\" takes an optional second argument, a string describing the
assertion. This message will be included in the error report.
(is (= 5 (+ 2 2)) \"Crazy arithmetic\")
In addition, you can document groups of assertions with the
\"testing\" macro, which takes a string followed by any number of
assertions. The string will be included in failure reports.
Calls to \"testing\" may be nested, and all of the strings will be
joined together with spaces in the final report, in a style
similar to RSpec <http://rspec.info/>
(testing \"Arithmetic\"
(testing \"with positive integers\"
(is (= 4 (+ 2 2)))
(is (= 7 (+ 3 4))))
(testing \"with negative integers\"
(is (= -4 (+ -2 -2)))
(is (= -1 (+ 3 -4)))))
Note that, unlike RSpec, the \"testing\" macro may only be used
INSIDE a \"deftest\" or \"with-test\" form (see below).
DEFINING TESTS
There are two ways to define tests. The \"with-test\" macro takes
a defn or def form as its first argument, followed by any number
of assertions. The tests will be stored as metadata on the
definition.
(with-test
(defn my-function [x y]
(+ x y))
(is (= 4 (my-function 2 2)))
(is (= 7 (my-function 3 4))))
As of Clojure SVN rev. 1221, this does not work with defmacro.
See http://code.google.com/p/clojure/issues/detail?id=51
The other way lets you define tests separately from the rest of
your code, even in a different namespace:
(deftest addition
(is (= 4 (+ 2 2)))
(is (= 7 (+ 3 4))))
(deftest subtraction
(is (= 1 (- 4 3)))
(is (= 3 (- 7 4))))
This creates functions named \"addition\" and \"subtraction\", which
can be called like any other function. Therefore, tests can be
grouped and composed, in a style similar to the test framework in
Peter Seibel's \"Practical Common Lisp\"
<http://www.gigamonkeys.com/book/practical-building-a-unit-test-framework.html>
(deftest arithmetic
(addition)
(subtraction))
The names of the nested tests will be joined in a list, like
\"(arithmetic addition)\", in failure reports. You can use nested
tests to set up a context shared by several tests.
RUNNING TESTS
Run tests with the function \"(run-tests namespaces...)\":
(run-tests 'your.namespace 'some.other.namespace)
If you don't specify any namespaces, the current namespace is
used. To run all tests in all namespaces, use \"(run-all-tests)\".
By default, these functions will search for all tests defined in
a namespace and run them in an undefined order. However, if you
are composing tests, as in the \"arithmetic\" example above, you
probably do not want the \"addition\" and \"subtraction\" tests run
separately. In that case, you must define a special function
named \"test-ns-hook\" that runs your tests in the correct order:
(defn test-ns-hook [cljs-test-ctx]
(arithmetic))
Note: test-ns-hook prevents execution of fixtures (see below).
FIXTURES
Fixtures allow you to run code before and after tests, to set up
the context in which tests should be run.
A fixture is just a function that calls another function passed as
an argument. It looks like this:
(defn my-fixture [f]
Perform setup, establish bindings, whatever.
(f) Then call the function we were passed.
Tear-down / clean-up code here.
)
Fixtures are attached to namespaces in one of two ways. \"each\"
fixtures are run repeatedly, once for each test function created
with \"deftest\" or \"with-test\". \"each\" fixtures are useful for
establishing a consistent before/after state for each test, like
clearing out database tables.
\"each\" fixtures can be attached to the current namespace like this:
(use-fixtures :each fixture1 fixture2 ...)
The fixture1, fixture2 are just functions like the example above.
They can also be anonymous functions, like this:
(use-fixtures :each (fn [f] setup... (f) cleanup...))
The other kind of fixture, a \"once\" fixture, is only run once,
around ALL the tests in the namespace. \"once\" fixtures are useful
for tasks that only need to be performed once, like establishing
database connections, or for time-consuming tasks.
Attach \"once\" fixtures to the current namespace like this:
(use-fixtures :once fixture1 fixture2 ...)
Note: Fixtures and test-ns-hook are mutually incompatible. If you
are using test-ns-hook, fixture functions will *never* be run.
SAVING TEST OUTPUT TO A FILE
All the test reporting functions write to the var *test-out*. By
default, this is the same as *out*, but you can rebind it to any
PrintWriter. For example, it could be a file opened with
clojure.java.io/writer.
EXTENDING TEST-IS (ADVANCED)
You can extend the behavior of the \"is\" macro by defining new
methods for the \"assert-expr\" multimethod. These methods are
called during expansion of the \"is\" macro, so they should return
quoted forms to be evaluated.
You can plug in your own test-reporting framework by rebinding
the \"report\" function: (report event)
The 'event' argument is a map. It will always have a :type key,
whose value will be a keyword signaling the type of event being
reported. Standard events with :type value of :pass, :fail, and
:error are called when an assertion passes, fails, and throws an
exception, respectively. In that case, the event will also have
the following keys:
:expected The form that was expected to be true
:actual A form representing what actually occurred
:message The string message given as an argument to 'is'
The \"testing\" strings will be a list in \"*testing-contexts*\", and
the vars being tested will be a list in \"*testing-vars*\".
Your \"report\" function should wrap any printing calls in the
\"with-test-out\" macro, which rebinds *out* to the current value
of *test-out*.
For additional event types, see the examples in the code.
"}
cemerick.cljs.test
(:require cljs.compiler
[cljs.analyzer :refer (*cljs-ns* get-expander)]
[clojure.template :as temp]))
;; TODO seems like there's no reason to expose this for cljs; you're not
;; likely to be shipping .cljs files into production
(defonce ^:dynamic ^:private
^{:doc "True by default. If set to false, no test functions will
be created by deftest, set-test, or with-test. Use this to omit
tests when compiling or loading production code."
:added "1.1"}
*load-tests* true)
(defmacro with-test-out
"Runs body with `*print-fn*` bound to the value of the ::test-print-fn in
[test-ctx], or `cljs.core/*print-fn*` if it is nil."
{:added "1.1"}
[test-env & body]
`(binding [cljs.core/*print-fn* (or (::test-print-fn ~test-env)
cljs.core/*print-fn*)]
~@body))
(defmacro with-test-ctx
"Establishes [test-ctx] as the \"test context\" for the enclosed [body] of
code. This is done in two ways:
* For asynchronous tests, the anaphoric `-test-ctx` binding may be used to refer
to [test-ctx] (allowing e.g. `is` to be used within the body provided to
`with-test-ctx` without explicitly passing a test context).
* For other tests, `with-test-ctx` binds `*test-ctx*` to [test-ctx], so that
typical patterns of factoring test assertions into other functions is possible
without explicitly passing the context around.
The test context is used to track and update the state of the broader test run.
Its internals are a clojurescript.test implementation detail, and should not be
accessed or depended upon by tests.
This macro emits [body] without decoration when used in a Clojure environment."
[test-ctx & body]
(if-not (:ns &env)
`(do ~@body)
`(let [~'-test-ctx ~test-ctx
async?# (:async (meta (:test-name ~'-test-ctx)))]
(binding [*test-ctx* (when-not async?# ~'-test-ctx)]
(try
~@body
(catch js/Error e#
(if async?#
(done e#)
; this will get picked up by the catch in test-function
(throw e#))))))))
(defmacro ^:private test-context
[]
(if (contains? (:locals &env) '-test-ctx)
'-test-ctx
`(assert-test-context *test-ctx*)))
;;; UTILITIES FOR ASSERTIONS
(def ^:private ^:dynamic *cljs-env*
"The current ClojureScript compilation environment, necessary
to determine if a symbol refers to a macro (or not) when determining
whether to use assert-predicate or not."
nil)
(defn function?
"Returns true if argument is a function or a symbol that resolves to
a function (not a macro)."
{:added "1.1"}
[x]
(and (symbol? x)
(not (.startsWith (name x) "."))
(not (get-expander x *cljs-env*))))
(defmacro ^:private throw-on-test-context-assertion-form
"This is a hack to ensure that a reasonable error is thrown (instead of
silent, possibly incorrect test success) when `is` is incorrectly used with an
explicit test context, e.g. (is -test-ctx (some-assertion))."
[x]
`(when (instance? TestContext ~x)
(throw (js/Error. "TestContext provided as [form] in `is` assertion. If using `is` with an explicit test context, use the 3-arg arity."))))
(defn assert-predicate
"Returns generic assertion code for any functional predicate. The
'expected' argument to 'report' will contains the original form, the
'actual' argument will contain the form with all its sub-forms
evaluated. If the predicate returns false, the 'actual' form will
be wrapped in (not...)."
{:added "1.1"}
[msg form]
(let [args (rest form)
pred (first form)]
`(let [values# (list ~@args)
result# (apply ~pred values#)]
(throw-on-test-context-assertion-form result#)
(if result#
(do-report (test-context)
{:type :pass, :message ~msg,
:expected '~form, :actual (cons ~pred values#)})
(do-report (test-context)
{:type :fail, :message ~msg,
:expected '~form, :actual (list '~'not (cons '~pred values#))}))
result#)))
(defn assert-any
"Returns generic assertion code for any test, including macros, Java
method calls, or isolated symbols."
{:added "1.1"}
[msg form]
`(let [value# ~form]
(throw-on-test-context-assertion-form value#)
(do-report (test-context)
{:type (if value# :pass :fail), :message ~msg,
:expected '~form, :actual value#})
value#))
;;; ASSERTION METHODS
;; You don't call these, but you can add methods to extend the 'is'
;; macro. These define different kinds of tests, based on the first
;; symbol in the test expression.
(defmulti assert-expr
(fn [msg form]
(cond
(nil? form) :always-fail
(seq? form) (first form)
:else :default)))
(defmethod assert-expr :always-fail [msg form]
;; nil test: always fail
`(do-report (test-context) {:type :fail, :message ~msg}))
(defmethod assert-expr :default [msg form]
(if (and (seq? form) (function? (first form)))
(assert-predicate msg form)
(assert-any msg form)))
(defmethod assert-expr 'instance? [msg form]
;; Test if x is an instance of y.
`(let [object# ~(nth form 2)]
(let [result# (instance? ~(nth form 1) object#)]
(if result#
(do-report (test-context)
{:type :pass, :message ~msg,
:expected '~form, :actual (type object#)})
(do-report (test-context)
{:type :fail, :message ~msg,
:expected '~form, :actual (type object#)}))
result#)))
(defmethod assert-expr 'thrown? [msg form]
;; (is (thrown? c expr))
;; Asserts that evaluating expr throws an exception of class c.
;; Returns the exception thrown.
(let [klass (second form)
body (nthnext form 2)]
`(try ~@body
(do-report (test-context)
{:type :fail, :message ~msg,
:expected '~form, :actual nil})
(~'catch ~klass e#
(do-report (test-context)
{:type :pass, :message ~msg,
:expected '~form, :actual e#})
e#))))
(defmethod assert-expr 'thrown-with-msg? [msg form]
;; (is (thrown-with-msg? c re expr))
;; Asserts that evaluating expr throws an exception of class c.
;; Also asserts that the message string of the exception matches
;; (with re-find) the regular expression re.
(let [klass (nth form 1)
re (nth form 2)
body (nthnext form 3)]
`(try ~@body
(do-report (test-context)
{:type :fail, :message ~msg,
:expected '~form, :actual nil})
(~'catch ~klass e#
(let [m# (.-message e#)]
(if (re-find ~re m#)
(do-report (test-context)
{:type :pass, :message ~msg,
:expected '~form, :actual e#})
(do-report (test-context)
{:type :fail, :message ~msg,
:expected '~form, :actual e#})))
e#))))
(defmacro try-expr
"Used by the 'is' macro to catch unexpected exceptions.
You don't call this."
{:added "1.1"}
[test-ctx msg form]
`(with-test-ctx ~test-ctx
(try ~(binding [*cljs-env* &env]
(assert-expr msg form))
(~'catch js/Error t#
(do-report (test-context)
{:type :error, :message ~msg,
:expected '~form, :actual t#})))))
;;; ASSERTION MACROS
;; You use these in your tests.
(defmacro is
"Generic assertion macro. 'form' is any predicate test.
'msg' is an optional message to attach to the assertion.
Example: (is (= 4 (+ 2 2)) \"Two plus two should be 4\")
Special forms:
(is (thrown? c body)) checks that an instance of c is thrown from
body, fails if not; then returns the thing thrown.
(is (thrown-with-msg? c re body)) checks that an instance of c is
thrown AND that the message on the exception matches (with
re-find) the regular expression re."
{:added "1.1"}
([form] `(try-expr (test-context) nil ~form))
([form msg] `(try-expr (test-context) ~msg ~form))
([test-ctx form msg] `(try-expr ~test-ctx ~msg ~form)))
(defmacro are
"Checks multiple assertions with a template expression.
See clojure.template/do-template for an explanation of
templates.
Example: (are [x y] (= x y)
2 (+ 1 1)
4 (* 2 2))
Expands to:
(do (is (= 2 (+ 1 1)))
(is (= 4 (* 2 2))))
Note: This breaks some reporting features, such as line numbers."
{:added "1.1"}
[argv expr & args]
(if (or
;; (are [] true) is meaningless but ok
(and (empty? argv) (empty? args))
;; Catch wrong number of args
(and (pos? (count argv))
(pos? (count args))
(zero? (mod (count args) (count argv)))))
`(temp/do-template ~argv (is ~expr) ~@args)
(throw (IllegalArgumentException. "The number of args doesn't match are's argv."))))
(defmacro testing
"Adds a new string to the list of testing contexts. May be nested,
but must occur inside a _synchronous_ test function (deftest)."
{:added "1.1"}
[string & body]
`(try
(swap! (:test-env (test-context)) update-in [::test-contexts] conj ~string)
~@body
(finally
(swap! (:test-env (test-context)) update-in [::test-contexts] pop))))
;;; DEFINING TESTS
(defn- munged-symbol
[& strs]
(symbol (cljs.compiler/munge (apply str strs))))
(defmacro set-test
[name & body]
(when *load-tests*
(let [mtest-name (munged-symbol *cljs-ns* "." name)
test-name (apply symbol (map str [*cljs-ns* name]))]
`(do
(def ~(vary-meta name assoc :declared true)
; not sure why vary-meta wasn't working here, perhaps a CLJS compiler hiccup
(with-meta ~name (merge ~(meta name)
; passing along fn metadata so that
; with-test-ctx can determine whether a test
; is async or not
{:name (with-meta '~test-name ~(meta name))
:test (fn ~(symbol (str name "-test"))
[test-ctx#]
(with-test-ctx test-ctx#
~@body))})))
(register-test! '~*cljs-ns* '~test-name ~mtest-name)
~name))))
; TODO this is absolutely pointless in CLJS.
(defmacro with-test
"Takes any definition form (that returns a Var) as the first argument.
Remaining body goes in the :test metadata function for that Var.
Note that the body of the test is wrapped in `with-test-ctx`, and so
`-test-ctx` is implicitly bound to the current test context.
When *load-tests* is false, only evaluates the definition, ignoring
the tests."
{:added "1.1"}
[definition & body]
`(do ~definition (set-test ~(second definition) ~@body)))
(defmacro deftest
"Defines a test function with no arguments. Test functions may call
other tests, so tests may be composed. If you compose tests, you
should also define a function named test-ns-hook; run-tests will
call test-ns-hook instead of testing all vars.
Note: Actually, the test body goes in the :test metadata on the var,
and the real function (the value of the var) calls test-var on
itself.
Note that the body of the test is wrapped in `with-test-ctx`, and so
`-test-ctx` is implicitly bound to the current test context.
When *load-tests* is false, deftest is ignored."
{:added "1.1"}
[name & body]
(when *load-tests*
`(do
; TODO this should return a map containing just the "summary" report, and an atom to watch for async results
(defn ~name [] (cemerick.cljs.test/test-var ~(munged-symbol *cljs-ns* "." name)))
(set-test ~name ~@body))))
(defmacro test-var
"Provides compatibility with the typical usage of clojure.test/test-var, e.g.
`(test-var #'test-name)`. This doesn't work in ClojureScript due to the lack of
the `var` special form. This macro emits a cljs-clean reference to the named
test fn, even if it's wrapped in a `(var ...)` form, so this:
(test-var #'test-name)
emits
(cemerick.cljs.test/test-function test-name)"
([var-sym] `(test-var (init-test-environment) ~var-sym))
([test-env var-sym]
`(cemerick.cljs.test/test-function
~test-env
~(if (and (sequential? var-sym) (= 'var (first var-sym)))
(second var-sym)
var-sym))))
(defmacro deftest-
"Like deftest but creates a private var."
{:added "1.1"}
[name & body]
`(deftest ~(vary-meta name assoc :private true) ~@body))
(defmacro deftesthook
[name & body]
`(do
(defn ~name ~@body)
(register-test-ns-hook! '~*cljs-ns* ~(munged-symbol *cljs-ns* "." name))
~name))
;;; DEFINING FIXTURES
(defmacro use-fixtures
"Wrap test runs in a fixture function to perform setup and
teardown. Using a fixture-type of :each wraps every test
individually, while :once wraps the whole run in a single function."
[fixture-type & args]
`(register-fixtures! '~*cljs-ns* ~fixture-type ~@args))
;;; RUNNING TESTS; (many more options available in test.cljs)
(defmacro ^:private test-runner-entry-point
[test-ctx & body]
`(let [entry-point?# *entry-point*]
(binding [*entry-point* false]
~@body
(finish-test-entry-point entry-point?# ~test-ctx))))
(defmacro run-tests
"Runs all tests in the given namespaces; prints results.
Defaults to current namespace if none given. Returns a map
summarizing test results."
{:added "1.1"}
([] `(run-tests* '~*cljs-ns*))
([& namespaces] `(let [namespaces# ~(vec namespaces)]
(apply run-tests*
(if (instance? cljs.core.Atom (first namespaces#))
(conj namespaces# '~*cljs-ns*)
namespaces#)))))
;;; SUPPORTING ASYNC
(defmacro done
"Must be called *once* by asynchronous tests when they are complete. This
will trigger final reporting of the progress of the test, and the start of the
next asynchronous test. A warning will be emitted if a test calls `done` more
than once. Tests must implement their own coordination among asynchronous
\"threads\" in order to ensure this.
A single Error argument may be provided upon an error; doing so will report the
error, and trigger final reporting and further test execution as per a non-error
`(done)` call.
When used in a Clojure environment, this macro is a no-op."
([] (when (:ns &env) `(done* (test-context))))
([error] (when (:ns &env) `(done* (test-context) ~error))))
(defmacro block-or-done
"A Clojure/ClojureScript portability aid that uses a core.async channel to
coordinate \"completion\" of a test.
[channel] should be a core.async channel that will yield a single truthy value
when the test in question is complete. This will trigger a `(done)` call in
ClojureScript, passing the value obtained from the channel if it is an error.
In Clojure, the code emitted by this macro will simply block on receiving that
value, allowing a fundamentally asynchronous test to complete before moving on
to the next clojure.test test."
[channel]
(if (:ns &env)
`(cljs.core.async.macros/go
(let [v (cljs.core.async/<! ~channel)]
(if (instance? js/Error v)
(done v)
(done))))
`(clojure.core.async/<!! ~channel)))