babashka/test/babashka/main_test.clj

401 lines
16 KiB
Clojure
Raw Normal View History

2019-08-09 12:51:42 +00:00
(ns babashka.main-test
(:require
2019-08-13 22:19:15 +00:00
[babashka.main :as main]
2019-08-28 21:42:15 +00:00
[babashka.test-utils :as test-utils]
[clojure.edn :as edn]
2019-12-18 15:38:21 +00:00
[clojure.java.io :as io]
2019-08-28 21:42:15 +00:00
[clojure.java.shell :refer [sh]]
[clojure.string :as str]
2019-11-11 20:14:30 +00:00
[clojure.test :as test :refer [deftest is testing]]
[sci.core :as sci]))
2019-08-09 12:51:42 +00:00
2020-04-08 21:12:16 +00:00
(defmethod clojure.test/report :begin-test-var [m]
(println "===" (-> m :var meta :name))
(println))
2019-08-09 21:08:49 +00:00
(defn bb [input & args]
2019-12-07 10:48:57 +00:00
(edn/read-string (apply test-utils/bb (when (some? input) (str input)) (map str args))))
2019-08-09 21:08:49 +00:00
(deftest parse-opts-test
(is (= 123 (bb nil "(println 123)")))
(is (= 123 (bb nil "-e" "(println 123)")))
(is (= 123 (bb nil "--eval" "(println 123)")))
(testing "distinguish automatically between expression or file name"
(is (= {:result 8080} (bb nil "test/babashka/scripts/tools.cli.bb")))
(is (thrown-with-msg? Exception #"does not exist" (bb nil "foo.clj")))
(is (thrown-with-msg? Exception #"does not exist" (bb nil "-help"))))
2020-01-31 16:33:01 +00:00
(is (= "1 2 3" (bb nil "-e" "(require '[clojure.string :as str1])" "-e" "(str1/join \" \" [1 2 3])")))
(is (= '("-e" "1") (bb nil "-e" "*command-line-args*" "--" "-e" "1"))))
2020-01-12 16:40:41 +00:00
(deftest print-error-test
(is (thrown-with-msg? Exception #"java.lang.NullPointerException"
(bb nil "(subs nil 0 0)"))))
2019-08-09 21:08:49 +00:00
(deftest main-test
(testing "-io behaves as identity"
2020-03-20 16:16:42 +00:00
(is (= "foo\nbar\n" (test-utils/bb "foo\nbar\n" "-io" "*input*"))))
2019-08-09 21:08:49 +00:00
(testing "if and when"
2019-12-20 22:51:24 +00:00
(is (= 1 (bb 0 '(if (zero? *input*) 1 2))))
(is (= 2 (bb 1 '(if (zero? *input*) 1 2))))
(is (= 1 (bb 0 '(when (zero? *input*) 1))))
(is (nil? (bb 1 '(when (zero? *input*) 1)))))
(testing "and and or"
2019-12-20 22:51:24 +00:00
(is (= false (bb 0 '(and false true *input*))))
(is (= 0 (bb 0 '(and true true *input*))))
(is (= 1 (bb 1 '(or false false *input*))))
(is (= false (bb false '(or false false *input*))))
(is (= 3 (bb false '(or false false *input* 3)))))
2019-08-09 21:08:49 +00:00
(testing "fn"
2019-12-20 22:51:24 +00:00
(is (= 2 (bb 1 "(#(+ 1 %) *input*)")))
(is (= [1 2 3] (bb 1 "(map #(+ 1 %) [0 1 2])")))
2019-12-20 22:51:24 +00:00
(is (= 1 (bb 1 "(#(when (odd? *input*) *input*))"))))
2019-08-09 21:08:49 +00:00
(testing "map"
(is (= [1 2 3] (bb 1 '(map inc [0 1 2])))))
2019-08-09 21:08:49 +00:00
(testing "keep"
(is (= [false true false] (bb 1 '(keep odd? [0 1 2])))))
(testing "->"
2019-12-20 22:51:24 +00:00
(is (= 4 (bb 1 '(-> *input* inc inc (inc))))))
(testing "->>"
2019-12-20 22:51:24 +00:00
(is (= 10 (edn/read-string (test-utils/bb "foo\n\baar\baaaaz" "-i" "(->> *input* (map count) (apply max))")))))
(testing "literals"
(is (= {:a 4
:b {:a 2}
:c [1 1]
:d #{1 2}}
2019-12-20 22:51:24 +00:00
(bb 1 '{:a (+ 1 2 *input*)
:b {:a (inc *input*)}
:c [*input* *input*]
:d #{*input* (inc *input*)}}))))
(testing "shuffle the contents of a file"
(let [in "foo\n Clojure is nice. \nbar\n If you're nice to clojure. "
in-lines (set (str/split in #"\n"))
out (test-utils/bb in
"-io"
2019-12-20 22:51:24 +00:00
(str '(shuffle *input*)))
out-lines (set (str/split out #"\n"))]
2019-08-13 22:19:15 +00:00
(is (= in-lines out-lines))))
(testing "find occurrences in file by line number"
2019-08-09 21:08:49 +00:00
(is (= '(1 3)
(->
(bb "foo\n Clojure is nice. \nbar\n If you're nice to clojure. "
"-i"
2019-12-20 22:51:24 +00:00
"(map-indexed #(-> [%1 %2]) *input*)")
(bb "(keep #(when (re-find #\"(?i)clojure\" (second %)) (first %)) *input*)"))))))
2019-08-13 22:19:15 +00:00
2019-12-07 10:48:57 +00:00
(deftest println-test
(is (= "hello\n" (test-utils/bb nil "(println \"hello\")"))))
2019-08-13 22:19:15 +00:00
(deftest input-test
2019-12-20 22:51:24 +00:00
(testing "bb doesn't wait for input if *input* isn't used"
2019-08-13 22:19:15 +00:00
(is (= "2\n" (with-out-str (main/main "(inc 1)"))))))
2019-08-14 11:38:39 +00:00
(deftest System-test
(let [res (bb nil "-f" "test/babashka/scripts/System.bb")]
(is (= "bar" (second res)))
(doseq [s res]
(is (not-empty s))))
(let [out (java.io.StringWriter.)
err (java.io.StringWriter.)
2019-12-07 10:48:57 +00:00
exit-code (sci/with-bindings {sci/out out
sci/err err}
(binding [*out* out *err* err]
(main/main "--time" "(println \"Hello world!\") (System/exit 42)")))]
(is (= (str out) "Hello world!\n"))
(is (re-find #"took" (str err)))
(is (= 42 exit-code))))
2019-08-15 04:28:00 +00:00
2019-08-16 20:22:58 +00:00
(deftest malformed-command-line-args-test
2019-08-15 04:28:00 +00:00
(is (thrown-with-msg? Exception #"File does not exist: non-existing\n"
2019-12-08 11:46:06 +00:00
(bb nil "-f" "non-existing"))))
2019-08-16 20:22:58 +00:00
2019-08-17 15:38:24 +00:00
(deftest ssl-test
2019-12-07 10:48:57 +00:00
(let [resp (bb nil "(slurp \"https://www.google.com\")")]
2019-08-17 20:19:46 +00:00
(is (re-find #"doctype html" resp))))
2019-08-16 20:22:58 +00:00
(deftest stream-test
2019-12-20 22:51:24 +00:00
(is (= "2\n3\n4\n" (test-utils/bb "1 2 3" "--stream" "(inc *input*)")))
(is (= "2\n3\n4\n" (test-utils/bb "{:x 2} {:x 3} {:x 4}" "--stream" "(:x *input*)")))
2019-08-16 20:22:58 +00:00
(let [x "foo\n\bar\n"]
2019-12-20 22:51:24 +00:00
(is (= x (test-utils/bb x "--stream" "-io" "*input*"))))
2019-08-16 20:22:58 +00:00
(let [x "f\n\b\n"]
2019-12-20 22:51:24 +00:00
(is (= x (test-utils/bb x "--stream" "-io" "(subs *input* 0 1)")))))
2019-08-17 21:44:17 +00:00
(deftest load-file-test
(let [tmp (java.io.File/createTempFile "script" ".clj")]
2020-03-20 14:12:15 +00:00
(spit tmp "(ns foo) (defn foo [x y] (+ x y)) (defn bar [x y] (* x y))")
(is (= "120\n" (test-utils/bb nil (format "(load-file \"%s\") (foo/bar (foo/foo 10 30) 3)"
(.getPath tmp)))))
(testing "namespace is restored after load file"
(is (= 'start-ns
(bb nil (format "(ns start-ns) (load-file \"%s\") (ns-name *ns*)"
(.getPath tmp))))))))
2019-08-18 06:40:28 +00:00
(deftest eval-test
(is (= "120\n" (test-utils/bb nil "(eval '(do (defn foo [x y] (+ x y))
(defn bar [x y] (* x y))
(bar (foo 10 30) 3)))"))))
2019-08-18 06:40:28 +00:00
(deftest preloads-test
;; THIS TEST REQUIRES:
;; export BABASHKA_PRELOADS='(defn __bb__foo [] "foo") (defn __bb__bar [] "bar")'
(when (System/getenv "BABASHKA_PRELOADS_TEST")
(is (= "foobar" (bb nil "(str (__bb__foo) (__bb__bar))")))))
(deftest io-test
(is (true? (bb nil "(.exists (io/file \"README.md\"))")))
(is (true? (bb nil "(.canWrite (io/file \"README.md\"))"))))
2019-08-28 21:42:15 +00:00
(deftest pipe-test
(when test-utils/native?
(let [out (:out (sh "bash" "-c" "./bb -o '(range)' |
2019-12-20 22:51:24 +00:00
./bb --stream '(* *input* *input*)' |
2019-08-28 21:42:15 +00:00
head -n10"))
out (str/split-lines out)
out (map edn/read-string out)]
2019-08-29 11:57:39 +00:00
(is (= (take 10 (map #(* % %) (range))) out))))
(when test-utils/native?
(let [out (:out (sh "bash" "-c" "./bb -O '(repeat \"dude\")' |
2019-12-20 22:51:24 +00:00
./bb --stream '(str *input* \"rino\")' |
./bb -I '(take 3 *input*)'"))
2019-08-29 11:57:39 +00:00
out (edn/read-string out)]
(is (= '("duderino" "duderino" "duderino") out)))))
2019-08-29 09:29:41 +00:00
(deftest lazy-text-in-test
(when test-utils/native?
2019-12-20 22:51:24 +00:00
(let [out (:out (sh "bash" "-c" "yes | ./bb -i '(take 2 *input*)'"))
2019-08-29 09:29:41 +00:00
out (edn/read-string out)]
(is (= '("y" "y") out)))))
(deftest future-test
(is (= 6 (bb nil "@(future (+ 1 2 3))"))))
2020-02-08 22:43:15 +00:00
(deftest promise-test
(is (= :timeout (bb nil "(deref (promise) 1 :timeout)")))
(is (= :ok (bb nil "(let [x (promise)]
(deliver x :ok)
@x)"))))
(deftest process-builder-test
(is (str/includes? (bb nil "
(def ls (-> (ProcessBuilder. [\"ls\"]) (.start)))
2020-01-08 10:48:40 +00:00
(def input (.getOutputStream ls))
(.write (io/writer input) \"hello\") ;; dummy test just to see if this works
(def output (.getInputStream ls))
2019-12-23 10:12:20 +00:00
(assert (int? (.waitFor ls)))
(slurp output)")
"LICENSE")))
(deftest create-temp-file-test
(let [temp-dir-path (System/getProperty "java.io.tmpdir")]
(is (= true
(bb nil (format "(let [tdir (io/file \"%s\")
tfile
(File/createTempFile \"ctf\" \"tmp\" tdir)]
(.deleteOnExit tfile) ; for cleanup
(.exists tfile))"
temp-dir-path))))))
(deftest wait-for-port-test
(let [server (test-utils/start-server! 1777)]
2019-12-23 10:12:20 +00:00
(is (= 1777 (:port (bb nil "(wait/wait-for-port \"127.0.0.1\" 1777)"))))
(test-utils/stop-server! server)
2019-12-31 13:18:00 +00:00
(is (= :timed-out (bb nil "(wait/wait-for-port \"127.0.0.1\" 1777 {:default :timed-out :timeout 50})"))))
(let [edn (bb nil (io/file "test" "babashka" "scripts" "socket_server.bb"))]
(is (= "127.0.0.1" (:host edn)))
(is (= 1777 (:port edn)))
(is (number? (:took edn)))))
(deftest wait-for-path-test
(let [temp-dir-path (System/getProperty "java.io.tmpdir")]
(is (not= :timed-out
(bb nil (format "(let [tdir (io/file \"%s\")
tfile
(File/createTempFile \"wfp\" \"tmp\" tdir)
tpath (.getPath tfile)]
(.delete tfile) ; delete now, but re-create it in a future
(future (Thread/sleep 50) (shell/sh \"touch\" tpath))
(wait/wait-for-path tpath
{:default :timed-out :timeout 100})
(.delete tfile))"
temp-dir-path))))
(is (= :timed-out
(bb nil (format "(let [tdir (io/file \"%s\")
tfile
(File/createTempFile \"wfp-to\" \"tmp\" tdir)
tpath (.getPath tfile)]
(.delete tfile) ; for timing out test and cleanup
(wait/wait-for-path tpath
{:default :timed-out :timeout 100}))"
temp-dir-path))))))
2019-09-07 08:43:53 +00:00
(deftest tools-cli-test
2019-09-11 21:37:25 +00:00
(is (= {:result 8080} (bb nil "test/babashka/scripts/tools.cli.bb"))))
(deftest try-catch-test
2020-03-20 22:39:28 +00:00
(is (zero? (bb nil "(try (/ 1 0) (catch ArithmeticException _ 0))")))
(is (= :got-it (bb nil "
(defn foo []
(throw (java.util.MissingResourceException. \"o noe!\" \"\" \"\")))
(defn bar
[]
(try (foo)
(catch java.util.MissingResourceException _
:got-it)))
(bar)
"))))
(deftest reader-conditionals-test
2020-02-19 22:58:49 +00:00
(is (= :hello (bb nil "#?(:bb :hello :default :bye)")))
(is (= :hello (bb nil "#?(:clj :hello :bb :bye)")))
(is (= [1 2] (bb nil "[1 2 #?@(:bb [] :clj [1])]"))))
2019-11-11 20:14:30 +00:00
(deftest csv-test
(is (= '(["Adult" "87727"] ["Elderly" "43914"] ["Child" "33411"] ["Adolescent" "29849"]
["Infant" "15238"] ["Newborn" "10050"] ["In Utero" "1198"])
(bb nil (.getPath (io/file "test" "babashka" "scripts" "csv.bb"))))))
2019-11-13 17:00:57 +00:00
2019-11-24 12:35:34 +00:00
(deftest assert-test ;; assert was first implemented in bb but moved to sci later
2019-11-13 17:00:57 +00:00
(is (thrown-with-msg? Exception #"should-be-true"
(bb nil "(def should-be-true false) (assert should-be-true)"))))
2019-11-13 20:57:05 +00:00
(deftest Pattern-test
(is (= ["1" "2" "3"]
(bb nil "(vec (.split (java.util.regex.Pattern/compile \"f\") \"1f2f3\"))")))
(is (true? (bb nil "(some? java.util.regex.Pattern/CANON_EQ)"))))
(deftest writer-test
(let [tmp-file (java.io.File/createTempFile "bbb" "bbb")
path (.getPath tmp-file)]
(bb nil (format "(with-open [w (io/writer \"%s\")]
(.write w \"foobar\n\")
(.append w \"barfoo\n\")
nil)"
path))
(is (= "foobar\nbarfoo\n" (slurp path)))))
(deftest binding-test
(is (= 6 (bb nil "(def w (java.io.StringWriter.))
(binding [clojure.core/*out* w]
(println \"hello\"))
(count (str w))"))))
(deftest with-out-str-test
(is (= 6 (bb nil "(count (with-out-str (println \"hello\")))"))))
(deftest with-in-str-test
(is (= 5 (bb nil "(count (with-in-str \"hello\" (read-line)))"))))
(deftest java-nio-test
(let [f (java.io.File/createTempFile "foo" "bar")
temp-path (.getPath f)
p (.toPath (io/file f))
p' (.resolveSibling p "f2")
f2 (.toFile p')]
(bb nil (format
"(let [f (io/file \"%s\")
2020-01-08 10:48:40 +00:00
p (.toPath (io/file f))
p' (.resolveSibling p \"f2\")]
(.delete (.toFile p'))
(dotimes [_ 2]
(try
(java.nio.file.Files/copy p p' (into-array java.nio.file.CopyOption []))
(catch java.nio.file.FileAlreadyExistsException _
(java.nio.file.Files/copy p p' (into-array [java.nio.file.StandardCopyOption/REPLACE_EXISTING]))))))"
temp-path))
(is (.exists f2))))
2019-12-07 10:48:57 +00:00
(deftest future-print-test
(testing "the root binding of sci/*out*"
2019-12-18 08:38:45 +00:00
(is (= "hello" (bb nil "@(future (prn \"hello\"))")))))
2019-12-07 10:48:57 +00:00
2019-12-18 12:46:07 +00:00
(deftest Math-test
(is (== 8.0 (bb nil "(Math/pow 2 3)"))))
2019-12-18 16:01:00 +00:00
(deftest Base64-test
(is (= "babashka"
(bb nil "(String. (.decode (java.util.Base64/getDecoder) (.encode (java.util.Base64/getEncoder) (.getBytes \"babashka\"))))"))))
(deftest Thread-test
(is (= "hello" (bb nil "(doto (java.lang.Thread. (fn [] (prn \"hello\"))) (.start) (.join)) nil"))))
2019-12-20 22:51:24 +00:00
(deftest dynvar-test
(is (= 1 (bb nil "(binding [*command-line-args* 1] *command-line-args*)")))
(is (= 1 (bb nil "(binding [*input* 1] *input*)"))))
2019-12-22 16:42:21 +00:00
(deftest file-in-error-msg-test
(is (thrown-with-msg? Exception #"error.bb"
(bb nil (.getPath (io/file "test" "babashka" "scripts" "error.bb"))))))
2019-12-22 19:09:52 +00:00
(deftest compatibility-test
(is (true? (bb nil "(set! *warn-on-reflection* true)"))))
(deftest clojure-main-repl-test
(is (= "\"> foo!\\nnil\\n> \"\n" (test-utils/bb nil "
(defn foo [] (println \"foo!\"))
(with-out-str
(with-in-str \"(foo)\"
(clojure.main/repl :init (fn []) :prompt (fn [] (print \"> \")))))"))))
(deftest command-line-args-test
(is (true? (bb nil "(nil? *command-line-args*)")))
(is (= ["1" "2" "3"] (bb nil "*command-line-args*" "1" "2" "3"))))
(deftest need-constructors-test
(testing "the clojure.lang.Delay constructor works"
(is (= 1 (bb nil "@(delay 1)"))))
(testing "the clojure.lang.MapEntry constructor works"
(is (true? (bb nil "(= (first {1 2}) (clojure.lang.MapEntry. 1 2))")))))
(deftest uberscript-test
(let [tmp-file (java.io.File/createTempFile "uberscript" ".clj")]
(.deleteOnExit tmp-file)
(is (empty? (bb nil "--uberscript" (.getPath tmp-file) "-e" "(System/exit 1)")))
(is (= "(System/exit 1)" (slurp tmp-file)))))
(deftest unrestricted-access
(testing "babashka is allowed to mess with built-in vars"
(is (= 1 (bb nil "
(def inc2 inc) (alter-var-root #'clojure.core/inc (constantly dec))
(let [res (inc 2)]
(alter-var-root #'clojure.core/inc (constantly inc2))
res)")))))
(deftest pprint-test
(testing "writer"
(is (string? (bb nil "(let [sw (java.io.StringWriter.)] (clojure.pprint/pprint (range 10) sw) (str sw))")))))
2020-03-06 09:33:22 +00:00
(deftest read-string-test
(testing "namespaced keyword via alias"
(is (= :clojure.string/foo
(bb nil "(ns foo (:require [clojure.string :as str])) (read-string \"::str/foo\")")))))
2020-03-20 16:16:42 +00:00
(deftest available-stream-test
(is (= 0 (bb nil "(.available System/in)"))))
2020-03-22 10:47:02 +00:00
(deftest file-reader-test
(when (str/includes? (str/lower-case (System/getProperty "os.name")) "linux")
(let [v (bb nil "(slurp (io/reader (java.io.FileReader. \"/proc/loadavg\")))")]
(prn "output:" v)
(is v))))
(deftest download-and-extract-test
(is (try (= 6 (bb nil (io/file "test" "babashka" "scripts" "download_and_extract_zip.bb")))
(catch Exception e
(is (str/includes? (str e) "timed out"))))))
(deftest get-message-on-exception-info-test
(is "foo" (bb nil "(try (throw (ex-info \"foo\" {})) (catch Exception e (.getMessage e)))")))
(deftest pushback-reader-test
(is (= "foo" (bb nil "
(require '[clojure.java.io :as io])
(let [pb (java.io.PushbackInputStream. (java.io.ByteArrayInputStream. (.getBytes \"foo\")))]
(.unread pb (.read pb))
(slurp pb))"))))
2019-12-18 08:38:45 +00:00
;;;; Scratch
(comment
(dotimes [_ 10] (wait-for-port-test)))