Can Prismatic schema.core / possibly be used in a Clojure function prerequisite?
I'm trying to use Prismaticschema.core/maybe
in a precondition for a function that takes an optional argument opts
, but it seems to always throw AssertionError
when I call the function without opts
:
(require '[schema.core :as schema])
(defn foo [& modules]
{:pre [(schema/validate (schema/maybe [(schema/enum :foo :bar)]) opts)]}
:yay)
(foo :foo)
;=> :yay
(foo :foo :bar)
;=> :yay
(foo)
;=> AssertionError Assert failed: (schema/validate (schema/maybe [(schema/enum :foo :bar)]) modules) user/foo (form-init3808809389777994177.clj:1)
Interestingly, this works as expected:
(schema/validate (schema/maybe [(schema/enum :foo :bar)]) nil)
;=> nil
I've used macroexpand
on defn
but nothing looks ordinary.
I can of course work around this with a precondition like
source to share
The function precondition must evaluate to true for the assertion, but schema/validate
returns the testable expression if the test passes and throws an exception if it fails. You will need to change your precondition to always return true if the check passes:
(defn foo [& opts]
{:pre [(or (schema/validate (schema/maybe [(schema/enum :foo :bar)]) opts) true)]}
:yay)
(foo :foo) ;=> :yay
(foo :foo :bar) ;=> :yay
(foo) ;=> :yay
(foo :baz) ;=> ExceptionInfo Value does not match schema: [(not (#{:foo :bar} :baz))]
source to share