Skip to content

Commit

Permalink
Support gen/gen (not serializable), fixes metosin#85
Browse files Browse the repository at this point in the history
  • Loading branch information
ikitommi committed Nov 22, 2019
1 parent 36c099f commit c0ba26f
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 4 deletions.
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -445,6 +445,14 @@ Scehmas can be used to generate values:
[:and {:gen/fmap '(partial str "kikka_")} string?]
{:seed 10, :size 10})
;; => "kikka_WT3K0yax2"

(require '[clojure.test.check.generators :as gen])

;; gen/gen (note, not serializable)
(mg/generate
[:sequential {:gen/gen (gen/list gen/neg-int)} int?]
{:size 42, :seed 42})
; => (-37 -13 -13 -24 -20 -11 -34 -40 -22 0 -10)
```

Generated values are valid:
Expand Down
4 changes: 2 additions & 2 deletions src/malli/generator.cljc
Original file line number Diff line number Diff line change
Expand Up @@ -80,8 +80,8 @@
#?(:clj (defmethod -generator :re [schema opts] (-re-gen schema opts)))

(defn- -create [schema opts]
(let [{:gen/keys [fmap elements]} (m/properties schema opts)
gen (when-not elements (-generator schema opts))
(let [{:gen/keys [gen fmap elements]} (m/properties schema opts)
gen (or gen (when-not elements (-generator schema opts)))
elements (when elements (gen/elements elements))]
(cond
fmap (gen/fmap (m/eval fmap) (or elements gen (gen/return nil)))
Expand Down
10 changes: 8 additions & 2 deletions test/malli/generator_test.cljc
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
(ns malli.generator-test
(:require [clojure.test :refer [deftest testing is]]
[clojure.test.check.generators :as gen]
[malli.json-schema-test :as json-schema-test]
[malli.generator :as mg]
[malli.core :as m]))
Expand Down Expand Up @@ -27,7 +28,7 @@
(let [re #"^\d+ \d+$"]
(m/validate re (mg/generate re)))

(let [re-test #"(?=.{8,})" ;; contains unsupported feature
(let [re-test #"(?=.{8,})" ;; contains unsupported feature
elements ["abcdefgh" "01234567"]
fmap '(fn [s] (str "prefix_" s))]
(is (thrown-with-msg? Exception #"Unsupported-feature" (mg/generator [:re re-test])))
Expand All @@ -52,4 +53,9 @@
(dotimes [_ 1000]
(#{1 2} (mg/generate [:and {:gen/elements [1 2]} int?])))
(dotimes [_ 1000]
(#{"1" "2"} (mg/generate [:and {:gen/elements [1 2], :gen/fmap 'str} int?])))))
(#{"1" "2"} (mg/generate [:and {:gen/elements [1 2], :gen/fmap 'str} int?]))))
(testing "gen/gen"
(dotimes [_ 1000]
(#{1 2} (mg/generate [:and {:gen/gen (gen/elements [1 2])} int?])))
(dotimes [_ 1000]
(#{"1" "2"} (mg/generate [:and {:gen/gen (gen/elements [1 2]) :gen/fmap str} int?])))))

0 comments on commit c0ba26f

Please sign in to comment.