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

welcome :string schema #205

Merged
merged 3 commits into from
Jun 8, 2020
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
18 changes: 18 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,24 @@ Maps keys are not limited to keywords:
; => true
```

## String schemas

Using a predicate:

```clj
(m/validate string? "kikka")
```

Using `:string` Schema:

```clj
(m/validate :string "kikka")
; => true

(m/validate [:string {:min 1, :max 4}] "")
; => false
```

## Function schemas

`:fn` allows any predicat function to be used:
Expand Down
32 changes: 31 additions & 1 deletion src/malli/core.cljc
Original file line number Diff line number Diff line change
Expand Up @@ -707,6 +707,35 @@
(-options [_] options)
(-form [_] form))))))

(defn- -string-schema []
^{:type ::into-schema}
(reify IntoSchema
(-into-schema [_ {:keys [min max] :as properties} children options]
(when-not (zero? (count children))
(fail! ::child-error {:name :string, :properties properties, :children children, :min 0, :max 0}))
(let [count-validator (cond
(not (or min max)) nil
(and min max) (fn [x] (let [size (count x)] (<= min size max)))
min (fn [x] (<= min (count x)))
max (fn [x] (<= (count x) max)))
validator (if count-validator (fn [x] (and (string? x) (count-validator x))) string?)
form (create-form :string properties children)]
^{:type ::schema}
(reify Schema
(-name [_] :string)
(-validator [_] validator)
(-explainer [this path]
(fn explain [x in acc]
(if (or (not (string? x)) (and count-validator (not (count-validator x))))
(conj acc (error path in this x)) acc)))
(-transformer [this transformer method options]
(-value-transformer transformer this method options))
(-accept [this visitor in options]
(visitor this (vec children) in options))
(-properties [_] properties)
(-options [_] options)
(-form [_] form))))))

(defn- -register [registry k schema]
(if (contains? registry k)
(fail! ::schema-already-registered {:key k, :registry registry}))
Expand Down Expand Up @@ -944,7 +973,8 @@
:tuple (-tuple-schema)
:multi (-multi-schema)
:re (-re-schema false)
:fn (-fn-schema)})
:fn (-fn-schema)
:string (-string-schema)})

(def default-registry
(clojure.core/merge predicate-registry class-registry comparator-registry base-registry))
9 changes: 8 additions & 1 deletion src/malli/error.cljc
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,14 @@
'associative? {:error/message {:en "should be associative"}}
'sequential? {:error/message {:en "should be sequential"}}
#?@(:clj ['ratio? {:error/message {:en "should be ratio"}}])
#?@(:clj ['bytes? {:error/message {:en "should be bytes"}}])})
#?@(:clj ['bytes? {:error/message {:en "should be bytes"}}])
:string {:error/fn {:en (fn [{:keys [schema]} _]
(let [{:keys [min max]} (m/properties schema)]
(cond
(not (or min max)) "should be string"
(and min max) (str "should be between " min " and " max " characters")
min (str "should be at least " min " characters")
max (str "should be at most " max " characters"))))}}})

(defn- -maybe-localized [x locale]
(if (map? x) (get x locale) x))
Expand Down
10 changes: 10 additions & 0 deletions src/malli/generator.cljc
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,15 @@

(defn- -double-gen [options] (gen/double* (merge {:infinite? false, :NaN? false} options)))

(defn- -string-gen [schema options]
(let [{:keys [min max]} (m/properties schema options)]
(cond
(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/vector gen/char-alphanumeric min (* 2 max)))
max (gen/fmap str/join (gen/vector gen/char-alphanumeric 0 max))
:else gen/string-alpha-numeric)))

(defn- -coll-gen [schema f options]
(let [{:keys [min max]} (m/properties schema options)
gen (-> schema m/children first (generator options))]
Expand Down Expand Up @@ -78,6 +87,7 @@
(defmethod -generator :maybe [schema options] (gen/one-of [(gen/return nil) (-> schema (m/children options) first (generator options))]))
(defmethod -generator :tuple [schema options] (apply gen/tuple (mapv #(generator % options) (m/children schema options))))
#?(:clj (defmethod -generator :re [schema options] (-re-gen schema options)))
(defmethod -generator :string [schema options] (-string-gen schema options))

(defn- -create [schema options]
(let [{:gen/keys [gen fmap elements]} (m/properties schema options)
Expand Down
6 changes: 5 additions & 1 deletion src/malli/json_schema.cljc
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
(ns malli.json-schema
(:require [malli.core :as m]))
(:require [malli.core :as m]
[clojure.set :as set]))

(defn unlift-keys [m ns-str]
(reduce-kv #(if (= ns-str (namespace %2)) (assoc %1 (keyword (name %2)) %3) %1) {} m))
Expand Down Expand Up @@ -88,6 +89,9 @@
(defmethod accept :re [_ schema _ options] {:type "string", :pattern (first (m/children schema options))})
(defmethod accept :fn [_ _ _ _] {})

(defmethod accept :string [_ schema _ _]
(merge {:type "string"} (-> schema m/properties (select-keys [:min :max]) (set/rename-keys {:min :minLength, :max :maxLenght}))))

(defn- -json-schema-visitor [schema children _in options]
(or (maybe-prefix schema :json-schema)
(merge (accept (m/name schema) schema children options)
Expand Down
32 changes: 32 additions & 0 deletions test/malli/core_test.cljc
Original file line number Diff line number Diff line change
Expand Up @@ -268,6 +268,38 @@

(is (= [:maybe 'int?] (m/form schema)))))

(testing "string schemas"
(let [schema (m/schema [:string {:min 1, :max 4}])]

(is (true? (m/validate schema "abba")))
(is (false? (m/validate schema "")))
(is (false? (m/validate schema "invalid")))
(is (false? (m/validate schema false)))

(is (nil? (m/explain schema "1")))
(is (results= {:schema [:string {:min 1, :max 4}]
:value false
:errors [{:path [], :in [], :schema [:string {:min 1, :max 4}], :value false}]}
(m/explain schema false)))
(is (results= {:schema [:string {:min 1, :max 4}]
:value "invalid"
:errors [{:path [], :in [], :schema [:string {:min 1, :max 4}], :value "invalid"}]}
(m/explain schema "invalid")))

(is (= "1" (m/decode schema "1" mt/string-transformer)))
(is (= "1" (m/decode schema "1" mt/json-transformer)))

(is (= "<-->" (m/decode
[:string {:decode/string {:enter #(str "<" %), :leave #(str % ">")}}]
"--" mt/string-transformer)))

(is (true? (m/validate (over-the-wire schema) "123")))

(is (= {:name :string, :properties {:min 1, :max 4}}
(m/accept schema m/map-syntax-visitor)))

(is (= [:string {:min 1, :max 4}] (m/form schema)))))

(testing "re schemas"
(doseq [form [[:re "^[a-z]+\\.[a-z]+$"]
[:re #"^[a-z]+\.[a-z]+$"]
Expand Down
17 changes: 17 additions & 0 deletions test/malli/error_test.cljc
Original file line number Diff line number Diff line change
Expand Up @@ -254,3 +254,20 @@
(-> schema
(m/explain 2)
(me/humanize)))))))

(deftest string-test
(is (= {:a ["should be string"],
:b ["should be at least 1 characters"],
:c ["should be at most 4 characters"],
:d ["should be between 1 and 4 characters"]}
(-> [:map
[:a :string]
[:b [:string {:min 1}]]
[:c [:string {:max 4}]]
[:d [:string {:min 1, :max 4}]]]
(m/explain
{:a 123
:b ""
:c "invalid"
:d ""})
(me/humanize)))))
7 changes: 7 additions & 0 deletions test/malli/generator_test.cljc
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,10 @@
(doseq [value (mg/sample ?schema {:seed 123})]
(is (m/validate ?schema value))))))

(testing "string"
(let [schema [:string {:min 1, :max 4}]]
(is (every? (partial m/validate schema) (mg/sample schema {:size 1000})))))

#?(:clj (testing "regex"
(let [re #"^\d+ \d+$"]
(m/validate re (mg/generate re)))
Expand All @@ -40,6 +44,7 @@
#?(:clj Exception, :cljs js/Error)
#":malli.generator/no-generator"
(mg/generate [:fn '(fn [x] (<= 0 x 10))]))))

(testing "generator override"
(testing "without generator"
(let [schema [:fn {:gen/fmap '(fn [_] (rand-int 10))}
Expand All @@ -49,11 +54,13 @@
(m/validate schema (mg/generate generator)))))
(testing "with generator"
(is (re-matches #"kikka_\d+" (mg/generate [:and {:gen/fmap '(partial str "kikka_")} pos-int?])))))

(testing "gen/elements"
(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?]))))

(testing "gen/gen"
(dotimes [_ 1000]
(#{1 2} (mg/generate [:and {:gen/gen (gen/elements [1 2])} int?])))
Expand Down
3 changes: 2 additions & 1 deletion test/malli/json_schema_test.cljc
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,8 @@
[[:tuple string? string?] {:type "array"
:items [{:type "string"} {:type "string"}]
:additionalItems false}]
[[:re "^[a-z]+\\.[a-z]+$"] {:type "string", :pattern "^[a-z]+\\.[a-z]+$"}]])
[[:re "^[a-z]+\\.[a-z]+$"] {:type "string", :pattern "^[a-z]+\\.[a-z]+$"}]
[[:string {:min 1, :max 4}] {:type "string", :minLength 1, :maxLenght 4}]])

(deftest json-schema-test
(doseq [[schema json-schema] expectations]
Expand Down
3 changes: 2 additions & 1 deletion test/malli/swagger_test.cljc
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,8 @@
:items {}
:x-items [{:type "string"}
{:type "string"}]}]
[[:re "^[a-z]+\\.[a-z]+$"] {:type "string", :pattern "^[a-z]+\\.[a-z]+$"}]])
[[:re "^[a-z]+\\.[a-z]+$"] {:type "string", :pattern "^[a-z]+\\.[a-z]+$"}]
[[:string {:min 1, :max 4}] {:type "string", :minLength 1, :maxLenght 4}]])

(deftest swagger-test
(doseq [[schema swagger-schema] expectations]
Expand Down