Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix #758: generate alphanumeric strings with :min/:max #759

Merged
merged 1 commit into from
Oct 7, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions src/malli/generator.cljc
Original file line number Diff line number Diff line change
Expand Up @@ -91,10 +91,10 @@
(defn- -string-gen [schema options]
(let [{:keys [min max]} (-min-max schema options)]
(cond
(and min (= min max)) (gen/fmap str/join (gen/vector gen/char min))
(and min max) (gen/fmap str/join (gen/vector gen/char min max))
min (gen/fmap str/join (gen/sized #(gen/vector gen/char min (+ min %))))
max (gen/fmap str/join (gen/vector gen/char 0 max))
(and min (= min max)) (gen/fmap str/join (gen/vector gen/char-alphanumeric min))
(and min max) (gen/fmap str/join (gen/vector gen/char-alphanumeric min max))
min (gen/fmap str/join (gen/sized #(gen/vector gen/char-alphanumeric min (+ min %))))
max (gen/fmap str/join (gen/vector gen/char-alphanumeric 0 max))
:else gen/string-alphanumeric)))

(defn- -coll-gen [schema f options]
Expand Down
37 changes: 37 additions & 0 deletions test/malli/generator_test.cljc
Original file line number Diff line number Diff line change
Expand Up @@ -825,3 +825,40 @@
(gen/sized #(gen/vector rec 1 (+ 1 %)))]))
(gen/one-of [(gen/return nil)]))
{:seed 0})))))

(defn alphanumeric-char? [c]
{:pre [(char? c)]}
(let [i (int c)]
(or (<= (int \a) i (int \z))
(<= (int \A) i (int \Z))
(<= (int \0) i (int \9)))))

(defn alphanumeric-string? [s]
{:pre [(string? s)]}
(every? alphanumeric-char? s))

(deftest string-gen-alphanumeric-test
(dotimes [seed 100]
(testing (pr-str seed)
(testing "(and min (= min max))"
(is (alphanumeric-string?
(mg/generate [:string {:min 10
:max 10}]
{:seed seed}))))
(testing "(and min max)"
(is (alphanumeric-string?
(mg/generate [:string {:min 10
:max 20}]
{:seed seed}))))
(testing "min"
(is (alphanumeric-string?
(mg/generate [:string {:min 10}]
{:seed seed}))))
(testing "max"
(is (alphanumeric-string?
(mg/generate [:string {:max 20}]
{:seed seed}))))
(testing ":else"
(is (alphanumeric-string?
(mg/generate [:string {}]
{:seed seed})))))))