Search code examples
clojureclojure.spec

Having some trouble getting clojure.spec exercise-fn working


In trying to use spec library, I'm getting errors in attempting to use exercise-fn. I've reduced this to the posted example at the main guide page with no change.

relevant code:

(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)))

Now, typing the following

(s/exercise-fn adder)

gives the error:

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

Dependencies/versions used, [org.clojure/clojure "1.9.0-beta3"] [org.clojure/tools.logging "0.4.0"] [org.clojure/test.check "0.9.0"]

Anyone have any ideas as to why this is breaking? Thanks.


Solution

  • You need to backquote the function name, which will add the namespace prefix:

    (s/exercise-fn `adder)
    

    For example, in my test code:

    (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)))
    

    Which results in:

    (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])
    

    Note that the namespace-qualified function name tst.tupelo.x.spec/ranged-rand is used.