Skip to content

Commit

Permalink
schema: support generation of oneof and (empty) bytes
Browse files Browse the repository at this point in the history
  • Loading branch information
st-cheewah committed Nov 12, 2023
1 parent a8caeb3 commit 9e4fc6f
Showing 1 changed file with 17 additions and 4 deletions.
21 changes: 17 additions & 4 deletions src/clojobuf/schema.cljc
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
(:require [clojobuf.constant :refer [sint32-max sint32-min sint53-max sint53-min sint64-max sint64-min uint32-max uint32-min uint64-max uint64-min]]
[clojobuf.util :refer [dot-qualify]]
[clojure.set :refer [map-invert]]
[clojure.test.check.generators :as gen]
[malli.core :as m]))

(defn- qualify-name [package name]
Expand Down Expand Up @@ -75,7 +76,7 @@
{:type `OneOf
:compile (fn [_properties [oneof targets] _options]
(when-not (and (keyword? oneof)
(every? keyword? targets))
(every? keyword? targets))
(m/-fail! ::invalid-children {:oneof oneof :targets targets}))
{:pred (fn [kvs] (if-let [target (kvs oneof)]
(and (contains? kvs target)
Expand All @@ -84,7 +85,20 @@
:min 2 ;; at least 1 child
:max 2 ;; at most 1 child
:type-properties {:error/fn (fn [_error _reg] {oneof (str "oneof condition not met: only this field's target can be set but not the other targets" )})
:error/path [oneof]}})}))
:error/path [oneof]
:gen/gen (gen/return (let [target (rand-nth targets)] {oneof target, target nil}))}})}))

(def Bytes
(m/-simple-schema
{:type `Bytes
:compile (fn [_properties [] _options]
{:pred #?(:clj bytes?
:cljs #(= js/Uint8Array (type %)))
:min 0 ;; no child
:max 0 ;; no child
:type-properties {:error/message "must be byte array"
:gen/gen (gen/return #?(:clj (byte-array 0)
:cljs (js/Uint8Array.)))}})}))

; -------------------- msg validator -----------------------------
(def vschemas-pb-types {:int32 [:int {:min sint32-min, :max sint32-max}]
Expand All @@ -103,8 +117,7 @@
(>= v 0)
(<= v uint64-max)))]]
:cljs [:int {:min uint64-min, :max uint64-max}])
:bytes #?(:clj 'bytes?
:cljs [:fn (fn [v] (= js/Uint8Array (type v)))])
:bytes Bytes
:oneof OneOf})

(defn- get-malli-type [typ]
Expand Down

0 comments on commit 9e4fc6f

Please sign in to comment.