Fork me on GitHub
#clojure-spec
<
2018-07-01
>
codonnell01: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)

ackerleytng06:07:44

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

ackerleytng06:07:08

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

codonnell12:07:30

@ackerleytng

(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

ackerleytng13:07:38

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})))))

ackerleytng13:07:16

tgen is clojure.test.check.generators

ackerleytng13:07:34

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

ackerleytng13:07:01

pos-int generates 0 sometimes, hence the inc

gfredericks13:07:38

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

codonnell13: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.

codonnell13:07:58

I'll definitely check out that talk, thanks.

ackerleytng13:07:56

@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 https://dev.clojure.org/jira/browse/CLJ-2311

codonnell22:07:25

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