我怎样才能获得 Clojure :pre &:post 报告他们的失败价值? [英] How can I get Clojure :pre & :post to report their failing value?
问题描述
(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.
当这些条件中的任何一个在 AssertionError 中失败时,我想要打印 s1
或 %
的值.所以我得到了类似的东西
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.
推荐答案
你可以用 is 包裹你的谓词
来自 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屋!