Back
are (clj)
(source)macro
(are argv expr & args)
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.
Examples
clojure
(ns clojure.test-clojure.parse
(:require
[clojure.test :refer :all]
[clojure.test.check :as chk]
[clojure.test.check.generators :as gen]
[clojure.test.check.properties :as prop])
(:import
[java.util UUID]))
(deftest test-parse-long
(are [s expected]
(= expected (parse-long s))
"100" 100
"+100" 100
"0" 0
"+0" 0
"-0" 0
"-42" -42
"9223372036854775807" Long/MAX_VALUE
"+9223372036854775807" Long/MAX_VALUE
"-9223372036854775808" Long/MIN_VALUE
"077" 77) ;; leading 0s are ignored! (not octal)
(are [s] ;; do not parse
(nil? (parse-long s))
"0.3" ;; no float
"9223372036854775808" ;; past max long
"-9223372036854775809" ;; past min long
"0xA0" ;; no hex
"2r010")) ;; no radix support
;; generative test - gen long -> str -> parse, compare
(deftest test-gen-parse-long
(let [res (chk/quick-check
100000
(prop/for-all* [gen/large-integer]
#(= % (-> % str parse-long))))]
(if (:result res)
(is true) ;; pass
(is (:result res) (pr-str res)))))
(deftest test-parse-double
(are [s expected]
(= expected (parse-double s))
"1.234" 1.234
"+1.234" 1.234
"-1.234" -1.234
"+0" +0.0
"-0.0" -0.0
"0.0" 0.0
"5" 5.0
"Infinity" Double/POSITIVE_INFINITY
"-Infinity" Double/NEGATIVE_INFINITY
"1.7976931348623157E308" Double/MAX_VALUE
"4.9E-324" Double/MIN_VALUE
"1.7976931348623157E309" Double/POSITIVE_INFINITY ;; past max double
"2.5e-324" Double/MIN_VALUE ;; past min double, above half minimum
"2.4e-324" 0.0) ;; below minimum double
(is (Double/isNaN (parse-double "NaN")))
(are [s] ;; nil on invalid string
(nil? (parse-double s))
"double" ;; invalid string
"1.7976931348623157G309")) ;; invalid, but similar to valid
;; generative test - gen double -> str -> parse, compare
(deftest test-gen-parse-double
(let [res (chk/quick-check
100000
(prop/for-all* [gen/double]
#(let [parsed (-> % str parse-double)]
(if (Double/isNaN %)
(Double/isNaN parsed)
(= % parsed)))))]
(if (:result res)
(is true) ;; pass
(is (:result res) (pr-str res)))))
(deftest test-parse-uuid
(is (parse-uuid (.toString (UUID/randomUUID))))
(is (nil? (parse-uuid "BOGUS"))) ;; nil on invalid uuid string
(are [s] ;; throw on invalid type (not string)
(try (parse-uuid s) (is false) (catch Throwable _ (is true)))
123
nil))
(are [s] ;; nil on invalid string
(nil? (parse-boolean s))
"abc"
"TRUE"
"FALSE"
" true ")
(are [s] ;; throw on invalid type (not string)
(try (parse-boolean s) (is false) (catch Throwable _ (is true)))
nil
false
true
100))
clojure
(ns clojure.test-clojure.rt
(:require [clojure.string :as string]
clojure.set)
(:use clojure.test clojure.test-helper))
(defn bare-rt-print
"Return string RT would print prior to print-initialize"
[x]
(with-out-str
(try
(push-thread-bindings {#'clojure.core/print-initialized false})
(clojure.lang.RT/print x *out*)
(finally
(pop-thread-bindings)))))
(deftest rt-print-prior-to-print-initialize
(testing "pattern literals"
(is (= "#\"foo\"" (bare-rt-print #"foo")))))
clojure
(ns clojure.test-clojure.transducers
(:require [clojure.string :as s]
[clojure.test :refer :all]
[clojure.test.check :as chk]
[clojure.test.check.generators :as gen]
[clojure.test.check.properties :as prop]
[clojure.test.check.clojure-test :as ctest]))
;; These $ versions are "safe" when used with possibly mixed numbers, sequences, etc
(deftest test-dedupe
(are [x y] (= (transduce (dedupe) conj x) y)
[] []
[1] [1]
[1 2 3] [1 2 3]
[1 2 3 1 2 2 1 1] [1 2 3 1 2 1]
[1 1 1 2] [1 2]
[1 1 1 1] [1]
(deftest test-cat
(are [x y] (= (transduce cat conj x) y)
[] []
[[1 2]] [1 2]
[[1 2] [3 4]] [1 2 3 4]
[[] [3 4]] [3 4]
[[1 2] []] [1 2]
[[] []] []
[[1 2] [3 4] [5 6]] [1 2 3 4 5 6]))
(deftest test-partition-all
(are [n coll y] (= (transduce (partition-all n) conj coll) y)
2 [1 2 3] '((1 2) (3))
2 [1 2 3 4] '((1 2) (3 4))
2 [] ()
1 [] ()
1 [1 2 3] '((1) (2) (3))
5 [1 2 3] '((1 2 3))))
(deftest test-take
(are [n y] (= (transduce (take n) conj [1 2 3 4 5]) y)
1 '(1)
3 '(1 2 3)
5 '(1 2 3 4 5)
9 '(1 2 3 4 5)
0 ()
-1 ()
-2 ()))
(deftest test-drop
(are [n y] (= (transduce (drop n) conj [1 2 3 4 5]) y)
1 '(2 3 4 5)
3 '(4 5)
5 ()
9 ()
0 '(1 2 3 4 5)
-1 '(1 2 3 4 5)
-2 '(1 2 3 4 5)))
(deftest test-take-nth
(are [n y] (= (transduce (take-nth n) conj [1 2 3 4 5]) y)
1 '(1 2 3 4 5)
2 '(1 3 5)
3 '(1 4)
4 '(1 5)
5 '(1)
9 '(1)))
(deftest test-take-while
(are [coll y] (= (transduce (take-while pos?) conj coll) y)
[] ()
[1 2 3 4] '(1 2 3 4)
[1 2 3 -1] '(1 2 3)
[1 -1 2 3] '(1)
[-1 1 2 3] ()
[-1 -2 -3] ()))
(deftest test-drop-while
(are [coll y] (= (transduce (drop-while pos?) conj coll) y)
[] ()
[1 2 3 4] ()
[1 2 3 -1] '(-1)
[1 -1 2 3] '(-1 2 3)
[-1 1 2 3] '(-1 1 2 3)
[-1 -2 -3] '(-1 -2 -3)))
(deftest test-distinct
(are [out in] (= out (sequence (distinct in)) (sequence (distinct) in))
[] []
(range 10) (range 10)
[0] (repeat 10 0)
[0 1 2] [0 0 1 1 2 2 1 1 0 0]
[1] [1 1N]))
(deftest test-interpose
(are [out in] (= out (sequence (interpose :s) in))
[] (range 0)
[0] (range 1)
[0 :s 1] (range 2)
[0 :s 1 :s 2] (range 3))
(testing "Can end reduction on separator or input"
(let [expected (interpose :s (range))]
(dotimes [i 10]
(is (= (take i expected)
(sequence (comp (interpose :s) (take i))
(range))))))))
clojure
(ns clojure.test-clojure.compilation
(:import (clojure.lang Compiler Compiler$CompilerException))
(:require [clojure.test.generative :refer (defspec)]
[clojure.data.generators :as gen]
[clojure.test-clojure.compilation.line-number-examples :as line])
(:use clojure.test
[clojure.test-helper :only (should-not-reflect should-print-err-message)]))
(deftest test-compiler-metadata
(let [m (meta #'when)]
(are [x y] (= x y)
(list? (:arglists m)) true
(> (count (:arglists m)) 0) true
(deftest clj-1568
(let [compiler-fails-at?
(fn [row col source]
(let [path (name (gensym "clj-1568.example-"))]
(try
(Compiler/load (java.io.StringReader. source) path "clj-1568.example")
nil
(catch Compiler$CompilerException e
(let [data (ex-data e)]
(= [path row col]
[(:clojure.error/source data) (:clojure.error/line data) (:clojure.error/column data)]))))))]
(testing "with error in the initial form"
(are [row col source] (compiler-fails-at? row col source)
;; note that the spacing of the following string is important
1 4 " (.foo nil)"
2 18 "
(/ 1 0)"))
(testing "with error in an non-initial form"
(are [row col source] (compiler-fails-at? row col source)
;; note that the spacing of the following string is important
3 18 "(:foo {})
clojure
(ns ^{:doc "Tests for clojure.core/gen-class"
:author "Stuart Halloway, Daniel Solano Gómez"}
clojure.test-clojure.genclass
(:use clojure.test clojure.test-helper)
(:require clojure.test_clojure.genclass.examples)
(:import [clojure.test_clojure.genclass.examples
ExampleClass
ExampleAnnotationClass
ProtectedFinalTester
ArrayDefInterface
ArrayGenInterface]
;todo - fix this, it depends on the order of things out of a hash-map
#_(deftest test-annotations
(let [annot-class ExampleAnnotationClass
foo-method (.getDeclaredMethod annot-class "foo" (into-array [String]))]
(testing "Class annotations:"
(is (= 2 (count (.getDeclaredAnnotations annot-class))))
(testing "@Deprecated"
(let [deprecated (.getAnnotation annot-class Deprecated)]
(is deprecated)))
(testing "@Target([])"
(let [resource (.getAnnotation annot-class Target)]
(is (= 0 (count (.value resource)))))))
(testing "Method annotations:"
(testing "@Deprecated void foo(String):"
(is (= 1 (count (.getDeclaredAnnotations foo-method))))
(is (.getAnnotation foo-method Deprecated))))
(testing "Parameter annotations:"
(let [param-annots (.getParameterAnnotations foo-method)]
(is (= 1 (alength param-annots)))
(let [first-param-annots (aget param-annots 0)]
(is (= 2 (alength first-param-annots)))
(testing "void foo(@Retention(…) String)"
(let [retention (aget first-param-annots 0)]
(is (instance? Retention retention))
(= RetentionPolicy/SOURCE (.value retention))))
(testing "void foo(@Target(…) String)"
(let [target (aget first-param-annots 1)]
(is (instance? Target target))
(is (= [ElementType/TYPE ElementType/PARAMETER] (seq (.value target)))))))))))
(deftest interface-array-type-hints
(let [array-types {:ints (class (int-array 0))
:bytes (class (byte-array 0))
:shorts (class (short-array 0))
:chars (class (char-array 0))
:longs (class (long-array 0))
:floats (class (float-array 0))
:doubles (class (double-array 0))
:booleans (class (boolean-array 0))
:maps (class (into-array java.util.Map []))}
array-types (assoc array-types
:maps-2d (class (into-array (:maps array-types) [])))
method-with-name (fn [name methods] (first (filter #(= name (.getName %)) methods)))
parameter-type (fn [method] (first (.getParameterTypes method)))
return-type (fn [method] (.getReturnType method))]
(testing "definterface"
(let [method-with-name #(method-with-name % (.getMethods ArrayDefInterface))]
(testing "sugar primitive array hints"
(are [name type] (= (type array-types)
(parameter-type (method-with-name name)))
"takesByteArray" :bytes
"takesCharArray" :chars
"takesShortArray" :shorts
"takesIntArray" :ints
"takesLongArray" :longs
"takesFloatArray" :floats
"takesDoubleArray" :doubles
"takesBooleanArray" :booleans))
(testing "raw primitive array hints"
(are [name type] (= (type array-types)
(return-type (method-with-name name)))
"returnsByteArray" :bytes
"returnsCharArray" :chars
"returnsShortArray" :shorts
"returnsIntArray" :ints
"returnsLongArray" :longs
"returnsFloatArray" :floats
"returnsDoubleArray" :doubles
"returnsBooleanArray" :booleans))))
(testing "gen-interface"
(let [method-with-name #(method-with-name % (.getMethods ArrayGenInterface))]
(testing "sugar primitive array hints"
(are [name type] (= (type array-types)
(parameter-type (method-with-name name)))
"takesByteArray" :bytes
"takesCharArray" :chars
"takesShortArray" :shorts
"takesIntArray" :ints
"takesLongArray" :longs
"takesFloatArray" :floats
"takesDoubleArray" :doubles
"takesBooleanArray" :booleans))
(testing "raw primitive array hints"
(are [name type] (= (type array-types)
(return-type (method-with-name name)))
"returnsByteArray" :bytes
"returnsCharArray" :chars
"returnsShortArray" :shorts
"returnsIntArray" :ints
"returnsLongArray" :longs
"returnsFloatArray" :floats
"returnsDoubleArray" :doubles
"returnsBooleanArray" :booleans))))))
clojure
(ns clojure.test-clojure.string
(:require [clojure.string :as s])
(:use clojure.test))
(deftest t-join
(are [x coll] (= x (s/join coll))
"" nil
"" []
"1" [1]
"12" [1 2])
(are [x sep coll] (= x (s/join sep coll))
"1,2,3" \, [1 2 3]
"" \, []
"1" \, [1]
"1 and-a 2 and-a 3" " and-a " [1 2 3]))
(deftest nil-handling
(are [f args] (thrown? NullPointerException (apply f args))
s/reverse [nil]
s/replace [nil #"foo" "bar"]
s/replace-first [nil #"foo" "bar"]
s/re-quote-replacement [nil]
s/capitalize [nil]
s/upper-case [nil]
s/lower-case [nil]
s/split [nil #"-"]
s/split [nil #"-" 1]
s/trim [nil]
s/triml [nil]
s/trimr [nil]
s/trim-newline [nil]))
(deftest char-sequence-handling
(are [result f args] (let [[^CharSequence s & more] args]
(= result (apply f (StringBuffer. s) more)))
"paz" s/reverse ["zap"]
"foo:bar" s/replace ["foo-bar" \- \:]
"ABC" s/replace ["abc" #"\w" s/upper-case]
"faa" s/replace ["foo" #"o" (StringBuffer. "a")]
"baz::quux" s/replace-first ["baz--quux" #"--" "::"]
"baz::quux" s/replace-first ["baz--quux" (StringBuffer. "--") (StringBuffer. "::")]
"zim-zam" s/replace-first ["zim zam" #" " (StringBuffer. "-")]
"\\\\ \\$" s/re-quote-replacement ["\\ $"]
"Pow" s/capitalize ["POW"]
"BOOM" s/upper-case ["boom"]
"whimper" s/lower-case ["whimPER"]
["foo" "bar"] s/split ["foo-bar" #"-"]
"calvino" s/trim [" calvino "]
"calvino " s/triml [" calvino "]
" calvino" s/trimr [" calvino "]
"the end" s/trim-newline ["the end\r\n\r\r\n"]
true s/blank? [" "]
["a" "b"] s/split-lines ["a\nb"]
"fa la la" s/escape ["fo lo lo" {\o \a}]))
clojure
(ns clojure.test-clojure.reader
(:use clojure.test)
(:use [clojure.instant :only [read-instant-date
read-instant-calendar
read-instant-timestamp]])
(:require clojure.walk
[clojure.edn :as edn]
[clojure.test.generative :refer (defspec)]
[clojure.test-clojure.generators :as cgen]
[clojure.edn :as edn])
(:import [clojure.lang BigInt Ratio]
java.io.File
java.util.TimeZone))
(deftest Literals
; 'nil 'false 'true are reserved by Clojure and are not symbols
(is (= 'nil nil))
(is (= 'false false))
(is (= 'true true)) )
(deftest Strings
(is (= "abcde" (str \a \b \c \d \e)))
(is (= "abc
def" (str \a \b \c \newline \space \space \d \e \f)))
(let [f (temp-file "clojure.core-reader" "test")]
(doseq [source [:string :file]]
(testing (str "Valid string literals read from " (name source))
(are [x form] (= x (code-units
(read-from source f (str "\"" form "\""))))
[] ""
[34] "\\\""
[10] "\\n"
[0] "\\u0000"
[0xd7ff] "\\ud7ff"
[0xd800] "\\ud800"
[0xdfff] "\\udfff"
[0xe000] "\\ue000"
[0xffff] "\\uffff"
[4 49] "\\u00041"))
(testing (str "Errors reading string literals from " (name source))
(are [err msg form] (thrown-with-cause-msg? err msg
(read-from source f (str "\"" form "\"")))
Exception #"EOF while reading string" "\\"
Exception #"Unsupported escape character: \\o" "\\o"
(deftest t-Characters
(let [f (temp-file "clojure.core-reader" "test")]
(doseq [source [:string :file]]
(testing (str "Valid char literals read from " (name source))
(are [x form] (= x (read-from source f form))
(first "o") "\\o"
(char 0) "\\o0"
(char 0) "\\o000"
(char 047) "\\o47"
(char 0377) "\\o377"
(first "u") "\\u"
(first "A") "\\u0041"
(char 0) "\\u0000"
(char 0xd7ff) "\\ud7ff"
(char 0xe000) "\\ue000"
(char 0xffff) "\\uffff"))
(testing (str "Errors reading char literals from " (name source))
(are [err msg form] (thrown-with-cause-msg? err msg (read-from source f form))
Exception #"EOF while reading character" "\\"
Exception #"Unsupported character: \\00" "\\00"
Exception #"Unsupported character: \\0009" "\\0009"
(deftest reading-keywords
(are [x y] (= x (binding [*ns* (the-ns 'user)] (read-string y)))
:foo ":foo"
:foo/bar ":foo/bar"
:user/foo "::foo")
(are [err msg form] (thrown-with-msg? err msg (read-string form))
Exception #"Invalid token: foo:" "foo:"
Exception #"Invalid token: :bar/" ":bar/"
Exception #"Invalid token: ::does.not/exist" "::does.not/exist"))
;; Lists
(deftest t-Syntax-quote
(are [x y] (= x y)
`() () ; was NPE before SVN r1337
))
(deftest Instants
(testing "Instants are read as java.util.Date by default"
(is (= java.util.Date (class #inst "2010-11-12T13:14:15.666"))))
(let [s "#inst \"2010-11-12T13:14:15.666-06:00\""]
(binding [*data-readers* {'inst read-instant-date}]
(testing "read-instant-date produces java.util.Date"
(is (= java.util.Date (class (read-string s)))))
(testing "java.util.Date instants round-trips"
(is (= (-> s read-string)
(-> s read-string pr-str read-string))))
(testing "java.util.Date instants round-trip throughout the year"
(doseq [month (range 1 13) day (range 1 29) hour (range 1 23)]
(let [s (format "#inst \"2010-%02d-%02dT%02d:14:15.666-06:00\"" month day hour)]
(is (= (-> s read-string)
(-> s read-string pr-str read-string))))))
(testing "java.util.Date handling DST in time zones"
(let [dtz (TimeZone/getDefault)]
(try
;; A timezone with DST in effect during 2010-11-12
(TimeZone/setDefault (TimeZone/getTimeZone "Australia/Sydney"))
(is (= (-> s read-string)
(-> s read-string pr-str read-string)))
(finally (TimeZone/setDefault dtz)))))
(testing "java.util.Date should always print in UTC"
(let [d (read-string s)
pstr (print-str d)
len (.length pstr)]
(is (= (subs pstr (- len 7)) "-00:00\"")))))
(binding [*data-readers* {'inst read-instant-calendar}]
(testing "read-instant-calendar produces java.util.Calendar"
(is (instance? java.util.Calendar (read-string s))))
(testing "java.util.Calendar round-trips"
(is (= (-> s read-string)
(-> s read-string pr-str read-string))))
(testing "java.util.Calendar remembers timezone in literal"
(is (= "#inst \"2010-11-12T13:14:15.666-06:00\""
(-> s read-string pr-str)))
(is (= (-> s read-string)
(-> s read-string pr-str read-string))))
(testing "java.util.Calendar preserves milliseconds"
(is (= 666 (-> s read-string
(.get java.util.Calendar/MILLISECOND)))))))
(let [s "#inst \"2010-11-12T13:14:15.123456789\""
s2 "#inst \"2010-11-12T13:14:15.123\""
s3 "#inst \"2010-11-12T13:14:15.123456789123\""]
(binding [*data-readers* {'inst read-instant-timestamp}]
(testing "read-instant-timestamp produces java.sql.Timestamp"
(is (= java.sql.Timestamp (class (read-string s)))))
(testing "java.sql.Timestamp preserves nanoseconds"
(is (= 123456789 (-> s read-string .getNanos)))
(is (= 123456789 (-> s read-string pr-str read-string .getNanos)))
;; truncate at nanos for s3
(is (= 123456789 (-> s3 read-string pr-str read-string .getNanos))))
(testing "java.sql.Timestamp should compare nanos"
(is (= (read-string s) (read-string s3)))
(is (not= (read-string s) (read-string s2)))))
(binding [*data-readers* {'inst read-instant-date}]
(testing "read-instant-date should truncate at milliseconds"
(is (= (read-string s) (read-string s2) (read-string s3))))))
(let [s "#inst \"2010-11-12T03:14:15.123+05:00\""
s2 "#inst \"2010-11-11T22:14:15.123Z\""]
(binding [*data-readers* {'inst read-instant-date}]
(testing "read-instant-date should convert to UTC"
(is (= (read-string s) (read-string s2)))))
(binding [*data-readers* {'inst read-instant-timestamp}]
(testing "read-instant-timestamp should convert to UTC"
(is (= (read-string s) (read-string s2)))))
(binding [*data-readers* {'inst read-instant-calendar}]
(testing "read-instant-calendar should preserve timezone"
(is (not= (read-string s) (read-string s2)))))))
(binding [*default-data-reader-fn* throw-on-unknown]
(testing "Unknown tag with custom throw-on-unknown"
(are [err msg form] (thrown-with-msg? err msg (read-string form))
Exception #"No data reader function for tag foo" "#foo [1 2]"
Exception #"No data reader function for tag bar/foo" "#bar/foo [1 2]"
Exception #"No data reader function for tag bar.baz/foo" "#bar.baz/foo [1 2]")))
(testing "Unknown tag out-of-the-box behavior (like Clojure 1.4)"
(are [err msg form] (thrown-with-msg? err msg (read-string form))
Exception #"No reader function for tag foo" "#foo [1 2]"
Exception #"No reader function for tag bar/foo" "#bar/foo [1 2]"
Exception #"No reader function for tag bar.baz/foo" "#bar.baz/foo [1 2]"))))
(deftest namespaced-map-errors
(are [err msg form] (thrown-with-msg? err msg (read-string form))
Exception #"Invalid token" "#:::"
Exception #"Namespaced map literal must contain an even number of forms" "#:s{1}"
Exception #"Namespaced map must specify a valid namespace" "#:s/t{1 2}"
Exception #"Unknown auto-resolved namespace alias" "#::BOGUS{1 2}"
Exception #"Namespaced map must specify a namespace" "#: s{:a 1}"
Exception #"Duplicate key: :user/a" "#::{:a 1 :a 2}"
Exception #"Duplicate key: user/a" "#::{a 1 a 2}"))
(are [l c s] (= {:line l :column c} (-> s str->lnpr read meta (select-keys [:line :column])))
42 99 "^{:line 42 :column 99} (1 2)"
1 99 "^{:column 99} (1 2)")
clojure
(ns clojure.test-clojure.sequences
(:require [clojure.test :refer :all]
[clojure.test.check.generators :as gen]
[clojure.test.check.properties :as prop]
[clojure.test.check.clojure-test :refer (defspec)])
(:import clojure.lang.IReduce))
(deftest test-equality
; lazy sequences
(are [x y] (= x y)
; fixed SVN 1288 - LazySeq and EmptyList equals/equiv
; http://groups.google.com/group/clojure/browse_frm/thread/286d807be9cae2a5#
(map inc nil) ()
(map inc ()) ()
(map inc []) ()
(map inc #{}) ()
(map inc {}) ()
(sequence (map inc) (range 10)) (range 1 11)
(range 1 11) (sequence (map inc) (range 10))))
(deftest test-lazy-seq
(are [x] (seq? x)
(lazy-seq nil)
(lazy-seq [])
(lazy-seq [1 2]))
(are [x y] (= x y)
(lazy-seq nil) ()
(lazy-seq [nil]) '(nil)
(deftest test-seq
(is (not (seq? (seq []))))
(is (seq? (seq [1 2])))
(is (not (.equals (seq [3]) (seq [3N]))))
(are [x y] (= x y)
(seq nil) nil
(seq [nil]) '(nil)
(deftest test-cons
(is (thrown? IllegalArgumentException (cons 1 2)))
(are [x y] (= x y)
(cons 1 nil) '(1)
(cons nil nil) '(nil)
(deftest test-empty
(are [x y] (and (= (empty x) y)
#_(= (class (empty x)) (class y)))
nil nil
;Tests that the comparator is preserved
;The first element should be the same in each set if preserved.
(deftest test-empty-sorted
(let [inv-compare (comp - compare)]
(are [x y] (= (first (into (empty x) x))
(first y))
(sorted-set 1 2 3) (sorted-set 1 2 3)
(sorted-set-by inv-compare 1 2 3) (sorted-set-by inv-compare 1 2 3)
(sorted-map 1 :a 2 :b 3 :c) (sorted-map 1 :a 2 :b 3 :c)
(sorted-map-by inv-compare 1 :a 2 :b 3 :c) (sorted-map-by inv-compare 1 :a 2 :b 3 :c))))
(deftest test-not-empty
; empty coll/seq => nil
(are [x] (= (not-empty x) nil)
()
[]
{}
#{}
(seq ())
(seq [])
(lazy-seq ())
(lazy-seq []) )
; non-empty coll/seq => identity
(are [x] (and (= (not-empty x) x)
(= (class (not-empty x)) (class x)))
'(1 2)
[1 2]
{:a 1}
#{1 2}
(seq '(1 2))
(seq [1 2])
(lazy-seq '(1 2))
(lazy-seq [1 2]) ))
(deftest test-first
;(is (thrown? Exception (first)))
(is (thrown? IllegalArgumentException (first true)))
(is (thrown? IllegalArgumentException (first false)))
(is (thrown? IllegalArgumentException (first 1)))
;(is (thrown? IllegalArgumentException (first 1 2)))
(is (thrown? IllegalArgumentException (first \a)))
(is (thrown? IllegalArgumentException (first 's)))
(is (thrown? IllegalArgumentException (first :k)))
(are [x y] (= x y)
(first nil) nil
(deftest test-next
; (is (thrown? IllegalArgumentException (next)))
(is (thrown? IllegalArgumentException (next true)))
(is (thrown? IllegalArgumentException (next false)))
(is (thrown? IllegalArgumentException (next 1)))
;(is (thrown? IllegalArgumentException (next 1 2)))
(is (thrown? IllegalArgumentException (next \a)))
(is (thrown? IllegalArgumentException (next 's)))
(is (thrown? IllegalArgumentException (next :k)))
(are [x y] (= x y)
(next nil) nil
(deftest test-last
(are [x y] (= x y)
(last nil) nil
;; (ffirst coll) = (first (first coll))
;;
(deftest test-ffirst
; (is (thrown? IllegalArgumentException (ffirst)))
(are [x y] (= x y)
(ffirst nil) nil
;; (fnext coll) = (first (next coll)) = (second coll)
;;
(deftest test-fnext
; (is (thrown? IllegalArgumentException (fnext)))
(are [x y] (= x y)
(fnext nil) nil
;; (nfirst coll) = (next (first coll))
;;
(deftest test-nfirst
; (is (thrown? IllegalArgumentException (nfirst)))
(are [x y] (= x y)
(nfirst nil) nil
;; (nnext coll) = (next (next coll))
;;
(deftest test-nnext
; (is (thrown? IllegalArgumentException (nnext)))
(are [x y] (= x y)
(nnext nil) nil
(deftest test-nth
; maps, sets are not supported
(is (thrown? UnsupportedOperationException (nth {} 0)))
(is (thrown? UnsupportedOperationException (nth {:a 1 :b 2} 0)))
(is (thrown? UnsupportedOperationException (nth #{} 0)))
(is (thrown? UnsupportedOperationException (nth #{1 2 3} 0)))
(are [x y] (= x y)
(nth '(1) 0) 1
(nth '(1 2 3) 0) 1
(nth '(1 2 3 4 5) 1) 2
(nth '(1 2 3 4 5) 4) 5
(nth '(1 2 3) 5 :not-found) :not-found
; regex Matchers
(let [m (re-matcher #"(a)(b)" "ababaa")]
(re-find m) ; => ["ab" "a" "b"]
(are [x y] (= x y)
(nth m 0) "ab"
(nth m 1) "a"
(nth m 2) "b"
(nth m 3 :not-found) :not-found
(nth m -1 :not-found) :not-found )
(is (thrown? IndexOutOfBoundsException (nth m 3)))
(is (thrown? IndexOutOfBoundsException (nth m -1))))
(let [m (re-matcher #"c" "ababaa")]
(re-find m) ; => nil
(are [x y] (= x y)
(nth m 0 :not-found) :not-found
(nth m 2 :not-found) :not-found
(nth m -1 :not-found) :not-found )
(is (thrown? IllegalStateException (nth m 0)))
(is (thrown? IllegalStateException (nth m 2)))
(is (thrown? IllegalStateException (nth m -1)))))
; distinct was broken for nil & false:
; fixed in rev 1278:
; http://code.google.com/p/clojure/source/detail?r=1278
;
(deftest test-distinct
(are [x y] (= x y)
(distinct ()) ()
(distinct '(1)) '(1)
(distinct '(1 2 3)) '(1 2 3)
(distinct '(1 2 3 1 1 1)) '(1 2 3)
(distinct '(1 1 1 2)) '(1 2)
(distinct '(1 2 1 2)) '(1 2)
(are [x] (= (distinct [x x]) [x])
nil
false true
0 42
0.0 3.14
2/3
0M 1M
\c
"" "abc"
'sym
:kw
() '(1 2)
[] [1 2]
{} {:a 1 :b 2}
#{} #{1 2} ))
(deftest test-interpose
(are [x y] (= x y)
(interpose 0 []) ()
(interpose 0 [1]) '(1)
(interpose 0 [1 2]) '(1 0 2)
(interpose 0 [1 2 3]) '(1 0 2 0 3) ))
(deftest test-interleave
(are [x y] (= x y)
(interleave [1 2] [3 4]) '(1 3 2 4)
(deftest test-zipmap
(are [x y] (= x y)
(zipmap [:a :b] [1 2]) {:a 1 :b 2}
(deftest test-concat
(are [x y] (= x y)
(concat) ()
(deftest test-cycle
(are [x y] (= x y)
(cycle []) ()
(deftest test-partition
(are [x y] (= x y)
(partition 2 [1 2 3]) '((1 2))
(partition 2 [1 2 3 4]) '((1 2) (3 4))
(partition 2 []) ()
(deftest test-partitionv
(are [x y] (= x y)
(partitionv 2 [1 2 3]) '((1 2))
(partitionv 2 [1 2 3 4]) '((1 2) (3 4))
(partitionv 2 []) ()
(deftest test-iterate
(are [x y] (= x y)
(take 0 (iterate inc 0)) ()
(take 1 (iterate inc 0)) '(0)
(take 2 (iterate inc 0)) '(0 1)
(take 5 (iterate inc 0)) '(0 1 2 3 4) )
(deftest test-reverse
(are [x y] (= x y)
(reverse nil) () ; since SVN 1294
(reverse []) ()
(reverse [1]) '(1)
(reverse [1 2 3]) '(3 2 1) ))
(deftest test-take
(are [x y] (= x y)
(take 1 [1 2 3 4 5]) '(1)
(take 3 [1 2 3 4 5]) '(1 2 3)
(take 5 [1 2 3 4 5]) '(1 2 3 4 5)
(take 9 [1 2 3 4 5]) '(1 2 3 4 5)
(deftest test-drop
(are [x y] (= x y)
(drop 1 [1 2 3 4 5]) '(2 3 4 5)
(drop 3 [1 2 3 4 5]) '(4 5)
(drop 5 [1 2 3 4 5]) ()
(drop 9 [1 2 3 4 5]) ()
(are [coll] (= (drop 4 coll) (drop -2 (drop 4 coll)))
[0 1 2 3 4 5]
(seq [0 1 2 3 4 5])
(range 6)
(repeat 6 :x))
)
(deftest test-nthrest
(are [x y] (= x y)
(nthrest [1 2 3 4 5] 1) '(2 3 4 5)
(nthrest [1 2 3 4 5] 3) '(4 5)
(nthrest [1 2 3 4 5] 5) ()
(nthrest [1 2 3 4 5] 9) ()
;; (nthrest coll 0) should return coll
(are [coll] (let [r (nthrest coll 0)] (and (= coll r) (= (class coll) (class r))))
[1 2 3]
(seq [1 2 3])
(range 10)
(repeat 10 :x)
(seq "abc") ))
(deftest test-nthnext
(are [x y] (= x y)
(nthnext [1 2 3 4 5] 1) '(2 3 4 5)
(nthnext [1 2 3 4 5] 3) '(4 5)
(nthnext [1 2 3 4 5] 5) nil
(nthnext [1 2 3 4 5] 9) nil
(deftest test-take-nth
(are [x y] (= x y)
(take-nth 1 [1 2 3 4 5]) '(1 2 3 4 5)
(take-nth 2 [1 2 3 4 5]) '(1 3 5)
(take-nth 3 [1 2 3 4 5]) '(1 4)
(take-nth 4 [1 2 3 4 5]) '(1 5)
(take-nth 5 [1 2 3 4 5]) '(1)
(take-nth 9 [1 2 3 4 5]) '(1)
(deftest test-take-while
(are [x y] (= x y)
(take-while pos? []) ()
(take-while pos? [1 2 3 4]) '(1 2 3 4)
(take-while pos? [1 2 3 -1]) '(1 2 3)
(take-while pos? [1 -1 2 3]) '(1)
(take-while pos? [-1 1 2 3]) ()
(take-while pos? [-1 -2 -3]) () ))
(deftest test-drop-while
(are [x y] (= x y)
(drop-while pos? []) ()
(drop-while pos? [1 2 3 4]) ()
(drop-while pos? [1 2 3 -1]) '(-1)
(drop-while pos? [1 -1 2 3]) '(-1 2 3)
(drop-while pos? [-1 1 2 3]) '(-1 1 2 3)
(drop-while pos? [-1 -2 -3]) '(-1 -2 -3) ))
(deftest test-butlast
(are [x y] (= x y)
(butlast []) nil
(butlast [1]) nil
(butlast [1 2 3]) '(1 2) ))
(deftest test-drop-last
(are [x y] (= x y)
; as butlast
(drop-last []) ()
(drop-last [1]) ()
(drop-last [1 2 3]) '(1 2)
(are [x y] (= x y)
(split-at 2 []) [() ()]
(split-at 2 [1 2 3 4 5]) [(list 1 2) (list 3 4 5)]
(are [x y] (= x y)
(split-with pos? []) [() ()]
(split-with pos? [1 2 -1 0 3 4]) [(list 1 2) (list -1 0 3 4)]
; infinite sequence => use take
(are [x y] (= x y)
(take 0 (repeat 7)) ()
(take 1 (repeat 7)) '(7)
(take 2 (repeat 7)) '(7 7)
(take 5 (repeat 7)) '(7 7 7 7 7) )
; limited sequence
(are [x y] (= x y)
(repeat 0 7) ()
(repeat 1 7) '(7)
(repeat 2 7) '(7 7)
(repeat 5 7) '(7 7 7 7 7)
; test different data types
(are [x] (= (repeat 3 x) (list x x x))
nil
false true
0 42
0.0 3.14
2/3
0M 1M
\c
"" "abc"
'sym
:kw
() '(1 2)
[] [1 2]
{} {:a 1 :b 2}
#{} #{1 2})
(deftest test-range
(are [x y] (= x y)
(take 100 (range)) (range 100)
(deftest range-meta
(are [r] (= r (with-meta r {:a 1}))
(range 10)
(range 5 10)
(range 5 10 1)
(range 10.0)
(range 5.0 10.0)
(range 5.0 10.0 1.0)))
(deftest test-empty?
(are [x] (empty? x)
nil
()
(lazy-seq nil) ; => ()
[]
{}
#{}
""
(into-array [])
(transient [])
(transient #{})
(transient {}))
(are [x] (not (empty? x))
'(1 2)
(lazy-seq [1 2])
[1 2]
{:a 1 :b 2}
#{1 2}
"abc"
(into-array [1 2])
(transient [1])
(transient #{1})
(transient {1 2})))
(deftest test-every?
; always true for nil or empty coll/seq
(are [x] (= (every? pos? x) true)
nil
() [] {} #{}
(lazy-seq [])
(into-array []) )
(are [x y] (= x y)
true (every? pos? [1])
true (every? pos? [1 2])
true (every? pos? [1 2 3 4 5])
(are [x y] (= x y)
true (every? #{:a} [:a :a])
;! false (every? #{:a} [:a :b]) ; Issue 68: every? returns nil instead of false
;! false (every? #{:a} [:b :b]) ; http://code.google.com/p/clojure/issues/detail?id=68
))
(deftest test-not-every?
; always false for nil or empty coll/seq
(are [x] (= (not-every? pos? x) false)
nil
() [] {} #{}
(lazy-seq [])
(into-array []) )
(are [x y] (= x y)
false (not-every? pos? [1])
false (not-every? pos? [1 2])
false (not-every? pos? [1 2 3 4 5])
(are [x y] (= x y)
false (not-every? #{:a} [:a :a])
true (not-every? #{:a} [:a :b])
true (not-every? #{:a} [:b :b]) ))
(deftest test-not-any?
; always true for nil or empty coll/seq
(are [x] (= (not-any? pos? x) true)
nil
() [] {} #{}
(lazy-seq [])
(into-array []) )
(are [x y] (= x y)
false (not-any? pos? [1])
false (not-any? pos? [1 2])
false (not-any? pos? [1 2 3 4 5])
(are [x y] (= x y)
false (not-any? #{:a} [:a :a])
false (not-any? #{:a} [:a :b])
true (not-any? #{:a} [:b :b]) ))
(deftest test-some
;; always nil for nil or empty coll/seq
(are [x] (= (some pos? x) nil)
nil
() [] {} #{}
(lazy-seq [])
(into-array []))
(are [x y] (= x y)
nil (some nil nil)
true (some pos? [1])
true (some pos? [1 2])
nil (some pos? [-1])
nil (some pos? [-1 -2])
true (some pos? [-1 2])
true (some pos? [1 -2])
:a (some #{:a} [:a :a])
:a (some #{:a} [:b :a])
nil (some #{:a} [:b :b])
:a (some #{:a} '(:a :b))
:a (some #{:a} #{:a :b})
))
(deftest test-flatten-present
(are [expected nested-val] (= (flatten nested-val) expected)
;simple literals
[] nil
[] 1
[] 'test
[] :keyword
[] 1/2
[] #"[\r\n]"
[] true
[] false
;vectors
[1 2 3 4 5] [[1 2] [3 4 [5]]]
[1 2 3 4 5] [1 2 3 4 5]
[#{1 2} 3 4 5] [#{1 2} 3 4 5]
;sets
[] #{}
[] #{#{1 2} 3 4 5}
[] #{1 2 3 4 5}
[] #{#{1 2} 3 4 5}
;lists
[] '()
[1 2 3 4 5] `(1 2 3 4 5)
;maps
[] {:a 1 :b 2}
[:a 1 :b 2] (sort-by key {:a 1 :b 2})
[] {[:a :b] 1 :c 2}
[:a :b 1 :c 2] (sort-by val {[:a :b] 1 :c 2})
[:a 1 2 :b 3] (sort-by key {:a [1 2] :b 3})
;Strings
[] "12345"
[\1 \2 \3 \4 \5] (seq "12345")
;fns
[] count
[count even? odd?] [count even? odd?]))
(deftest test-partition-by
(are [test-seq] (= (partition-by (comp even? count) test-seq)
[["a"] ["bb" "cccc" "dd"] ["eee" "f"] ["" "hh"]])
["a" "bb" "cccc" "dd" "eee" "f" "" "hh"]
'("a" "bb" "cccc" "dd" "eee" "f" "" "hh"))
(is (=(partition-by #{\a \e \i \o \u} "abcdefghijklm")
[[\a] [\b \c \d] [\e] [\f \g \h] [\i] [\j \k \l \m]]))
;; CLJ-1764 regression test
(is (=(first (second (partition-by zero? (range))))
1)))
(deftest test-frequencies
(are [expected test-seq] (= (frequencies test-seq) expected)
{\p 2, \s 4, \i 4, \m 1} "mississippi"
{1 4 2 2 3 1} [1 1 1 1 2 2 3]
{1 4 2 2 3 1} '(1 1 1 1 2 2 3)))
(deftest test-ArrayIter
(are [arr expected]
(let [iter (clojure.lang.ArrayIter/createFromObject arr)]
(loop [accum []]
(if (.hasNext iter)
(recur (conj accum (.next iter)))
(is (= expected accum)))))
nil []
(object-array ["a" "b" "c"]) ["a" "b" "c"]
(boolean-array [false true false]) [false true false]
(byte-array [1 2]) [(byte 1) (byte 2)]
(short-array [1 2]) [1 2]
(int-array [1 2]) [1 2]
(long-array [1 2]) [1 2]
(float-array [2.0 -2.5]) [2.0 -2.5]
(double-array [1.2 -3.5]) [1.2 -3.5]
(char-array [\H \i]) [\H \i]))
(deftest test-reduce-on-coll-seqs
;; reduce on seq of coll, both with and without an init
(are [coll expected expected-init]
(and
(= expected-init (reduce conj [:init] (seq coll)))
(= expected (reduce conj (seq coll))))
;; (seq [ ... ])
[] [] [:init]
[1] 1 [:init 1]
[[1] 2] [1 2] [:init [1] 2]
(are [coll expected expected-init]
(and
(= expected-init (reduce + 100 (seq coll)))
(= expected (reduce + (seq coll))))
clojure
(ns clojure.test-clojure.math
(:require
[clojure.test :refer :all]
[clojure.math :as m]))
(defn neg-zero?
[^double d]
(and (zero? d) (< (Double/compare d 0.0) 0)))
(defn pos-zero?
[^double d]
(and (zero? d) (not (< (Double/compare d 0.0) 0))))
clojure
(ns clojure.test-clojure.data-structures
(:use clojure.test
[clojure.test.generative :exclude (is)])
(:require [clojure.test-clojure.generators :as cgen]
[clojure.data.generators :as gen]
[clojure.string :as string])
(:import [java.util Collection]))
;; *** Generative ***
(defspec subcollection-counts-are-consistent
identity
[^{:tag cgen/ednable-collection} coll]
(let [n (count coll)]
(dotimes [i n]
(is (= n
(+ i (count (nthnext coll i)))
(+ i (count (drop i coll))))))))
(deftest test-equality
; nil is not equal to any other value
(are [x] (not (= nil x))
true false
0 0.0
\space
"" #""
() [] #{} {}
(lazy-seq nil) ; SVN 1292: fixed (= (lazy-seq nil) nil)
(lazy-seq ())
(lazy-seq [])
(lazy-seq {})
(lazy-seq #{})
(lazy-seq "")
(lazy-seq (into-array []))
(new Object) )
; vectors equal other seqs by items equality
(are [x y] (= x y)
'() [] ; regression fixed in r1208; was not equal
'(1) [1]
'(1 2) [1 2]
; list and vector vs. set and map
(are [x y] (not= x y)
; only () equals []
() #{}
() {}
[] #{}
[] {}
#{} {}
; only '(1) equals [1]
'(1) #{1}
[1] #{1} )
; sorted-map, hash-map and array-map - classes differ, but content is equal
;; TODO: reimplement all-are with new do-template?
;; (all-are (not= (class _1) (class _2))
;; (sorted-map :a 1)
;; (hash-map :a 1)
;; (array-map :a 1))
;; (all-are (= _1 _2)
;; (sorted-map)
;; (hash-map)
;; (array-map))
;; (all-are (= _1 _2)
;; (sorted-map :a 1)
;; (hash-map :a 1)
;; (array-map :a 1))
;; (all-are (= _1 _2)
;; (sorted-map :a 1 :z 3 :c 2)
;; (hash-map :a 1 :z 3 :c 2)
;; (array-map :a 1 :z 3 :c 2))
; struct-map vs. sorted-map, hash-map and array-map
(are [x] (and (not= (class (struct equality-struct 1 2)) (class x))
(= (struct equality-struct 1 2) x))
(sorted-map-by compare :a 1 :b 2)
(sorted-map :a 1 :b 2)
(hash-map :a 1 :b 2)
(array-map :a 1 :b 2))
; sorted-set vs. hash-set
(is (not= (class (sorted-set 1)) (class (hash-set 1))))
(are [x y] (= x y)
(sorted-set-by <) (hash-set)
(sorted-set-by < 1) (hash-set 1)
(sorted-set-by < 3 2 1) (hash-set 3 2 1)
(sorted-set) (hash-set)
(sorted-set 1) (hash-set 1)
(sorted-set 3 2 1) (hash-set 3 2 1) ))
(deftest test-count
(let [EMPTY clojure.lang.PersistentQueue/EMPTY]
(are [x y] (= (count x) y)
EMPTY 0
(into EMPTY [:a :b]) 2
(-> (into EMPTY [:a :b]) pop pop) 0
nil 0
; different types
(are [x] (= (count [x]) 1)
nil true false
0 0.0 "" \space
() [] #{} {} ))
(are [x y] (= x y)
(conj nil 1) '(1)
(conj nil 3 2 1) '(1 2 3)
(are [x y] (= x y)
(peek nil) nil
(are [x y] (= x y)
(pop nil) nil
(deftest test-list
(are [x] (list? x)
()
'()
(list)
(list 1 2 3) )
; order is important
(are [x y] (not (= x y))
(list 1 2) (list 2 1)
(list 3 1 2) (list 1 2 3) )
(are [x y] (= x y)
'() ()
(list) '()
(list 1) '(1)
(list 1 2) '(1 2)
(deftest test-find
(are [x y] (= x y)
(find {} :a) nil
(deftest test-contains?
; contains? is designed to work preferably on maps and sets
(are [x y] (= x y)
(contains? {} :a) false
(contains? {} nil) false
; contains? also works on java.util.Map and java.util.Set.
(are [x y] (= x y)
(contains? (java.util.HashMap. {}) :a) false
(contains? (java.util.HashMap. {}) nil) false
; numerically indexed collections (e.g. vectors and Java arrays)
; => test if the numeric key is WITHIN THE RANGE OF INDEXES
(are [x y] (= x y)
(contains? [] 0) false
(contains? [] -1) false
(contains? [] 1) false
; 'contains?' will not operate on non-associative things
(are [x] (is (thrown? Exception (contains? x 1)))
'(1 2 3)
3))
(deftest test-keys
(are [x y] (= x y) ; other than map data structures
(keys ()) nil
(keys []) nil
(keys #{}) nil
(keys "") nil )
(are [x y] (= x y)
; (class {:a 1}) => clojure.lang.PersistentArrayMap
(keys {}) nil
(keys {:a 1}) '(:a)
(keys {nil 1}) '(nil)
(diff (keys {:a 1 :b 2}) '(:a :b)) nil ; (keys {:a 1 :b 2}) '(:a :b)
(deftest test-vals
(are [x y] (= x y) ; other than map data structures
(vals ()) nil
(vals []) nil
(vals #{}) nil
(vals "") nil )
(are [x y] (= x y)
; (class {:a 1}) => clojure.lang.PersistentArrayMap
(vals {}) nil
(vals {:a 1}) '(1)
(vals {nil 1}) '(1)
(diff (vals {:a 1 :b 2}) '(1 2)) nil ; (vals {:a 1 :b 2}) '(1 2)
;; doesn't throw
(let [cmp #(compare (count %1) (count %2))]
(assoc (sorted-map-by cmp) () 1)
(assoc (sorted-map-by cmp) #{} 1)
(assoc (sorted-map-by cmp) {} 1)))
(deftest test-key
(are [x] (= (key (first (hash-map x :value))) x)
nil
false true
0 42
0.0 3.14
2/3
0M 1M
\c
"" "abc"
'sym
:kw
() '(1 2)
[] [1 2]
{} {:a 1 :b 2}
#{} #{1 2} ))
(deftest test-val
(are [x] (= (val (first (hash-map :key x))) x)
nil
false true
0 42
0.0 3.14
2/3
0M 1M
\c
"" "abc"
'sym
:kw
() '(1 2)
[] [1 2]
{} {:a 1 :b 2}
#{} #{1 2} ))
(deftest test-get
(let [m {:a 1, :b 2, :c {:d 3, :e 4}, :f nil, :g false, nil {:h 5}}]
(is (thrown? IllegalArgumentException (get-in {:a 1} 5)))
(are [x y] (= x y)
(get m :a) 1
(get m :e) nil
(get m :e 0) 0
(get m nil) {:h 5}
(get m :b 0) 2
(get m :f 0) nil
(deftest test-nested-map-destructuring
(let [sample-map {:a 1 :b {:a 2}}
{ao1 :a {ai1 :a} :b} sample-map
{ao2 :a {ai2 :a :as m1} :b :as m2} sample-map
{ao3 :a {ai3 :a :as m} :b :as m} sample-map
{{ai4 :a :as m} :b ao4 :a :as m} sample-map]
(are [i o] (and (= i 2)
(= o 1))
ai1 ao1
ai2 ao2
ai3 ao3
ai4 ao4)))
(deftest test-map-entry?
(testing "map-entry? = false"
(are [entry]
(false? (map-entry? entry))
nil 5 #{1 2} '(1 2) {:a 1} [] [0] [1 2 3]))
(testing "map-entry? = true"
(are [entry]
(true? (map-entry? entry))
(first (doto (java.util.HashMap.) (.put "x" 1))))))
(deftest test-hash-set
(are [x] (set? x)
#{}
#{1 2}
(hash-set)
(hash-set 1 2) )
; order isn't important
(are [x y] (= x y)
#{1 2} #{2 1}
#{3 1 2} #{1 2 3}
(hash-set 1 2) (hash-set 2 1)
(hash-set 3 1 2) (hash-set 1 2 3) )
(are [x y] (= x y)
; equal classes
(class #{}) (class (hash-set))
(class #{1 2}) (class (hash-set 1 2))
; creates set?
(are [x] (set? x)
(sorted-set)
(sorted-set 1 2) )
; equal and unique
(are [x] (and (= (sorted-set x) #{x})
(= (sorted-set x x) (sorted-set x)))
nil
false true
0 42
0.0 3.14
2/3
0M 1M
\c
"" "abc"
'sym
:kw
[] [1 2]
)
; cannot be cast to java.lang.Comparable
(is (thrown? ClassCastException (sorted-set ())))
(is (thrown? ClassCastException (sorted-set {})))
(is (thrown? ClassCastException (sorted-set #{})))
(is (thrown? ClassCastException (sorted-set '(1 2) '(1 2))))
(is (thrown? ClassCastException (sorted-set {:a 1 :b 2} {:a 1 :b 2})))
(is (thrown? ClassCastException (sorted-set #{1 2} #{1 2})))
(are [x y] (= x y)
; generating
(sorted-set) #{}
(sorted-set 1) #{1}
(sorted-set 1 2) #{1 2}
; creates set?
(are [x] (set? x)
(sorted-set-by <)
(sorted-set-by < 1 2) )
; equal and unique
(are [x] (and (= (sorted-set-by compare x) #{x})
(= (sorted-set-by compare x x) (sorted-set-by compare x)))
nil
false true
0 42
0.0 3.14
2/3
0M 1M
\c
"" "abc"
'sym
:kw
() ; '(1 2)
[] [1 2]
{} ; {:a 1 :b 2}
#{} ; #{1 2}
)
; cannot be cast to java.lang.Comparable
; NB: not a ClassCastException, but a RuntimeException is thrown,
; requires discussion on whether this should be symmetric with test-sorted-set
(is (thrown? Exception (sorted-set-by compare '(1 2) '(1 2))))
(is (thrown? Exception (sorted-set-by compare {:a 1 :b 2} {:a 1 :b 2})))
(is (thrown? Exception (sorted-set-by compare #{1 2} #{1 2})))
(are [x y] (= x y)
; generating
(sorted-set-by >) #{}
(sorted-set-by > 1) #{1}
(sorted-set-by > 1 2) #{1 2}
; special cases
(sorted-set-by compare nil) #{nil}
(sorted-set-by compare 1 nil) #{nil 1}
(sorted-set-by compare nil 2) #{nil 2}
(sorted-set-by compare #{}) #{#{}} ))
(deftest test-set
; set?
(are [x] (set? (set x))
() '(1 2)
[] [1 2]
#{} #{1 2}
{} {:a 1 :b 2}
(into-array []) (into-array [1 2])
"" "abc" )
; unique
(are [x] (= (set [x x]) #{x})
nil
false true
0 42
0.0 3.14
2/3
0M 1M
\c
"" "abc"
'sym
:kw
() '(1 2)
[] [1 2]
{} {:a 1 :b 2}
#{} #{1 2} )
; conversion
(are [x y] (= (set x) y)
() #{}
'(1 2) #{1 2}
; identity
(are [x] (= (disj x) x)
nil
#{}
#{1 2 3}
; different data types
#{nil
false true
0 42
0.0 3.14
2/3
0M 1M
\c
"" "abc"
'sym
:kw
[] [1 2]
{} {:a 1 :b 2}
#{} #{1 2}} )
; type identity
(are [x] (= (class (disj x)) (class x))
(hash-set)
(hash-set 1 2)
(sorted-set)
(sorted-set 1 2) )
(are [x y] (= x y)
(disj nil :a) nil
(disj nil :a :b) nil
(deftest test-queues
(let [EMPTY clojure.lang.PersistentQueue/EMPTY]
(are [x y] (= x y)
EMPTY EMPTY
(into EMPTY (range 50)) (into EMPTY (range 50))
(conj EMPTY (Long. -1)) (conj EMPTY (Integer. -1))
(hash (conj EMPTY (Long. -1))) (hash (conj EMPTY (Integer. -1)))
(hash [1 2 3]) (hash (conj EMPTY 1 2 3))
(range 5) (into EMPTY (range 5))
(range 1 6) (-> EMPTY
(into (range 6))
pop))
(are [x y] (not= x y)
(range 5) (into EMPTY (range 6))
(range 6) (into EMPTY (range 5))
(range 0 6) (-> EMPTY
(into (range 6))
pop)
(range 1 6) (-> EMPTY
(into (range 7))
pop))))
;; Sets
(is (thrown? IllegalArgumentException
(read-string "#{1 2 3 4 1 5}")))
;; If there are duplicate items when doing (conj #{} x1 x2 ...),
;; the behavior is that the metadata of the first item is kept.
(are [s x] (all-equal-sets-incl-meta s
(apply conj #{} x)
(set x)
(apply hash-set x)
(apply sorted-set x)
(apply sorted-set-by cmp-first x))
#{x1 y2} [x1 y2]
#{x1 z3a} [x1 z3a z3b]
#{w5b} [w5b w5a w5c]
#{z3a x1} [z3a z3b x1])
;; Maps
(is (thrown? IllegalArgumentException
(read-string "{:a 1, :b 2, :a -1, :c 3}")))
;; If there are duplicate keys when doing (assoc {} k1 v1 k2 v2
;; ...), the behavior is that the metadata of the first duplicate
;; key is kept, but mapped to the last value with an equal key
;; (where metadata of keys are not compared).
(are [h x] (all-equal-maps-incl-meta h
(apply assoc {} x)
(apply hash-map x)
(apply sorted-map x)
(apply sorted-map-by cmp-first x)
(apply array-map x))
{x1 2, z3a 4} [x1 2, z3a 4]
{x1 2, z3a 5} [x1 2, z3a 4, z3b 5]
{z3a 5} [z3a 2, z3a 4, z3b 5]
{z3b 4, x1 5} [z3b 2, z3a 4, x1 5]
{z3b v4b, x1 5} [z3b v4a, z3a v4b, x1 5]
{x1 v4a, w5a v4c, v4a z3b, y2 2} [x1 v4a, w5a v4a, w5b v4b,
v4a z3a, y2 2, v4b z3b, w5c v4c])))
(deftest test-assoc
(are [x y] (= x y)
[4] (assoc [] 0 4)
[5 -7] (assoc [] 0 5 1 -7)
{:a 1} (assoc {} :a 1)
{nil 1} (assoc {} nil 1)
{:a 2 :b -2} (assoc {} :b -2 :a 2))
(is (thrown? IllegalArgumentException (assoc [] 0 5 1)))
(is (thrown? IllegalArgumentException (assoc {} :b -2 :a))))
(defn case-indendent-string-cmp [s1 s2]
(compare (string/lower-case s1) (string/lower-case s2)))
(deftest trailing-map-destructuring
(let [sample-map {:a 1 :b 2}
add (fn [& {:keys [a b]}] (+ a b))
addn (fn [n & {:keys [a b]}] (+ n a b))]
(testing "that kwargs are applied properly given a map in place of the key/val pairs"
(is (= 3 (add :a 1 :b 2)))
(is (= 3 (add {:a 1 :b 2})))
(is (= 13 (addn 10 :a 1 :b 2)))
(is (= 13 (addn 10 {:a 1 :b 2})))
(is (= 103 ((partial addn 100) :a 1 {:b 2})))
(is (= 103 ((partial addn 100 :a 1) {:b 2})))
(is (= 107 ((partial addn 100 :a 1) {:a 5 :b 2}))))
(testing "built maps"
(let [{:as m1} (list :a 1 :b 2)
{:as m2} (list :a 1 :b 2 {:c 3})
{:as m3} (list :a 1 :b 2 {:a 0})
{:keys [a4] :as m4} (list nil)]
(= m1 {:a 1 :b 2})
(= m2 {:a 1 :b 2 :c 3})
(= m3 {:a 0 :b 2})
(= m1 (seq-to-map-for-destructuring (list :a 1 :b 2)))
(= m2 (seq-to-map-for-destructuring (list :a 1 :b 2 {:c 3})))
(= m3 (seq-to-map-for-destructuring (list :a 1 :b 2 {:a 0})))
(= a4 nil)))))
clojure
(ns clojure.test-clojure.protocols
(:use clojure.test clojure.test-clojure.protocols.examples)
(:require [clojure.test-clojure.protocols.more-examples :as other]
[clojure.set :as set]
clojure.test-helper)
(:import [clojure.test_clojure.protocols.examples ExampleInterface]))
(deftest protocols-test
(testing "protocol fns have useful metadata"
(let [common-meta {:ns (find-ns 'clojure.test-clojure.protocols.examples)
:protocol #'ExampleProtocol :tag nil}]
(are [m f] (= (merge common-meta m)
(meta (var f)))
{:name 'foo :arglists '([a]) :doc "method with one arg"} foo
{:name 'bar :arglists '([a b]) :doc "method with two args"} bar
{:name 'baz :arglists '([a] [a b]) :doc "method with multiple arities" :tag 'java.lang.String} baz
{:name 'with-quux :arglists '([a]) :doc "method name with a hyphen"} with-quux)))
(testing "protocol fns throw IllegalArgumentException if no impl matches"
(is (thrown-with-msg?
IllegalArgumentException
#"No implementation of method: :foo of protocol: #'clojure.test-clojure.protocols.examples/ExampleProtocol found for class: java.lang.Long"
(foo 10))))
(testing "protocols generate a corresponding interface using _ instead of - for method names"
(is (= ["bar" "baz" "baz" "foo" "with_quux"] (method-names clojure.test_clojure.protocols.examples.ExampleProtocol))))
(testing "protocol will work with instances of its interface (use for interop, not in Clojure!)"
(let [obj (proxy [clojure.test_clojure.protocols.examples.ExampleProtocol] []
(foo [] "foo!"))]
(is (= "foo!" (.foo obj)) "call through interface")
(is (= "foo!" (foo obj)) "call through protocol")))
(testing "you can implement just part of a protocol if you want"
(let [obj (reify ExampleProtocol
(baz [a b] "two-arg baz!"))]
(is (= "two-arg baz!" (baz obj nil)))
(is (thrown? AbstractMethodError (baz obj)))))
(testing "error conditions checked when defining protocols"
(is (thrown-with-cause-msg?
Exception
#"Definition of function m in protocol badprotdef must take at least one arg."
(eval '(defprotocol badprotdef (m [])))))
(is (thrown-with-cause-msg?
Exception
#"Function m in protocol badprotdef was redefined. Specify all arities in single definition."
(eval '(defprotocol badprotdef (m [this arg]) (m [this arg1 arg2]))))))
(testing "you can redefine a protocol with different methods"
(eval '(defprotocol Elusive (old-method [x])))
(eval '(defprotocol Elusive (new-method [x])))
(is (= :new-method (eval '(new-method (reify Elusive (new-method [x] :new-method))))))
(is (fails-with-cause? IllegalArgumentException #"No method of interface: .*\.Elusive found for function: old-method of protocol: Elusive \(The protocol method may have been defined before and removed\.\)"
(eval '(old-method (reify Elusive (new-method [x] :new-method))))))))
(deftest marker-tests
(testing "That a marker protocol has no methods"
(is (= '() (method-names clojure.test_clojure.protocols.examples.MarkerProtocol))))
(testing "That types with markers are reportedly satifying them."
(let [hm (HasMarkers.)
wgm (WillGetMarker.)]
(is (satisfies? MarkerProtocol hm))
(is (satisfies? MarkerProtocol2 hm))
(is (satisfies? MarkerProtocol wgm)))))
(deftest defrecord-interfaces-test
(testing "java.util.Map"
(let [rec (r 1 2)]
(is (= 2 (.size rec)))
(is (= 3 (.size (assoc rec :c 3))))
(is (not (.isEmpty rec)))
(is (.isEmpty (EmptyRecord.)))
(is (.containsKey rec :a))
(is (not (.containsKey rec :c)))
(is (.containsValue rec 1))
(is (not (.containsValue rec 3)))
(is (= 1 (.get rec :a)))
(is (thrown? UnsupportedOperationException (.put rec :a 1)))
(is (thrown? UnsupportedOperationException (.remove rec :a)))
(is (thrown? UnsupportedOperationException (.putAll rec {})))
(is (thrown? UnsupportedOperationException (.clear rec)))
(is (= #{:a :b} (.keySet rec)))
(is (= #{1 2} (set (.values rec))))
(is (= #{[:a 1] [:b 2]} (.entrySet rec)))
))
(testing "IPersistentCollection"
(testing ".cons"
(let [rec (r 1 2)]
(are [x] (= rec (.cons rec x))
nil {})
(is (= (r 1 3) (.cons rec {:b 3})))
(is (= (r 1 4) (.cons rec [:b 4])))
(is (= (r 1 5) (.cons rec (MapEntry. :b 5))))))))
(defn compare-huge-types
[hugeL hugeR]
(and
(= (.a hugeL) (.a hugeR))
(= (.b hugeL) (.b hugeR))
(= (.c hugeL) (.c hugeR))
(= (.d hugeL) (.d hugeR))
(= (.e hugeL) (.e hugeR))
(= (.f hugeL) (.f hugeR))
(= (.g hugeL) (.g hugeR))
(= (.h hugeL) (.h hugeR))
(= (.i hugeL) (.i hugeR))
(= (.j hugeL) (.j hugeR))
(= (.k hugeL) (.k hugeR))
(= (.l hugeL) (.l hugeR))
(= (.m hugeL) (.m hugeR))
(= (.n hugeL) (.n hugeR))
(= (.o hugeL) (.o hugeR))
(= (.p hugeL) (.p hugeR))
(= (.q hugeL) (.q hugeR))
(= (.r hugeL) (.r hugeR))
(= (.s hugeL) (.s hugeR))
(= (.t hugeL) (.t hugeR))
(= (.u hugeL) (.u hugeR))
(= (.v hugeL) (.v hugeR))
(= (.w hugeL) (.w hugeR))
(= (.x hugeL) (.x hugeR))
(= (.y hugeL) (.y hugeR))
(= (.z hugeL) (.z hugeR))))
(deftest deftype-factory-fn
(testing "that the ->T factory is gen'd for a deftype and that it works"
(is (= (.a (TypeToTestFactory. 42)) (.a (->TypeToTestFactory 42))))
(is (compare-huge-types
(TypeToTestHugeFactories. 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)
(->TypeToTestHugeFactories 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))))
(testing "that the generated factory checks arity constraints"
(is (thrown? clojure.lang.ArityException (->TypeToTestHugeFactories 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)))
(is (thrown? clojure.lang.ArityException (->TypeToTestHugeFactories 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)))))
(deftest test-ctor-literals
(testing "that constructor calls to print-dup'able classes are supported as literals"
(is (= "Hi" #java.lang.String["Hi"]))
(is (= 42 #java.lang.Long[42]))
(is (= 42 #java.lang.Long["42"]))
(is (= [:a 42] #clojure.lang.MapEntry[:a 42])))
(testing "that constructor literals are embeddable"
(is (= 42 #java.lang.Long[#java.lang.String["42"]])))
(testing "that constructor literals work for deftypes too"
(is (= (.a (TypeToTestFactory. 42)) (.a #clojure.test_clojure.protocols.TypeToTestFactory[42])))
(is (compare-huge-types
(TypeToTestHugeFactories. 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)
#clojure.test_clojure.protocols.TypeToTestHugeFactories[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]))))
(testing "that records and types are evalable"
(is (= (RecordToTestLiterals. 42) (eval #clojure.test_clojure.protocols.RecordToTestLiterals[42])))
(is (= (RecordToTestLiterals. 42) (eval #clojure.test_clojure.protocols.RecordToTestLiterals{:a 42})))
(is (= (RecordToTestLiterals. 42) (eval (RecordToTestLiterals. 42))))
(is (= (RecordToTestLiterals. (RecordToTestLiterals. 42))
(eval #clojure.test_clojure.protocols.RecordToTestLiterals[#clojure.test_clojure.protocols.RecordToTestLiterals[42]])))
(is (= (RecordToTestLiterals. (RecordToTestLiterals. 42))
(eval #clojure.test_clojure.protocols.RecordToTestLiterals[#clojure.test_clojure.protocols.RecordToTestLiterals{:a 42}])))
(is (= (RecordToTestLiterals. (RecordToTestLiterals. 42))
(eval #clojure.test_clojure.protocols.RecordToTestLiterals{:a #clojure.test_clojure.protocols.RecordToTestLiterals[42]})))
(is (= 42 (.a (eval #clojure.test_clojure.protocols.TypeToTestLiterals[42])))))
(testing "that ctor literals only work with constants or statics"
(is (thrown? Exception (read-string "#java.util.Locale[(str 'en)]")))
(is (thrown? Exception (read-string "(let [s \"en\"] #java.util.Locale[(str 'en)])")))
(is (thrown? Exception (read-string "#clojure.test_clojure.protocols.RecordToTestLiterals{(keyword \"a\") 42}"))))
(testing "that ctors can have whitespace after class name but before {"
(is (= (RecordToTestLiterals. 42)
(read-string "#clojure.test_clojure.protocols.RecordToTestLiterals {:a 42}"))))
(testing "that the correct errors are thrown with malformed literals"
(is (thrown-with-msg?
Exception
#"Unreadable constructor form.*"
(read-string "#java.util.Locale(\"en\")")))
(is (thrown-with-msg?
Exception
#"Unexpected number of constructor arguments.*"
(read-string "#java.util.Locale[\"\" \"\" \"\" \"\"]")))
(is (thrown? Exception (read-string "#java.util.Nachos(\"en\")")))))
(deftest test-record-and-type-field-names
(testing "that types and records allow names starting with double-underscore.
This is a regression test for CLJ-837."
(let [r (RecordToTest__. 1 2)
t (TypeToTest__. 3 4)]
(are [x y] (= x y)
1 (:__a r)
2 (:___b r)
3 (.__a t)
4 (.___b t)))))
clojure
(ns clojure.test-clojure.java-interop
(:use clojure.test)
(:require [clojure.data :as data]
[clojure.inspector]
[clojure.pprint :as pp]
[clojure.set :as set]
[clojure.test-clojure.proxy.examples :as proxy-examples])
(:import java.util.Base64
(java.util.concurrent.atomic AtomicLong AtomicInteger)))
(deftest test-dot
; (.instanceMember instance args*)
(are [x] (= x "FRED")
(.toUpperCase "fred")
(. "fred" toUpperCase)
(. "fred" (toUpperCase)) )
(are [x] (= x true)
(.startsWith "abcde" "ab")
(. "abcde" startsWith "ab")
(. "abcde" (startsWith "ab")) )
; (.instanceMember Classname args*)
(are [x] (= x "java.lang.String")
(.getName String)
(. (identity String) getName)
(. (identity String) (getName)) )
; (Classname/staticMethod args*)
(are [x] (= x 7)
(Math/abs -7)
(. Math abs -7)
(. Math (abs -7)) )
; (. target -prop)
(let [p (java.awt.Point. 1 2)]
(are [x y] (= x y)
1 (.-x p)
2 (.-y p)
1 (. p -x)
2 (. p -y)
1 (. (java.awt.Point. 1 2) -x)
2 (. (java.awt.Point. 1 2) -y)))
; Classname/staticField
(are [x] (= x 2147483647)
Integer/MAX_VALUE
(. Integer MAX_VALUE) ))
(deftest test-doto
(let [m (doto (new java.util.HashMap)
(.put "a" 1)
(.put "b" 2))]
(are [x y] (= x y)
(class m) java.util.HashMap
m {"a" 1 "b" 2} )))
(deftest test-new
; Integer
(are [expr cls value] (and (= (class expr) cls)
(= expr value))
(new java.lang.Integer 42) java.lang.Integer 42
(java.lang.Integer. 123) java.lang.Integer 123 )
; Date
(are [x] (= (class x) java.util.Date)
(new java.util.Date)
(java.util.Date.) ))
(deftest test-instance?
; evaluation
(are [x y] (= x y)
(instance? java.lang.Integer (+ 1 2)) false
(instance? java.lang.Long (+ 1 2)) true )
; different types
(are [type literal] (instance? literal type)
1 java.lang.Long
1.0 java.lang.Double
1M java.math.BigDecimal
\a java.lang.Character
"a" java.lang.String )
; it is a Long, nothing else
(are [x y] (= (instance? x 42) y)
java.lang.Integer false
java.lang.Long true
java.lang.Character false
java.lang.String false )
(deftest test-bean
(let [b (bean java.awt.Color/black)]
(are [x y] (= x y)
(map? b) true
(:alpha b) 255
(:transparency b) 1
(deftest test-proxy-chain
(testing "That the proxy functions can chain"
(are [x y] (= x y)
(-> (get-proxy-class Object)
construct-proxy
(init-proxy {})
(update-proxy {"toString" (fn [_] "chain chain chain")})
str)
"chain chain chain"
(deftest test-bases
(are [x] (nil? (bases x))
java.lang.Object ;; no super classes/interfaces
java.lang.Comparable) ;; no super interfaces
(are [x y] (set/subset? (set y) (set x))
(bases java.lang.Math) [java.lang.Object]
(bases java.util.Collection) [java.lang.Iterable]
(bases java.lang.Integer) [java.lang.Number java.lang.Comparable]))
(deftest test-supers
(are [x y] (set/subset? y (set x))
(supers java.lang.Math)
#{java.lang.Object}
(supers java.lang.Integer)
#{java.lang.Number java.lang.Object
java.lang.Comparable java.io.Serializable} ))
; Arrays: [alength] aget aset [make-array to-array into-array to-array-2d aclone]
; [float-array, int-array, etc]
; amap, areduce
; given size (and empty)
(are [x] (and (= (alength (~type-array x)) x)
(= (vec (~type-array x)) (repeat x 0)))
0 1 5 )
; copy of a sequence
(are [x] (and (= (alength (~type-array x)) (count x))
(= (vec (~type-array x)) x))
[]
[1]
[1 -2 3 0 5] )
; given size and init-value
(are [x] (and (= (alength (~type-array x 42)) x)
(= (vec (~type-array x 42)) (repeat x 42)))
0 1 5 )
; given size and init-seq
(are [x y z] (and (= (alength (~type-array x y)) x)
(= (vec (~type-array x y)) z))
0 [] []
0 [1] []
0 [1 2 3] []
1 [] [0]
1 [1] [1]
1 [1 2 3] [1]
5 [] [0 0 0 0 0]
5 [1] [1 0 0 0 0]
5 [1 2 3] [1 2 3 0 0]
5 [1 2 3 4 5] [1 2 3 4 5]
5 [1 2 3 4 5 6 7] [1 2 3 4 5] )))
(deftest-type-array int-array int)
(deftest-type-array long-array long)
;todo, fix, test broken for float/double, should compare to 1.0 2.0 etc
#_(deftest-type-array float-array float)
#_(deftest-type-array double-array double)
; separate test for exceptions (doesn't work with above macro...)
(deftest test-type-array-exceptions
(are [x] (thrown? NegativeArraySizeException x)
(int-array -1)
(long-array -1)
(float-array -1)
(double-array -1) ))
; one-dimensional
(are [x] (= (alength (make-array Integer x)) x)
0 1 5 )
(let [a (make-array Long 5)]
(aset a 3 42)
(are [x y] (= x y)
(aget a 3) 42
(class (aget a 3)) Long ))
; multi-dimensional
(let [a (make-array Long 3 2 4)]
(aset a 0 1 2 987)
(are [x y] (= x y)
(alength a) 3
(alength (first a)) 2
(alength (first (first a))) 4
(deftest test-to-array
(let [v [1 "abc" :kw \c []]
a (to-array v)]
(are [x y] (= x y)
; length
(alength a) (count v)
; different kinds of collections
(are [x] (and (= (alength (to-array x)) (count x))
(= (vec (to-array x)) (vec x)))
()
'(1 2)
[]
[1 2]
(sorted-set)
(sorted-set 1 2)
(int-array 0)
(int-array [1 2 3])
(defmacro test-to-passed-array-for [collection-type]
`(deftest ~(symbol (str "test-to-passed-array-for-" collection-type))
(let [string-array# (make-array String 5)
shorter# (~collection-type "1" "2" "3")
same-length# (~collection-type "1" "2" "3" "4" "5")
longer# (~collection-type "1" "2" "3" "4" "5" "6")]
(are [expected actual] (array-typed-equals expected actual)
(into-array String ["1" "2" "3" nil nil]) (.toArray shorter# string-array#)
(into-array String ["1" "2" "3" "4" "5"]) (.toArray same-length# string-array#)
(into-array String ["1" "2" "3" "4" "5" "6"]) (.toArray longer# string-array#)))))
(deftest test-into-array
; compatible types only
(is (thrown? IllegalArgumentException (into-array [1 "abc" :kw])))
(is (thrown? IllegalArgumentException (into-array [1.2 4])))
(is (thrown? IllegalArgumentException (into-array [(byte 2) (short 3)])))
(is (thrown? IllegalArgumentException (into-array Byte/TYPE [100000000000000])))
; simple case
(let [v [1 2 3 4 5]
a (into-array v)]
(are [x y] (= x y)
(alength a) (count v)
(vec a) v
(class (first a)) (class (first v)) ))
(is (= [nil 1 2] (seq (into-array [nil 1 2]))))
(let [types [Integer/TYPE
Byte/TYPE
Float/TYPE
Short/TYPE
Double/TYPE
Long/TYPE]
values [(byte 2) (short 3) (int 4) 5]]
(for [t types]
(let [a (into-array t values)]
(is (== (aget a 0) 2))
(is (== (aget a 1) 3))
(is (== (aget a 2) 4))
(is (== (aget a 3) 5)))))
; different kinds of collections
(are [x] (and (= (alength (into-array x)) (count x))
(= (vec (into-array x)) (vec x))
(= (alength (into-array Long/TYPE x)) (count x))
(= (vec (into-array Long/TYPE x)) (vec x)))
()
'(1 2)
[]
[1 2]
(sorted-set)
(sorted-set 1 2)
; ragged array
(let [v [[1] [2 3] [4 5 6]]
a (to-array-2d v)]
(are [x y] (= x y)
(alength a) (count v)
(alength (aget a 0)) (count (nth v 0))
(alength (aget a 1)) (count (nth v 1))
(alength (aget a 2)) (count (nth v 2))
; empty array
(let [a (to-array-2d [])]
(are [x y] (= x y)
(alength a) 0
(vec a) [] )))
(deftest test-alength
(are [x] (= (alength x) 0)
(int-array 0)
(long-array 0)
(float-array 0)
(double-array 0)
(boolean-array 0)
(byte-array 0)
(char-array 0)
(short-array 0)
(make-array Integer/TYPE 0)
(to-array [])
(into-array [])
(to-array-2d []) )
(are [x] (= (alength x) 1)
(int-array 1)
(long-array 1)
(float-array 1)
(double-array 1)
(boolean-array 1)
(byte-array 1)
(char-array 1)
(short-array 1)
(make-array Integer/TYPE 1)
(to-array [1])
(into-array [1])
(to-array-2d [[1]]) )
(are [x] (= (alength x) 3)
(int-array 3)
(long-array 3)
(float-array 3)
(double-array 3)
(boolean-array 3)
(byte-array 3)
(char-array 3)
(short-array 3)
(make-array Integer/TYPE 3)
(to-array [1 "a" :k])
(into-array [1 2 3])
(to-array-2d [[1] [2 3] [4 5 6]]) ))
(deftest test-aclone
; clone all arrays except 2D
(are [x] (and (= (alength (aclone x)) (alength x))
(= (vec (aclone x)) (vec x)))
(int-array 0)
(long-array 0)
(float-array 0)
(double-array 0)
(boolean-array 0)
(byte-array 0)
(char-array 0)
(short-array 0)
(make-array Integer/TYPE 0)
(to-array [])
(into-array [])
; clone 2D
(are [x] (and (= (alength (aclone x)) (alength x))
(= (map alength (aclone x)) (map alength x))
(= (map vec (aclone x)) (map vec x)))
(to-array-2d [])
(to-array-2d [[1] [2 3] [4 5 6]]) ))
(deftest test-boolean
(are [x y] (and (instance? java.lang.Boolean (boolean x))
(= (boolean x) y))
nil false
false false
true true
clojure
(ns clojure.test-clojure.numbers
(:use clojure.test
[clojure.test.generative :exclude (is)]
clojure.template)
(:require [clojure.data.generators :as gen]
[clojure.test-helper :as helper]))
(deftest Coerced-BigDecimal
(doseq [v [(bigdec 3) (bigdec (inc (bigint Long/MAX_VALUE)))]]
(are [x] (true? x)
(instance? BigDecimal v)
(number? v)
(decimal? v)
(not (float? v)))))
(deftest BigInteger-conversions
(doseq [coerce-fn [bigint biginteger]]
(doseq [v (map coerce-fn [ Long/MAX_VALUE
13178456923875639284562345789M
13178456923875639284562345789N
Float/MAX_VALUE
(- Float/MAX_VALUE)
Double/MAX_VALUE
(- Double/MAX_VALUE)
(* 2 (bigdec Double/MAX_VALUE)) ])]
(are [x] (true? x)
(integer? v)
(number? v)
(not (decimal? v))
(not (float? v))))))
(deftest equality-tests
;; = only returns true for numbers that are in the same category,
;; where category is one of INTEGER, FLOATING, DECIMAL, RATIO.
(all-pairs-equal #'= [(byte 2) (short 2) (int 2) (long 2)
(bigint 2) (biginteger 2)])
(all-pairs-equal #'= [(float 2.0) (double 2.0)])
(all-pairs-equal #'= [(float 0.0) (double 0.0) (float -0.0) (double -0.0)])
(all-pairs-equal #'= [2.0M 2.00M])
(all-pairs-equal #'= [(float 1.5) (double 1.5)])
(all-pairs-equal #'= [1.50M 1.500M])
(all-pairs-equal #'= [0.0M 0.00M])
(all-pairs-equal #'= [(/ 1 2) (/ 2 4)])
(deftest unchecked-cast-num-obj
(do-template [prim-array cast]
(are [n]
(let [a (prim-array 1)]
(aset a 0 (cast n)))
(Byte. Byte/MAX_VALUE)
(Short. Short/MAX_VALUE)
(Integer. Integer/MAX_VALUE)
(Long. Long/MAX_VALUE)
(Float. Float/MAX_VALUE)
(Double. Double/MAX_VALUE))
byte-array
unchecked-byte
short-array
unchecked-short
char-array
unchecked-char
int-array
unchecked-int
long-array
unchecked-long
float-array
unchecked-float
double-array
unchecked-double))
(deftest unchecked-cast-num-prim
(do-template [prim-array cast]
(are [n]
(let [a (prim-array 1)]
(aset a 0 (cast n)))
Byte/MAX_VALUE
Short/MAX_VALUE
Integer/MAX_VALUE
Long/MAX_VALUE
Float/MAX_VALUE
Double/MAX_VALUE)
byte-array
unchecked-byte
short-array
unchecked-short
char-array
unchecked-char
int-array
unchecked-int
long-array
unchecked-long
float-array
unchecked-float
double-array
unchecked-double))
(deftest test-add
(are [x y] (= x y)
(+) 0
(+ 1) 1
(+ 1 2) 3
(+ 1 2 3) 6
(are [x y] (< (- x y) DELTA)
(+ 1.2) 1.2
(+ 1.1 2.4) 3.5
(+ 1.1 2.2 3.3) 6.6 )
(deftest test-subtract
(is (thrown? IllegalArgumentException (-)))
(are [x y] (= x y)
(- 1) -1
(- 1 2) -1
(- 1 2 3) -4
(are [x y] (< (- x y) DELTA)
(- 1.2) -1.2
(- 2.2 1.1) 1.1
(- 6.6 2.2 1.1) 3.3 )
(deftest test-multiply
(are [x y] (= x y)
(*) 1
(* 2) 2
(* 2 3) 6
(* 2 3 4) 24
(are [x y] (< (- x y) DELTA)
(* 1.2) 1.2
(* 2.0 1.2) 2.4
(* 3.5 2.0 1.2) 8.4 )
(deftest test-multiply-longs-at-edge
(are [x] (= x 9223372036854775808N)
(*' -1 Long/MIN_VALUE)
(*' Long/MIN_VALUE -1)
(* -1N Long/MIN_VALUE)
(* Long/MIN_VALUE -1N)
(* -1 (bigint Long/MIN_VALUE))
(* (bigint Long/MIN_VALUE) -1))
(is (thrown? ArithmeticException (* Long/MIN_VALUE -1)))
(is (thrown? ArithmeticException (* -1 Long/MIN_VALUE))))
(deftest test-divide
(are [x y] (= x y)
(/ 1) 1
(/ 2) 1/2
(/ 3 2) 3/2
(/ 4 2) 2
(/ 24 3 2) 4
(/ 24 3 2 -1) -4
(are [x y] (< (- x y) DELTA)
(/ 4.5 3) 1.5
(/ 4.5 3.0 3.0) 0.5 )
(deftest test-divide-bigint-at-edge
(are [x] (= x (-' Long/MIN_VALUE))
(/ Long/MIN_VALUE -1N)
(/ (bigint Long/MIN_VALUE) -1)
(/ (bigint Long/MIN_VALUE) -1N)
(quot Long/MIN_VALUE -1N)
(quot (bigint Long/MIN_VALUE) -1)
(quot (bigint Long/MIN_VALUE) -1N)))
(are [x y] (= x y)
(mod 4 2) 0
(mod 3 2) 1
(mod 6 4) 2
(mod 0 5) 0
; divide by zero
(is (thrown? ArithmeticException (rem 9 0)))
(is (thrown? ArithmeticException (rem 0 0)))
(are [x y] (= x y)
(rem 4 2) 0
(rem 3 2) 1
(rem 6 4) 2
(rem 0 5) 0
; divide by zero
(is (thrown? ArithmeticException (quot 9 0)))
(is (thrown? ArithmeticException (quot 0 0)))
(are [x y] (= x y)
(quot 4 2) 2
(quot 3 2) 1
(quot 6 4) 1
(quot 0 5) 0
(deftest test-even?
(are [x] (true? x)
(even? -4)
(not (even? -3))
(even? 0)
(not (even? 5))
(even? 8))
(is (thrown? IllegalArgumentException (even? 1/2)))
(is (thrown? IllegalArgumentException (even? (double 10)))))
(deftest test-odd?
(are [x] (true? x)
(not (odd? -4))
(odd? -3)
(not (odd? 0))
(odd? 5)
(not (odd? 8)))
(is (thrown? IllegalArgumentException (odd? 1/2)))
(is (thrown? IllegalArgumentException (odd? (double 10)))))
(deftest test-bit-shift-left
(are [x y] (= x y)
2r10 (bit-shift-left 2r1 1)
2r100 (bit-shift-left 2r1 2)
2r1000 (bit-shift-left 2r1 3)
2r00101110 (bit-shift-left 2r00010111 1)
2r00101110 (apply bit-shift-left [2r00010111 1])
0 (bit-shift-left 2r10 -1) ; truncated to least 6-bits, 63
(expt 2 32) (bit-shift-left 1 32)
(expt 2 16) (bit-shift-left 1 10000) ; truncated to least 6-bits, 16
)
(is (thrown? IllegalArgumentException (bit-shift-left 1N 1))))
(deftest test-bit-shift-right
(are [x y] (= x y)
2r0 (bit-shift-right 2r1 1)
2r010 (bit-shift-right 2r100 1)
2r001 (bit-shift-right 2r100 2)
2r000 (bit-shift-right 2r100 3)
2r0001011 (bit-shift-right 2r00010111 1)
2r0001011 (apply bit-shift-right [2r00010111 1])
0 (bit-shift-right 2r10 -1) ; truncated to least 6-bits, 63
1 (bit-shift-right (expt 2 32) 32)
1 (bit-shift-right (expt 2 16) 10000) ; truncated to least 6-bits, 16
-1 (bit-shift-right -2r10 1)
)
(is (thrown? IllegalArgumentException (bit-shift-right 1N 1))))
(deftest test-unsigned-bit-shift-right
(are [x y] (= x y)
2r0 (unsigned-bit-shift-right 2r1 1)
2r010 (unsigned-bit-shift-right 2r100 1)
2r001 (unsigned-bit-shift-right 2r100 2)
2r000 (unsigned-bit-shift-right 2r100 3)
2r0001011 (unsigned-bit-shift-right 2r00010111 1)
2r0001011 (apply unsigned-bit-shift-right [2r00010111 1])
0 (unsigned-bit-shift-right 2r10 -1) ; truncated to least 6-bits, 63
1 (unsigned-bit-shift-right (expt 2 32) 32)
1 (unsigned-bit-shift-right (expt 2 16) 10000) ; truncated to least 6-bits, 16
9223372036854775807 (unsigned-bit-shift-right -2r10 1)
)
(is (thrown? IllegalArgumentException (unsigned-bit-shift-right 1N 1))))
;; arrays
(deftest test-array-types
(are [x y z] (= (Class/forName x) (class y) (class z))
"[Z" (boolean-array 1) (booleans (boolean-array 1 true))
"[B" (byte-array 1) (bytes (byte-array 1 (byte 1)))
"[C" (char-array 1) (chars (char-array 1 \a))
"[S" (short-array 1) (shorts (short-array 1 (short 1)))
"[F" (float-array 1) (floats (float-array 1 1))
"[D" (double-array 1) (doubles (double-array 1 1))
"[I" (int-array 1) (ints (int-array 1 1))
"[J" (long-array 1) (longs (long-array 1 1))))
(deftest test-arbitrary-precision-subtract
(are [x y] (= x y)
9223372036854775808N (-' 0 -9223372036854775808)
clojure.lang.BigInt (class (-' 0 -9223372036854775808))
java.lang.Long (class (-' 0 -9223372036854775807))))
(deftest test-min-max
(testing "min/max on different numbers of floats and doubles"
(are [xmin xmax a]
(and (= (Float. xmin) (min (Float. a)))
(= (Float. xmax) (max (Float. a)))
(= xmin (min a))
(= xmax (max a)))
0.0 0.0 0.0)
(are [xmin xmax a b]
(and (= (Float. xmin) (min (Float. a) (Float. b)))
(= (Float. xmax) (max (Float. a) (Float. b)))
(= xmin (min a b))
(= xmax (max a b)))
-1.0 0.0 0.0 -1.0
-1.0 0.0 -1.0 0.0
0.0 1.0 0.0 1.0
0.0 1.0 1.0 0.0)
(are [xmin xmax a b c]
(and (= (Float. xmin) (min (Float. a) (Float. b) (Float. c)))
(= (Float. xmax) (max (Float. a) (Float. b) (Float. c)))
(= xmin (min a b c))
(= xmax (max a b c)))
-1.0 1.0 0.0 1.0 -1.0
-1.0 1.0 0.0 -1.0 1.0
-1.0 1.0 -1.0 1.0 0.0))
(testing "min/max preserves type of winner"
(is (= java.lang.Long (class (max 10))))
(is (= java.lang.Long (class (max 1.0 10))))
(is (= java.lang.Long (class (max 10 1.0))))
(is (= java.lang.Long (class (max 10 1.0 2.0))))
(is (= java.lang.Long (class (max 1.0 10 2.0))))
(is (= java.lang.Long (class (max 1.0 2.0 10))))
(is (= java.lang.Double (class (max 1 2 10.0 3 4 5))))
(is (= java.lang.Long (class (min 10))))
(is (= java.lang.Long (class (min 1.0 -10))))
(is (= java.lang.Long (class (min -10 1.0))))
(is (= java.lang.Long (class (min -10 1.0 2.0))))
(is (= java.lang.Long (class (min 1.0 -10 2.0))))
(is (= java.lang.Long (class (min 1.0 2.0 -10))))
(is (= java.lang.Double (class (min 1 2 -10.0 3 4 5))))))
(deftest test-abs
(are [in ex] (= ex (abs in))
-1 1
1 1
Long/MIN_VALUE Long/MIN_VALUE ;; special case!
-1.0 1.0
-0.0 0.0
##-Inf ##Inf
##Inf ##Inf
-123.456M 123.456M
-123N 123N
-1/5 1/5)
(is (NaN? (abs ##NaN))))
(deftest clj-868
(testing "min/max: NaN is contagious"
(letfn [(fnan? [^Float x] (Float/isNaN x))
(dnan? [^double x] (Double/isNaN x))]
(are [minmax]
(are [nan? nan zero]
(every? nan? (map minmax
[ nan zero zero]
[zero nan zero]
[zero zero nan]))
fnan? Float/NaN (Float. 0.0)
dnan? Double/NaN 0.0)
min
max))))
(deftest test-nan-comparison
(are [x y] (= x y)
(< 1000 Double/NaN) (< 1000 (Double. Double/NaN))
(<= 1000 Double/NaN) (<= 1000 (Double. Double/NaN))
(> 1000 Double/NaN) (> 1000 (Double. Double/NaN))
(>= 1000 Double/NaN) (>= 1000 (Double. Double/NaN))))
(deftest test-nan-as-operand
(testing "All numeric operations with NaN as an operand produce NaN as a result"
(let [nan Double/NaN
onan (cast Object Double/NaN)]
(are [x] (Double/isNaN x)
(+ nan 1)
(+ nan 0)
(+ nan 0.0)
(+ 1 nan)
(+ 0 nan)
(+ 0.0 nan)
(+ nan nan)
(- nan 1)
(- nan 0)
(- nan 0.0)
(- 1 nan)
(- 0 nan)
(- 0.0 nan)
(- nan nan)
(* nan 1)
(* nan 0)
(* nan 0.0)
(* 1 nan)
(* 0 nan)
(* 0.0 nan)
(* nan nan)
(/ nan 1)
(/ nan 0)
(/ nan 0.0)
(/ 1 nan)
(/ 0 nan)
(/ 0.0 nan)
(/ nan nan)
(+ onan 1)
(+ onan 0)
(+ onan 0.0)
(+ 1 onan)
(+ 0 onan)
(+ 0.0 onan)
(+ onan onan)
(- onan 1)
(- onan 0)
(- onan 0.0)
(- 1 onan)
(- 0 onan)
(- 0.0 onan)
(- onan onan)
(* onan 1)
(* onan 0)
(* onan 0.0)
(* 1 onan)
(* 0 onan)
(* 0.0 onan)
(* onan onan)
(/ onan 1)
(/ onan 0)
(/ onan 0.0)
(/ 1 onan)
(/ 0 onan)
(/ 0.0 onan)
(/ onan onan)
(+ nan onan)
(+ onan nan)
(- nan onan)
(- onan nan)
(* nan onan)
(* onan nan)
(/ nan onan)
(/ onan nan) ))))
viebel/klipse
http://localhost:5014/index-dev.html?cljs_in=(ns%20my.user%0A%20%20(%3Arequire%20%5Bclojure.test.check%20%3Aas%20tc%5D%0A%20%20%20%20%20%20%20%20%20%20%20%20%5Bclojure.test.check.generators%20%3Aas%20gen%5D%0A%20%20%20%20%20%20%20%20%20%20%20%20%5Bclojure.test.check.properties%20%3Aas%20prop%20%3Ainclude-macros%20true%5D))%0A%0A(def%20sort-idempotent-prop%0A%20%20(prop%2Ffor-all%20%5Bv%20(gen%2Fvector%20gen%2Fint)%5D%0A%20%20%20%20(%3D%20(sort%20v)%20(sort%20(sort%20v)))))%0A%0A(tc%2Fquick-check%20100%20sort-idempotent-prop)%0A&eval_only=1&external-libs=%5Bhttps%3A%2F%2Fraw.githubusercontent.com%2Fviebel%2Ftest.check%2Fmaster%2Fsrc%2Fmain%2Fclojure%2F%5D
(ns my.frame
(:require [viebel.a8a0349b00689c40571b0faaa36a9ae8.raw.foo :refer [square]]))
(square 19)
clj-kondo/clj-kondo
"}}}}
(:require [expectations.clojure.test :as t]))
(t/expecting "numeric behavior"
(t/expect (t/more-of {:keys [a b]} ;; bindings are recognized
even? a
odd? b)
{:a (* 2 13) :b (* 3 13)})
(t/expect pos? (* -3 -5)))
jmingtan/clonings
(ns scalars.scalars4
(:require [clojure.test :refer [deftest testing is]]))
;; Symbols are identifiers that can refer to other values:
;; https://clojure.org/reference/data_structures#Symbols