如何制作自定义clojure.spec生成器?

时间:2017-10-05 18:47:18

标签: clojure clojure.spec

我试图规范以下名为Connection的数据结构:

{:id "some string" :channel "instance of org.httpkit.server.AsyncChannel" }

这是我的规格:

(defn make-channel []
  (proxy [AsyncChannel] [nil nil]
    (toString [] "mock AsyncChannel")))

(defn channel-gen
  []
  (->> (s/gen (s/int-in 0 1))
       (gen/fmap (fn [_] (make-channel)))))

(s/def ::channel (s/spec (::channel-type)
                         :gen channel-gen))

(s/def ::id string?)

(s/def ::connection (s/keys :req-un [::channel ::id]))

(s/fdef make-connection
        :args ::channel
        :ret ::connection)

我收到以下错误,我不知道这里有什么问题:

clojure.lang.ExceptionInfo: Unable to construct gen at: [] for: gameserve.ws$make_connection@788ffa19
clojure.lang.Compiler$CompilerException: clojure.lang.ExceptionInfo: Unable to construct gen at: [] for: gameserve.ws$make_connection@788ffa19 #:clojure.spec.alpha{:path [], :form #object[gameserve.ws$make_connection 0x788ffa19 "gameserve.ws$make_connection@788ffa19"], :failure :no-gen}

1 个答案:

答案 0 :(得分:3)

我无法重现您的错误,但想指出一些可能有助于您实现这一目标的事情。

gen/fmap忽略其参数事物已经是一件事:gen/return

这里你要调用一个没有参数的关键字,这将抛出一个IllegalArgumentException。只需移除::channel-type周围的parens。

(s/def ::channel (s/spec (::channel-type)
                         :gen channel-gen))

在这里,您正在制作一个谈论单一事物的args规范。 :args始终是一个参数序列,如果函数只接受一个参数,则它是一个长度为1的序列。您通常使用s/cat

(s/fdef make-connection
  :args ::channel
  :ret ::connection)

以下适用于我。 (它假设您的频道内容正确。)

(ns foo.core
  (:require
   [clojure.spec.gen.alpha :as gen]
   [clojure.spec.alpha :as s]))

(defn make-channel []
  :mock-channel)

(defn channel-gen
  []
  (gen/return (make-channel)))

(s/def ::channel-type any?)

(s/def ::channel (s/spec ::channel-type
                         :gen channel-gen))

(s/def ::id string?)

(s/def ::connection (s/keys :req-un [::channel ::id]))

(defn make-connection [c])

(s/fdef make-connection
  :args (s/cat :c ::channel)
  :ret ::connection)

(comment

  (s/exercise ::connection)
  ;;=> ([{:channel :mock-channel, :id ""} {:channel :mock-channel, :id ""}]
  ;;    [{:channel :mock-channel, :id "k"} {:channel :mock-channel, :id "k"}] ,,,)

  (s/exercise-fn `make-connection)
  ;;=> ([(:mock-channel) nil] [(:mock-channel) nil] ,,,)

  )