clojure.specexercise-fn 工作时遇到一些问题

Ste*_* B. 1 clojure clojure.spec

在尝试使用spec库时,我在尝试使用exercise-fn时遇到错误。我已将其简化为主指南页面上发布的示例,没有任何更改。

相关代码:

(ns spec1
  (:require [clojure.spec.alpha :as s]))

;;this and the fdef are literal copies from the example page
(defn adder [x] #(+ x %))

(s/fdef adder
  :args (s/cat :x number?)
  :ret (s/fspec :args (s/cat :y number?)
                :ret number?)
  :fn #(= (-> % :args :x) ((:ret %) 0)))
Run Code Online (Sandbox Code Playgroud)

现在,输入以下内容

(s/exercise-fn adder)
Run Code Online (Sandbox Code Playgroud)

给出错误:

Exception No :args spec found, can't generate  clojure.spec.alpha/exercise-fn (alpha.clj:1833)
Run Code Online (Sandbox Code Playgroud)

使用的依赖项/版本,[org.clojure/clojure "1.9.0-beta3"] [org.clojure/tools.logging "0.4.0"] [org.clojure/test.check "0.9.0"]

任何人都知道为什么会出现这种情况吗?谢谢。

Ala*_*son 5

您需要对函数名称进行反引号,这将添加名称空间前缀:

(s/exercise-fn `adder)
Run Code Online (Sandbox Code Playgroud)

例如,在我的测试代码中:

(s/fdef ranged-rand
  :args (s/and
          (s/cat :start int? :end int?)
          #(< (:start %) (:end %) 1e9)) ; need add 1e9 limit to avoid integer overflow
  :ret int?
  :fn (s/and #(>= (:ret %) (-> % :args :start))
             #(< (:ret %) (-> % :args :end))))

(dotest
  (when true
    (stest/instrument `ranged-rand)
    (is (thrown? Exception (ranged-rand 8 5))))
  (spyx (s/exercise-fn `ranged-rand)))
Run Code Online (Sandbox Code Playgroud)

结果是:

(s/exercise-fn (quote tst.tupelo.x.spec/ranged-rand)) 
  => ([(-2 0) -1] [(-4 1) -1] [(-2 0) -2] [(-1 0) -1] [(-14 6) -4] 
      [(-36 51) 45] [(-28 -3) -7] [(0 28) 27] [(-228 -53) -130] [(-2 0) -1])
Run Code Online (Sandbox Code Playgroud)

tst.tupelo.x.spec/ranged-rand请注意,使用了命名空间限定的函数名称。