Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Meaningful error message for Clojure.Spec validation in :pre

Tags:

I used the last days to dig deeper into clojure.spec in Clojure and ClojureScript.

Until now I find it most useful, to use specs as guards in :pre and :post in public functions that rely on data in a certain format.

(defn person-name [person]
  {:pre [(s/valid? ::person person)]
   :post [(s/valid? string? %)]}
  (str (::first-name person) " " (::last-name person)))

The issue with that approach is, that I get a java.lang.AssertionError: Assert failed: (s/valid? ::person person) without any information about what exactly did not met the specification.

Has anyone an idea how to get a better error message in :pre or :post guards?

I know about conform and explain*, but that does not help in those :pre or :post guards.

like image 400
DiegoFrings Avatar asked Jun 17 '16 15:06

DiegoFrings


Video Answer


2 Answers

I think the idea is that you use spec/instrument to validate function input and output rather than pre and post conditions.

There's a good example toward the bottom of this blog post: http://gigasquidsoftware.com/blog/2016/05/29/one-fish-spec-fish/ . Quick summary: you can define a spec for a function, including both input and return values using the :args and :ret keys (thus replacing both pre and post conditions), with spec/fdef, instrument it, and you get output similar to using explain when it fails to meet spec.

Minimal example derived from that link:

(spec/fdef your-func
    :args even?
    :ret  string?)


(spec/instrument #'your-func)

And that's equivalent to putting a precondition that the function has an integer argument and a postcondition that it returns a string. Except you get much more useful errors, just like you're looking for.

More details in the official guide: https://clojure.org/guides/spec ---see under the heading "Spec'ing functions".

like image 38
Paul Gowder Avatar answered Oct 09 '22 14:10

Paul Gowder


In newer alphas, there is now s/assert which can be used to assert that an input or return value matches a spec. If valid, the original value is returned. If invalid, an assertion error is thrown with the explain result. Assertions can be turned on or off and can even optionally be omitted from the compiled code entirely to have 0 production impact.

(s/def ::first-name string?)
(s/def ::last-name string?)
(s/def ::person (s/keys :req [::first-name ::last-name]))
(defn person-name [person]
  (s/assert ::person person)
  (s/assert string? (str (::first-name person) " " (::last-name person))))

(s/check-asserts true)

(person-name 10)
=> CompilerException clojure.lang.ExceptionInfo: Spec assertion failed
val: 10 fails predicate: map?
:clojure.spec/failure  :assertion-failed
 #:clojure.spec{:problems [{:path [], :pred map?, :val 10, :via [], :in []}], :failure :assertion-failed}
like image 157
Alex Miller Avatar answered Oct 09 '22 14:10

Alex Miller