Clojure spec - override check generator for predicate

501 Views Asked by At

Is there a way to override generator for a core predicate function when calling clojure.spec.test.alpha/check?

It is possible to override predicate generator by path inside s/gen:

(gen/generate
 (s/gen
  (s/cat :s string?)
  {[:s] #(gen/return "xyz")}))

But that option doesn't exist for test/check:

(defn xyz [s] s)

(s/fdef xyz
  :args (s/cat :s string?)
  :ret  string?)

;; throws
(test/check
 `xyz
 {:gen {[:args :s] #(gen/return "xyz")}})

Name or symbol must be provided, but what is the name for the string? spec? I've tried using symbols, both 'string? and `string? but it didn't work either.

Overriding generator by wrapping string? with s/with-gen inside s/fdef causes generator-code to be displayed inside function's docs... that affects readability imo.

Defining new spec ::string just for this purpose doesn't feel right.

1

There are 1 best solutions below

2
On
(ns so.spec
    (:require [clojure.spec.gen.alpha :as gen]
              [clojure.spec.alpha :as s]
              [clojure.spec.test.alpha :as st]))

(defn xyz [s]
    ; only to make sure it gets called
    (prn s)
    s)

(s/def ::xyz-arguments (s/cat :s string?))

(s/fdef xyz
        :args ::xyz-arguments
        :ret string?)

(st/check
    'so.spec/xyz
    {:gen {::xyz-arguments #(gen/return '("xyz"))}})