Skip to content

Commit 662410d

Browse files
tests for case (#296)
Signed-off-by: Stuart Halloway <[email protected]>
1 parent 26c18ac commit 662410d

File tree

1 file changed

+64
-1
lines changed

1 file changed

+64
-1
lines changed

test/clojure/test_clojure/control.clj

Lines changed: 64 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
; the terms of this license.
77
; You must not remove this notice, or any other, from this software.
88

9-
; Author: Frantisek Sodomka, Mike Hinchey
9+
; Author: Frantisek Sodomka, Mike Hinchey, Stuart Halloway
1010

1111
;;
1212
;; Test "flow control" constructs.
@@ -268,3 +268,66 @@
268268

269269
; locking, monitor-enter, monitor-exit
270270

271+
; case
272+
(deftest test-case
273+
(testing "can match many kinds of things"
274+
(let [two 2
275+
test-fn
276+
#(case %
277+
1 :number
278+
"foo" :string
279+
\a :char
280+
pow :symbol
281+
:zap :keyword
282+
(2 \b "bar") :one-of-many
283+
[1 2] :sequential-thing
284+
{:a 2} :map
285+
{:r 2 :d 2} :droid
286+
#{2 3 4 5} :set
287+
[1 [[[2]]]] :deeply-nested
288+
:default)]
289+
(are [result input] (= result (test-fn input))
290+
:number 1
291+
:string "foo"
292+
:char \a
293+
:keyword :zap
294+
:symbol 'pow
295+
:one-of-many 2
296+
:one-of-many \b
297+
:one-of-many "bar"
298+
:sequential-thing [1 2]
299+
:sequential-thing (list 1 2)
300+
:sequential-thing [1 two]
301+
:map {:a 2}
302+
:map {:a two}
303+
:set #{2 3 4 5}
304+
:set #{two 3 4 5}
305+
:default #{2 3 4 5 6}
306+
:droid {:r 2 :d 2}
307+
:deeply-nested [1 [[[two]]]]
308+
:default :anything-not-appearing-above)))
309+
(testing "throws IllegalArgumentException if no match"
310+
(is (thrown-with-msg?
311+
IllegalArgumentException #"No matching clause: 2"
312+
(case 2 1 :ok))))
313+
(testing "sorting doesn't matter"
314+
(let [test-fn
315+
#(case %
316+
{:b 2 :a 1} :map
317+
#{3 2 1} :set
318+
:default)]
319+
(are [result input] (= result (test-fn input))
320+
:map {:a 1 :b 2}
321+
:map (sorted-map :a 1 :b 2)
322+
:set #{3 2 1}
323+
:set (sorted-set 2 1 3))))
324+
(testing "test constants are *not* evaluated"
325+
(let [test-fn
326+
;; never write code like this...
327+
#(case %
328+
(throw (RuntimeException. "boom")) :piece-of-throw-expr
329+
:no-match)]
330+
(are [result input] (= result (test-fn input))
331+
:piece-of-throw-expr 'throw
332+
:piece-of-throw-expr '[RuntimeException. "boom"]
333+
:no-match nil))))

0 commit comments

Comments
 (0)