Search code examples
clojureplumatic-schema

Generate from regular expression with Plumatic Schema generators


Regexes seem to be accepted schemas:

(require '[schema.core :as schema])

(schema/validate #"^..$" "hi") ; => "hi"

But schema-generators can't seem to generate from them:

(require '[schema-generators.generators :as gen])

(gen/generate #"^..$")
; 1. Unhandled java.lang.RuntimeException
;    You must provide a leaf generator for
;    schema.spec.leaf.LeafSpec@3d398cfd

Is it possible to work around this in some way?


Solution

  • If we use the miner/strgen library we can indeed work up a solution:

    (require '[schema.core  :as schema]
             '[miner.strgen :as strgen]
             '[schema-generators.generators :as gen])
    
    (def two-char #"^..$")
    (schema/validate two-char "hi") ; => "hi"
    
    (gen/generate two-char {two-char (strgen/string-generator #"^..$")})
    ; => "x["
    

    Though it should be noted that this only provides a generator for the regex #"^..$" in perticular and not regular expressions in general. We need a better solution, perhaps extend some protocol somewhere.