2016-01-22 78 views
3

繼此SO post之後,我想在我的函數中打印前提條件的值。Clojure:破解前的報告失敗值

我有一個dir?輔助函數(隨意跳過這一項):

(defn dir? [s] 
    "returns true if the string passed is is an existing directory" 
    (->> (clojure.java.io/file s) 
     ((juxt #(.exists %) #(.isDirectory %))) 
     (every? true?))) 

它工作得很好,並使用is宏觀然而,在以下情況下(可能是解構)失敗對我來說,我得到了一些不錯的錯誤信息,我可以看到兩個測試並獲得通過的參數:

(is (dir? (io/file "resources/static"))) ;; => true 

(is (dir? (io/file "resources/statice"))) ;; typo, error below 

FAIL in [email protected] (boot.user4515592986834245937.clj:86) expected: (dir? (io/file "resources/statice")) actual: (not (dir? #object[java.io.File 0x6730a420 "resources/statice"]))

然而,試圖用我的時候噸的前提:pre,我得到一個醜陋的錯誤:

(defn make-something 
    [&{:keys [dir] 
    :or {dir "default-dir"}}] 
    {:pre [(is (dir? (clojure.java.io/file dir)))]} 
    ;;... do something with these 
) 

(make-something :dir "resources/statices") ;; doesn't exist 

clojure.lang.Compiler$CompilerException: java.lang.AssertionError: Assert failed: (is (dir? (io/file dir))), compiling:(boot.user4515592986834245937.clj:80:12) java.lang.AssertionError: Assert failed: (is (dir? (io/file dir)))

如何我在函數得到一個不錯的錯誤消息,就像上面的那個?

萬一它很重要,我使用Clojure 1.7。

+0

應該在stdout中打印「nice」錯誤消息。 – DanLebrero

+1

memfn在clojure 1.0之前被depricure,#(。isDirectory ...)形式現在更爲普通 –

+0

@ArthurUlfeldt哦有趣,我沒看到那個地方。你從哪裏得到這些信息?它不在源代碼中https://github.com/clojure/clojure/blob/clojure-1.7.0/src/clj/clojure/core.clj#L3717 – nha

回答

1

您需要檢查您的代碼(dir?函數)。以下片段適用於我:

(require '[clojure.java.io :as io]) 

(defn dir? [s] 
    (let [dir (io/file s)] 
    (and (.exists dir) 
     (.isDirectory dir)))) 

(defn make-something 
    [& {:keys [dir] :or {dir "default-dir"}}] 
    {:pre [(is (dir? dir))]} 
    (println dir)) 

(make-something :dir "/tmp") 
out => /tmp 
ret => nil 

(make-something :dir "/xxxx") 
FAIL in [email protected] (form-init3332271312167175068.clj:1) 
expected: (dir? dir) 
actual: (not (dir? "/xxxx")) 

AssertionError Assert failed: (is (dir? dir)) user/make-sth (form-init3332271312167175068.clj:1) 
+0

這是因爲我在Arthur的評論後手工編輯了代碼。你的代碼現在在我的REPL中起作用,所以我接受了你的答案(儘管Clojure 1.8 - 我沒有在原始問題中用1.7進行測試)。 – nha