如何获得Clojure:pre& :post报告他们的失败值? [英] How can I get Clojure :pre & :post to report their failing value?

查看:154
本文介绍了如何获得Clojure:pre& :post报告他们的失败值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(defn string-to-string [s1] 
  {:pre  [(string? s1)]
   :post [(string? %)]}
  s1)



我喜欢:pre和:post条件,他们让我找出当我把方钉在圆孔更快。也许是错了,但我喜欢使用他们作为一种穷人类型检查器。这不是哲学,这是一个简单的问题。

I like :pre and :post conditions, they allow me to figure out when I have put "square pegs in round holes" more quickly. Perhaps it is wrong, but I like using them as a sort of poor mans type checker. This isn't philosophy though, this is a simple question.

在上面的代码中,我应该很容易能够确定 s1 :pre 条件中的函数参数。类似地,:post 条件中的始终是函数返回值。

It seems in the above code that I should easily be able to determine that s1 is a function argument in the :pre condition. Similarily, % in the :post condition is always the function return value.

我想要打印的值 s1 当这些相应的条件在AssertionError中失败。所以我得到像

What I would like is to print the value of s1 or % when either of these respective conditions fail within the AssertionError. So I get something like

(string-to-string 23)

AssertionError Assert failed: (string? s1) 
(pr-str s1) => 23 

对于每个被标识为来自函数参数列表的变量,AssertionError包含一行并在失败的测试中引用。当函数的返回值失败:post 条件时,我也想要类似的东西。

With the AssertionError containing a single line for every variable that was identified as being from the function argument list and that was referenced in the failing test. I would also like something similar when the return value of the function fails the :post condition.

这将使它很容易快速发现如何滥用一个函数,当尝试从AssertionError诊断。它至少会让我知道值是 nil 还是一个实际值(这是我最常见的错误)。

This would make it trivial to quickly spot how I misused a function when trying to diagnose from the AssertionError. It would at least let me know if the value is nil or an actual value (which is the most common error I make).

我有一些想法,这可以用一个宏,但我想知道是否有任何安全和全局的方式基本上只是重新定义(defn (fn 和朋友这样:pre :post 也会打印导致测试失败的值。

I have some ideas that this could be done with a macro, but I was wondering if there was any safe and global way to basically just redefine what (defn and (fn and friends do so that :pre and :post would also print the value(s) that lead to the test failing.

推荐答案

a href =http://clojuredocs.org/clojure_core/clojure.test/is> 是 宏 clojure.test

You could wrap your predicate with the is macro from clojure.test

(defn string-to-string [s1] 
  {:pre  [(is (string? s1))]
   :post [(is (string? %))]}
 s1)

然后你得到:

(string-to-string 10)
;FAIL in clojure.lang.PersistentList$EmptyList@1 (scratch.clj:5)
;expected: (string? s1)
;actual: (not (string? 10))

这篇关于如何获得Clojure:pre& :post报告他们的失败值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆