Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@holyjak
Last active October 2, 2019 16:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save holyjak/8cadc0d939c8e637ef6bf75b070d28b4 to your computer and use it in GitHub Desktop.
Save holyjak/8cadc0d939c8e637ef6bf75b070d28b4 to your computer and use it in GitHub Desktop.
Override clojure.spec.alpha/gensub for friendly exceptions for failed such-that - see https://clojure.atlassian.net/browse/CLJ-2097
;; Normally the exception thrown by such-that does not point to the failed spec, which makes it useless
;; Eval this to override it and include `path` to the spec (and `form`, not sure which better)
(in-ns 'clojure.spec.alpha)
(defn- gensub
[spec overrides path rmap form]
;;(prn {:spec spec :over overrides :path path :form form})
(let [spec (specize spec)]
(if-let [g (c/or (when-let [gfn (c/or (get overrides (c/or (spec-name spec) spec))
(get overrides path))]
(gfn))
(gen* spec overrides path rmap))]
(gen/such-that #(valid? spec %) g {:max-tries 100
:ex-fn (fn [{:keys [max-tries]}]
(ex-info (str "Couldn't satisfy " (spec-name spec) " after " max-tries " tries.")
{:max max-tries
:path path
:sample-explain (->> (first (gen/sample g 1))
(explain-data spec)
:clojure.spec.alpha/problems)}))}
(let [abbr (abbrev form)]
(throw (ex-info (str "Unable to construct gen at: " path " for: " abbr)
{::path path ::form form ::failure :no-gen}))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment