repl和测试运行器之间的不一致

时间:2015-09-15 12:04:06

标签: testing clojure macros

我在测试clojure宏时遇到了一些问题。当我通过repl放置代码时,它的行为与预期一致,但是当我试图在测试中期望这种行为时,我会回来取而代之。我有一种感觉,它与测试运行器如何处理宏扩展有关,但我不确定到底发生了什么。任何建议/替代方法来测试此代码表示赞赏。

以下是我尝试测试

的宏的简化示例
(defmacro macro-with-some-validation
  [-name- & forms]
    (assert-symbols [-name-])
    `(defn ~-name- [] (println "You passed the validation")))

  (macroexpand-1 (read-string "(macro-with-some-validation my-name (forms))"))
  ;; ->
  (clojure.core/defn my-name [] (clojure.core/println "You passed the validation"))

传递给repl时

  (macroexpand-1 (read-string "(macro-with-some-validation 'not-symbol (forms))"))
  ;; ->
  rulesets.core-test=> Exception Non-symbol passed in to function.  chibi-1-0-0.core/assert-symbols (core.clj:140)

但是经过测试

  (deftest macro-with-some-validation-bad
    (testing "Passing in a non-symbol to the macro"
(is (thrown? Exception
             (macroexpand-1 (read-string "(macro-with-some-validation 'not-symbol (forms))"))))))

  ;; after a lein test ->
  FAIL in (macro-with-some-validation-bad) (core_test.clj:50)
  Passing in a non-symbol to the macro
  expected: (thrown? Exception (macroexpand-1 (read-string "(macro-with-some-validation 'not-symbol (forms))")))
    actual: nil

感谢。

编辑:忘记包含断言符号的来源以防其重要

(defn assert-symbol [symbol]
  (if (not (instance? clojure.lang.Symbol symbol))
        (throw (Exception. "Non-symbol passed in to function."))))

(defn assert-symbols [symbols]
  (if (not (every? #(instance? clojure.lang.Symbol %) symbols))
    (throw (Exception. "Non-symbol passed in to function."))))

1 个答案:

答案 0 :(得分:0)

将我的读取字符串更改为`之后,我能够让代码再次运行。但是,读取字符串无法正常工作仍然很奇怪。谢谢你的帮助。

相关问题