如何在Clojure测试中停用日志?

时间:2019-06-04 16:06:46

标签: testing logging clojure

问题

我想在测试主体内给[ { "ID": 58896, "type": "verification_step", "step": "GMLC/E911/CMAS Significant" }, { "ID": 58895, "type": "verification_step", "step": "Outage Agreed w/ Business" } ] 做类似行为的黑洞,以保持日志输出看起来整洁。

print

我希望test-thing能够调用(deftest some-test (testing "something" (logless (is (= 22 (test-thing 14)))))) 以及其他类似的对println的调用,并且希望那些东西不再污染我的测试输出。

总体上有公认的方法吗?

我找到了这个人(with-out-str),但是它捕获的是字符串,而不是我想要的字符串。

背景

我对Clojure还是陌生的,主要来自JavaScript世界。到目前为止爆炸!但是还有很多东西需要我学习。

在Clojure中,而不是Clojure.script(如果有关系的话)

1 个答案:

答案 0 :(得分:2)

只需使用with-out-str,然后忽略字符串即可。

请注意,这不会捕获错误消息或Java库中的消息。如果您想捕获和/或取消此输出,我在the Tupelo library中编写了3个其他函数,您可能会觉得有用:

代码如下:

   (defmacro with-system-err-str
     "Evaluates exprs in a context in which JVM System/err is bound to a fresh
     PrintStream.  Returns the string created by any nested printing calls."
     [& body]
     `(let [baos# (ByteArrayOutputStream.)
            ps#   (PrintStream. baos#)]
        (System/setErr ps#)
        ~@body
        (System/setErr System/err)
        (.close ps#)
        (.toString baos#)))

如果需要,可以这样创建一个新的宏:

(defmacro with-printing-suppressed
  "Evaluates exprs in a context in which JVM System/err and System/out captured & discarded."
  [& body]
  `(let [baos# (ByteArrayOutputStream.)
         ps#   (PrintStream. baos#)
         s#    (new java.io.StringWriter)]
     (System/setErr ps#)
     (System/setOut ps#)
     (binding [*err* s#
               *out* s#]
       (let [result# (do ~@body)]
         (.close ps#)
         (System/setErr System/err)
         (System/setOut System/out)
         result#))))

(defn stuff []
  (println "***** doing stuff *****")
  42)

然后对其进行测试:

  (println "calling - before")
  (is= 42 (with-printing-suppressed 
            (stuff)))
  (println "calling - after")

结果:

calling - before
calling - after