[英]How do I make custom clojure.spec generator?
我正在嘗試指定以下稱為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}
我無法重現您的錯誤,但想指出一些可能有助於您解決此問題的方法。
您的gen/fmap
忽略其參數事物已經是一件事情: gen/return
。
在這里,您要調用不帶參數的關鍵字,這將引發IllegalArgumentException
。 只需刪除::channel-type
周圍的括號即可。
(s/def ::channel (s/spec (::channel-type)
:gen channel-gen))
在這里,您正在制定一個討論單個問題的args規范。 :args
始終是一個參數序列,如果函數僅接受一個參數,則其長度為一。 您通常會使用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] ,,,)
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.