Fork me on GitHub
Chris O’Donnell01:07:43

Does anyone know of an efficient way to generate a multi-spec value with a particular tag? (ie. without doing a such-that and hoping to get lucky)


@codonnell what do you mean by a multi-spec value? have an example?


If i run a stest/check and hit an error, how do i inspect the value that was generated? my return value is a function. I fspecced it, and one of the inputs to that function, generated during stest/check is causing the spec to fail

Chris O’Donnell12:07:30


(s/def ::type #{::a ::b})
(s/def ::a-value pos-int?)
(s/def ::b-value keyword?)

(defmulti mymap-type ::type)
(defmethod mymap-type ::a [_]
  (s/keys :req [::type ::a-value]))
(defmethod mymap-type ::b [_]
  (s/keys :req [::type ::b-value]))
(s/def ::mymap (s/multi-spec mymap-type ::type))
;; How to generate a mymap value with tag ::a here without using gen/such-that


something like this?

(s/conform ::mymap {::type ::a
                    ::a-value 1})
(s/conform ::mymap {::type ::b
                    ::b-value :foo})

(map (partial s/explain-data ::mymap)
     (gen/sample (tgen/let [type_ (gen/elements [::a ::b])
                            a-value tgen/pos-int
                            b-value (gen/keyword)]
                   (conj {::type type_} 
                         (if (= type_ ::a)
                           {::a-value (inc a-value)}
                           {::b-value b-value})))))


tgen is clojure.test.check.generators


[clojure.spec.gen.alpha :as gen]


pos-int generates 0 sometimes, hence the inc


s-pos-int doesn't generate zeros, fyi

Chris O’Donnell13:07:12

I'd prefer not to build up the value manually like that, since the actual spec I'm working with is much more complex than the toy example I posted above.

Chris O’Donnell13:07:58

I'll definitely check out that talk, thanks.


@gfredericks thanks for giving that talk!! I loved the pictures too

❤️ 4
☝️ 4
Andreas Liljeqvist22:07:22

@codonnell (gen/sample (s/gen ::mymap {::type #(gen/return ::a)}))

Andreas Liljeqvist22:07:14

It would have been, but there is a bug with providing a generator for the dispatch key - See my bug report and patch

Chris O’Donnell22:07:25

thanks @andreas862, that is exactly what I was looking for. Hopefully your patch is accepted!